--- python2.7-2.7.6.orig/debian/2to3-2.7.1 +++ python2.7-2.7.6/debian/2to3-2.7.1 @@ -0,0 +1,41 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.40.4. +.TH 2TO3-2.7 "1" "January 2012" "2to3-2.7 2.7" "User Commands" +.SH NAME +2to3-2.7 \- Python2 to Python3 converter +.SH SYNOPSIS +.B 2to3 +[\fIoptions\fR] \fIfile|dir \fR... +.SH OPTIONS +.TP +\fB\-h\fR, \fB\-\-help\fR +show this help message and exit +.TP +\fB\-d\fR, \fB\-\-doctests_only\fR +Fix up doctests only +.TP +\fB\-f\fR FIX, \fB\-\-fix\fR=\fIFIX\fR +Each FIX specifies a transformation; default: all +.TP +\fB\-j\fR PROCESSES, \fB\-\-processes\fR=\fIPROCESSES\fR +Run 2to3 concurrently +.TP +\fB\-x\fR NOFIX, \fB\-\-nofix\fR=\fINOFIX\fR +Prevent a transformation from being run +.TP +\fB\-l\fR, \fB\-\-list\-fixes\fR +List available transformations +.TP +\fB\-p\fR, \fB\-\-print\-function\fR +Modify the grammar so that print() is a function +.TP +\fB\-v\fR, \fB\-\-verbose\fR +More verbose logging +.TP +\fB\-\-no\-diffs\fR +Don't show diffs of the refactoring +.TP +\fB\-w\fR, \fB\-\-write\fR +Write back modified files +.TP +\fB\-n\fR, \fB\-\-nobackups\fR +Don't write backups for modified files --- python2.7-2.7.6.orig/debian/FAQ.html +++ python2.7-2.7.6/debian/FAQ.html @@ -0,0 +1,8997 @@ + + +The Whole Python FAQ + + + +

The Whole Python FAQ

+Last changed on Wed Feb 12 21:31:08 2003 CET + +

(Entries marked with ** were changed within the last 24 hours; +entries marked with * were changed within the last 7 days.) +

+ +

+


+

1. General information and availability

+ + +

+


+

2. Python in the real world

+ + +

+


+

3. Building Python and Other Known Bugs

+ + +

+


+

4. Programming in Python

+ + +

+


+

5. Extending Python

+ + +

+


+

6. Python's design

+ + +

+


+

7. Using Python on non-UNIX platforms

+ + +

+


+

8. Python on Windows

+ + +
+

1. General information and availability

+ +
+

1.1. What is Python?

+Python is an interpreted, interactive, object-oriented programming +language. It incorporates modules, exceptions, dynamic typing, very +high level dynamic data types, and classes. Python combines +remarkable power with very clear syntax. It has interfaces to many +system calls and libraries, as well as to various window systems, and +is extensible in C or C++. It is also usable as an extension language +for applications that need a programmable interface. Finally, Python +is portable: it runs on many brands of UNIX, on the Mac, and on PCs +under MS-DOS, Windows, Windows NT, and OS/2. +

+To find out more, the best thing to do is to start reading the +tutorial from the documentation set (see a few questions further +down). +

+See also question 1.17 (what is Python good for). +

+ +Edit this entry / +Log info + +/ Last changed on Mon May 26 16:05:18 1997 by +GvR +

+ +


+

1.2. Why is it called Python?

+Apart from being a computer scientist, I'm also a fan of "Monty +Python's Flying Circus" (a BBC comedy series from the seventies, in +the -- unlikely -- case you didn't know). It occurred to me one day +that I needed a name that was short, unique, and slightly mysterious. +And I happened to be reading some scripts from the series at the +time... So then I decided to call my language Python. +

+By now I don't care any more whether you use a Python, some other +snake, a foot or 16-ton weight, or a wood rat as a logo for Python! +

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 24 00:50:41 2000 by +GvR +

+ +


+

1.3. How do I obtain a copy of the Python source?

+The latest Python source distribution is always available from +python.org, at http://www.python.org/download. The latest development sources can be obtained via anonymous CVS from SourceForge, at http://www.sf.net/projects/python . +

+The source distribution is a gzipped tar file containing the complete C source, LaTeX +documentation, Python library modules, example programs, and several +useful pieces of freely distributable software. This will compile and +run out of the box on most UNIX platforms. (See section 7 for +non-UNIX information.) +

+Older versions of Python are also available from python.org. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 9 17:06:16 2002 by +A.M. Kuchling +

+ +


+

1.4. How do I get documentation on Python?

+All documentation is available on-line, starting at http://www.python.org/doc/. +

+The LaTeX source for the documentation is part of the source +distribution. If you don't have LaTeX, the latest Python +documentation set is available, in various formats like postscript +and html, by anonymous ftp - visit the above URL for links to the +current versions. +

+PostScript for a high-level description of Python is in the file nluug-paper.ps +(a separate file on the ftp site). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 21 12:02:55 1998 by +Ken Manheimer +

+ +


+

1.5. Are there other ftp sites that mirror the Python distribution?

+The following anonymous ftp sites keep mirrors of the Python +distribution: +

+USA: +

+

+        ftp://ftp.python.org/pub/python/
+        ftp://gatekeeper.dec.com/pub/plan/python/
+        ftp://ftp.uu.net/languages/python/
+        ftp://ftp.wustl.edu/graphics/graphics/sgi-stuff/python/
+        ftp://ftp.sterling.com/programming/languages/python/
+        ftp://uiarchive.cso.uiuc.edu/pub/lang/python/
+        ftp://ftp.pht.com/mirrors/python/python/
+	ftp://ftp.cdrom.com/pub/python/
+
+Europe: +

+

+        ftp://ftp.cwi.nl/pub/python/
+        ftp://ftp.funet.fi/pub/languages/python/
+        ftp://ftp.sunet.se/pub/lang/python/
+        ftp://unix.hensa.ac.uk/mirrors/uunet/languages/python/
+        ftp://ftp.lip6.fr/pub/python/
+        ftp://sunsite.cnlab-switch.ch/mirror/python/
+        ftp://ftp.informatik.tu-muenchen.de/pub/comp/programming/languages/python/
+
+Australia: +

+

+        ftp://ftp.dstc.edu.au/pub/python/
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 24 09:20:49 1999 by +A.M. Kuchling +

+ +


+

1.6. Is there a newsgroup or mailing list devoted to Python?

+There is a newsgroup, comp.lang.python, +and a mailing list. The newsgroup and mailing list are gatewayed into +each other -- if you can read news it's unnecessary to subscribe to +the mailing list. To subscribe to the mailing list +(python-list@python.org) visit its Mailman webpage at +http://www.python.org/mailman/listinfo/python-list +

+More info about the newsgroup and mailing list, and about other lists, +can be found at +http://www.python.org/psa/MailingLists.html. +

+Archives of the newsgroup are kept by Deja News and accessible +through the "Python newsgroup search" web page, +http://www.python.org/search/search_news.html. +This page also contains pointer to other archival collections. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jun 23 09:29:36 1999 by +GvR +

+ +


+

1.7. Is there a WWW page devoted to Python?

+Yes, http://www.python.org/ is the official Python home page. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 14:42:59 1997 by +Ken Manheimer +

+ +


+

1.8. Is the Python documentation available on the WWW?

+Yes. Python 2.0 documentation is available from +http://www.pythonlabs.com/tech/python2.0/doc/ and from +http://www.python.org/doc/. Note that most documentation +is available for on-line browsing as well as for downloading. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:14:08 2001 by +Moshe Zadka +

+ +


+

1.9. Are there any books on Python?

+Yes, many, and more are being published. See +the python.org Wiki at http://www.python.org/cgi-bin/moinmoin/PythonBooks for a list. +

+You can also search online bookstores for "Python" +(and filter out the Monty Python references; or +perhaps search for "Python" and "language"). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Aug 5 19:08:49 2002 by +amk +

+ +


+

1.10. Are there any published articles about Python that I can reference?

+If you can't reference the web site, and you don't want to reference the books +(see previous question), there are several articles on Python that you could +reference. +

+Most publications about Python are collected on the Python web site: +

+

+    http://www.python.org/doc/Publications.html
+
+It is no longer recommended to reference this +very old article by Python's author: +

+

+    Guido van Rossum and Jelke de Boer, "Interactively Testing Remote
+    Servers Using the Python Programming Language", CWI Quarterly, Volume
+    4, Issue 4 (December 1991), Amsterdam, pp 283-303.
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Jul 4 20:52:31 1998 by +GvR +

+ +


+

1.11. Are there short introductory papers or talks on Python?

+There are several - you can find links to some of them collected at +http://www.python.org/doc/Hints.html#intros. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:04:05 1997 by +Ken Manheimer +

+ +


+

1.12. How does the Python version numbering scheme work?

+Python versions are numbered A.B.C or A.B. A is the major version +number -- it is only incremented for really major changes in the +language. B is the minor version number, incremented for less +earth-shattering changes. C is the micro-level -- it is +incremented for each bugfix release. See PEP 6 for more information +about bugfix releases. +

+Not all releases have bugfix releases. +Note that in the past (ending with 1.5.2), +micro releases have added significant changes; +in fact the changeover from 0.9.9 to 1.0.0 was the first time +that either A or B changed! +

+Alpha, beta and release candidate versions have an additional suffixes. +The suffix for an alpha version is "aN" for some small number N, the +suffix for a beta version is "bN" for some small number N, and the +suffix for a release candidate version is "cN" for some small number N. +

+Note that (for instance) all versions labeled 2.0aN precede the +versions labeled 2.0bN, which precede versions labeled 2.0cN, and +those precede 2.0. +

+As a rule, no changes are made between release candidates and the final +release unless there are show-stopper bugs. +

+You may also find version numbers with a "+" suffix, e.g. "2.2+". +These are unreleased versions, built directly from the CVS trunk. +

+See also the documentation for sys.version, sys.hexversion, and +sys.version_info. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 14 06:34:17 2002 by +GvR +

+ +


+

1.13. How do I get a beta test version of Python?

+All releases, including alphas, betas and release candidates, are announced on +comp.lang.python and comp.lang.python.announce newsgroups, +which are gatewayed into the python-list@python.org and +python-announce@python.org. In addition, all these announcements appear on +the Python home page, at http://www.python.org. +

+You can also access the development version of Python through CVS. See http://sourceforge.net/cvs/?group_id=5470 for details. If you're not familiar with CVS, documents like http://linux.oreillynet.com/pub/a/linux/2002/01/03/cvs_intro.html +provide an introduction. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 00:57:08 2002 by +Neal Norwitz +

+ +


+

1.14. Are there copyright restrictions on the use of Python?

+Hardly. You can do anything you want with the source, as long as +you leave the copyrights in, and display those copyrights in any +documentation about Python that you produce. Also, don't use the +author's institute's name in publicity without prior written +permission, and don't hold them responsible for anything (read the +actual copyright for a precise legal wording). +

+In particular, if you honor the copyright rules, it's OK to use Python +for commercial use, to sell copies of Python in source or binary form, +or to sell products that enhance Python or incorporate Python (or part +of it) in some form. I would still like to know about all commercial +use of Python! +

+ +Edit this entry / +Log info +

+ +


+

1.15. Why was Python created in the first place?

+Here's a very brief summary of what got me started: +

+I had extensive experience with implementing an interpreted language +in the ABC group at CWI, and from working with this group I had +learned a lot about language design. This is the origin of many +Python features, including the use of indentation for statement +grouping and the inclusion of very-high-level data types (although the +details are all different in Python). +

+I had a number of gripes about the ABC language, but also liked many +of its features. It was impossible to extend the ABC language (or its +implementation) to remedy my complaints -- in fact its lack of +extensibility was one of its biggest problems. +I had some experience with using Modula-2+ and talked with the +designers of Modula-3 (and read the M3 report). M3 is the origin of +the syntax and semantics used for exceptions, and some other Python +features. +

+I was working in the Amoeba distributed operating system group at +CWI. We needed a better way to do system administration than by +writing either C programs or Bourne shell scripts, since Amoeba had +its own system call interface which wasn't easily accessible from the +Bourne shell. My experience with error handling in Amoeba made me +acutely aware of the importance of exceptions as a programming +language feature. +

+It occurred to me that a scripting language with a syntax like ABC +but with access to the Amoeba system calls would fill the need. I +realized that it would be foolish to write an Amoeba-specific +language, so I decided that I needed a language that was generally +extensible. +

+During the 1989 Christmas holidays, I had a lot of time on my hand, +so I decided to give it a try. During the next year, while still +mostly working on it in my own time, Python was used in the Amoeba +project with increasing success, and the feedback from colleagues made +me add many early improvements. +

+In February 1991, after just over a year of development, I decided +to post to USENET. The rest is in the Misc/HISTORY file. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 00:06:23 1997 by +GvR +

+ +


+

1.16. Do I have to like "Monty Python's Flying Circus"?

+No, but it helps. Pythonistas like the occasional reference to SPAM, +and of course, nobody expects the Spanish Inquisition +

+The two main reasons to use Python are: +

+

+ - Portable
+ - Easy to learn
+
+The three main reasons to use Python are: +

+

+ - Portable
+ - Easy to learn
+ - Powerful standard library
+
+(And nice red uniforms.) +

+And remember, there is no rule six. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 28 10:39:21 1997 by +GvR +

+ +


+

1.17. What is Python good for?

+Python is used in many situations where a great deal of dynamism, +ease of use, power, and flexibility are required. +

+In the area of basic text +manipulation core Python (without any non-core extensions) is easier +to use and is roughly as fast as just about any language, and this makes Python +good for many system administration type tasks and for CGI programming +and other application areas that manipulate text and strings and such. +

+When augmented with +standard extensions (such as PIL, COM, Numeric, oracledb, kjbuckets, +tkinter, win32api, etc.) +or special purpose extensions (that you write, perhaps using helper tools such +as SWIG, or using object protocols such as ILU/CORBA or COM) Python +becomes a very convenient "glue" or "steering" +language that helps make heterogeneous collections of unrelated +software packages work together. +For example by combining Numeric with oracledb you can help your +SQL database do statistical analysis, or even Fourier transforms. +One of the features that makes Python excel in the "glue language" role +is Python's simple, usable, and powerful C language runtime API. +

+Many developers also use Python extensively as a graphical user +interface development aide. +

+ +Edit this entry / +Log info + +/ Last changed on Sat May 24 10:13:11 1997 by +Aaron Watters +

+ +


+

1.18. Can I use the FAQ Wizard software to maintain my own FAQ?

+Sure. It's in Tools/faqwiz/ of the python source tree. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Mar 29 06:50:32 2002 by +Aahz +

+ +


+

1.19. Which editor has good support for editing Python source code?

+On Unix, the first choice is Emacs/XEmacs. There's an elaborate +mode for editing Python code, which is available from the Python +source distribution (Misc/python-mode.el). It's also bundled +with XEmacs (we're still working on legal details to make it possible +to bundle it with FSF Emacs). And it has its own web page: +

+

+    http://www.python.org/emacs/python-mode/index.html
+
+There are many other choices, for Unix, Windows or Macintosh. +Richard Jones compiled a table from postings on the Python newsgroup: +

+

+    http://www.bofh.asn.au/~richard/editors.html
+
+See also FAQ question 7.10 for some more Mac and Win options. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 15 23:21:04 1998 by +Gvr +

+ +


+

1.20. I've never programmed before. Is there a Python tutorial?

+There are several, and at least one book. +All information for beginning Python programmers is collected here: +

+

+    http://www.python.org/doc/Newbies.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Sep 5 05:34:07 2001 by +GvR +

+ +


+

1.21. Where in the world is www.python.org located?

+It's currently in Amsterdam, graciously hosted by XS4ALL: +

+

+    http://www.xs4all.nl
+
+Thanks to Thomas Wouters for setting this up!!!! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 3 21:49:27 2001 by +GvR +

+ +


+

2. Python in the real world

+ +
+

2.1. How many people are using Python?

+Certainly thousands, and quite probably tens of thousands of users. +More are seeing the light each day. The comp.lang.python newsgroup is +very active, but overall there is no accurate estimate of the number of subscribers or Python users. +

+Jacek Artymiak has created a Python Users Counter; you can see the +current count by visiting +http://www.wszechnica.safenet.pl/cgi-bin/checkpythonuserscounter.py +(this will not increment the counter; use the link there if you haven't +added yourself already). Most Python users appear not to have registered themselves. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Feb 21 23:29:18 2002 by +GvR +

+ +


+

2.2. Have any significant projects been done in Python?

+At CWI (the former home of Python), we have written a 20,000 line +authoring environment for transportable hypermedia presentations, a +5,000 line multimedia teleconferencing tool, as well as many many +smaller programs. +

+At CNRI (Python's new home), we have written two large applications: +Grail, a fully featured web browser (see +http://grail.cnri.reston.va.us), +and the Knowbot Operating Environment, +a distributed environment for mobile code. +

+The University of Virginia uses Python to control a virtual reality +engine. See http://alice.cs.cmu.edu. +

+The ILU project at Xerox PARC can generate Python glue for ILU +interfaces. See ftp://ftp.parc.xerox.com/pub/ilu/ilu.html. ILU +is a free CORBA compliant ORB which supplies distributed object +connectivity to a host of platforms using a host of languages. +

+Mark Hammond and Greg Stein and others are interfacing Python to +Microsoft's COM and ActiveX architectures. This means, among other +things, that Python may be used in active server pages or as a COM +controller (for example to automatically extract from or insert information +into Excel or MSAccess or any other COM aware application). +Mark claims Python can even be a ActiveX scripting host (which +means you could embed JScript inside a Python application, if you +had a strange sense of humor). Python/AX/COM is distributed as part +of the PythonWin distribution. +

+The University of California, Irvine uses a student administration +system called TELE-Vision written entirely in Python. Contact: Ray +Price rlprice@uci.edu. +

+The Melbourne Cricket Ground (MCG) in Australia (a 100,000+ person venue) +has it's scoreboard system written largely in Python on MS Windows. +Python expressions are used to create almost every scoring entry that +appears on the board. The move to Python/C++ away from exclusive C++ +has provided a level of functionality that would simply not have been +viable otherwise. +

+See also the next question. +

+Note: this FAQ entry is really old. +See http://www.python.org/psa/Users.html for a more recent list. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 25 13:24:15 2000 by +GvR +

+ +


+

2.3. Are there any commercial projects going on using Python?

+Yes, there's lots of commercial activity using Python. See +http://www.python.org/psa/Users.html for a list. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 14 18:17:33 1998 by +ken +

+ +


+

2.4. How stable is Python?

+Very stable. New, stable releases have been coming out roughly every 3 to 12 months since 1991, and this seems likely to continue. +

+With the introduction of retrospective "bugfix" releases the stability of the language implementations can be, and is being, improved independently of the new features offered by more recent major or minor releases. Bugfix releases, indicated by a third component of the version number, only fix known problems and do not gratuitously introduce new and possibly incompatible features or modified library functionality. +

+Release 2.2 got its first bugfix on April 10, 2002. The new version +number is now 2.2.1. The 2.1 release, at 2.1.3, can probably be +considered the "most stable" platform because it has been bugfixed +twice. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 23 10:20:04 2002 by +Jens Kubieziel +

+ +


+

2.5. What new developments are expected for Python in the future?

+See http://www.python.org/peps/ for the Python Enhancement +Proposals (PEPs). PEPs are design +documents +describing a suggested new feature for Python, providing +a concise technical specification and a rationale. +

+Also, follow the discussions on the python-dev mailing list. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 9 17:09:51 2002 by +A.M. Kuchling +

+ +


+

2.6. Is it reasonable to propose incompatible changes to Python?

+In general, no. There are already millions of lines of Python code +around the world, so any changes in the language that invalidates more +than a very small fraction of existing programs has to be frowned +upon. Even if you can provide a conversion program, there still is +the problem of updating all documentation. Providing a gradual +upgrade path is the only way if a feature has to be changed. +

+See http://www.python.org/peps/pep-0005.html for the proposed +mechanism for creating backwards-incompatibilities. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 1 22:13:47 2002 by +Fred Drake +

+ +


+

2.7. What is the future of Python?

+Please see http://www.python.org/peps/ for proposals of future +activities. One of the PEPs (Python Enhancement Proposals) deals +with the PEP process and PEP format -- see +http://www.python.org/peps/pep-0001.html if you want to +submit a PEP. In http://www.python.org/peps/pep-0042.html there +is a list of wishlists the Python Development team plans to tackle. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 1 22:15:46 2002 by +Fred Drake +

+ +


+

2.8. What was the PSA, anyway?

+The Python Software Activity was +created by a number of Python aficionados who want Python to be more +than the product and responsibility of a single individual. +The PSA was not an independent organization, but lived +under the umbrealla of CNRI. +

+The PSA has been superseded by the Python Software Foundation, +an independent non-profit organization. The PSF's home page +is at http://www.python.org/psf/. +

+Some pages created by the PSA still live at +http://www.python.org/psa/ +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 25 18:19:44 2002 by +GvR +

+ +


+

2.9. Deleted

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:51:30 2001 by +Moshe Zadka +

+ +


+

2.10. Deleted

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:52:19 2001 by +Moshe Zadka +

+ +


+

2.11. Is Python Y2K (Year 2000) Compliant?

+As of January, 2001 no major problems have been reported and Y2K +compliance seems to be a non-issue. +

+Since Python is available free of charge, there are no absolute +guarantees. If there are unforeseen problems, liability is the +user's rather than the developers', and there is nobody you can sue for damages. +

+Python does few +date manipulations, and what it does is all based on the Unix +representation for time (even on non-Unix systems) which uses seconds +since 1970 and won't overflow until 2038. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 8 17:19:32 2001 by +Steve Holden +

+ +


+

2.12. Is Python a good language in a class for beginning programmers?

+Yes. This long answer attempts to address any concerns you might +have with teaching Python as a programmer's first language. +(If you want to discuss Python's use in education, then +you may be interested in joining the edu-sig mailinglist. +See http://www.python.org/sigs/edu-sig/ ) +

+It is still common to start students with a procedural +(subset of a) statically typed language such as Pascal, C, or +a subset of C++ or Java. I think that students may be better +served by learning Python as their first language. Python has +a very simple and consistent syntax and a large standard library. +Most importantly, using Python in a beginning programming course +permits students to concentrate on important programming skills, +such as problem decomposition and data type design. +

+With Python, students can be quickly introduced to basic concepts +such as loops and procedures. They can even probably work with +user-defined objects in their very first course. They could +implement a tree structure as nested Python lists, for example. +They could be introduced to objects in their first course if +desired. For a student who has never programmed before, using +a statically typed language seems unnatural. It presents +additional complexity that the student must master and slows +the pace of the course. The students are trying to learn to +think like a computer, decompose problems, design consistent +interfaces, and encapsulate data. While learning to use a +statically typed language is important, it is not necessarily the +best topic to address in the students' first programming course. +

+Many other aspects of Python make it a good first language. +Python has a large standard library (like Java) so that +students can be assigned programming projects very early in the +course that do something. Assignments aren't restricted to the +standard four-function calculator and check balancing programs. +By using the standard library, students can gain the satisfaction +of working on realistic applications as they learn the fundamentals +of programming. Using the standard library also teaches students +about code reuse. +

+Python's interactive interpreter also enables students to +test language features while they're programming. They can keep +a window with the interpreter running while they enter their +programs' source in another window. If they can't remember the +methods for a list, they can do something like this: +

+

+ >>> L = []
+ >>> dir(L)
+ ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
+ 'reverse', 'sort']
+ >>> print L.append.__doc__
+ L.append(object) -- append object to end
+ >>> L.append(1)
+ >>> L
+ [1]
+
+With the interpreter, documentation is never far from the +student as he's programming. +

+There are also good IDEs for Python. Guido van Rossum's IDLE +is a cross-platform IDE for Python that is written in Python +using Tk. There is also a Windows specific IDE called PythonWin. +Emacs users will be happy to know that there is a very good Python +mode for Emacs. All of these programming environments provide +syntax highlighting, auto-indenting, and access to the interactive +interpreter while coding. For more information about IDEs, see XXX. +

+If your department is currently using Pascal because it was +designed to be a teaching language, then you'll be happy to +know that Guido van Rossum designed Python to be simple to +teach to everyone but powerful enough to implement real world +applications. Python makes a good language for first time +programmers because that was one of Python's design goals. +There are papers at http://www.python.org/doc/essays/ on the Python website +by Python's creator explaining his objectives for the language. +One that may interest you is titled "Computer Programming for Everybody" +http://www.python.org/doc/essays/cp4e.html +

+If you're seriously considering Python as a language for your +school, Guido van Rossum may even be willing to correspond with +you about how the language would fit in your curriculum. +See http://www.python.org/doc/FAQ.html#2.2 for examples of +Python's use in the "real world." +

+While Python, its source code, and its IDEs are freely +available, this consideration should not rule +out other languages. There are other free languages (Java, +free C compilers), and many companies are willing to waive some +or all of their fees for student programming tools if it +guarantees that a whole graduating class will know how to +use their tools. That is, if one of the requirements for +the language that will be taught is that it be freely +available, then Python qualifies, but this requirement +does not preclude other languages. +

+While Python jobs may not be as prevalent as C/C++/Java jobs, +teachers should not worry about teaching students critical job +skills in their first course. The skills that win students a +job are those they learn in their senior classes and internships. +Their first programming courses are there to lay a solid +foundation in programming fundamentals. The primary question +in choosing the language for such a course should be which +language permits the students to learn this material without +hindering or limiting them. +

+Another argument for Python is that there are many tasks for +which something like C++ is overkill. That's where languages +like Python, Perl, Tcl, and Visual Basic thrive. It's critical +for students to know something about these languages. (Every +employer for whom I've worked used at least one such language.) +Of the languages listed above, Python probably makes the best +language in a programming curriculum since its syntax is simple, +consistent, and not unlike other languages (C/C++/Java) that +are probably in the curriculum. By starting students with +Python, a department simultaneously lays the foundations for +other programming courses and introduces students to the type +of language that is often used as a "glue" language. As an +added bonus, Python can be used to interface with Microsoft's +COM components (thanks to Mark Hammond). There is also Jython, +a Java implementation of the Python interpreter, that can be +used to connect Java components. +

+If you currently start students with Pascal or C/C++ or Java, +you may be worried they will have trouble learning a statically +typed language after starting with Python. I think that this +fear most often stems from the fact that the teacher started +with a statically typed language, and we tend to like to teach +others in the same way we were taught. In reality, the +transition from Python to one of these other languages is +quite simple. +

+To motivate a statically typed language such as C++, begin the +course by explaining that unlike Python, their first language, +C++ is compiled to a machine dependent executable. Explain +that the point is to make a very fast executable. To permit +the compiler to make optimizations, programmers must help it +by specifying the "types" of variables. By restricting each +variable to a specific type, the compiler can reduce the +book-keeping it has to do to permit dynamic types. The compiler +also has to resolve references at compile time. Thus, the +language gains speed by sacrificing some of Python's dynamic +features. Then again, the C++ compiler provides type safety +and catches many bugs at compile time instead of run time (a +critical consideration for many commercial applications). C++ +is also designed for very large programs where one may want to +guarantee that others don't touch an object's implementation. +C++ provides very strong language features to separate an object's +implementation from its interface. Explain why this separation +is a good thing. +

+The first day of a C++ course could then be a whirlwind introduction +to what C++ requires and provides. The point here is that after +a semester or two of Python, students are hopefully competent +programmers. They know how to handle loops and write procedures. +They've also worked with objects, thought about the benefits of +consistent interfaces, and used the technique of subclassing to +specialize behavior. Thus, a whirlwind introduction to C++ could +show them how objects and subclassing looks in C++. The +potentially difficult concepts of object-oriented design were +taught without the additional obstacles presented by a language +such as C++ or Java. When learning one of these languages, +the students would already understand the "road map." They +understand objects; they would just be learning how objects +fit in a statically typed languages. Language requirements +and compiler errors that seem unnatural to beginning programmers +make sense in this new context. Many students will find it +helpful to be able to write a fast prototype of their algorithms +in Python. Thus, they can test and debug their ideas before +they attempt to write the code in the new language, saving the +effort of working with C++ types for when they've discovered a +working solution for their assignments. When they get annoyed +with the rigidity of types, they'll be happy to learn about +containers and templates to regain some of the lost flexibility +Python afforded them. Students may also gain an appreciation +for the fact that no language is best for every task. They'll +see that C++ is faster, but they'll know that they can gain +flexibility and development speed with a Python when execution +speed isn't critical. +

+If you have any concerns that weren't addressed here, try +posting to the Python newsgroup. Others there have done some +work with using Python as an instructional tool. Good luck. +We'd love to hear about it if you choose Python for your course. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 2 19:32:35 2002 by +Bill Sconce +

+ +


+

3. Building Python and Other Known Bugs

+ +
+

3.1. Is there a test set?

+Sure. You can run it after building with "make test", or you can +run it manually with this command at the Python prompt: +

+

+ import test.autotest
+
+In Python 1.4 or earlier, use +

+

+ import autotest
+
+The test set doesn't test all features of Python, +but it goes a long way to confirm that Python is actually working. +

+NOTE: if "make test" fails, don't just mail the output to the +newsgroup -- this doesn't give enough information to debug the +problem. Instead, find out which test fails, and run that test +manually from an interactive interpreter. For example, if +"make test" reports that test_spam fails, try this interactively: +

+

+ import test.test_spam
+
+This generally produces more verbose output which can be diagnosed +to debug the problem. If you find a bug in Python or the libraries, or in the tests, please report this in the Python bug tracker at SourceForge: +

+http://sourceforge.net/tracker/?func=add&group_id=5470&atid=105470 +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:29:36 2001 by +Fred Drake +

+ +


+

3.2. When running the test set, I get complaints about floating point operations, but when playing with floating point operations I cannot find anything wrong with them.

+The test set makes occasional unwarranted assumptions about the +semantics of C floating point operations. Until someone donates a +better floating point test set, you will have to comment out the +offending floating point tests and execute similar tests manually. +

+ +Edit this entry / +Log info +

+ +


+

3.3. Link errors after rerunning the configure script.

+It is generally necessary to run "make clean" after a configuration +change. +

+ +Edit this entry / +Log info +

+ +


+

3.4. The python interpreter complains about options passed to a script (after the script name).

+You are probably linking with GNU getopt, e.g. through -liberty. +Don't. The reason for the complaint is that GNU getopt, unlike System +V getopt and other getopt implementations, doesn't consider a +non-option to be the end of the option list. A quick (and compatible) +fix for scripts is to add "--" to the interpreter, like this: +

+

+        #! /usr/local/bin/python --
+
+You can also use this interactively: +

+

+        python -- script.py [options]
+
+Note that a working getopt implementation is provided in the Python +distribution (in Python/getopt.c) but not automatically used. +

+ +Edit this entry / +Log info +

+ +


+

3.5. When building on the SGI, make tries to run python to create glmodule.c, but python hasn't been built or installed yet.

+Comment out the line mentioning glmodule.c in Setup and build a +python without gl first; install it or make sure it is in your $PATH, +then edit the Setup file again to turn on the gl module, and make +again. You don't need to do "make clean"; you do need to run "make +Makefile" in the Modules subdirectory (or just run "make" at the +toplevel). +

+ +Edit this entry / +Log info +

+ +


+

3.6. I use VPATH but some targets are built in the source directory.

+On some systems (e.g. Sun), if the target already exists in the +source directory, it is created there instead of in the build +directory. This is usually because you have previously built without +VPATH. Try running "make clobber" in the source directory. +

+ +Edit this entry / +Log info +

+ +


+

3.7. Trouble building or linking with the GNU readline library.

+You can use the GNU readline library to improve the interactive user +interface: this gives you line editing and command history when +calling python interactively. Its sources are distributed with +Python (at least for 2.0). Uncomment the line +

+#readline readline.c -lreadline -ltermcap +

+in Modules/Setup. The configuration option --with-readline +is no longer supported, at least in Python 2.0. Some hints on +building and using the readline library: +On SGI IRIX 5, you may have to add the following +to rldefs.h: +

+

+        #ifndef sigmask
+        #define sigmask(sig) (1L << ((sig)-1))
+        #endif
+
+On some systems, you will have to add #include "rldefs.h" to the +top of several source files, and if you use the VPATH feature, you +will have to add dependencies of the form foo.o: foo.c to the +Makefile for several values of foo. +The readline library requires use of the termcap library. A +known problem with this is that it contains entry points which +cause conflicts with the STDWIN and SGI GL libraries. The STDWIN +conflict can be solved by adding a line saying '#define werase w_erase' to the +stdwin.h file (in the STDWIN distribution, subdirectory H). The +GL conflict has been solved in the Python configure script by a +hack that forces use of the static version of the termcap library. +Check the newsgroup gnu.bash.bug news:gnu.bash.bug for +specific problems with the readline library (I don't read this group +but I've been told that it is the place for readline bugs). +

+ +Edit this entry / +Log info + +/ Last changed on Sat Dec 2 18:23:48 2000 by +Issac Trotts +

+ +


+

3.8. Trouble with socket I/O on older Linux 1.x versions.

+Once you've built Python, use it to run the regen script in the +Lib/plat-linux2 directory. Apparently the files as distributed don't match the system headers on some Linux versions. +

+Note that this FAQ entry only applies to Linux kernel versions 1.x.y; +these are hardly around any more. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 30 20:05:52 2002 by +Jens Kubieziel +

+ +


+

3.9. Trouble with prototypes on Ultrix.

+Ultrix cc seems broken -- use gcc, or edit config.h to #undef +HAVE_PROTOTYPES. +

+ +Edit this entry / +Log info +

+ +


+

3.10. Other trouble building Python on platform X.

+Please submit the details to the SourceForge bug tracker: +

+

+  http://sourceforge.net/tracker/?group_id=5470&atid=105470
+
+and we'll look +into it. Please provide as many details as possible. In particular, +if you don't tell us what type of computer and what operating system +(and version) you are using it will be difficult for us to figure out +what is the matter. If you have compilation output logs, +please use file uploads -- don't paste everything in the message box. +

+In many cases, we won't have access to the same hardware or operating system version, so please, if you have a SourceForge account, log in before filing your report, or if you don't have an account, include an email address at which we can reach you for further questions. Logging in to SourceForge first will also cause SourceForge to send you updates as we act on your report. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:53:18 2001 by +Fred Drake +

+ +


+

3.11. How to configure dynamic loading on Linux.

+This is now automatic as long as your Linux version uses the ELF +object format (all recent Linuxes do). +

+ +Edit this entry / +Log info +

+ +


+

3.12. I can't get shared modules to work on Linux 2.0 (Slackware96)?

+This is a bug in the Slackware96 release. The fix is simple: Make sure +that there is a link from /lib/libdl.so to /lib/libdl.so.1 so that the +following links are setup: /lib/libdl.so -> /lib/libdl.so.1 +/lib/libdl.so.1 -> /lib/libdl.so.1.7.14 You may have to rerun the +configure script, after rm'ing the config.cache file, before you +attempt to rebuild python after this fix. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 15:45:03 1997 by +GvR +

+ +


+

3.13. Trouble when making modules shared on Linux.

+This happens when you have built Python for static linking and then +enable +
+  *shared*
+
+in the Setup file. Shared library code must be +compiled with "-fpic". If a .o file for the module already exist that +was compiled for static linking, you must remove it or do "make clean" +in the Modules directory. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 13:42:30 1997 by +GvR +

+ +


+

3.14. [deleted]

+[ancient information on threads on linux (when thread support +was not standard) used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 2 17:27:13 2002 by +Erno Kuusela +

+ +


+

3.15. Errors when linking with a shared library containing C++ code.

+Link the main Python binary with C++. Change the definition of +LINKCC in Modules/Makefile to be your C++ compiler. You may have to +edit config.c slightly to make it compilable with C++. +

+ +Edit this entry / +Log info +

+ +


+

3.16. Deleted

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 16:02:22 2001 by +GvR +

+ +


+

3.17. Deleted.

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 15:54:57 2001 by +GvR +

+ +


+

3.18. Compilation or link errors for the _tkinter module

+Most likely, there's a version mismatch between the Tcl/Tk header +files (tcl.h and tk.h) and the Tcl/Tk libraries you are using e.g. +"-ltk8.0" and "-ltcl8.0" arguments for _tkinter in the Setup file). +It is possible to install several versions of the Tcl/Tk libraries, +but there can only be one version of the tcl.h and tk.h header +files. If the library doesn't match the header, you'll get +problems, either when linking the module, or when importing it. +Fortunately, the version number is clearly stated in each file, +so this is easy to find. Reinstalling and using the latest +version usually fixes the problem. +

+(Also note that when compiling unpatched Python 1.5.1 against +Tcl/Tk 7.6/4.2 or older, you get an error on Tcl_Finalize. See +the 1.5.1 patch page at http://www.python.org/1.5/patches-1.5.1/.) +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 11 00:49:14 1998 by +Gvr +

+ +


+

3.19. I configured and built Python for Tcl/Tk but "import Tkinter" fails.

+Most likely, you forgot to enable the line in Setup that says +"TKPATH=:$(DESTLIB)/tkinter". +

+ +Edit this entry / +Log info +

+ +


+

3.20. [deleted]

+[ancient information on a gcc+tkinter bug on alpha was here] +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 16:46:23 2002 by +Erno Kuusela +

+ +


+

3.21. Several common system calls are missing from the posix module.

+Most likely, all test compilations run by the configure script +are failing for some reason or another. Have a look in config.log to +see what could be the reason. A common reason is specifying a +directory to the --with-readline option that doesn't contain the +libreadline.a file. +

+ +Edit this entry / +Log info +

+ +


+

3.22. ImportError: No module named string, on MS Windows.

+Most likely, your PYTHONPATH environment variable should be set to +something like: +

+set PYTHONPATH=c:\python;c:\python\lib;c:\python\scripts +

+(assuming Python was installed in c:\python) +

+ +Edit this entry / +Log info +

+ +


+

3.23. Core dump on SGI when using the gl module.

+There are conflicts between entry points in the termcap and curses +libraries and an entry point in the GL library. There's a hack of a +fix for the termcap library if it's needed for the GNU readline +library, but it doesn't work when you're using curses. Concluding, +you can't build a Python binary containing both the curses and gl +modules. +

+ +Edit this entry / +Log info +

+ +


+

3.24. "Initializer not a constant" while building DLL on MS-Windows

+Static type object initializers in extension modules may cause compiles to +fail with an error message like "initializer not a constant". +Fredrik Lundh <Fredrik.Lundh@image.combitech.se> explains: +

+This shows up when building DLL under MSVC. There's two ways to +address this: either compile the module as C++, or change your code to +something like: +

+

+  statichere PyTypeObject bstreamtype = {
+      PyObject_HEAD_INIT(NULL) /* must be set by init function */
+      0,
+      "bstream",
+      sizeof(bstreamobject),
+
+
+  ...
+
+
+  void
+  initbstream()
+  {
+      /* Patch object type */
+      bstreamtype.ob_type = &PyType_Type;
+      Py_InitModule("bstream", functions);
+      ...
+  }
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 14:58:05 1997 by +Aaron Watters +

+ +


+

3.25. Output directed to a pipe or file disappears on Linux.

+Some people have reported that when they run their script +interactively, it runs great, but that when they redirect it +to a pipe or file, no output appears. +

+

+    % python script.py
+    ...some output...
+    % python script.py >file
+    % cat file
+    % # no output
+    % python script.py | cat
+    % # no output
+    %
+
+This was a bug in Linux kernel. It is fixed and should not appear anymore. So most Linux users are not affected by this. +

+If redirection doesn't work on your Linux system, check what shell you are using. Shells like (t)csh doesn't support redirection. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 16 13:38:30 2003 by +Jens Kubieziel +

+ +


+

3.26. [deleted]

+[ancient libc/linux problem was here] +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 16:48:08 2002 by +Erno Kuusela +

+ +


+

3.27. [deleted]

+[ancient linux + threads + tk problem was described here] +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 16:49:08 2002 by +Erno Kuusela +

+ +


+

3.28. How can I test if Tkinter is working?

+Try the following: +

+

+  python
+  >>> import _tkinter
+  >>> import Tkinter
+  >>> Tkinter._test()
+
+This should pop up a window with two buttons, +one "Click me" and one "Quit". +

+If the first statement (import _tkinter) fails, your Python +installation probably has not been configured to support Tcl/Tk. +On Unix, if you have installed Tcl/Tk, you have to rebuild Python +after editing the Modules/Setup file to enable the _tkinter module +and the TKPATH environment variable. +

+It is also possible to get complaints about Tcl/Tk version +number mismatches or missing TCL_LIBRARY or TK_LIBRARY +environment variables. These have to do with Tcl/Tk installation +problems. +

+A common problem is to have installed versions of tcl.h and tk.h +that don't match the installed version of the Tcl/Tk libraries; +this usually results in linker errors or (when using dynamic +loading) complaints about missing symbols during loading +the shared library. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 28 17:01:46 1997 by +Guido van Rossum +

+ +


+

3.29. Is there a way to get the interactive mode of the python interpreter to perform function/variable name completion?

+(From a posting by Guido van Rossum) +

+On Unix, if you have enabled the readline module (i.e. if Emacs-style +command line editing and bash-style history works for you), you can +add this by importing the undocumented standard library module +"rlcompleter". When completing a simple identifier, it +completes keywords, built-ins and globals in __main__; when completing +NAME.NAME..., it evaluates (!) the expression up to the last dot and +completes its attributes. +

+This way, you can do "import string", type "string.", hit the +completion key twice, and see the list of names defined by the +string module. +

+Tip: to use the tab key as the completion key, call +

+

+    readline.parse_and_bind("tab: complete")
+
+You can put this in a ~/.pythonrc file, and set the PYTHONSTARTUP +environment variable to ~/.pythonrc. This will cause the completion to be enabled +whenever you run Python interactively. +

+Notes (see the docstring for rlcompleter.py for more information): +

+* The evaluation of the NAME.NAME... form may cause arbitrary +application defined code to be executed if an object with a +__getattr__ hook is found. Since it is the responsibility of the +application (or the user) to enable this feature, I consider this an +acceptable risk. More complicated expressions (e.g. function calls or +indexing operations) are not evaluated. +

+* GNU readline is also used by the built-in functions input() and +raw_input(), and thus these also benefit/suffer from the complete +features. Clearly an interactive application can benefit by +specifying its own completer function and using raw_input() for all +its input. +

+* When stdin is not a tty device, GNU readline is never +used, and this module (and the readline module) are silently inactive. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:55:24 1998 by +A.M. Kuchling +

+ +


+

3.30. Why is the Python interpreter not built as a shared library?

+(This is a Unix question; on Mac and Windows, it is a shared +library.) +

+It's just a nightmare to get this to work on all different platforms. +Shared library portability is a pain. And yes, I know about GNU libtool +-- but it requires me to use its conventions for filenames etc, and it +would require a complete and utter rewrite of all the makefile and +config tools I'm currently using. +

+In practice, few applications embed Python -- it's much more common to +have Python extensions, which already are shared libraries. Also, +serious embedders often want total control over which Python version +and configuration they use so they wouldn't want to use a standard +shared library anyway. So while the motivation of saving space +when lots of apps embed Python is nice in theory, I +doubt that it will save much in practice. (Hence the low priority I +give to making a shared library.) +

+For Linux systems, the simplest method of producing libpython1.5.so seems to +be (originally from the Minotaur project web page, +http://www.equi4.com/minotaur/minotaur.html): +

+

+  make distclean 
+  ./configure 
+  make OPT="-fpic -O2" 
+  mkdir .extract 
+  (cd .extract; ar xv ../libpython1.5.a) 
+  gcc -shared -o libpython1.5.so .extract/*.o 
+  rm -rf .extract
+
+In Python 2.3 this will be supported by the standard build routine +(at least on Linux) with --enable-shared. Note however that there +is little advantage, and it slows down Python because of the need +for PIC code and the extra cost at startup time to find the library. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 30 13:36:55 2002 by +GvR +

+ +


+

3.31. Build with GCC on Solaris 2.6 (SunOS 5.6) fails

+If you have upgraded Solaris 2.5 or 2.5.1 to Solaris 2.6, +but you have not upgraded +your GCC installation, the compile may fail, e.g. like this: +

+

+ In file included from /usr/include/sys/stream.h:26,
+                  from /usr/include/netinet/in.h:38,
+                  from /usr/include/netdb.h:96,
+                  from ./socketmodule.c:121:
+ /usr/include/sys/model.h:32: #error "No DATAMODEL_NATIVE specified"
+
+Solution: rebuild GCC for Solaris 2.6. +You might be able to simply re-run fixincludes, but +people have had mixed success with doing that. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 21 11:18:46 1998 by +GvR +

+ +


+

3.32. Running "make clean" seems to leave problematic files that cause subsequent builds to fail.

+Use "make clobber" instead. +

+Use "make clean" to reduce the size of the source/build directory +after you're happy with your build and installation. +If you have already tried to build python and you'd like to start +over, you should use "make clobber". It does a "make clean" and also +removes files such as the partially built Python library from a previous build. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 24 20:39:26 1999 by +TAB +

+ +


+

3.33. Submitting bug reports and patches

+To report a bug or submit a patch, please use the relevant service +from the Python project at SourceForge. +

+Bugs: http://sourceforge.net/tracker/?group_id=5470&atid=105470 +

+Patches: http://sourceforge.net/tracker/?group_id=5470&atid=305470 +

+If you have a SourceForge account, please log in before submitting your bug report; this will make it easier for us to contact you regarding your report in the event we have follow-up questions. It will also enable SourceForge to send you update information as we act on your bug. If you do not have a SourceForge account, please consider leaving your name and email address as part of the report. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:58:26 2001 by +Fred Drake +

+ +


+

3.34. I can't load shared libraries under Python 1.5.2, Solaris 7, and gcc 2.95.2

+When trying to load shared libraries, you may see errors like: +ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/lib/python1.5/site-packages/Perp/util/du_SweepUtilc.so: +
+ symbol PyExc_RuntimeError: referenced symbol not found
+
+

+There is a problem with the configure script for Python 1.5.2 +under Solaris 7 with gcc 2.95 . configure should set the make variable +LINKFORSHARED=-Xlinker -export-dynamic +

+

+in Modules/Makefile, +

+Manually add this line to the Modules/Makefile. +This builds a Python executable that can load shared library extensions (xxx.so) . +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 19 10:37:05 2001 by +GvR +

+ +


+

3.35. In the regression test, test___all__ fails for the profile module. What's wrong?

+If you have been using the profile module, and have properly calibrated a copy of the module as described in the documentation for the profiler: +

+http://www.python.org/doc/current/lib/profile-calibration.html +

+then it is possible that the regression test "test___all__" will fail if you run the regression test manually rather than using "make test" in the Python source directory. This will happen if you have set your PYTHONPATH environment variable to include the directory containing your calibrated profile module. You have probably calibrated the profiler using an older version of the profile module which does not define the __all__ value, added to the module as of Python 2.1. +

+The problem can be fixed by removing the old calibrated version of the profile module and using the latest version to do a fresh calibration. In general, you will need to re-calibrate for each version of Python anyway, since the performance characteristics can change in subtle ways that impact profiling. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 27 10:44:10 2001 by +Fred Drake +

+ +


+

3.36. relocations remain against allocatable but non-writable sections

+This linker error occurs on Solaris if you attempt to build an extension module which incorporates position-dependent (non-PIC) code. A common source of problems is that a static library (.a file), such as libreadline.a or libcrypto.a is linked with the extension module. The error specifically occurs when using gcc as the compiler, but /usr/ccs/bin/ld as the linker. +

+The following solutions and work-arounds are known: +

+1. Rebuild the libraries (libreadline, libcrypto) with -fPIC (-KPIC if using the system compiler). This is recommended; all object files in a shared library should be position-independent. +

+2. Statically link the extension module and its libraries into the Python interpreter, by editing Modules/Setup. +

+3. Use GNU ld instead of /usr/ccs/bin/ld; GNU ld will accept non-PIC code in shared libraries (and mark the section writable) +

+4. Pass -mimpure-text to GCC when linking the module. This will force gcc to not pass -z text to ld; in turn, ld will make all text sections writable. +

+Options 3 and 4 are not recommended, since the ability to share code across processes is lost. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 29 12:05:11 2002 by +Martin v. Löwis +

+ +


+

4. Programming in Python

+ +
+

4.1. Is there a source code level debugger with breakpoints, step, etc.?

+Yes. +

+Module pdb is a rudimentary but adequate console-mode debugger for Python. It is part of the standard Python library, and is documented in the Library Reference Manual. (You can also write your own debugger by using the code for pdb as an example.) +

+The IDLE interactive development environment, which is part of the standard Python distribution (normally available in Tools/idle), includes a graphical debugger. There is documentation for the IDLE debugger at http://www.python.org/idle/doc/idle2.html#Debugger +

+Pythonwin is a Python IDE that includes a GUI debugger based on bdb. The Pythonwin debugger colors breakpoints and has quite a few cool features (including debugging non-Pythonwin programs). A reference can be found at http://www.python.org/ftp/python/pythonwin/pwindex.html +More recent versions of PythonWin are available as a part of the ActivePython distribution (see http://www.activestate.com/Products/ActivePython/index.html). +

+Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at http://packages.debian.org/unstable/devel/pydb.html +and DDD can be found at http://www.gnu.org/software/ddd/ +

+There are a number of commmercial Python IDEs that include graphical debuggers. They include: +

+

+ * Wing IDE (http://wingide.com/) 
+ * Komodo IDE (http://www.activestate.com/Products/Komodo/)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 28 01:43:41 2003 by +Stephen Ferg +

+ +


+

4.2. Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)? (Also phrased as: Can I use a built-in type as base class?)

+In Python 2.2, you can inherit from builtin classes such as int, list, dict, etc. +

+In previous versions of Python, you can easily create a Python class which serves as a wrapper around a built-in object, e.g. (for dictionaries): +

+

+        # A user-defined class behaving almost identical
+        # to a built-in dictionary.
+        class UserDict:
+                def __init__(self): self.data = {}
+                def __repr__(self): return repr(self.data)
+                def __cmp__(self, dict):
+                        if type(dict) == type(self.data):
+                                return cmp(self.data, dict)
+                        else:
+                                return cmp(self.data, dict.data)
+                def __len__(self): return len(self.data)
+                def __getitem__(self, key): return self.data[key]
+                def __setitem__(self, key, item): self.data[key] = item
+                def __delitem__(self, key): del self.data[key]
+                def keys(self): return self.data.keys()
+                def items(self): return self.data.items()
+                def values(self): return self.data.values()
+                def has_key(self, key): return self.data.has_key(key)
+
+A2. See Jim Fulton's ExtensionClass for an example of a mechanism +which allows you to have superclasses which you can inherit from in +Python -- that way you can have some methods from a C superclass (call +it a mixin) and some methods from either a Python superclass or your +subclass. ExtensionClass is distributed as a part of Zope (see +http://www.zope.org), but will be phased out with Zope 3, since +Zope 3 uses Python 2.2 or later which supports direct inheritance +from built-in types. Here's a link to the original paper about +ExtensionClass: +http://debian.acm.ndsu.nodak.edu/doc/python-extclass/ExtensionClass.html +

+A3. The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html) +provides a way of doing this from C++ (i.e. you can inherit from an +extension class written in C++ using the BPL). +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 28 21:09:52 2002 by +GvR +

+ +


+

4.3. Is there a curses/termcap package for Python?

+The standard Python source distribution comes with a curses module in +the Modules/ subdirectory, though it's not compiled by default (note +that this is not available in the Windows distribution -- there is +no curses module for Windows). +

+In Python versions before 2.0 the module only supported plain curses; +you couldn't use ncurses features like colors with it (though it would +link with ncurses). +

+In Python 2.0, the curses module has been greatly extended, starting +from Oliver Andrich's enhanced version, to provide many additional +functions from ncurses and SYSV curses, such as colour, alternative +character set support, pads, and mouse support. This means the +module is no longer compatible with operating systems that only +have BSD curses, but there don't seem to be any currently +maintained OSes that fall into this category. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 23 20:24:06 2002 by +Tim Peters +

+ +


+

4.4. Is there an equivalent to C's onexit() in Python?

+For Python 2.0: The new atexit module provides a register function that +is similar to C's onexit. See the Library Reference for details. For +2.0 you should not assign to sys.exitfunc! +

+For Python 1.5.2: You need to import sys and assign a function to +sys.exitfunc, it will be called when your program exits, is +killed by an unhandled exception, or (on UNIX) receives a +SIGHUP or SIGTERM signal. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:14:55 2000 by +Bjorn Pettersen +

+ +


+

4.5. [deleted]

+[python used to lack nested scopes, it was explained here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:18:22 2002 by +Erno Kuusela +

+ +


+

4.6. How do I iterate over a sequence in reverse order?

+If it is a list, the fastest solution is +

+

+        list.reverse()
+        try:
+                for x in list:
+                        "do something with x"
+        finally:
+                list.reverse()
+
+This has the disadvantage that while you are in the loop, the list +is temporarily reversed. If you don't like this, you can make a copy. +This appears expensive but is actually faster than other solutions: +

+

+        rev = list[:]
+        rev.reverse()
+        for x in rev:
+                <do something with x>
+
+If it's not a list, a more general but slower solution is: +

+

+        for i in range(len(sequence)-1, -1, -1):
+                x = sequence[i]
+                <do something with x>
+
+A more elegant solution, is to define a class which acts as a sequence +and yields the elements in reverse order (solution due to Steve +Majewski): +

+

+        class Rev:
+                def __init__(self, seq):
+                        self.forw = seq
+                def __len__(self):
+                        return len(self.forw)
+                def __getitem__(self, i):
+                        return self.forw[-(i + 1)]
+
+You can now simply write: +

+

+        for x in Rev(list):
+                <do something with x>
+
+Unfortunately, this solution is slowest of all, due to the method +call overhead... +

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 21:10:50 1997 by +GvR +

+ +


+

4.7. My program is too slow. How do I speed it up?

+That's a tough one, in general. There are many tricks to speed up +Python code; I would consider rewriting parts in C only as a last +resort. One thing to notice is that function and (especially) method +calls are rather expensive; if you have designed a purely OO interface +with lots of tiny functions that don't do much more than get or set an +instance variable or call another method, you may consider using a +more direct way, e.g. directly accessing instance variables. Also see +the standard module "profile" (described in the Library Reference +manual) which makes it possible to find out where +your program is spending most of its time (if you have some patience +-- the profiling itself can slow your program down by an order of +magnitude). +

+Remember that many standard optimization heuristics you +may know from other programming experience may well apply +to Python. For example it may be faster to send output to output +devices using larger writes rather than smaller ones in order to +avoid the overhead of kernel system calls. Thus CGI scripts +that write all output in "one shot" may be notably faster than +those that write lots of small pieces of output. +

+Also, be sure to use "aggregate" operations where appropriate. +For example the "slicing" feature allows programs to chop up +lists and other sequence objects in a single tick of the interpreter +mainloop using highly optimized C implementations. Thus to +get the same effect as +

+

+  L2 = []
+  for i in range[3]:
+       L2.append(L1[i])
+
+it is much shorter and far faster to use +

+

+  L2 = list(L1[:3]) # "list" is redundant if L1 is a list.
+
+Note that the map() function, particularly used with +builtin methods or builtin functions can be a convenient +accelerator. For example to pair the elements of two +lists together: +

+

+  >>> map(None, [1,2,3], [4,5,6])
+  [(1, 4), (2, 5), (3, 6)]
+
+or to compute a number of sines: +

+

+  >>> map( math.sin, (1,2,3,4))
+  [0.841470984808, 0.909297426826, 0.14112000806,   -0.756802495308]
+
+The map operation completes very quickly in such cases. +

+Other examples of aggregate operations include the join and split +methods of string objects. For example if s1..s7 are large (10K+) strings then +"".join([s1,s2,s3,s4,s5,s6,s7]) may be far faster than +the more obvious s1+s2+s3+s4+s5+s6+s7, since the "summation" +will compute many subexpressions, whereas join does all +copying in one pass. For manipulating strings also consider the +regular expression libraries and the "substitution" operations +String % tuple and String % dictionary. Also be sure to use +the list.sort builtin method to do sorting, and see FAQ's 4.51 +and 4.59 for examples of moderately advanced usage -- list.sort beats +other techniques for sorting in all but the most extreme +circumstances. +

+There are many other aggregate operations +available in the standard libraries and in contributed libraries +and extensions. +

+Another common trick is to "push loops into functions or methods." +For example suppose you have a program that runs slowly and you +use the profiler (profile.run) to determine that a Python function ff +is being called lots of times. If you notice that ff +

+

+   def ff(x):
+       ...do something with x computing result...
+       return result
+
+tends to be called in loops like (A) +

+

+   list = map(ff, oldlist)
+
+or (B) +

+

+   for x in sequence:
+       value = ff(x)
+       ...do something with value...
+
+then you can often eliminate function call overhead by rewriting +ff to +

+

+   def ffseq(seq):
+       resultseq = []
+       for x in seq:
+           ...do something with x computing result...
+           resultseq.append(result)
+       return resultseq
+
+and rewrite (A) to +

+

+    list = ffseq(oldlist)
+
+and (B) to +

+

+    for value in ffseq(sequence):
+        ...do something with value...
+
+Other single calls ff(x) translate to ffseq([x])[0] with little +penalty. Of course this technique is not always appropriate +and there are other variants, which you can figure out. +

+You can gain some performance by explicitly storing the results of +a function or method lookup into a local variable. A loop like +

+

+    for key in token:
+        dict[key] = dict.get(key, 0) + 1
+
+resolves dict.get every iteration. If the method isn't going to +change, a faster implementation is +

+

+    dict_get = dict.get  # look up the method once
+    for key in token:
+        dict[key] = dict_get(key, 0) + 1
+
+Default arguments can be used to determine values once, at +compile time instead of at run time. This can only be done for +functions or objects which will not be changed during program +execution, such as replacing +

+

+    def degree_sin(deg):
+        return math.sin(deg * math.pi / 180.0)
+
+with +

+

+    def degree_sin(deg, factor = math.pi/180.0, sin = math.sin):
+        return sin(deg * factor)
+
+Because this trick uses default arguments for terms which should +not be changed, it should only be used when you are not concerned +with presenting a possibly confusing API to your users. +

+

+For an anecdote related to optimization, see +

+

+	http://www.python.org/doc/essays/list2str.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:03:54 2002 by +Neal Norwitz +

+ +


+

4.8. When I have imported a module, then edit it, and import it again (into the same Python process), the changes don't seem to take place. What is going on?

+For reasons of efficiency as well as consistency, Python only reads +the module file on the first time a module is imported. (Otherwise a +program consisting of many modules, each of which imports the same +basic module, would read the basic module over and over again.) To +force rereading of a changed module, do this: +

+

+        import modname
+        reload(modname)
+
+Warning: this technique is not 100% fool-proof. In particular, +modules containing statements like +

+

+        from modname import some_objects
+
+will continue to work with the old version of the imported objects. +

+ +Edit this entry / +Log info +

+ +


+

4.9. How do I find the current module name?

+A module can find out its own module name by looking at the +(predefined) global variable __name__. If this has the value +'__main__' you are running as a script. +

+ +Edit this entry / +Log info +

+ +


+

4.10. I have a module in which I want to execute some extra code when it is run as a script. How do I find out whether I am running as a script?

+See the previous question. E.g. if you put the following on the +last line of your module, main() is called only when your module is +running as a script: +

+

+        if __name__ == '__main__': main()
+
+

+ +Edit this entry / +Log info +

+ +


+

4.11. I try to run a program from the Demo directory but it fails with ImportError: No module named ...; what gives?

+This is probably an optional module (written in C!) which hasn't +been configured on your system. This especially happens with modules +like "Tkinter", "stdwin", "gl", "Xt" or "Xm". For Tkinter, STDWIN and +many other modules, see Modules/Setup.in for info on how to add these +modules to your Python, if it is possible at all. Sometimes you will +have to ftp and build another package first (e.g. Tcl and Tk for Tkinter). +Sometimes the module only works on specific platforms (e.g. gl only works +on SGI machines). +

+NOTE: if the complaint is about "Tkinter" (upper case T) and you have +already configured module "tkinter" (lower case t), the solution is +not to rename tkinter to Tkinter or vice versa. There is probably +something wrong with your module search path. Check out the value of +sys.path. +

+For X-related modules (Xt and Xm) you will have to do more work: they +are currently not part of the standard Python distribution. You will +have to ftp the Extensions tar file, i.e. +ftp://ftp.python.org/pub/python/src/X-extension.tar.gz and follow +the instructions there. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 12 21:31:08 2003 by +Jens Kubieziel +

+ +


+

4.12. [deleted]

+[stdwin (long dead windowing library) entry deleted] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 08:30:13 2002 by +Erno Kuusela +

+ +


+

4.13. What GUI toolkits exist for Python?

+Depending on what platform(s) you are aiming at, there are several. +

+Currently supported solutions: +

+Cross-platform: +

+Tk: +

+There's a neat object-oriented interface to the Tcl/Tk widget set, +called Tkinter. It is part of the standard Python distribution and +well-supported -- all you need to do is build and install Tcl/Tk and +enable the _tkinter module and the TKPATH definition in Modules/Setup +when building Python. This is probably the easiest to install and +use, and the most complete widget set. It is also very likely that in +the future the standard Python GUI API will be based on or at least +look very much like the Tkinter interface. For more info about Tk, +including pointers to the source, see the Tcl/Tk home page at +http://www.scriptics.com. Tcl/Tk is now fully +portable to the Mac and Windows platforms (NT and 95 only); you need +Python 1.4beta3 or later and Tk 4.1patch1 or later. +

+wxWindows: +

+There's an interface to wxWindows called wxPython. wxWindows is a +portable GUI class library written in C++. It supports GTK, Motif, +MS-Windows and Mac as targets. Ports to other platforms are being +contemplated or have already had some work done on them. wxWindows +preserves the look and feel of the underlying graphics toolkit, and +there is quite a rich widget set and collection of GDI classes. +See the wxWindows page at http://www.wxwindows.org/ for more details. +wxPython is a python extension module that wraps many of the wxWindows +C++ classes, and is quickly gaining popularity amongst Python +developers. You can get wxPython as part of the source or CVS +distribution of wxWindows, or directly from its home page at +http://alldunn.com/wxPython/. +

+Gtk+: +

+PyGtk bindings for the Gtk+ Toolkit by James Henstridge exist; see ftp://ftp.daa.com.au/pub/james/python/. Note that there are two incompatible bindings. If you are using Gtk+ 1.2.x you should get the 0.6.x PyGtk bindings from +

+

+    ftp://ftp.gtk.org/pub/python/v1.2
+
+If you plan to use Gtk+ 2.0 with Python (highly recommended if you are just starting with Gtk), get the most recent distribution from +

+

+    ftp://ftp.gtk.org/pub/python/v2.0
+
+If you are adventurous, you can also check out the source from the Gnome CVS repository. Set your CVS directory to :pserver:anonymous@anoncvs.gnome.org:/cvs/gnome and check the gnome-python module out from the repository. +

+Other: +

+There are also bindings available for the Qt toolkit (PyQt), and for KDE (PyKDE); see http://www.thekompany.com/projects/pykde/. +

+For OpenGL bindings, see http://starship.python.net/~da/PyOpenGL. +

+Platform specific: +

+The Mac port has a rich and ever-growing set of modules that support +the native Mac toolbox calls. See the documentation that comes with +the Mac port. See ftp://ftp.python.org/pub/python/mac. Support +by Jack Jansen jack@cwi.nl. +

+Pythonwin by Mark Hammond (MHammond@skippinet.com.au) +includes an interface to the Microsoft Foundation +Classes and a Python programming environment using it that's written +mostly in Python. See http://www.python.org/windows/. +

+There's an object-oriented GUI based on the Microsoft Foundation +Classes model called WPY, supported by Jim Ahlstrom jim@interet.com. +Programs written in WPY run unchanged and with native look and feel on +Windows NT/95, Windows 3.1 (using win32s), and on Unix (using Tk). +Source and binaries for Windows and Linux are available in +ftp://ftp.python.org/pub/python/wpy/. +

+Obsolete or minority solutions: +

+There's an interface to X11, including the Athena and Motif widget +sets (and a few individual widgets, like Mosaic's HTML widget and +SGI's GL widget) available from +ftp://ftp.python.org/pub/python/src/X-extension.tar.gz. +Support by Sjoerd Mullender sjoerd@cwi.nl. +

+On top of the X11 interface there's the vpApp +toolkit by Per Spilling, now also maintained by Sjoerd Mullender +sjoerd@cwi.nl. See ftp://ftp.cwi.nl/pub/sjoerd/vpApp.tar.gz. +

+For SGI IRIX only, there are unsupported interfaces to the complete +GL (Graphics Library -- low level but very good 3D capabilities) as +well as to FORMS (a buttons-and-sliders-etc package built on top of GL +by Mark Overmars -- ftp'able from +ftp://ftp.cs.ruu.nl/pub/SGI/FORMS/). This is probably also +becoming obsolete, as OpenGL takes over (see above). +

+There's an interface to STDWIN, a platform-independent low-level +windowing interface for Mac and X11. This is totally unsupported and +rapidly becoming obsolete. The STDWIN sources are at +ftp://ftp.cwi.nl/pub/stdwin/. +

+There is an interface to WAFE, a Tcl interface to the X11 +Motif and Athena widget sets. WAFE is at +http://www.wu-wien.ac.at/wafe/wafe.html. +

+ +Edit this entry / +Log info + +/ Last changed on Mon May 13 21:40:39 2002 by +Skip Montanaro +

+ +


+

4.14. Are there any interfaces to database packages in Python?

+Yes! See the Database Topic Guide at +http://www.python.org/topics/database/ for details. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 4 20:12:19 2000 by +Barney Warplug +

+ +


+

4.15. Is it possible to write obfuscated one-liners in Python?

+Yes. See the following three examples, due to Ulf Bartelt: +

+

+        # Primes < 1000
+        print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
+        map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))
+
+
+        # First 10 Fibonacci numbers
+        print map(lambda x,f=lambda x,f:(x<=1) or (f(x-1,f)+f(x-2,f)): f(x,f),
+        range(10))
+
+
+        # Mandelbrot set
+        print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
+        Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
+        Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
+        i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
+        >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
+        64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
+        ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
+        #    \___ ___/  \___ ___/  |   |   |__ lines on screen
+        #        V          V      |   |______ columns on screen
+        #        |          |      |__________ maximum of "iterations"
+        #        |          |_________________ range on y axis
+        #        |____________________________ range on x axis
+
+Don't try this at home, kids! +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 15:48:33 1997 by +GvR +

+ +


+

4.16. Is there an equivalent of C's "?:" ternary operator?

+Not directly. In many cases you can mimic a?b:c with "a and b or +c", but there's a flaw: if b is zero (or empty, or None -- anything +that tests false) then c will be selected instead. In many cases you +can prove by looking at the code that this can't happen (e.g. because +b is a constant or has a type that can never be false), but in general +this can be a problem. +

+Tim Peters (who wishes it was Steve Majewski) suggested the following +solution: (a and [b] or [c])[0]. Because [b] is a singleton list it +is never false, so the wrong path is never taken; then applying [0] to +the whole thing gets the b or c that you really wanted. Ugly, but it +gets you there in the rare cases where it is really inconvenient to +rewrite your code using 'if'. +

+As a last resort it is possible to implement the "?:" operator as a function: +

+

+    def q(cond,on_true,on_false):
+        from inspect import isfunction
+
+
+        if cond:
+            if not isfunction(on_true): return on_true
+            else: return apply(on_true)
+        else:
+            if not isfunction(on_false): return on_false 
+            else: return apply(on_false)
+
+In most cases you'll pass b and c directly: q(a,b,c). To avoid evaluating b +or c when they shouldn't be, encapsulate them +within a lambda function, e.g.: q(a,lambda: b, lambda: c). +

+

+

+It has been asked why Python has no if-then-else expression, +since most language have one; it is a frequently requested feature. +

+There are several possible answers: just as many languages do +just fine without one; it can easily lead to less readable code; +no sufficiently "Pythonic" syntax has been discovered; a search +of the standard library found remarkably few places where using an +if-then-else expression would make the code more understandable. +

+Nevertheless, in an effort to decide once and for all whether +an if-then-else expression should be added to the language, +PEP 308 (http://www.python.org/peps/pep-0308.html) has been +put forward, proposing a specific syntax. The community can +now vote on this issue. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 19:41:13 2003 by +David Goodger +

+ +


+

4.17. My class defines __del__ but it is not called when I delete the object.

+There are several possible reasons for this. +

+The del statement does not necessarily call __del__ -- it simply +decrements the object's reference count, and if this reaches zero +__del__ is called. +

+If your data structures contain circular links (e.g. a tree where +each child has a parent pointer and each parent has a list of +children) the reference counts will never go back to zero. You'll +have to define an explicit close() method which removes those +pointers. Please don't ever call __del__ directly -- __del__ should +call close() and close() should make sure that it can be called more +than once for the same object. +

+If the object has ever been a local variable (or argument, which is +really the same thing) to a function that caught an expression in an +except clause, chances are that a reference to the object still exists +in that function's stack frame as contained in the stack trace. +Normally, deleting (better: assigning None to) sys.exc_traceback will +take care of this. If a stack was printed for an unhandled +exception in an interactive interpreter, delete sys.last_traceback +instead. +

+There is code that deletes all objects when the interpreter exits, +but it is not called if your Python has been configured to support +threads (because other threads may still be active). You can define +your own cleanup function using sys.exitfunc (see question 4.4). +

+Finally, if your __del__ method raises an exception, a warning message is printed to sys.stderr. +

+

+Starting with Python 2.0, a garbage collector periodically reclaims the space used by most cycles with no external references. (See the "gc" module documentation for details.) There are, however, pathological cases where it can be expected to fail. Moreover, the garbage collector runs some time after the last reference to your data structure vanishes, so your __del__ method may be called at an inconvenient and random time. This is inconvenient if you're trying to reproduce a problem. Worse, the order in which object's __del__ methods are executed is arbitrary. +

+Another way to avoid cyclical references is to use the "weakref" module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling pointers (if they need them!). +

+Question 6.14 is intended to explain the new garbage collection algorithm. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 10 15:27:28 2002 by +Matthias Urlichs +

+ +


+

4.18. How do I change the shell environment for programs called using os.popen() or os.system()? Changing os.environ doesn't work.

+You must be using either a version of python before 1.4, or on a +(rare) system that doesn't have the putenv() library function. +

+Before Python 1.4, modifying the environment passed to subshells was +left out of the interpreter because there seemed to be no +well-established portable way to do it (in particular, some systems, +have putenv(), others have setenv(), and some have none at all). As +of Python 1.4, almost all Unix systems do have putenv(), and so does +the Win32 API, and thus the os module was modified so that changes to +os.environ are trapped and the corresponding putenv() call is made. +

+ +Edit this entry / +Log info +

+ +


+

4.19. What is a class?

+A class is the particular object type created by executing +a class statement. Class objects are used as templates, to create +instance objects, which embody both the data structure +(attributes) and program routines (methods) specific to a datatype. +

+A class can be based on one or more other classes, called its base +class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined +by inheritance. +

+The term "classic class" is used to refer to the original +class implementation in Python. One problem with classic +classes is their inability to use the built-in data types +(such as list and dictionary) as base classes. Starting +with Python 2.2 an attempt is in progress to unify user-defined +classes and built-in types. It is now possible to declare classes +that inherit from built-in types. +

+ +Edit this entry / +Log info + +/ Last changed on Mon May 27 01:31:21 2002 by +Steve Holden +

+ +


+

4.20. What is a method?

+A method is a function that you normally call as +x.name(arguments...) for some object x. The term is used for methods +of classes and class instances as well as for methods of built-in +objects. (The latter have a completely different implementation and +only share the way their calls look in Python code.) Methods of +classes (and class instances) are defined as functions inside the +class definition. +

+ +Edit this entry / +Log info +

+ +


+

4.21. What is self?

+Self is merely a conventional name for the first argument of a +method -- i.e. a function defined inside a class definition. A method +defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for +some instance x of the class in which the definition occurs; +the called method will think it is called as meth(x, a, b, c). +

+ +Edit this entry / +Log info +

+ +


+

4.22. What is an unbound method?

+An unbound method is a method defined in a class that is not yet +bound to an instance. You get an unbound method if you ask for a +class attribute that happens to be a function. You get a bound method +if you ask for an instance attribute. A bound method knows which +instance it belongs to and calling it supplies the instance automatically; +an unbound method only knows which class it wants for its first +argument (a derived class is also OK). Calling an unbound method +doesn't "magically" derive the first argument from the context -- you +have to provide it explicitly. +

+Trivia note regarding bound methods: each reference to a bound +method of a particular object creates a bound method object. If you +have two such references (a = inst.meth; b = inst.meth), they will +compare equal (a == b) but are not the same (a is not b). +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 6 18:07:25 1998 by +Clarence Gardner +

+ +


+

4.23. How do I call a method defined in a base class from a derived class that overrides it?

+If your class definition starts with "class Derived(Base): ..." +then you can call method meth defined in Base (or one of Base's base +classes) as Base.meth(self, arguments...). Here, Base.meth is an +unbound method (see previous question). +

+ +Edit this entry / +Log info +

+ +


+

4.24. How do I call a method from a base class without using the name of the base class?

+DON'T DO THIS. REALLY. I MEAN IT. It appears that you could call +self.__class__.__bases__[0].meth(self, arguments...) but this fails when +a doubly-derived method is derived from your class: for its instances, +self.__class__.__bases__[0] is your class, not its base class -- so +(assuming you are doing this from within Derived.meth) you would start +a recursive call. +

+Often when you want to do this you are forgetting that classes +are first class in Python. You can "point to" the class you want +to delegate an operation to either at the instance or at the +subclass level. For example if you want to use a "glorp" +operation of a superclass you can point to the right superclass +to use. +

+

+  class subclass(superclass1, superclass2, superclass3):
+      delegate_glorp = superclass2
+      ...
+      def glorp(self, arg1, arg2):
+            ... subclass specific stuff ...
+            self.delegate_glorp.glorp(self, arg1, arg2)
+       ...
+
+
+  class subsubclass(subclass):
+       delegate_glorp = superclass3
+       ...
+
+Note, however that setting delegate_glorp to subclass in +subsubclass would cause an infinite recursion on subclass.delegate_glorp. Careful! Maybe you are getting too fancy for your own good. Consider simplifying the design (?). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jul 28 13:58:22 1997 by +aaron watters +

+ +


+

4.25. How can I organize my code to make it easier to change the base class?

+You could define an alias for the base class, assign the real base +class to it before your class definition, and use the alias throughout +your class. Then all you have to change is the value assigned to the +alias. Incidentally, this trick is also handy if you want to decide +dynamically (e.g. depending on availability of resources) which base +class to use. Example: +

+

+        BaseAlias = <real base class>
+        class Derived(BaseAlias):
+                def meth(self):
+                        BaseAlias.meth(self)
+                        ...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 15:49:57 1997 by +GvR +

+ +


+

4.26. How can I find the methods or attributes of an object?

+This depends on the object type. +

+For an instance x of a user-defined class, instance attributes are +found in the dictionary x.__dict__, and methods and attributes defined +by its class are found in x.__class__.__bases__[i].__dict__ (for i in +range(len(x.__class__.__bases__))). You'll have to walk the tree of +base classes to find all class methods and attributes. +

+Many, but not all built-in types define a list of their method names +in x.__methods__, and if they have data attributes, their names may be +found in x.__members__. However this is only a convention. +

+For more information, read the source of the standard (but +undocumented) module newdir. +

+ +Edit this entry / +Log info +

+ +


+

4.27. I can't seem to use os.read() on a pipe created with os.popen().

+os.read() is a low-level function which takes a file descriptor (a +small integer). os.popen() creates a high-level file object -- the +same type used for sys.std{in,out,err} and returned by the builtin +open() function. Thus, to read n bytes from a pipe p created with +os.popen(), you need to use p.read(n). +

+ +Edit this entry / +Log info +

+ +


+

4.28. How can I create a stand-alone binary from a Python script?

+Even though there are Python compilers being developed, +you probably don't need a real compiler, if all you want +is a stand-alone program. There are three solutions to that. +

+One is to use the freeze tool, which is included in the Python +source tree as Tools/freeze. It converts Python byte +code to C arrays. Using a C compiler, you can embed all +your modules into a new program, which is then linked +with the standard Python modules. +

+It works by scanning your source recursively for import statements +(in both forms) and looking for the modules in the standard Python path +as well as in the source directory (for built-in modules). It then +1 the modules written in Python to C code (array initializers +that can be turned into code objects using the marshal module) and +creates a custom-made config file that only contains those built-in +modules which are actually used in the program. It then compiles the +generated C code and links it with the rest of the Python interpreter +to form a self-contained binary which acts exactly like your script. +

+(Hint: the freeze program only works if your script's filename ends in +".py".) +

+There are several utilities which may be helpful. The first is Gordon McMillan's installer at +

+

+    http://www.mcmillan-inc.com/install1.html
+
+which works on Windows, Linux and at least some forms of Unix. +

+Another is Thomas Heller's py2exe (Windows only) at +

+

+    http://starship.python.net/crew/theller/py2exe/
+
+A third is Christian Tismer's SQFREEZE +(http://starship.python.net/crew/pirx/) which appends the byte code +to a specially-prepared Python interpreter, which +will find the byte code in executable. +

+A fourth is Fredrik Lundh's Squeeze +(http://www.pythonware.com/products/python/squeeze/). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jun 19 14:01:30 2002 by +Gordon McMillan +

+ +


+

4.29. What WWW tools are there for Python?

+See the chapters titled "Internet Protocols and Support" and +"Internet Data Handling" in the Library Reference +Manual. Python is full of good things which will help you build server-side and client-side web systems. +

+A summary of available frameworks is maintained by Paul Boddie at +

+

+    http://thor.prohosting.com/~pboddie/Python/web_modules.html
+
+Cameron Laird maintains a useful set of pages about Python web technologies at +

+

+   http://starbase.neosoft.com/~claird/comp.lang.python/web_python.html/
+
+There was a web browser written in Python, called Grail -- +see http://sourceforge.net/project/grail/. This project has been terminated; http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/grail/grail/README gives more details. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Nov 11 22:48:25 2002 by +GvR +

+ +


+

4.30. How do I run a subprocess with pipes connected to both input and output?

+Use the standard popen2 module. For example: +

+

+	import popen2
+	fromchild, tochild = popen2.popen2("command")
+	tochild.write("input\n")
+	tochild.flush()
+	output = fromchild.readline()
+
+Warning: in general, it is unwise to +do this, because you can easily cause a deadlock where your +process is blocked waiting for output from the child, while the child +is blocked waiting for input from you. This can be caused +because the parent expects the child to output more text than it does, +or it can be caused by data being stuck in stdio buffers due to lack +of flushing. The Python parent can of course explicitly flush the data +it sends to the child before it reads any output, but if the child is +a naive C program it can easily have been written to never explicitly +flush its output, even if it is interactive, since flushing is +normally automatic. +

+Note that a deadlock is also possible if you use popen3 to read +stdout and stderr. If one of the two is too large for the internal +buffer (increasing the buffersize does not help) and you read() +the other one first, there is a deadlock, too. +

+Note on a bug in popen2: unless your program calls wait() +or waitpid(), finished child processes are never removed, +and eventually calls to popen2 will fail because of a limit on +the number of child processes. Calling os.waitpid with the +os.WNOHANG option can prevent this; a good place to insert such +a call would be before calling popen2 again. +

+Another way to produce a deadlock: Call a wait() and there is +still more output from the program than what fits into the +internal buffers. +

+In many cases, all you really need is to run some data through a +command and get the result back. Unless the data is infinite in size, +the easiest (and often the most efficient!) way to do this is to write +it to a temporary file and run the command with that temporary file as +input. The standard module tempfile exports a function mktemp() which +generates unique temporary file names. +

+

+ import tempfile
+ import os
+ class Popen3:
+    """
+    This is a deadlock-save version of popen, that returns
+    an object with errorlevel, out (a string) and err (a string).
+    (capturestderr may not work under windows.)
+    Example: print Popen3('grep spam','\n\nhere spam\n\n').out
+    """
+    def __init__(self,command,input=None,capturestderr=None):
+        outfile=tempfile.mktemp()
+        command="( %s ) > %s" % (command,outfile)
+        if input:
+            infile=tempfile.mktemp()
+            open(infile,"w").write(input)
+            command=command+" <"+infile
+        if capturestderr:
+            errfile=tempfile.mktemp()
+            command=command+" 2>"+errfile
+        self.errorlevel=os.system(command) >> 8
+        self.out=open(outfile,"r").read()
+        os.remove(outfile)
+        if input:
+            os.remove(infile)
+        if capturestderr:
+            self.err=open(errfile,"r").read()
+            os.remove(errfile)
+
+Note that many interactive programs (e.g. vi) don't work well with +pipes substituted for standard input and output. You will have to use +pseudo ttys ("ptys") instead of pipes. There is some undocumented +code to use these in the library module pty.py -- I'm afraid you're on +your own here. +

+A different answer is a Python interface to Don Libes' "expect" +library. A Python extension that interfaces to expect is called "expy" +and available from +http://expectpy.sourceforge.net/. +

+A pure Python solution that works like expect is pexpect of Noah Spurrier. +A beta version is available from +http://pexpect.sourceforge.net/ +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 3 16:31:31 2002 by +Tobias Polzin +

+ +


+

4.31. How do I call a function if I have the arguments in a tuple?

+Use the built-in function apply(). For instance, +

+

+    func(1, 2, 3)
+
+is equivalent to +

+

+    args = (1, 2, 3)
+    apply(func, args)
+
+Note that func(args) is not the same -- it calls func() with exactly +one argument, the tuple args, instead of three arguments, the integers +1, 2 and 3. +

+In Python 2.0, you can also use extended call syntax: +

+f(*args) is equivalent to apply(f, args) +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:42:50 2001 by +Moshe Zadka +

+ +


+

4.32. How do I enable font-lock-mode for Python in Emacs?

+If you are using XEmacs 19.14 or later, any XEmacs 20, FSF Emacs 19.34 +or any Emacs 20, font-lock should work automatically for you if you +are using the latest python-mode.el. +

+If you are using an older version of XEmacs or Emacs you will need +to put this in your .emacs file: +

+

+        (defun my-python-mode-hook ()
+          (setq font-lock-keywords python-font-lock-keywords)
+          (font-lock-mode 1))
+        (add-hook 'python-mode-hook 'my-python-mode-hook)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 6 16:18:46 1998 by +Barry Warsaw +

+ +


+

4.33. Is there a scanf() or sscanf() equivalent?

+Not as such. +

+For simple input parsing, the easiest approach is usually to split +the line into whitespace-delimited words using string.split(), and to +convert decimal strings to numeric values using int(), +long() or float(). (Python's int() is 32-bit and its +long() is arbitrary precision.) string.split supports an optional +"sep" parameter which is useful if the line uses something other +than whitespace as a delimiter. +

+For more complicated input parsing, regular expressions (see module re) +are better suited and more powerful than C's sscanf(). +

+There's a contributed module that emulates sscanf(), by Steve Clift; +see contrib/Misc/sscanfmodule.c of the ftp site: +

+

+    http://www.python.org/ftp/python/contrib-09-Dec-1999/Misc/
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:07:51 2002 by +Neal Norwitz +

+ +


+

4.34. Can I have Tk events handled while waiting for I/O?

+Yes, and you don't even need threads! But you'll have to +restructure your I/O code a bit. Tk has the equivalent of Xt's +XtAddInput() call, which allows you to register a callback function +which will be called from the Tk mainloop when I/O is possible on a +file descriptor. Here's what you need: +

+

+        from Tkinter import tkinter
+        tkinter.createfilehandler(file, mask, callback)
+
+The file may be a Python file or socket object (actually, anything +with a fileno() method), or an integer file descriptor. The mask is +one of the constants tkinter.READABLE or tkinter.WRITABLE. The +callback is called as follows: +

+

+        callback(file, mask)
+
+You must unregister the callback when you're done, using +

+

+        tkinter.deletefilehandler(file)
+
+Note: since you don't know *how many bytes* are available for reading, +you can't use the Python file object's read or readline methods, since +these will insist on reading a predefined number of bytes. For +sockets, the recv() or recvfrom() methods will work fine; for other +files, use os.read(file.fileno(), maxbytecount). +

+ +Edit this entry / +Log info +

+ +


+

4.35. How do I write a function with output parameters (call by reference)?

+[Mark Lutz] The thing to remember is that arguments are passed by +assignment in Python. Since assignment just creates references to +objects, there's no alias between an argument name in the caller and +callee, and so no call-by-reference per se. But you can simulate it +in a number of ways: +

+1) By using global variables; but you probably shouldn't :-) +

+2) By passing a mutable (changeable in-place) object: +

+

+      def func1(a):
+          a[0] = 'new-value'     # 'a' references a mutable list
+          a[1] = a[1] + 1        # changes a shared object
+
+
+      args = ['old-value', 99]
+      func1(args)
+      print args[0], args[1]     # output: new-value 100
+
+3) By returning a tuple, holding the final values of arguments: +

+

+      def func2(a, b):
+          a = 'new-value'        # a and b are local names
+          b = b + 1              # assigned to new objects
+          return a, b            # return new values
+
+
+      x, y = 'old-value', 99
+      x, y = func2(x, y)
+      print x, y                 # output: new-value 100
+
+4) And other ideas that fall-out from Python's object model. For instance, it might be clearer to pass in a mutable dictionary: +

+

+      def func3(args):
+          args['a'] = 'new-value'     # args is a mutable dictionary
+          args['b'] = args['b'] + 1   # change it in-place
+
+
+      args = {'a':' old-value', 'b': 99}
+      func3(args)
+      print args['a'], args['b']
+
+5) Or bundle-up values in a class instance: +

+

+      class callByRef:
+          def __init__(self, **args):
+              for (key, value) in args.items():
+                  setattr(self, key, value)
+
+
+      def func4(args):
+          args.a = 'new-value'        # args is a mutable callByRef
+          args.b = args.b + 1         # change object in-place
+
+
+      args = callByRef(a='old-value', b=99)
+      func4(args)
+      print args.a, args.b
+
+
+   But there's probably no good reason to get this complicated :-).
+
+[Python's author favors solution 3 in most cases.] +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 8 23:49:46 1997 by +David Ascher +

+ +


+

4.36. Please explain the rules for local and global variables in Python.

+[Ken Manheimer] In Python, procedure variables are implicitly +global, unless they are assigned anywhere within the block. +In that case +they are implicitly local, and you need to explicitly declare them as +'global'. +

+Though a bit surprising at first, a moment's consideration explains +this. On one hand, requirement of 'global' for assigned vars provides +a bar against unintended side-effects. On the other hand, if global +were required for all global references, you'd be using global all the +time. Eg, you'd have to declare as global every reference to a +builtin function, or to a component of an imported module. This +clutter would defeat the usefulness of the 'global' declaration for +identifying side-effects. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 28 09:53:27 1998 by +GvR +

+ +


+

4.37. How can I have modules that mutually import each other?

+Suppose you have the following modules: +

+foo.py: +

+

+	from bar import bar_var
+	foo_var=1
+
+bar.py: +

+

+	from foo import foo_var
+	bar_var=2
+
+The problem is that the above is processed by the interpreter thus: +

+

+	main imports foo
+	Empty globals for foo are created
+	foo is compiled and starts executing
+	foo imports bar
+	Empty globals for bar are created
+	bar is compiled and starts executing
+	bar imports foo (which is a no-op since there already is a module named foo)
+	bar.foo_var = foo.foo_var
+	...
+
+The last step fails, because Python isn't done with interpreting foo yet and the global symbol dict for foo is still empty. +

+The same thing happens when you use "import foo", and then try to access "foo.one" in global code. +

+

+There are (at least) three possible workarounds for this problem. +

+Guido van Rossum recommends to avoid all uses of "from <module> import ..." (so everything from an imported module is referenced as <module>.<name>) and to place all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. +

+

+Jim Roskind suggests the following order in each module: +

+

+ exports (globals, functions, and classes that don't need imported base classes)
+ import statements
+ active code (including globals that are initialized from imported values).
+
+Python's author doesn't like this approach much because the imports +appear in a strange place, but has to admit that it works. +

+

+

+Matthias Urlichs recommends to restructure your code so that the recursive import is not necessary in the first place. +

+

+These solutions are not mutually exclusive. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 06:52:51 2002 by +Matthias Urlichs +

+ +


+

4.38. How do I copy an object in Python?

+Try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can. +

+Dictionaries have a copy method. Sequences can be copied by slicing: +

+ new_l = l[:]
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:40:26 2002 by +Erno Kuusela +

+ +


+

4.39. How to implement persistent objects in Python? (Persistent == automatically saved to and restored from disk.)

+The library module "pickle" now solves this in a very general way +(though you still can't store things like open files, sockets or +windows), and the library module "shelve" uses pickle and (g)dbm to +create persistent mappings containing arbitrary Python objects. +For possibly better performance also look for the latest version +of the relatively recent cPickle module. +

+A more awkward way of doing things is to use pickle's little sister, +marshal. The marshal module provides very fast ways to store +noncircular basic Python types to files and strings, and back again. +Although marshal does not do fancy things like store instances or +handle shared references properly, it does run extremely fast. For +example loading a half megabyte of data may take less than a +third of a second (on some machines). This often beats doing +something more complex and general such as using gdbm with +pickle/shelve. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 8 22:59:00 1997 by +David Ascher +

+ +


+

4.40. I try to use __spam and I get an error about _SomeClassName__spam.

+Variables with double leading underscore are "mangled" to provide a +simple but effective way to define class private variables. See the +chapter "New in Release 1.4" in the Python Tutorial. +

+ +Edit this entry / +Log info +

+ +


+

4.41. How do I delete a file? And other file questions.

+Use os.remove(filename) or os.unlink(filename); for documentation, +see the posix section of the library manual. They are the same, +unlink() is simply the Unix name for this function. In earlier +versions of Python, only os.unlink() was available. +

+To remove a directory, use os.rmdir(); use os.mkdir() to create one. +

+To rename a file, use os.rename(). +

+To truncate a file, open it using f = open(filename, "r+"), and use +f.truncate(offset); offset defaults to the current seek position. +(The "r+" mode opens the file for reading and writing.) +There's also os.ftruncate(fd, offset) for files opened with os.open() +-- for advanced Unix hacks only. +

+The shutil module also contains a number of functions to work on files +including copyfile, copytree, and rmtree amongst others. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:30:01 2000 by +Bjorn Pettersen +

+ +


+

4.42. How to modify urllib or httplib to support HTTP/1.1?

+Recent versions of Python (2.0 and onwards) support HTTP/1.1 natively. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:56:56 2001 by +Moshe Zadka +

+ +


+

4.43. Unexplicable syntax errors in compile() or exec.

+When a statement suite (as opposed to an expression) is compiled by +compile(), exec or execfile(), it must end in a newline. In some +cases, when the source ends in an indented block it appears that at +least two newlines are required. +

+ +Edit this entry / +Log info +

+ +


+

4.44. How do I convert a string to a number?

+For integers, use the built-in int() function, e.g. int('144') == 144. Similarly, long() converts from string to long integer, e.g. long('144') == 144L; and float() to floating-point, e.g. float('144') == 144.0. +

+Note that these are restricted to decimal interpretation, so +that int('0144') == 144 and int('0x144') raises ValueError. For Python +2.0 int takes the base to convert from as a second optional argument, so +int('0x144', 16) == 324. +

+For greater flexibility, or before Python 1.5, import the module +string and use the string.atoi() function for integers, +string.atol() for long integers, or string.atof() for +floating-point. E.g., +string.atoi('100', 16) == string.atoi('0x100', 0) == 256. +See the library reference manual section for the string module for +more details. +

+While you could use the built-in function eval() instead of +any of those, this is not recommended, because someone could pass you +a Python expression that might have unwanted side effects (like +reformatting your disk). It also has the effect of interpreting numbers +as Python expressions, so that e.g. eval('09') gives a syntax error +since Python regards numbers starting with '0' as octal (base 8). +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:37:34 2000 by +Bjorn Pettersen +

+ +


+

4.45. How do I convert a number to a string?

+To convert, e.g., the number 144 to the string '144', use the +built-in function repr() or the backquote notation (these are +equivalent). If you want a hexadecimal or octal representation, use +the built-in functions hex() or oct(), respectively. For fancy +formatting, use the % operator on strings, just like C printf formats, +e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. +See the library reference manual for details. +

+ +Edit this entry / +Log info +

+ +


+

4.46. How do I copy a file?

+There's the shutil module which contains a copyfile() +function that implements a copy loop; +it isn't good enough for the Macintosh, though: +it doesn't copy the resource fork and Finder info. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 02:59:40 2001 by +Moshe Zadka +

+ +


+

4.47. How do I check if an object is an instance of a given class or of a subclass of it?

+If you are developing the classes from scratch it might be better to +program in a more proper object-oriented style -- instead of doing a different +thing based on class membership, why not use a method and define the +method differently in different classes? +

+However, there are some legitimate situations +where you need to test for class membership. +

+In Python 1.5, you can use the built-in function isinstance(obj, cls). +

+The following approaches can be used with earlier Python versions: +

+An unobvious method is to raise the object +as an exception and to try to catch the exception with the class you're +testing for: +

+

+	def is_instance_of(the_instance, the_class):
+	    try:
+		raise the_instance
+	    except the_class:
+		return 1
+	    except:
+		return 0
+
+This technique can be used to distinguish "subclassness" +from a collection of classes as well +

+

+                try:
+                              raise the_instance
+                except Audible:
+                              the_instance.play(largo)
+                except Visual:
+                              the_instance.display(gaudy)
+                except Olfactory:
+                              sniff(the_instance)
+                except:
+                              raise ValueError, "dunno what to do with this!"
+
+This uses the fact that exception catching tests for class or subclass +membership. +

+A different approach is to test for the presence of a class attribute that +is presumably unique for the given class. For instance: +

+

+	class MyClass:
+	    ThisIsMyClass = 1
+	    ...
+
+
+	def is_a_MyClass(the_instance):
+	    return hasattr(the_instance, 'ThisIsMyClass')
+
+This version is easier to inline, and probably faster (inlined it +is definitely faster). The disadvantage is that someone else could cheat: +

+

+	class IntruderClass:
+	    ThisIsMyClass = 1    # Masquerade as MyClass
+	    ...
+
+but this may be seen as a feature (anyway, there are plenty of other ways +to cheat in Python). Another disadvantage is that the class must be +prepared for the membership test. If you do not "control the +source code" for the class it may not be advisable to modify the +class to support testability. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 2 15:16:04 1998 by +GvR +

+ +


+

4.48. What is delegation?

+Delegation refers to an object oriented technique Python programmers +may implement with particular ease. Consider the following: +

+

+  from string import upper
+
+
+  class UpperOut:
+        def __init__(self, outfile):
+              self.__outfile = outfile
+        def write(self, str):
+              self.__outfile.write( upper(str) )
+        def __getattr__(self, name):
+              return getattr(self.__outfile, name)
+
+Here the UpperOut class redefines the write method +to convert the argument string to upper case before +calling the underlying self.__outfile.write method, but +all other methods are delegated to the underlying +self.__outfile object. The delegation is accomplished +via the "magic" __getattr__ method. Please see the +language reference for more information on the use +of this method. +

+Note that for more general cases delegation can +get trickier. Particularly when attributes must be set +as well as gotten the class must define a __settattr__ +method too, and it must do so carefully. +

+The basic implementation of __setattr__ is roughly +equivalent to the following: +

+

+   class X:
+        ...
+        def __setattr__(self, name, value):
+             self.__dict__[name] = value
+        ...
+
+Most __setattr__ implementations must modify +self.__dict__ to store local state for self without +causing an infinite recursion. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:11:24 1997 by +aaron watters +

+ +


+

4.49. How do I test a Python program or component.

+We presume for the purposes of this question you are interested +in standalone testing, rather than testing your components inside +a testing framework. The best-known testing framework for Python +is the PyUnit module, maintained at +

+

+    http://pyunit.sourceforge.net/
+
+For standalone testing, it helps to write the program so that +it may be easily tested by using good modular design. +In particular your program +should have almost all functionality encapsulated in either functions +or class methods -- and this sometimes has the surprising and +delightful effect of making the program run faster (because +local variable accesses are faster than global accesses). +Furthermore the program should avoid depending on mutating +global variables, since this makes testing much more difficult to do. +

+The "global main logic" of your program may be as simple +as +

+

+  if __name__=="__main__":
+       main_logic()
+
+at the bottom of the main module of your program. +

+Once your program is organized as a tractable collection +of functions and class behaviours you should write test +functions that exercise the behaviours. A test suite +can be associated with each module which automates +a sequence of tests. This sounds like a lot of work, but +since Python is so terse and flexible it's surprisingly easy. +You can make coding much more pleasant and fun by +writing your test functions in parallel with the "production +code", since this makes it easy to find bugs and even +design flaws earlier. +

+"Support modules" that are not intended to be the main +module of a program may include a "test script interpretation" +which invokes a self test of the module. +

+

+   if __name__ == "__main__":
+      self_test()
+
+Even programs that interact with complex external +interfaces may be tested when the external interfaces are +unavailable by using "fake" interfaces implemented in +Python. For an example of a "fake" interface, the following +class defines (part of) a "fake" file interface: +

+

+ import string
+ testdata = "just a random sequence of characters"
+
+
+ class FakeInputFile:
+   data = testdata
+   position = 0
+   closed = 0
+
+
+   def read(self, n=None):
+       self.testclosed()
+       p = self.position
+       if n is None:
+          result= self.data[p:]
+       else:
+          result= self.data[p: p+n]
+       self.position = p + len(result)
+       return result
+
+
+   def seek(self, n, m=0):
+       self.testclosed()
+       last = len(self.data)
+       p = self.position
+       if m==0: 
+          final=n
+       elif m==1:
+          final=n+p
+       elif m==2:
+          final=len(self.data)+n
+       else:
+          raise ValueError, "bad m"
+       if final<0:
+          raise IOError, "negative seek"
+       self.position = final
+
+
+   def isatty(self):
+       return 0
+
+
+   def tell(self):
+       return self.position
+
+
+   def close(self):
+       self.closed = 1
+
+
+   def testclosed(self):
+       if self.closed:
+          raise IOError, "file closed"
+
+Try f=FakeInputFile() and test out its operations. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:12:10 2002 by +Neal Norwitz +

+ +


+

4.50. My multidimensional list (array) is broken! What gives?

+You probably tried to make a multidimensional array like this. +

+

+   A = [[None] * 2] * 3
+
+This makes a list containing 3 references to the same list of length +two. Changes to one row will show in all rows, which is probably not +what you want. The following works much better: +

+

+   A = [None]*3
+   for i in range(3):
+        A[i] = [None] * 2
+
+This generates a list containing 3 different lists of length two. +

+If you feel weird, you can also do it in the following way: +

+

+   w, h = 2, 3
+   A = map(lambda i,w=w: [None] * w, range(h))
+
+For Python 2.0 the above can be spelled using a list comprehension: +

+

+   w,h = 2,3
+   A = [ [None]*w for i in range(h) ]
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:18:35 2000 by +Bjorn Pettersen +

+ +


+

4.51. I want to do a complicated sort: can you do a Schwartzian Transform in Python?

+Yes, and in Python you only have to write it once: +

+

+ def st(List, Metric):
+     def pairing(element, M = Metric):
+           return (M(element), element)
+     paired = map(pairing, List)
+     paired.sort()
+     return map(stripit, paired)
+
+
+ def stripit(pair):
+     return pair[1]
+
+This technique, attributed to Randal Schwartz, sorts the elements +of a list by a metric which maps each element to its "sort value". +For example, if L is a list of string then +

+

+   import string
+   Usorted = st(L, string.upper)
+
+
+   def intfield(s):
+         return string.atoi( string.strip(s[10:15] ) )
+
+
+   Isorted = st(L, intfield)
+
+Usorted gives the elements of L sorted as if they were upper +case, and Isorted gives the elements of L sorted by the integer +values that appear in the string slices starting at position 10 +and ending at position 15. In Python 2.0 this can be done more +naturally with list comprehensions: +

+

+  tmp1 = [ (x.upper(), x) for x in L ] # Schwartzian transform
+  tmp1.sort()
+  Usorted = [ x[1] for x in tmp1 ]
+
+
+  tmp2 = [ (int(s[10:15]), s) for s in L ] # Schwartzian transform
+  tmp2.sort()
+  Isorted = [ x[1] for x in tmp2 ]
+
+

+Note that Isorted may also be computed by +

+

+   def Icmp(s1, s2):
+         return cmp( intfield(s1), intfield(s2) )
+
+
+   Isorted = L[:]
+   Isorted.sort(Icmp)
+
+but since this method computes intfield many times for each +element of L, it is slower than the Schwartzian Transform. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Jun 1 19:18:46 2002 by +Neal Norwitz +

+ +


+

4.52. How to convert between tuples and lists?

+The function tuple(seq) converts any sequence into a tuple with +the same items in the same order. +For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') +yields ('a', 'b', 'c'). If the argument is +a tuple, it does not make a copy but returns the same object, so +it is cheap to call tuple() when you aren't sure that an object +is already a tuple. +

+The function list(seq) converts any sequence into a list with +the same items in the same order. +For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') +yields ['a', 'b', 'c']. If the argument is a list, +it makes a copy just like seq[:] would. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 14 14:18:53 1998 by +Tim Peters +

+ +


+

4.53. Files retrieved with urllib contain leading garbage that looks like email headers.

+Extremely old versions of Python supplied libraries which +did not support HTTP/1.1; the vanilla httplib in Python 1.4 +only recognized HTTP/1.0. In Python 2.0 full HTTP/1.1 support is included. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 8 17:26:18 2001 by +Steve Holden +

+ +


+

4.54. How do I get a list of all instances of a given class?

+Python does not keep track of all instances of a class (or of a +built-in type). +

+You can program the class's constructor to keep track of all +instances, but unless you're very clever, this has the disadvantage +that the instances never get deleted,because your list of all +instances keeps a reference to them. +

+(The trick is to regularly inspect the reference counts of the +instances you've retained, and if the reference count is below a +certain level, remove it from the list. Determining that level is +tricky -- it's definitely larger than 1.) +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 27 23:52:16 1997 by +GvR +

+ +


+

4.55. A regular expression fails with regex.error: match failure.

+This is usually caused by too much backtracking; the regular +expression engine has a fixed size stack which holds at most 4000 +backtrack points. Every character matched by e.g. ".*" accounts for a +backtrack point, so even a simple search like +

+

+  regex.match('.*x',"x"*5000)
+
+will fail. +

+This is fixed in the re module introduced with +Python 1.5; consult the Library Reference section on re for more information. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 30 12:35:49 1998 by +A.M. Kuchling +

+ +


+

4.56. I can't get signal handlers to work.

+The most common problem is that the signal handler is declared +with the wrong argument list. It is called as +

+

+	handler(signum, frame)
+
+so it should be declared with two arguments: +

+

+	def handler(signum, frame):
+		...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed May 28 09:29:08 1997 by +GvR +

+ +


+

4.57. I can't use a global variable in a function? Help!

+Did you do something like this? +

+

+   x = 1 # make a global
+
+
+   def f():
+         print x # try to print the global
+         ...
+         for j in range(100):
+              if q>3:
+                 x=4
+
+Any variable assigned in a function is local to that function. +unless it is specifically declared global. Since a value is bound +to x as the last statement of the function body, the compiler +assumes that x is local. Consequently the "print x" +attempts to print an uninitialized local variable and will +trigger a NameError. +

+In such cases the solution is to insert an explicit global +declaration at the start of the function, making it +

+

+

+   def f():
+         global x
+         print x # try to print the global
+         ...
+         for j in range(100):
+              if q>3:
+                 x=4
+
+

+In this case, all references to x are interpreted as references +to the x from the module namespace. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 12 15:52:12 2001 by +Steve Holden +

+ +


+

4.58. What's a negative index? Why doesn't list.insert() use them?

+Python sequences are indexed with positive numbers and +negative numbers. For positive numbers 0 is the first index +1 is the second index and so forth. For negative indices -1 +is the last index and -2 is the pentultimate (next to last) index +and so forth. Think of seq[-n] as the same as seq[len(seq)-n]. +

+Using negative indices can be very convenient. For example +if the string Line ends in a newline then Line[:-1] is all of Line except +the newline. +

+Sadly the list builtin method L.insert does not observe negative +indices. This feature could be considered a mistake but since +existing programs depend on this feature it may stay around +forever. L.insert for negative indices inserts at the start of the +list. To get "proper" negative index behaviour use L[n:n] = [x] +in place of the insert method. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:03:18 1997 by +aaron watters +

+ +


+

4.59. How can I sort one list by values from another list?

+You can sort lists of tuples. +

+

+  >>> list1 = ["what", "I'm", "sorting", "by"]
+  >>> list2 = ["something", "else", "to", "sort"]
+  >>> pairs = map(None, list1, list2)
+  >>> pairs
+  [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
+  >>> pairs.sort()
+  >>> pairs
+  [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
+  >>> result = pairs[:]
+  >>> for i in xrange(len(result)): result[i] = result[i][1]
+  ...
+  >>> result
+  ['else', 'sort', 'to', 'something']
+
+And if you didn't understand the question, please see the +example above ;c). Note that "I'm" sorts before "by" because +uppercase "I" comes before lowercase "b" in the ascii order. +Also see 4.51. +

+In Python 2.0 this can be done like: +

+

+ >>> list1 = ["what", "I'm", "sorting", "by"]
+ >>> list2 = ["something", "else", "to", "sort"]
+ >>> pairs = zip(list1, list2)
+ >>> pairs
+ [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
+ >>> pairs.sort()
+ >>> result = [ x[1] for x in pairs ]
+ >>> result
+ ['else', 'sort', 'to', 'something']
+
+[Followup] +

+Someone asked, why not this for the last steps: +

+

+  result = []
+  for p in pairs: result.append(p[1])
+
+This is much more legible. However, a quick test shows that +it is almost twice as slow for long lists. Why? First of all, +the append() operation has to reallocate memory, and while it +uses some tricks to avoid doing that each time, it still has +to do it occasionally, and apparently that costs quite a bit. +Second, the expression "result.append" requires an extra +attribute lookup. The attribute lookup could be done away +with by rewriting as follows: +

+

+  result = []
+  append = result.append
+  for p in pairs: append(p[1])
+
+which gains back some speed, but is still considerably slower +than the original solution, and hardly less convoluted. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 12:56:35 2000 by +Bjorn Pettersen +

+ +


+

4.60. Why doesn't dir() work on builtin types like files and lists?

+It does starting with Python 1.5. +

+Using 1.4, you can find out which methods a given object supports +by looking at its __methods__ attribute: +

+

+    >>> List = []
+    >>> List.__methods__
+    ['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort']
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 16 14:56:42 1999 by +Skip Montanaro +

+ +


+

4.61. How can I mimic CGI form submission (METHOD=POST)?

+I would like to retrieve web pages that are the result of POSTing a +form. Is there existing code that would let me do this easily? +

+Yes. Here's a simple example that uses httplib. +

+

+    #!/usr/local/bin/python
+
+
+    import httplib, sys, time
+
+
+    ### build the query string
+    qs = "First=Josephine&MI=Q&Last=Public"
+
+
+    ### connect and send the server a path
+    httpobj = httplib.HTTP('www.some-server.out-there', 80)
+    httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
+    ### now generate the rest of the HTTP headers...
+    httpobj.putheader('Accept', '*/*')
+    httpobj.putheader('Connection', 'Keep-Alive')
+    httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
+    httpobj.putheader('Content-length', '%d' % len(qs))
+    httpobj.endheaders()
+    httpobj.send(qs)
+    ### find out what the server said in response...
+    reply, msg, hdrs = httpobj.getreply()
+    if reply != 200:
+	sys.stdout.write(httpobj.getfile().read())
+
+Note that in general for "url encoded posts" (the default) query strings must be "quoted" to, for example, change equals signs and spaces to an encoded form when they occur in name or value. Use urllib.quote to perform this quoting. For example to send name="Guy Steele, Jr.": +

+

+   >>> from urllib import quote
+   >>> x = quote("Guy Steele, Jr.")
+   >>> x
+   'Guy%20Steele,%20Jr.'
+   >>> query_string = "name="+x
+   >>> query_string
+   'name=Guy%20Steele,%20Jr.'
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 21 03:47:07 1999 by +TAB +

+ +


+

4.62. If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?

+Databases opened for write access with the bsddb module (and often by +the anydbm module, since it will preferentially use bsddb) must +explicitly be closed using the close method of the database. The +underlying libdb package caches database contents which need to be +converted to on-disk form and written, unlike regular open files which +already have the on-disk bits in the kernel's write buffer, where they +can just be dumped by the kernel with the program exits. +

+If you have initialized a new bsddb database but not written anything to +it before the program crashes, you will often wind up with a zero-length +file and encounter an exception the next time the file is opened. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:15:01 2002 by +Neal Norwitz +

+ +


+

4.63. How do I make a Python script executable on Unix?

+You need to do two things: the script file's mode must be executable +(include the 'x' bit), and the first line must begin with #! +followed by the pathname for the Python interpreter. +

+The first is done by executing 'chmod +x scriptfile' or perhaps +'chmod 755 scriptfile'. +

+The second can be done in a number of way. The most straightforward +way is to write +

+

+  #!/usr/local/bin/python
+
+as the very first line of your file - or whatever the pathname is +where the python interpreter is installed on your platform. +

+If you would like the script to be independent of where the python +interpreter lives, you can use the "env" program. On almost all +platforms, the following will work, assuming the python interpreter +is in a directory on the user's $PATH: +

+

+  #! /usr/bin/env python
+
+Note -- *don't* do this for CGI scripts. The $PATH variable for +CGI scripts is often very minimal, so you need to use the actual +absolute pathname of the interpreter. +

+Occasionally, a user's environment is so full that the /usr/bin/env +program fails; or there's no env program at all. +In that case, you can try the following hack (due to Alex Rezinsky): +

+

+  #! /bin/sh
+  """:"
+  exec python $0 ${1+"$@"}
+  """
+
+The disadvantage is that this defines the script's __doc__ string. +However, you can fix that by adding +

+

+  __doc__ = """...Whatever..."""
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 15 09:19:16 2001 by +Neal Norwitz +

+ +


+

4.64. How do you remove duplicates from a list?

+See the Python Cookbook for a long discussion of many cool ways: +

+

+    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
+
+Generally, if you don't mind reordering the List +

+

+   if List:
+      List.sort()
+      last = List[-1]
+      for i in range(len(List)-2, -1, -1):
+          if last==List[i]: del List[i]
+          else: last=List[i]
+
+If all elements of the list may be used as +dictionary keys (ie, they are all hashable) +this is often faster +

+

+   d = {}
+   for x in List: d[x]=x
+   List = d.values()
+
+Also, for extremely large lists you might +consider more optimal alternatives to the first one. +The second one is pretty good whenever it can +be used. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:56:33 2002 by +Tim Peters +

+ +


+

4.65. Are there any known year 2000 problems in Python?

+I am not aware of year 2000 deficiencies in Python 1.5. Python does +very few date calculations and for what it does, it relies on the C +library functions. Python generally represent times either as seconds +since 1970 or as a tuple (year, month, day, ...) where the year is +expressed with four digits, which makes Y2K bugs unlikely. So as long +as your C library is okay, Python should be okay. Of course, I cannot +vouch for your Python code! +

+Given the nature of freely available software, I have to add that this statement is not +legally binding. The Python copyright notice contains the following +disclaimer: +

+

+  STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
+  REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
+  MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
+  CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
+  DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
+  PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+  TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+  PERFORMANCE OF THIS SOFTWARE.
+
+The good news is that if you encounter a problem, you have full +source available to track it down and fix it! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Apr 10 14:59:31 1998 by +GvR +

+ +


+

4.66. I want a version of map that applies a method to a sequence of objects! Help!

+Get fancy! +

+

+  def method_map(objects, method, arguments):
+       """method_map([a,b], "flog", (1,2)) gives [a.flog(1,2), b.flog(1,2)]"""
+       nobjects = len(objects)
+       methods = map(getattr, objects, [method]*nobjects)
+       return map(apply, methods, [arguments]*nobjects)
+
+It's generally a good idea to get to know the mysteries of map and apply +and getattr and the other dynamic features of Python. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jan 5 14:21:14 1998 by +Aaron Watters +

+ +


+

4.67. How do I generate random numbers in Python?

+The standard library module "random" implements a random number +generator. Usage is simple: +

+

+    import random
+
+
+    random.random()
+
+This returns a random floating point number in the range [0, 1). +

+There are also many other specialized generators in this module, such +as +

+

+    randrange(a, b) chooses an integer in the range [a, b)
+    uniform(a, b) chooses a floating point number in the range [a, b)
+    normalvariate(mean, sdev) sample from normal (Gaussian) distribution
+
+Some higher-level functions operate on sequences directly, such as +

+

+    choice(S) chooses random element from a given sequence
+    shuffle(L) shuffles a list in-place, i.e. permutes it randomly
+
+There's also a class, Random, which you can instantiate +to create independent multiple random number generators. +

+All this is documented in the library reference manual. Note that +the module "whrandom" is obsolete. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 01:16:51 2002 by +Neal Norwitz +

+ +


+

4.68. How do I access the serial (RS232) port?

+There's a Windows serial communication module (for communication +over RS 232 serial ports) at +

+

+  ftp://ftp.python.org/pub/python/contrib/sio-151.zip
+  http://www.python.org/ftp/python/contrib/sio-151.zip
+
+For DOS, try Hans Nowak's Python-DX, which supports this, at: +

+

+  http://www.cuci.nl/~hnowak/
+
+For Unix, see a usenet post by Mitch Chapman: +

+

+  http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com
+
+For Win32, POSIX(Linux, BSD, *), Jython, Chris': +

+

+  http://pyserial.sourceforge.net
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 2 21:11:07 2002 by +Chris Liechti +

+ +


+

4.69. Images on Tk-Buttons don't work in Py15?

+They do work, but you must keep your own reference to the image +object now. More verbosely, you must make sure that, say, a global +variable or a class attribute refers to the object. +

+Quoting Fredrik Lundh from the mailinglist: +

+

+  Well, the Tk button widget keeps a reference to the internal
+  photoimage object, but Tkinter does not.  So when the last
+  Python reference goes away, Tkinter tells Tk to release the
+  photoimage.  But since the image is in use by a widget, Tk
+  doesn't destroy it.  Not completely.  It just blanks the image,
+  making it completely transparent...
+
+
+  And yes, there was a bug in the keyword argument handling
+  in 1.4 that kept an extra reference around in some cases.  And
+  when Guido fixed that bug in 1.5, he broke quite a few Tkinter
+  programs...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Feb 3 11:31:03 1998 by +Case Roole +

+ +


+

4.70. Where is the math.py (socket.py, regex.py, etc.) source file?

+If you can't find a source file for a module it may be a builtin +or dynamically loaded module implemented in C, C++ or other +compiled language. In this case you may not have the source +file or it may be something like mathmodule.c, somewhere in +a C source directory (not on the Python Path). +

+Fredrik Lundh (fredrik@pythonware.com) explains (on the python-list): +

+There are (at least) three kinds of modules in Python: +1) modules written in Python (.py); +2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); +3) modules written in C and linked with the interpreter; to get a list +of these, type: +

+

+    import sys
+    print sys.builtin_module_names
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Feb 3 13:55:33 1998 by +Aaron Watters +

+ +


+

4.71. How do I send mail from a Python script?

+The standard library module smtplib does this. +Here's a very simple interactive mail +sender that uses it. This method will work on any host that +supports an SMTP listener. +

+

+    import sys, smtplib
+
+
+    fromaddr = raw_input("From: ")
+    toaddrs  = raw_input("To: ").split(',')
+    print "Enter message, end with ^D:"
+    msg = ''
+    while 1:
+        line = sys.stdin.readline()
+        if not line:
+            break
+        msg = msg + line
+
+
+    # The actual mail send
+    server = smtplib.SMTP('localhost')
+    server.sendmail(fromaddr, toaddrs, msg)
+    server.quit()
+
+If the local host doesn't have an SMTP listener, you need to find one. The simple method is to ask the user. Alternately, you can use the DNS system to find the mail gateway(s) responsible for the source address. +

+A Unix-only alternative uses sendmail. The location of the +sendmail program varies between systems; sometimes it is +/usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual +page will help you out. Here's some sample code: +

+

+  SENDMAIL = "/usr/sbin/sendmail" # sendmail location
+  import os
+  p = os.popen("%s -t -i" % SENDMAIL, "w")
+  p.write("To: cary@ratatosk.org\n")
+  p.write("Subject: test\n")
+  p.write("\n") # blank line separating headers from body
+  p.write("Some text\n")
+  p.write("some more text\n")
+  sts = p.close()
+  if sts != 0:
+      print "Sendmail exit status", sts
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:05:12 2002 by +Matthias Urlichs +

+ +


+

4.72. How do I avoid blocking in connect() of a socket?

+The select module is widely known to help with asynchronous +I/O on sockets once they are connected. However, it is less +than common knowledge how to avoid blocking on the initial +connect() call. Jeremy Hylton has the following advice (slightly +edited): +

+To prevent the TCP connect from blocking, you can set the socket to +non-blocking mode. Then when you do the connect(), you will either +connect immediately (unlikely) or get an exception that contains the +errno. errno.EINPROGRESS indicates that the connection is in +progress, but hasn't finished yet. Different OSes will return +different errnos, so you're going to have to check. I can tell you +that different versions of Solaris return different errno values. +

+In Python 1.5 and later, you can use connect_ex() to avoid +creating an exception. It will just return the errno value. +

+To poll, you can call connect_ex() again later -- 0 or errno.EISCONN +indicate that you're connected -- or you can pass this socket to +select (checking to see if it is writeable). +

+ +Edit this entry / +Log info + +/ Last changed on Tue Feb 24 21:30:45 1998 by +GvR +

+ +


+

4.73. How do I specify hexadecimal and octal integers?

+To specify an octal digit, precede the octal value with a zero. For example, +to set the variable "a" to the octal value "10" (8 in decimal), type: +

+

+    >>> a = 010
+
+To verify that this works, you can type "a" and hit enter while in the +interpreter, which will cause Python to spit out the current value of "a" +in decimal: +

+

+    >>> a
+    8
+
+Hexadecimal is just as easy. Simply precede the hexadecimal number with a +zero, and then a lower or uppercase "x". Hexadecimal digits can be specified +in lower or uppercase. For example, in the Python interpreter: +

+

+    >>> a = 0xa5
+    >>> a
+    165
+    >>> b = 0XB2
+    >>> b
+    178
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Mar 3 12:53:16 1998 by +GvR +

+ +


+

4.74. How to get a single keypress at a time?

+For Windows, see question 8.2. Here is an answer for Unix (see also 4.94). +

+There are several solutions; some involve using curses, which is a +pretty big thing to learn. Here's a solution without curses, due +to Andrew Kuchling (adapted from code to do a PGP-style +randomness pool): +

+

+        import termios, sys, os
+        fd = sys.stdin.fileno()
+        old = termios.tcgetattr(fd)
+        new = termios.tcgetattr(fd)
+        new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
+        new[6][termios.VMIN] = 1
+        new[6][termios.VTIME] = 0
+        termios.tcsetattr(fd, termios.TCSANOW, new)
+        s = ''    # We'll save the characters typed and add them to the pool.
+        try:
+            while 1:
+                c = os.read(fd, 1)
+                print "Got character", `c`
+                s = s+c
+        finally:
+            termios.tcsetattr(fd, termios.TCSAFLUSH, old)
+
+You need the termios module for any of this to work, and I've only +tried it on Linux, though it should work elsewhere. It turns off +stdin's echoing and disables canonical mode, and then reads a +character at a time from stdin, noting the time after each keystroke. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 24 00:36:56 2002 by +chris +

+ +


+

4.75. How can I overload constructors (or methods) in Python?

+(This actually applies to all methods, but somehow the question +usually comes up first in the context of constructors.) +

+Where in C++ you'd write +

+

+    class C {
+        C() { cout << "No arguments\n"; }
+        C(int i) { cout << "Argument is " << i << "\n"; }
+    }
+
+in Python you have to write a single constructor that catches all +cases using default arguments. For example: +

+

+    class C:
+        def __init__(self, i=None):
+            if i is None:
+                print "No arguments"
+            else:
+                print "Argument is", i
+
+This is not entirely equivalent, but close enough in practice. +

+You could also try a variable-length argument list, e.g. +

+

+        def __init__(self, *args):
+            ....
+
+The same approach works for all method definitions. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 20 11:55:55 1998 by +GvR +

+ +


+

4.76. How do I pass keyword arguments from one method to another?

+Use apply. For example: +

+

+    class Account:
+        def __init__(self, **kw):
+            self.accountType = kw.get('accountType')
+            self.balance = kw.get('balance')
+
+
+    class CheckingAccount(Account):
+        def __init__(self, **kw):
+            kw['accountType'] = 'checking'
+            apply(Account.__init__, (self,), kw)
+
+
+    myAccount = CheckingAccount(balance=100.00)
+
+In Python 2.0 you can call it directly using the new ** syntax: +

+

+    class CheckingAccount(Account):
+        def __init__(self, **kw):
+            kw['accountType'] = 'checking'
+            Account.__init__(self, **kw)
+
+or more generally: +

+

+ >>> def f(x, *y, **z):
+ ...  print x,y,z
+ ...
+ >>> Y = [1,2,3]
+ >>> Z = {'foo':3,'bar':None}
+ >>> f('hello', *Y, **Z)
+ hello (1, 2, 3) {'foo': 3, 'bar': None}
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 28 13:04:01 2000 by +Bjorn Pettersen +

+ +


+

4.77. What module should I use to help with generating HTML?

+Check out HTMLgen written by Robin Friedrich. It's a class library +of objects corresponding to all the HTML 3.2 markup tags. It's used +when you are writing in Python and wish to synthesize HTML pages for +generating a web or for CGI forms, etc. +

+It can be found in the FTP contrib area on python.org or on the +Starship. Use the search engines there to locate the latest version. +

+It might also be useful to consider DocumentTemplate, which offers clear +separation between Python code and HTML code. DocumentTemplate is part +of the Bobo objects publishing system (http:/www.digicool.com/releases) +but can be used independantly of course! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 28 09:54:58 1998 by +GvR +

+ +


+

4.78. How do I create documentation from doc strings?

+Use gendoc, by Daniel Larson. See +

+http://starship.python.net/crew/danilo/ +

+It can create HTML from the doc strings in your Python source code. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Oct 7 17:15:51 2002 by +Phil Rittenhouse +

+ +


+

4.79. How do I read (or write) binary data?

+For complex data formats, it's best to use +use the struct module. It's documented in the library reference. +It allows you to take a string read from a file containing binary +data (usually numbers) and convert it to Python objects; and vice +versa. +

+For example, the following code reads two 2-byte integers +and one 4-byte integer in big-endian format from a file: +

+

+  import struct
+
+
+  f = open(filename, "rb")  # Open in binary mode for portability
+  s = f.read(8)
+  x, y, z = struct.unpack(">hhl", s)
+
+The '>' in the format string forces bin-endian data; the letter +'h' reads one "short integer" (2 bytes), and 'l' reads one +"long integer" (4 bytes) from the string. +

+For data that is more regular (e.g. a homogeneous list of ints or +floats), you can also use the array module, also documented +in the library reference. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Oct 7 09:16:45 1998 by +GvR +

+ +


+

4.80. I can't get key bindings to work in Tkinter

+An oft-heard complaint is that event handlers bound to events +with the bind() method don't get handled even when the appropriate +key is pressed. +

+The most common cause is that the widget to which the binding applies +doesn't have "keyboard focus". Check out the Tk documentation +for the focus command. Usually a widget is given the keyboard +focus by clicking in it (but not for labels; see the taketocus +option). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:37:33 1998 by +GvR +

+ +


+

4.81. "import crypt" fails

+[Unix] +

+Starting with Python 1.5, the crypt module is disabled by default. +In order to enable it, you must go into the Python source tree and +edit the file Modules/Setup to enable it (remove a '#' sign in +front of the line starting with '#crypt'). Then rebuild. +You may also have to add the string '-lcrypt' to that same line. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 5 08:57:09 1998 by +GvR +

+ +


+

4.82. Are there coding standards or a style guide for Python programs?

+Yes, Guido has written the "Python Style Guide". See +http://www.python.org/doc/essays/styleguide.html +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 29 09:50:27 1998 by +Joseph VanAndel +

+ +


+

4.83. How do I freeze Tkinter applications?

+Freeze is a tool to create stand-alone applications (see 4.28). +

+When freezing Tkinter applications, the applications will not be +truly stand-alone, as the application will still need the tcl and +tk libraries. +

+One solution is to ship the application with the tcl and tk libraries, +and point to them at run-time using the TCL_LIBRARY and TK_LIBRARY +environment variables. +

+To get truly stand-alone applications, the Tcl scripts that form +the library have to be integrated into the application as well. One +tool supporting that is SAM (stand-alone modules), which is part +of the Tix distribution (http://tix.mne.com). Build Tix with SAM +enabled, perform the appropriate call to Tclsam_init etc inside +Python's Modules/tkappinit.c, and link with libtclsam +and libtksam (you might include the Tix libraries as well). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 20 17:35:01 1999 by +Martin v. Löwis +

+ +


+

4.84. How do I create static class data and static class methods?

+[Tim Peters, tim_one@email.msn.com] +

+Static data (in the sense of C++ or Java) is easy; static methods (again in the sense of C++ or Java) are not supported directly. +

+STATIC DATA +

+For example, +

+

+    class C:
+        count = 0   # number of times C.__init__ called
+
+
+        def __init__(self):
+            C.count = C.count + 1
+
+
+        def getcount(self):
+            return C.count  # or return self.count
+
+c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C. +

+Caution: within a method of C, +

+

+    self.count = 42
+
+creates a new and unrelated instance vrbl named "count" in self's own dict. So rebinding of a class-static data name needs the +

+

+    C.count = 314
+
+form whether inside a method or not. +

+

+STATIC METHODS +

+Static methods (as opposed to static data) are unnatural in Python, because +

+

+    C.getcount
+
+returns an unbound method object, which can't be invoked without supplying an instance of C as the first argument. +

+The intended way to get the effect of a static method is via a module-level function: +

+

+    def getcount():
+        return C.count
+
+If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation. +

+Several tortured schemes for faking static methods can be found by searching DejaNews. Most people feel such cures are worse than the disease. Perhaps the least obnoxious is due to Pekka Pessi (mailto:ppessi@hut.fi): +

+

+    # helper class to disguise function objects
+    class _static:
+        def __init__(self, f):
+            self.__call__ = f
+
+
+    class C:
+        count = 0
+
+
+        def __init__(self):
+            C.count = C.count + 1
+
+
+        def getcount():
+            return C.count
+        getcount = _static(getcount)
+
+
+        def sum(x, y):
+            return x + y
+        sum = _static(sum)
+
+
+    C(); C()
+    c = C()
+    print C.getcount()  # prints 3
+    print c.getcount()  # prints 3
+    print C.sum(27, 15) # prints 42
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 21 21:35:38 1999 by +Tim Peters +

+ +


+

4.85. __import__('x.y.z') returns <module 'x'>; how do I get z?

+Try +

+

+   __import__('x.y.z').y.z
+
+For more realistic situations, you may have to do something like +

+

+   m = __import__(s)
+   for i in string.split(s, ".")[1:]:
+       m = getattr(m, i)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 28 11:01:43 1999 by +GvR +

+ +


+

4.86. Basic thread wisdom

+Please note that there is no way to take advantage of +multiprocessor hardware using the Python thread model. The interpreter +uses a global interpreter lock (GIL), +which does not allow multiple threads to be concurrently active. +

+If you write a simple test program like this: +

+

+  import thread
+  def run(name, n):
+      for i in range(n): print name, i
+  for i in range(10):
+      thread.start_new(run, (i, 100))
+
+none of the threads seem to run! The reason is that as soon as +the main thread exits, all threads are killed. +

+A simple fix is to add a sleep to the end of the program, +sufficiently long for all threads to finish: +

+

+  import thread, time
+  def run(name, n):
+      for i in range(n): print name, i
+  for i in range(10):
+      thread.start_new(run, (i, 100))
+  time.sleep(10) # <----------------------------!
+
+But now (on many platforms) the threads don't run in parallel, +but appear to run sequentially, one at a time! The reason is +that the OS thread scheduler doesn't start a new thread until +the previous thread is blocked. +

+A simple fix is to add a tiny sleep to the start of the run +function: +

+

+  import thread, time
+  def run(name, n):
+      time.sleep(0.001) # <---------------------!
+      for i in range(n): print name, i
+  for i in range(10):
+      thread.start_new(run, (i, 100))
+  time.sleep(10)
+
+Some more hints: +

+Instead of using a time.sleep() call at the end, it's +better to use some kind of semaphore mechanism. One idea is to +use a the Queue module to create a queue object, let each thread +append a token to the queue when it finishes, and let the main +thread read as many tokens from the queue as there are threads. +

+Use the threading module instead of the thread module. It's part +of Python since version 1.5.1. It takes care of all these details, +and has many other nice features too! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:21:55 2003 by +GvR +

+ +


+

4.87. Why doesn't closing sys.stdout (stdin, stderr) really close it?

+Python file objects are a high-level layer of abstraction on top of C streams, which in turn are a medium-level layer of abstraction on top of (among other things) low-level C file descriptors. +

+For most file objects f you create in Python via the builtin "open" function, f.close() marks the Python file object as being closed from Python's point of view, and also arranges to close the underlying C stream. This happens automatically too, in f's destructor, when f becomes garbage. +

+But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C: doing +

+

+    sys.stdout.close() # ditto for stdin and stderr
+
+marks the Python-level file object as being closed, but does not close the associated C stream (provided sys.stdout is still bound to its default value, which is the stream C also calls "stdout"). +

+To close the underlying C stream for one of these three, you should first be sure that's what you really want to do (e.g., you may confuse the heck out of extension modules trying to do I/O). If it is, use os.close: +

+

+    os.close(0)   # close C's stdin stream
+    os.close(1)   # close C's stdout stream
+    os.close(2)   # close C's stderr stream
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 17 02:22:35 1999 by +Tim Peters +

+ +


+

4.88. What kinds of global value mutation are thread-safe?

+[adapted from c.l.py responses by Gordon McMillan & GvR] +

+A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions (how frequently it offers to switch can be set via sys.setcheckinterval). Each bytecode instruction-- and all the C implementation code reached from it --is therefore atomic. +

+In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared vrbls of builtin data types (ints, lists, dicts, etc) that "look atomic" really are. +

+For example, these are atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y +are objects, i, j are ints): +

+

+    L.append(x)
+    L1.extend(L2)
+    x = L[i]
+    x = L.pop()
+    L1[i:j] = L2
+    L.sort()
+    x = y
+    x.field = y
+    D[x] = y
+    D1.update(D2)
+    D.keys()
+
+These aren't: +

+

+    i = i+1
+    L.append(L[-1])
+    L[i] = L[j]
+    D[x] = D[x] + 1
+
+Note: operations that replace other objects may invoke those other objects' __del__ method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:21:03 2003 by +GvR +

+ +


+

4.89. How do I modify a string in place?

+Strings are immutable (see question 6.2) so you cannot modify a string +directly. If you need an object with this ability, try converting the +string to a list or take a look at the array module. +

+

+    >>> s = "Hello, world"
+    >>> a = list(s)
+    >>> print a
+    ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
+    >>> a[7:] = list("there!")
+    >>> import string
+    >>> print string.join(a, '')
+    'Hello, there!'
+
+
+    >>> import array
+    >>> a = array.array('c', s)
+    >>> print a
+    array('c', 'Hello, world')
+    >>> a[0] = 'y' ; print a
+    array('c', 'yello world')
+    >>> a.tostring()
+    'yello, world'
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue May 18 01:22:47 1999 by +Andrew Dalke +

+ +


+

4.90. How to pass on keyword/optional parameters/arguments

+Q: How can I pass on optional or keyword parameters from one function to another? +

+

+	def f1(a, *b, **c):
+		...
+
+A: In Python 2.0 and above: +

+

+	def f2(x, *y, **z):
+		...
+		z['width']='14.3c'
+		...
+		f1(x, *y, **z)
+
+
+   Note: y can be any sequence (e.g., list or tuple) and z must be a dict.
+
+

+A: For versions prior to 2.0, use 'apply', like: +

+

+	def f2(x, *y, **z):
+		...
+		z['width']='14.3c'
+		...
+		apply(f1, (x,)+y, z)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:20:56 2002 by +Matthias Urlichs +

+ +


+

4.91. How can I get a dictionary to display its keys in a consistent order?

+In general, dictionaries store their keys in an unpredictable order, +so the display order of a dictionary's elements will be similarly +unpredictable. +(See +Question 6.12 +to understand why this is so.) +

+This can be frustrating if you want to save a printable version to a +file, make some changes and then compare it with some other printed +dictionary. If you have such needs you can subclass UserDict.UserDict +to create a SortedDict class that prints itself in a predictable order. +Here's one simpleminded implementation of such a class: +

+

+  import UserDict, string
+
+
+  class SortedDict(UserDict.UserDict):
+    def __repr__(self):
+      result = []
+      append = result.append
+      keys = self.data.keys()
+      keys.sort()
+      for k in keys:
+        append("%s: %s" % (`k`, `self.data[k]`))
+      return "{%s}" % string.join(result, ", ")
+
+
+    ___str__ = __repr__
+
+

+This will work for many common situations you might encounter, though +it's far from a perfect solution. (It won't have any effect on the +pprint module and does not transparently handle values that are or +contain dictionaries. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 16 17:31:06 1999 by +Skip Montanaro +

+ +


+

4.92. Is there a Python tutorial?

+Yes. See question 1.20 at +http://www.python.org/doc/FAQ.html#1.20 +

+ +Edit this entry / +Log info + +/ Last changed on Sat Dec 4 16:04:00 1999 by +TAB +

+ +


+

4.93. Deleted

+See 4.28 +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 28 20:40:37 2002 by +GvR +

+ +


+

4.94. How do I get a single keypress without blocking?

+There are several solutions; some involve using curses, which is a +pretty big thing to learn. Here's a solution without curses. (see also 4.74, for Windows, see question 8.2) +

+

+  import termios, fcntl, sys, os
+  fd = sys.stdin.fileno()
+
+
+  oldterm = termios.tcgetattr(fd)
+  newattr = termios.tcgetattr(fd)
+  newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
+  termios.tcsetattr(fd, termios.TCSANOW, newattr)
+
+
+  oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
+  fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
+
+
+  try:
+      while 1:
+          try:
+              c = sys.stdin.read(1)
+              print "Got character", `c`
+          except IOError: pass
+  finally:
+      termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
+      fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
+
+

+You need the termios and the fcntl module for any of this to work, +and I've only tried it on Linux, though it should work elsewhere. +

+In this code, characters are read and printed one at a time. +

+termios.tcsetattr() turns off stdin's echoing and disables canonical +mode. fcntl.fnctl() is used to obtain stdin's file descriptor flags +and modify them for non-blocking mode. Since reading stdin when it is +empty results in an IOError, this error is caught and ignored. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 24 00:39:06 2002 by +chris +

+ +


+

4.95. Is there an equivalent to Perl chomp()? (Remove trailing newline from string)

+There are two partial substitutes. If you want to remove all trailing +whitespace, use the method string.rstrip(). Otherwise, if there is only +one line in the string, use string.splitlines()[0]. +

+

+ -----------------------------------------------------------------------
+
+
+ rstrip() is too greedy, it strips all trailing white spaces.
+ splitlines() takes ControlM as line boundary.
+ Consider these strings as input:
+   "python python    \r\n"
+   "python\rpython\r\n"
+   "python python   \r\r\r\n"
+ The results from rstrip()/splitlines() are perhaps not what we want.
+
+
+ It seems re can perform this task.
+
+

+

+ #!/usr/bin/python 
+ # requires python2                                                             
+
+
+ import re, os, StringIO
+
+
+ lines=StringIO.StringIO(
+   "The Python Programming Language\r\n"
+   "The Python Programming Language \r \r \r\r\n"
+   "The\rProgramming\rLanguage\r\n"
+   "The\rProgramming\rLanguage\r\r\r\r\n"
+   "The\r\rProgramming\r\rLanguage\r\r\r\r\n"
+ )
+
+
+ ln=re.compile("(?:[\r]?\n|\r)$") # dos:\r\n, unix:\n, mac:\r, others: unknown
+ # os.linesep does not work if someone ftps(in binary mode) a dos/mac text file
+ # to your unix box
+ #ln=re.compile(os.linesep + "$")
+
+
+ while 1:
+   s=lines.readline()
+   if not s: break
+   print "1.(%s)" % `s.rstrip()`
+   print "2.(%s)" % `ln.sub( "", s, 1)`
+   print "3.(%s)" % `s.splitlines()[0]`
+   print "4.(%s)" % `s.splitlines()`
+   print
+
+
+ lines.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 8 09:51:34 2001 by +Crystal +

+ +


+

4.96. Why is join() a string method when I'm really joining the elements of a (list, tuple, sequence)?

+Strings became much more like other standard types starting in release 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. These new methods have been widely accepted, but the one which appears to make (some) programmers feel uncomfortable is: +

+

+    ", ".join(['1', '2', '4', '8', '16'])
+
+which gives the result +

+

+    "1, 2, 4, 8, 16"
+
+There are two usual arguments against this usage. +

+The first runs along the lines of: "It looks really ugly using a method of a string literal (string constant)", to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals. Get over it! +

+The second objection is typically cast as: "I am really telling a sequence to join its members together with a string constant". Sadly, you aren't. For some reason there seems to be much less difficulty with having split() as a string method, since in that case it is easy to see that +

+

+    "1, 2, 4, 8, 16".split(", ")
+
+is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space). In this case a Unicode string returns a list of Unicode strings, an ASCII string returns a list of ASCII strings, and everyone is happy. +

+join() is a string method because in using it you are telling the separator string to iterate over an arbitrary sequence, forming string representations of each of the elements, and inserting itself between the elements' representations. This method can be used with any argument which obeys the rules for sequence objects, inluding any new classes you might define yourself. +

+Because this is a string method it can work for Unicode strings as well as plain ASCII strings. If join() were a method of the sequence types then the sequence types would have to decide which type of string to return depending on the type of the separator. +

+If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write +

+

+    string.join(['1', '2', '4', '8', '16'], ", ")
+
+You will just have to try and forget that the string module actually uses the syntax you are compaining about to implement the syntax you prefer! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 2 15:51:58 2002 by +Steve Holden +

+ +


+

4.97. How can my code discover the name of an object?

+Generally speaking, it can't, because objects don't really have names. The assignment statement does not store the assigned value in the name but a reference to it. Essentially, assignment creates a binding of a name to a value. The same is true of def and class statements, but in that case the value is a callable. Consider the following code: +

+

+    class A:
+        pass
+
+
+    B = A
+
+
+    a = B()
+    b = a
+    print b
+    <__main__.A instance at 016D07CC>
+    print a
+    <__main__.A instance at 016D07CC>
+
+

+Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value. +

+Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 8 03:53:39 2001 by +Steve Holden +

+ +


+

4.98. Why are floating point calculations so inaccurate?

+The development version of the Python Tutorial now contains an Appendix with more info: +
+    http://www.python.org/doc/current/tut/node14.html
+
+People are often very surprised by results like this: +

+

+ >>> 1.2-1.0
+ 0.199999999999999996
+
+And think it is a bug in Python. It's not. It's a problem caused by +the internal representation of a floating point number. A floating point +number is stored as a fixed number of binary digits. +

+In decimal math, there are many numbers that can't be represented +with a fixed number of decimal digits, i.e. +1/3 = 0.3333333333....... +

+In the binary case, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. There are +a lot of numbers that can't be represented. The digits are cut off at +some point. +

+Since Python 1.6, a floating point's repr() function prints as many +digits are necessary to make eval(repr(f)) == f true for any float f. +The str() function prints the more sensible number that was probably +intended: +

+

+ >>> 0.2
+ 0.20000000000000001
+ >>> print 0.2
+ 0.2
+
+Again, this has nothing to do with Python, but with the way the +underlying C platform handles floating points, and ultimately with +the inaccuracy you'll always have when writing down numbers of fixed +number of digit strings. +

+One of the consequences of this is that it is dangerous to compare +the result of some computation to a float with == ! +Tiny inaccuracies may mean that == fails. +

+Instead try something like this: +

+

+ epsilon = 0.0000000000001 # Tiny allowed error
+ expected_result = 0.4
+
+
+ if expected_result-epsilon <= computation() <= expected_result+epsilon:
+    ...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Apr 1 22:18:47 2002 by +Fred Drake +

+ +


+

4.99. I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?

+Don't panic! Your data are probably intact. The most frequent cause +for the error is that you tried to open an earlier Berkeley DB file +with a later version of the Berkeley DB library. +

+Many Linux systems now have all three versions of Berkeley DB +available. If you are migrating from version 1 to a newer version use +db_dump185 to dump a plain text version of the database. +If you are migrating from version 2 to version 3 use db2_dump to create +a plain text version of the database. In either case, use db_load to +create a new native database for the latest version installed on your +computer. If you have version 3 of Berkeley DB installed, you should +be able to use db2_load to create a native version 2 database. +

+You should probably move away from Berkeley DB version 1 files because +the hash file code contains known bugs that can corrupt your data. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 29 16:04:29 2001 by +Skip Montanaro +

+ +


+

4.100. What are the "best practices" for using import in a module?

+First, the standard modules are great. Use them! The standard Python library is large and varied. Using modules can save you time and effort and will reduce maintainenance cost of your code. (Other programs are dedicated to supporting and fixing bugs in the standard Python modules. Coworkers may also be familiar with themodules that you use, reducing the amount of time it takes them to understand your code.) +

+The rest of this answer is largely a matter of personal preference, but here's what some newsgroup posters said (thanks to all who responded) +

+In general, don't use +

+ from modulename import *
+
+Doing so clutters the importer's namespace. Some avoid this idiom even with the few modules that were designed to be imported in this manner. (Modules designed in this manner include Tkinter, thread, and wxPython.) +

+Import modules at the top of a file, one module per line. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports. +

+Move imports into a local scope (such as at the top of a function definition) if there are a lot of imports, and you're trying to avoid the cost (lots of initialization time) of many imports. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive (because of the one time initialization of the module) but that loading a module multiple times is virtually free (a couple of dictionary lookups). Even if the module name has gone out of scope, the module is probably available in sys.modules. Thus, there isn't really anything wrong with putting no imports at the module level (if they aren't needed) and putting all of the imports at the function level. +

+It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon says: +

+ Circular imports are fine where both modules use the "import <module>"
+ form of import. They fail when the 2nd module wants to grab a name
+ out of the first ("from module import name") and the import is at
+ the top level. That's because names in the 1st are not yet available,
+ (the first module is busy importing the 2nd).  
+
+In this case, if the 2nd module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import. +

+It may also be necessary to move imports out of the top level of code +if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option. +

+If only instances of a specific class uses a module, then it is reasonable to import the module in the class's __init__ method and then assign the module to an instance variable so that the module is always available (via that instance variable) during the life of the object. Note that to delay an import until the class is instantiated, the import must be inside a method. Putting the import inside the class but outside of any method still causes the import to occur when the module is initialized. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 4 04:44:47 2001 by +TAB +

+ +


+

4.101. Is there a tool to help find bugs or perform static analysis?

+Yes. PyChecker is a static analysis tool for finding bugs +in Python source code as well as warning about code complexity +and style. +

+You can get PyChecker from: http://pychecker.sf.net. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 10 15:42:11 2001 by +Neal +

+ +


+

4.102. UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)

+This error indicates that your Python installation can handle +only 7-bit ASCII strings. There are a couple ways to fix or +workaround the problem. +

+If your programs must handle data in arbitary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For instance, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by "value" is encoded as UTF-8: +

+

+    value = unicode(value, "utf-8")
+
+will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError. +

+If you only want strings coverted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails: +

+

+    try:
+        x = unicode(value, "ascii")
+    except UnicodeError:
+        value = unicode(value, "utf-8")
+    else:
+        # value was valid ASCII data
+        pass
+
+

+If you normally use a character set encoding other than US-ASCII and only need to handle data in that encoding, the simplest way to fix the problem may be simply to set the encoding in sitecustomize.py. The following code is just a modified version of the encoding setup code from site.py with the relevant lines uncommented. +

+

+    # Set the string encoding used by the Unicode implementation.
+    # The default is 'ascii'
+    encoding = "ascii" # <= CHANGE THIS if you wish
+
+
+    # Enable to support locale aware default string encodings.
+    import locale
+    loc = locale.getdefaultlocale()
+    if loc[1]:
+        encoding = loc[1]
+    if encoding != "ascii":
+        import sys
+        sys.setdefaultencoding(encoding)
+
+

+Also note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 13 04:45:41 2002 by +Skip Montanaro +

+ +


+

4.103. Using strings to call functions/methods

+There are various techniques: +

+* Use a dictionary pre-loaded with strings and functions. The primary +advantage of this technique is that the strings do not need to match the +names of the functions. This is also the primary technique used to +emulate a case construct: +

+

+    def a():
+        pass
+
+
+    def b():
+        pass
+
+
+    dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs
+
+
+    dispatch[get_input()]()  # Note trailing parens to call function
+
+* Use the built-in function getattr(): +

+

+    import foo
+    getattr(foo, 'bar')()
+
+Note that getattr() works on any object, including classes, class +instances, modules, and so on. +

+This is used in several places in the standard library, like +this: +

+

+    class Foo:
+        def do_foo(self):
+            ...
+
+
+        def do_bar(self):
+            ...
+
+
+     f = getattr(foo_instance, 'do_' + opname)
+     f()
+
+

+* Use locals() or eval() to resolve the function name: +

+def myFunc(): +

+    print "hello"
+
+fname = "myFunc" +

+f = locals()[fname] +f() +

+f = eval(fname) +f() +

+Note: Using eval() can be dangerous. If you don't have absolute control +over the contents of the string, all sorts of things could happen... +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 08:14:58 2002 by +Erno Kuusela +

+ +


+

4.104. How fast are exceptions?

+A try/except block is extremely efficient. Actually executing an +exception is expensive. In older versions of Python (prior to 2.0), it +was common to code this idiom: +

+

+    try:
+        value = dict[key]
+    except KeyError:
+        dict[key] = getvalue(key)
+        value = dict[key]
+
+This idiom only made sense when you expected the dict to have the key +95% of the time or more; other times, you coded it like this: +

+

+    if dict.has_key(key):
+        value = dict[key]
+    else:
+        dict[key] = getvalue(key)
+        value = dict[key]
+
+In Python 2.0 and higher, of course, you can code this as +

+

+    value = dict.setdefault(key, getvalue(key))
+
+However this evaluates getvalue(key) always, regardless of whether it's needed or not. So if it's slow or has a side effect you should use one of the above variants. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 9 10:12:30 2002 by +Yeti +

+ +


+

4.105. Sharing global variables across modules

+The canonical way to share information across modules within a single +program is to create a special module (often called config or cfg). +Just import the config module in all modules of your application; the +module then becomes available as a global name. Because there is only +one instance of each module, any changes made to the module object get +reflected everywhere. For example: +

+config.py: +

+

+    pass
+
+mod.py: +

+

+    import config
+    config.x = 1
+
+main.py: +

+

+    import config
+    import mod
+    print config.x
+
+Note that using a module is also the basis for implementing the +Singleton design pattern, for the same reason. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 23 23:07:19 2002 by +Aahz +

+ +


+

4.106. Why is cPickle so slow?

+Use the binary option. We'd like to make that the default, but it would +break backward compatibility: +

+

+    largeString = 'z' * (100 * 1024)
+    myPickle = cPickle.dumps(largeString, 1)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 22 19:54:25 2002 by +Aahz +

+ +


+

4.107. When importing module XXX, why do I get "undefined symbol: PyUnicodeUCS2_..." ?

+You are using a version of Python that uses a 4-byte representation for +Unicode characters, but the extension module you are importing (possibly +indirectly) was compiled using a Python that uses a 2-byte representation +for Unicode characters (the default). +

+If instead the name of the undefined symbol starts with PyUnicodeUCS4_, +the problem is the same by the relationship is reversed: Python was +built using 2-byte Unicode characters, and the extension module was +compiled using a Python with 4-byte Unicode characters. +

+This can easily occur when using pre-built extension packages. RedHat +Linux 7.x, in particular, provides a "python2" binary that is compiled +with 4-byte Unicode. This only causes the link failure if the extension +uses any of the PyUnicode_*() functions. It is also a problem if if an +extension uses any of the Unicode-related format specifiers for +Py_BuildValue (or similar) or parameter-specifications for +PyArg_ParseTuple(). +

+You can check the size of the Unicode character a Python interpreter is +using by checking the value of sys.maxunicode: +

+

+  >>> import sys
+  >>> if sys.maxunicode > 65535:
+  ...     print 'UCS4 build'
+  ... else:
+  ...     print 'UCS2 build'
+
+The only way to solve this problem is to use extension modules compiled +with a Python binary built using the same size for Unicode characters. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Aug 27 15:00:17 2002 by +Fred Drake +

+ +


+

4.108. How do I create a .pyc file?

+QUESTION: +

+I have a module and I wish to generate a .pyc file. +How do I do it? Everything I read says that generation of a .pyc file is +"automatic", but I'm not getting anywhere. +

+

+ANSWER: +

+When a module is imported for the first time (or when the source is more +recent than the current compiled file) a .pyc file containing the compiled code should be created in the +same directory as the .py file. +

+One reason that a .pyc file may not be created is permissions problems with the directory. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. +

+However, in most cases, that's not the problem. +

+Creation of a .pyc file is "automatic" if you are importing a module and Python has the +ability (permissions, free space, etc...) to write the compiled module +back to the directory. But note that running Python on a top level script is not considered an +import and so no .pyc will be created automatically. For example, if you have a top-level module abc.py that imports another module xyz.py, when you run abc, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc isn't imported. +

+If you need to create abc.pyc -- that is, to create a .pyc file for a +module that is not imported -- you can. (Look up +the py_compile and compileall modules in the Library Reference.) +

+You can manually compile any module using the "py_compile" module. One +way is to use the compile() function in that module interactively: +

+

+    >>> import py_compile
+    >>> py_compile.compile('abc.py')
+
+This will write the .pyc to the same location as abc.py (or you +can override that with the optional parameter cfile). +

+You can also automatically compile all files in a directory or +directories using the "compileall" module, which can also be run +straight from the command line. +

+You can do it from the shell (or DOS) prompt by entering: +

+       python compile.py abc.py
+
+or +
+       python compile.py *
+
+Or you can write a script to do it on a list of filenames that you enter. +

+

+     import sys
+     from py_compile import compile
+
+
+     if len(sys.argv) <= 1:
+        sys.exit(1)
+
+
+     for file in sys.argv[1:]:
+        compile(file)
+
+ACKNOWLEDGMENTS: +

+Steve Holden, David Bolen, Rich Somerfield, Oleg Broytmann, Steve Ferg +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 12 15:58:25 2003 by +Stephen Ferg +

+ +


+

5. Extending Python

+ +
+

5.1. Can I create my own functions in C?

+Yes, you can create built-in modules containing functions, +variables, exceptions and even new types in C. This is explained in +the document "Extending and Embedding the Python Interpreter" (http://www.python.org/doc/current/ext/ext.html). Also read the chapter +on dynamic loading. +

+There's more information on this in each of the Python books: +Programming Python, Internet Programming with Python, and Das Python-Buch +(in German). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 10 05:18:57 2001 by +Fred L. Drake, Jr. +

+ +


+

5.2. Can I create my own functions in C++?

+Yes, using the C-compatibility features found in C++. Basically +you place extern "C" { ... } around the Python include files and put +extern "C" before each function that is going to be called by the +Python interpreter. Global or static C++ objects with constructors +are probably not a good idea. +

+ +Edit this entry / +Log info +

+ +


+

5.3. How can I execute arbitrary Python statements from C?

+The highest-level function to do this is PyRun_SimpleString() which takes +a single string argument which is executed in the context of module +__main__ and returns 0 for success and -1 when an exception occurred +(including SyntaxError). If you want more control, use PyRun_String(); +see the source for PyRun_SimpleString() in Python/pythonrun.c. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 20:08:14 1997 by +Bill Tutt +

+ +


+

5.4. How can I evaluate an arbitrary Python expression from C?

+Call the function PyRun_String() from the previous question with the +start symbol eval_input (Py_eval_input starting with 1.5a1); it +parses an expression, evaluates it and returns its value. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:23:18 1997 by +David Ascher +

+ +


+

5.5. How do I extract C values from a Python object?

+That depends on the object's type. If it's a tuple, +PyTupleSize(o) returns its length and PyTuple_GetItem(o, i) +returns its i'th item; similar for lists with PyListSize(o) +and PyList_GetItem(o, i). For strings, PyString_Size(o) returns +its length and PyString_AsString(o) a pointer to its value +(note that Python strings may contain null bytes so strlen() +is not safe). To test which type an object is, first make sure +it isn't NULL, and then use PyString_Check(o), PyTuple_Check(o), +PyList_Check(o), etc. +

+There is also a high-level API to Python objects which is +provided by the so-called 'abstract' interface -- read +Include/abstract.h for further details. It allows for example +interfacing with any kind of Python sequence (e.g. lists and tuples) +using calls like PySequence_Length(), PySequence_GetItem(), etc.) +as well as many other useful protocols. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:34:20 1997 by +David Ascher +

+ +


+

5.6. How do I use Py_BuildValue() to create a tuple of arbitrary length?

+You can't. Use t = PyTuple_New(n) instead, and fill it with +objects using PyTuple_SetItem(t, i, o) -- note that this "eats" a +reference count of o. Similar for lists with PyList_New(n) and +PyList_SetItem(l, i, o). Note that you must set all the tuple items to +some value before you pass the tuple to Python code -- +PyTuple_New(n) initializes them to NULL, which isn't a valid Python +value. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 31 18:15:29 1997 by +Guido van Rossum +

+ +


+

5.7. How do I call an object's method from C?

+The PyObject_CallMethod() function can be used to call an arbitrary +method of an object. The parameters are the object, the name of the +method to call, a format string like that used with Py_BuildValue(), and the argument values: +

+

+    PyObject *
+    PyObject_CallMethod(PyObject *object, char *method_name,
+                        char *arg_format, ...);
+
+This works for any object that has methods -- whether built-in or +user-defined. You are responsible for eventually DECREF'ing the +return value. +

+To call, e.g., a file object's "seek" method with arguments 10, 0 +(assuming the file object pointer is "f"): +

+

+        res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
+        if (res == NULL) {
+                ... an exception occurred ...
+        }
+        else {
+                Py_DECREF(res);
+        }
+
+Note that since PyObject_CallObject() always wants a tuple for the +argument list, to call a function without arguments, pass "()" for the +format, and to call a function with one argument, surround the argument +in parentheses, e.g. "(i)". +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 6 16:15:46 2002 by +Neal Norwitz +

+ +


+

5.8. How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?

+(Due to Mark Hammond): +

+In Python code, define an object that supports the "write()" method. +Redirect sys.stdout and sys.stderr to this object. +Call print_error, or just allow the standard traceback mechanism to +work. Then, the output will go wherever your write() method sends it. +

+The easiest way to do this is to use the StringIO class in the standard +library. +

+Sample code and use for catching stdout: +

+	>>> class StdoutCatcher:
+	...  def __init__(self):
+	...   self.data = ''
+	...  def write(self, stuff):
+	...   self.data = self.data + stuff
+	...  
+	>>> import sys
+	>>> sys.stdout = StdoutCatcher()
+	>>> print 'foo'
+	>>> print 'hello world!'
+	>>> sys.stderr.write(sys.stdout.data)
+	foo
+	hello world!
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Dec 16 18:34:25 1998 by +Richard Jones +

+ +


+

5.9. How do I access a module written in Python from C?

+You can get a pointer to the module object as follows: +

+

+        module = PyImport_ImportModule("<modulename>");
+
+If the module hasn't been imported yet (i.e. it is not yet present in +sys.modules), this initializes the module; otherwise it simply returns +the value of sys.modules["<modulename>"]. Note that it doesn't enter +the module into any namespace -- it only ensures it has been +initialized and is stored in sys.modules. +

+You can then access the module's attributes (i.e. any name defined in +the module) as follows: +

+

+        attr = PyObject_GetAttrString(module, "<attrname>");
+
+Calling PyObject_SetAttrString(), to assign to variables in the module, also works. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:56:40 1997 by +david ascher +

+ +


+

5.10. How do I interface to C++ objects from Python?

+Depending on your requirements, there are many approaches. To do +this manually, begin by reading the "Extending and Embedding" document +(Doc/ext.tex, see also http://www.python.org/doc/). Realize +that for the Python run-time system, there isn't a whole lot of +difference between C and C++ -- so the strategy to build a new Python +type around a C structure (pointer) type will also work for C++ +objects. +

+A useful automated approach (which also works for C) is SWIG: +http://www.swig.org/. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Oct 15 05:14:01 1999 by +Sjoerd Mullender +

+ +


+

5.11. mSQLmodule (or other old module) won't build with Python 1.5 (or later)

+Since python-1.4 "Python.h" will have the file includes needed in an +extension module. +Backward compatibility is dropped after version 1.4 and therefore +mSQLmodule.c will not build as "allobjects.h" cannot be found. +The following change in mSQLmodule.c is harmless when building it with +1.4 and necessary when doing so for later python versions: +

+Remove lines: +

+

+	#include "allobjects.h"
+	#include "modsupport.h"
+
+And insert instead: +

+

+	#include "Python.h"
+
+You may also need to add +

+

+                #include "rename2.h"
+
+if the module uses "old names". +

+This may happen with other ancient python modules as well, +and the same fix applies. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Dec 21 02:03:35 1997 by +GvR +

+ +


+

5.12. I added a module using the Setup file and the make fails! Huh?

+Setup must end in a newline, if there is no newline there it gets +very sad. Aside from this possibility, maybe you have other +non-Python-specific linkage problems. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jun 24 15:54:01 1997 by +aaron watters +

+ +


+

5.13. I want to compile a Python module on my Red Hat Linux system, but some files are missing.

+Red Hat's RPM for Python doesn't include the +/usr/lib/python1.x/config/ directory, which contains various files required +for compiling Python extensions. +Install the python-devel RPM to get the necessary files. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 26 13:44:04 1999 by +A.M. Kuchling +

+ +


+

5.14. What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?

+This means that you have created an extension module named "yourmodule", but your module init function does not initialize with that name. +

+Every module init function will have a line similar to: +

+

+  module = Py_InitModule("yourmodule", yourmodule_functions);
+
+If the string passed to this function is not the same name as your extenion module, the SystemError will be raised. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 25 07:16:08 1999 by +Mark Hammond +

+ +


+

5.15. How to tell "incomplete input" from "invalid input"?

+Sometimes you want to emulate the Python interactive interpreter's +behavior, where it gives you a continuation prompt when the input +is incomplete (e.g. you typed the start of an "if" statement +or you didn't close your parentheses or triple string quotes), +but it gives you a syntax error message immediately when the input +is invalid. +

+In Python you can use the codeop module, which approximates the +parser's behavior sufficiently. IDLE uses this, for example. +

+The easiest way to do it in C is to call PyRun_InteractiveLoop() +(in a separate thread maybe) and let the Python interpreter handle +the input for you. You can also set the PyOS_ReadlineFunctionPointer +to point at your custom input function. See Modules/readline.c and +Parser/myreadline.c for more hints. +

+However sometimes you have to run the embedded Python interpreter +in the same thread as your rest application and you can't allow the +PyRun_InteractiveLoop() to stop while waiting for user input. +The one solution then is to call PyParser_ParseString() +and test for e.error equal to E_EOF (then the input is incomplete). +Sample code fragment, untested, inspired by code from Alex Farber: +

+

+  #include <Python.h>
+  #include <node.h>
+  #include <errcode.h>
+  #include <grammar.h>
+  #include <parsetok.h>
+  #include <compile.h>
+
+
+  int testcomplete(char *code)
+    /* code should end in \n */
+    /* return -1 for error, 0 for incomplete, 1 for complete */
+  {
+    node *n;
+    perrdetail e;
+
+
+    n = PyParser_ParseString(code, &_PyParser_Grammar,
+                             Py_file_input, &e);
+    if (n == NULL) {
+      if (e.error == E_EOF) 
+        return 0;
+      return -1;
+    }
+
+
+    PyNode_Free(n);
+    return 1;
+  }
+
+Another solution is trying to compile the received string with +Py_CompileString(). If it compiles fine - try to execute the returned +code object by calling PyEval_EvalCode(). Otherwise save the input for +later. If the compilation fails, find out if it's an error or just +more input is required - by extracting the message string from the +exception tuple and comparing it to the "unexpected EOF while parsing". +Here is a complete example using the GNU readline library (you may +want to ignore SIGINT while calling readline()): +

+

+  #include <stdio.h>
+  #include <readline.h>
+
+
+  #include <Python.h>
+  #include <object.h>
+  #include <compile.h>
+  #include <eval.h>
+
+
+  int main (int argc, char* argv[])
+  {
+    int i, j, done = 0;                          /* lengths of line, code */
+    char ps1[] = ">>> ";
+    char ps2[] = "... ";
+    char *prompt = ps1;
+    char *msg, *line, *code = NULL;
+    PyObject *src, *glb, *loc;
+    PyObject *exc, *val, *trb, *obj, *dum;
+
+
+    Py_Initialize ();
+    loc = PyDict_New ();
+    glb = PyDict_New ();
+    PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());
+
+
+    while (!done)
+    {
+      line = readline (prompt);
+
+
+      if (NULL == line)                          /* CTRL-D pressed */
+      {
+        done = 1;
+      }
+      else
+      {
+        i = strlen (line);
+
+
+        if (i > 0)
+          add_history (line);                    /* save non-empty lines */
+
+
+        if (NULL == code)                        /* nothing in code yet */
+          j = 0;
+        else
+          j = strlen (code);
+
+
+        code = realloc (code, i + j + 2);
+        if (NULL == code)                        /* out of memory */
+          exit (1);
+
+
+        if (0 == j)                              /* code was empty, so */
+          code[0] = '\0';                        /* keep strncat happy */
+
+
+        strncat (code, line, i);                 /* append line to code */
+        code[i + j] = '\n';                      /* append '\n' to code */
+        code[i + j + 1] = '\0';
+
+
+        src = Py_CompileString (code, "<stdin>", Py_single_input);       
+
+
+        if (NULL != src)                         /* compiled just fine - */
+        {
+          if (ps1  == prompt ||                  /* ">>> " or */
+              '\n' == code[i + j - 1])           /* "... " and double '\n' */
+          {                                               /* so execute it */
+            dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
+            Py_XDECREF (dum);
+            Py_XDECREF (src);
+            free (code);
+            code = NULL;
+            if (PyErr_Occurred ())
+              PyErr_Print ();
+            prompt = ps1;
+          }
+        }                                        /* syntax error or E_EOF? */
+        else if (PyErr_ExceptionMatches (PyExc_SyntaxError))           
+        {
+          PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */
+
+
+          if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
+              !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
+          {
+            Py_XDECREF (exc);
+            Py_XDECREF (val);
+            Py_XDECREF (trb);
+            prompt = ps2;
+          }
+          else                                   /* some other syntax error */
+          {
+            PyErr_Restore (exc, val, trb);
+            PyErr_Print ();
+            free (code);
+            code = NULL;
+            prompt = ps1;
+          }
+        }
+        else                                     /* some non-syntax error */
+        {
+          PyErr_Print ();
+          free (code);
+          code = NULL;
+          prompt = ps1;
+        }
+
+
+        free (line);
+      }
+    }
+
+
+    Py_XDECREF(glb);
+    Py_XDECREF(loc);
+    Py_Finalize();
+    exit(0);
+  }
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 15 09:47:24 2000 by +Alex Farber +

+ +


+

5.16. How do I debug an extension?

+When using gdb with dynamically loaded extensions, you can't set a +breakpoint in your extension until your extension is loaded. +

+In your .gdbinit file (or interactively), add the command +

+br _PyImport_LoadDynamicModule +

+

+$ gdb /local/bin/python +

+gdb) run myscript.py +

+gdb) continue # repeat until your extension is loaded +

+gdb) finish # so that your extension is loaded +

+gdb) br myfunction.c:50 +

+gdb) continue +

+ +Edit this entry / +Log info + +/ Last changed on Fri Oct 20 11:10:32 2000 by +Joe VanAndel +

+ +


+

5.17. How do I find undefined Linux g++ symbols, __builtin_new or __pure_virtural

+To dynamically load g++ extension modules, you must recompile python, relink python using g++ (change LINKCC in the python Modules Makefile), and link your extension module using g++ (e.g., "g++ -shared -o mymodule.so mymodule.o"). +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jan 14 18:03:51 2001 by +douglas orr +

+ +


+

5.18. How do I define and create objects corresponding to built-in/extension types

+Usually you would like to be able to inherit from a Python type when +you ask this question. The bottom line for Python 2.2 is: types and classes are miscible. You build instances by calling classes, and you can build subclasses to your heart's desire. +

+You need to be careful when instantiating immutable types like integers or strings. See http://www.amk.ca/python/2.2/, section 2, for details. +

+Prior to version 2.2, Python (like Java) insisted that there are first-class and second-class objects (the former are types, the latter classes), and never the twain shall meet. +

+The library has, however, done a good job of providing class wrappers for the more commonly desired objects (see UserDict, UserList and UserString for examples), and more are always welcome if you happen to be in the mood to write code. These wrappers still exist in Python 2.2. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 10 15:14:07 2002 by +Matthias Urlichs +

+ +


+

6. Python's design

+ +
+

6.1. Why isn't there a switch or case statement in Python?

+You can do this easily enough with a sequence of +if... elif... elif... else. There have been some proposals for switch +statement syntax, but there is no consensus (yet) on whether and how +to do range tests. +

+ +Edit this entry / +Log info +

+ +


+

6.2. Why does Python use indentation for grouping of statements?

+Basically I believe that using indentation for grouping is +extremely elegant and contributes a lot to the clarity of the average +Python program. Most people learn to love this feature after a while. +Some arguments for it: +

+Since there are no begin/end brackets there cannot be a disagreement +between grouping perceived by the parser and the human reader. I +remember long ago seeing a C fragment like this: +

+

+        if (x <= y)
+                x++;
+                y--;
+        z++;
+
+and staring a long time at it wondering why y was being decremented +even for x > y... (And I wasn't a C newbie then either.) +

+Since there are no begin/end brackets, Python is much less prone to +coding-style conflicts. In C there are loads of different ways to +place the braces (including the choice whether to place braces around +single statements in certain cases, for consistency). If you're used +to reading (and writing) code that uses one style, you will feel at +least slightly uneasy when reading (or being required to write) +another style. +Many coding styles place begin/end brackets on a line by themself. +This makes programs considerably longer and wastes valuable screen +space, making it harder to get a good overview over a program. +Ideally, a function should fit on one basic tty screen (say, 20 +lines). 20 lines of Python are worth a LOT more than 20 lines of C. +This is not solely due to the lack of begin/end brackets (the lack of +declarations also helps, and the powerful operations of course), but +it certainly helps! +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 16:00:15 1997 by +GvR +

+ +


+

6.3. Why are Python strings immutable?

+There are two advantages. One is performance: knowing that a +string is immutable makes it easy to lay it out at construction time +-- fixed and unchanging storage requirements. (This is also one of +the reasons for the distinction between tuples and lists.) The +other is that strings in Python are considered as "elemental" as +numbers. No amount of activity will change the value 8 to anything +else, and in Python, no amount of activity will change the string +"eight" to anything else. (Adapted from Jim Roskind) +

+ +Edit this entry / +Log info +

+ +


+

6.4. Delete

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:05:25 2001 by +Moshe Zadka +

+ +


+

6.5. Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

+The major reason is history. Functions were used for those +operations that were generic for a group of types and which +were intended to work even for objects that didn't have +methods at all (e.g. numbers before type/class unification +began, or tuples). +

+It is also convenient to have a function that can readily be applied +to an amorphous collection of objects when you use the functional features of Python (map(), apply() et al). +

+In fact, implementing len(), max(), min() as a built-in function is +actually less code than implementing them as methods for each type. +One can quibble about individual cases but it's a part of Python, +and it's too late to change such things fundamentally now. The +functions have to remain to avoid massive code breakage. +

+Note that for string operations Python has moved from external functions +(the string module) to methods. However, len() is still a function. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 30 14:08:58 2002 by +Steve Holden +

+ +


+

6.6. Why can't I derive a class from built-in types (e.g. lists or files)?

+As of Python 2.2, you can derive from built-in types. For previous versions, the answer is: +

+This is caused by the relatively late addition of (user-defined) +classes to the language -- the implementation framework doesn't easily +allow it. See the answer to question 4.2 for a work-around. This +may be fixed in the (distant) future. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 23 02:53:22 2002 by +Neal Norwitz +

+ +


+

6.7. Why must 'self' be declared and used explicitly in method definitions and calls?

+So, is your current programming language C++ or Java? :-) +When classes were added to Python, this was (again) the simplest way of +implementing methods without too many changes to the interpreter. The +idea was borrowed from Modula-3. It turns out to be very useful, for +a variety of reasons. +

+First, it makes it more obvious that you are using a method or +instance attribute instead of a local variable. Reading "self.x" or +"self.meth()" makes it absolutely clear that an instance variable or +method is used even if you don't know the class definition by heart. +In C++, you can sort of tell by the lack of a local variable +declaration (assuming globals are rare or easily recognizable) -- but +in Python, there are no local variable declarations, so you'd have to +look up the class definition to be sure. +

+Second, it means that no special syntax is necessary if you want to +explicitly reference or call the method from a particular class. In +C++, if you want to use a method from base class that is overridden in +a derived class, you have to use the :: operator -- in Python you can +write baseclass.methodname(self, <argument list>). This is +particularly useful for __init__() methods, and in general in cases +where a derived class method wants to extend the base class method of +the same name and thus has to call the base class method somehow. +

+Lastly, for instance variables, it solves a syntactic problem with +assignment: since local variables in Python are (by definition!) those +variables to which a value assigned in a function body (and that +aren't explicitly declared global), there has to be some way to tell +the interpreter that an assignment was meant to assign to an instance +variable instead of to a local variable, and it should preferably be +syntactic (for efficiency reasons). C++ does this through +declarations, but Python doesn't have declarations and it would be a +pity having to introduce them just for this purpose. Using the +explicit "self.var" solves this nicely. Similarly, for using instance +variables, having to write "self.var" means that references to +unqualified names inside a method don't have to search the instance's +directories. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 12 08:01:50 2001 by +Steve Holden +

+ +


+

6.8. Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

+Answer 1: Unfortunately, the interpreter pushes at least one C stack +frame for each Python stack frame. Also, extensions can call back into +Python at almost random moments. Therefore a complete threads +implementation requires thread support for C. +

+Answer 2: Fortunately, there is Stackless Python, which has a completely redesigned interpreter loop that avoids the C stack. It's still experimental but looks very promising. Although it is binary compatible with standard Python, it's still unclear whether Stackless will make it into the core -- maybe it's just too revolutionary. Stackless Python currently lives here: http://www.stackless.com. A microthread implementation that uses it can be found here: http://world.std.com/~wware/uthread.html. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 15 08:18:16 2000 by +Just van Rossum +

+ +


+

6.9. Why can't lambda forms contain statements?

+Python lambda forms cannot contain statements because Python's +syntactic framework can't handle statements nested inside expressions. +

+However, in Python, this is not a serious problem. Unlike lambda +forms in other languages, where they add functionality, Python lambdas +are only a shorthand notation if you're too lazy to define a function. +

+Functions are already first class objects in Python, and can be +declared in a local scope. Therefore the only advantage of using a +lambda form instead of a locally-defined function is that you don't need to invent a name for the function -- but that's just a local variable to which the function object (which is exactly the same type of object that a lambda form yields) is assigned! +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 14 14:15:17 1998 by +Tim Peters +

+ +


+

6.10. [deleted]

+[lambda vs non-nested scopes used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:20:56 2002 by +Erno Kuusela +

+ +


+

6.11. [deleted]

+[recursive functions vs non-nested scopes used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:22:04 2002 by +Erno Kuusela +

+ +


+

6.12. Why is there no more efficient way of iterating over a dictionary than first constructing the list of keys()?

+As of Python 2.2, you can now iterate over a dictionary directly, +using the new implied dictionary iterator: +

+

+    for k in d: ...
+
+There are also methods returning iterators over the values and items: +

+

+    for k in d.iterkeys(): # same as above
+    for v in d.itervalues(): # iterate over values
+    for k, v in d.iteritems(): # iterate over items
+
+All these require that you do not modify the dictionary during the loop. +

+For previous Python versions, the following defense should do: +

+Have you tried it? I bet it's fast enough for your purposes! In +most cases such a list takes only a few percent of the space occupied +by the dictionary. Apart from the fixed header, +the list needs only 4 bytes (the size of a pointer) per +key. A dictionary uses 12 bytes per key plus between 30 and 70 +percent hash table overhead, plus the space for the keys and values. +By necessity, all keys are distinct objects, and a string object (the most +common key type) costs at least 20 bytes plus the length of the +string. Add to that the values contained in the dictionary, and you +see that 4 bytes more per item really isn't that much more memory... +

+A call to dict.keys() makes one fast scan over the dictionary +(internally, the iteration function does exist) copying the pointers +to the key objects into a pre-allocated list object of the right size. +The iteration time isn't lost (since you'll have to iterate anyway -- +unless in the majority of cases your loop terminates very prematurely +(which I doubt since you're getting the keys in random order). +

+I don't expose the dictionary iteration operation to Python +programmers because the dictionary shouldn't be modified during the +entire iteration -- if it is, there's a small chance that the +dictionary is reorganized because the hash table becomes too full, and +then the iteration may miss some items and see others twice. Exactly +because this only occurs rarely, it would lead to hidden bugs in +programs: it's easy never to have it happen during test runs if you +only insert or delete a few items per iteration -- but your users will +surely hit upon it sooner or later. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:24:08 2002 by +GvR +

+ +


+

6.13. Can Python be compiled to machine code, C or some other language?

+Not easily. Python's high level data types, dynamic typing of +objects and run-time invocation of the interpreter (using eval() or +exec) together mean that a "compiled" Python program would probably +consist mostly of calls into the Python run-time system, even for +seemingly simple operations like "x+1". +

+Several projects described in the Python newsgroup or at past +Python conferences have shown that this approach is feasible, +although the speedups reached so far are only modest (e.g. 2x). +JPython uses the same strategy for compiling to Java bytecode. +(Jim Hugunin has demonstrated that in combination with whole-program +analysis, speedups of 1000x are feasible for small demo programs. +See the website for the 1997 Python conference.) +

+Internally, Python source code is always translated into a "virtual +machine code" or "byte code" representation before it is interpreted +(by the "Python virtual machine" or "bytecode interpreter"). In order +to avoid the overhead of parsing and translating modules that rarely +change over and over again, this byte code is written on a file whose +name ends in ".pyc" whenever a module is parsed (from a file whose +name ends in ".py"). When the corresponding .py file is changed, it +is parsed and translated again and the .pyc file is rewritten. +

+There is no performance difference once the .pyc file has been loaded +(the bytecode read from the .pyc file is exactly the same as the bytecode +created by direct translation). The only difference is that loading +code from a .pyc file is faster than parsing and translating a .py +file, so the presence of precompiled .pyc files will generally improve +start-up time of Python scripts. If desired, the Lib/compileall.py +module/script can be used to force creation of valid .pyc files for a +given set of modules. +

+Note that the main script executed by Python, even if its filename +ends in .py, is not compiled to a .pyc file. It is compiled to +bytecode, but the bytecode is not saved to a file. +

+If you are looking for a way to translate Python programs in order to +distribute them in binary form, without the need to distribute the +interpreter and library as well, have a look at the freeze.py script +in the Tools/freeze directory. This creates a single binary file +incorporating your program, the Python interpreter, and those parts of +the Python library that are needed by your program. Of course, the +resulting binary will only run on the same type of platform as that +used to create it. +

+Newsflash: there are now several programs that do this, to some extent. +Look for Psyco, Pyrex, PyInline, Py2Cmod, and Weave. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:26:19 2002 by +GvR +

+ +


+

6.14. How does Python manage memory?

+The details of Python memory management depend on the implementation. +The standard Python implementation (the C implementation) uses reference +counting and another mechanism to collect reference cycles. +

+Jython relies on the Java runtime; so it uses +the JVM's garbage collector. This difference can cause some subtle +porting problems if your Python code depends on the behavior of +the reference counting implementation. +

+The reference cycle collector was added in CPython 2.0. It +periodically executes a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. A new gc module provides functions to perform a garbage collection, obtain debugging statistics, and tuning the collector's parameters. +

+The detection of cycles can be disabled when Python is compiled, if you can't afford even a tiny speed penalty or suspect that the cycle collection is buggy, by specifying the "--without-cycle-gc" switch when running the configure script. +

+Sometimes objects get stuck in "tracebacks" temporarily and hence are not deallocated when you might expect. Clear the tracebacks via +

+

+       import sys
+       sys.exc_traceback = sys.last_traceback = None
+
+Tracebacks are used for reporting errors and implementing debuggers and related things. They contain a portion of the program state extracted during the handling of an exception (usually the most recent exception). +

+In the absence of circularities and modulo tracebacks, Python programs need not explicitly manage memory. +

+Why python doesn't use a more traditional garbage collection +scheme? For one thing, unless this were +added to C as a standard feature, it's a portability pain in the ass. +And yes, I know about the Xerox library. It has bits of assembler +code for most common platforms. Not for all. And although it is +mostly transparent, it isn't completely transparent (when I once +linked Python with it, it dumped core). +

+Traditional GC also becomes a problem when Python gets embedded into +other applications. While in a stand-alone Python it may be fine to +replace the standard malloc() and free() with versions provided by the +GC library, an application embedding Python may want to have its own +substitute for malloc() and free(), and may not want Python's. Right +now, Python works with anything that implements malloc() and free() +properly. +

+In Jython, the following code (which is +fine in C Python) will probably run out of file descriptors long before +it runs out of memory: +

+

+        for file in <very long list of files>:
+                f = open(file)
+                c = f.read(1)
+
+Using the current reference counting and destructor scheme, each new +assignment to f closes the previous file. Using GC, this is not +guaranteed. Sure, you can think of ways to fix this. But it's not +off-the-shelf technology. If you want to write code that will +work with any Python implementation, you should explicitly close +the file; this will work regardless of GC: +

+

+       for file in <very long list of files>:
+                f = open(file)
+                c = f.read(1)
+                f.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:35:38 2002 by +Erno Kuusela +

+ +


+

6.15. Why are there separate tuple and list data types?

+This is done so that tuples can be immutable while lists are mutable. +

+Immutable tuples are useful in situations where you need to pass a few +items to a function and don't want the function to modify the tuple; +for example, +

+

+	point1 = (120, 140)
+	point2 = (200, 300)
+	record(point1, point2)
+	draw(point1, point2)
+
+You don't want to have to think about what would happen if record() +changed the coordinates -- it can't, because the tuples are immutable. +

+On the other hand, when creating large lists dynamically, it is +absolutely crucial that they are mutable -- adding elements to a tuple +one by one requires using the concatenation operator, which makes it +quadratic in time. +

+As a general guideline, use tuples like you would use structs in C or +records in Pascal, use lists like (variable length) arrays. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:26:03 1997 by +GvR +

+ +


+

6.16. How are lists implemented?

+Despite what a Lisper might think, Python's lists are really +variable-length arrays. The implementation uses a contiguous +array of references to other objects, and keeps a pointer +to this array (as well as its length) in a list head structure. +

+This makes indexing a list (a[i]) an operation whose cost is +independent of the size of the list or the value of the index. +

+When items are appended or inserted, the array of references is resized. +Some cleverness is applied to improve the performance of appending +items repeatedly; when the array must be grown, some extra space +is allocated so the next few times don't require an actual resize. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:32:24 1997 by +GvR +

+ +


+

6.17. How are dictionaries implemented?

+Python's dictionaries are implemented as resizable hash tables. +

+Compared to B-trees, this gives better performance for lookup +(the most common operation by far) under most circumstances, +and the implementation is simpler. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 23:51:14 1997 by +Vladimir Marangozov +

+ +


+

6.18. Why must dictionary keys be immutable?

+The hash table implementation of dictionaries uses a hash value +calculated from the key value to find the key. If the key were +a mutable object, its value could change, and thus its hash could +change. But since whoever changes the key object can't tell that +is incorporated in a dictionary, it can't move the entry around in +the dictionary. Then, when you try to look up the same object +in the dictionary, it won't be found, since its hash value is different; +and if you try to look up the old value, it won't be found either, +since the value of the object found in that hash bin differs. +

+If you think you need to have a dictionary indexed with a list, +try to use a tuple instead. The function tuple(l) creates a tuple +with the same entries as the list l. +

+Some unacceptable solutions that have been proposed: +

+- Hash lists by their address (object ID). This doesn't work because +if you construct a new list with the same value it won't be found; +e.g., +

+

+  d = {[1,2]: '12'}
+  print d[[1,2]]
+
+will raise a KeyError exception because the id of the [1,2] used +in the second line differs from that in the first line. +In other words, dictionary keys should be compared using '==', not using 'is'. +

+- Make a copy when using a list as a key. This doesn't work because +the list (being a mutable object) could contain a reference to itself, +and then the copying code would run into an infinite loop. +

+- Allow lists as keys but tell the user not to modify them. This would +allow a class of hard-to-track bugs in programs that I'd rather not see; +it invalidates an important invariant of dictionaries (every value in +d.keys() is usable as a key of the dictionary). +

+- Mark lists as read-only once they are used as a dictionary key. +The problem is that it's not just the top-level object that could change +its value; you could use a tuple containing a list as a key. Entering +anything as a key into a dictionary would require marking all objects +reachable from there as read-only -- and again, self-referential objects +could cause an infinite loop again (and again and again). +

+There is a trick to get around this if you need to, but +use it at your own risk: You +can wrap a mutable structure inside a class instance which +has both a __cmp__ and a __hash__ method. +

+

+   class listwrapper:
+        def __init__(self, the_list):
+              self.the_list = the_list
+        def __cmp__(self, other):
+              return self.the_list == other.the_list
+        def __hash__(self):
+              l = self.the_list
+              result = 98767 - len(l)*555
+              for i in range(len(l)):
+                   try:
+                        result = result + (hash(l[i]) % 9999999) * 1001 + i
+                   except:
+                        result = (result % 7777777) + i * 333
+              return result
+
+Note that the hash computation is complicated by the +possibility that some members of the list may be unhashable +and also by the possibility of arithmetic overflow. +

+You must make +sure that the hash value for all such wrapper objects that reside in a +dictionary (or other hash based structure), remain fixed while +the object is in the dictionary (or other structure). +

+Furthermore it must always be the case that if +o1 == o2 (ie o1.__cmp__(o2)==0) then hash(o1)==hash(o2) +(ie, o1.__hash__() == o2.__hash__()), regardless of whether +the object is in a dictionary or not. +If you fail to meet these restrictions dictionaries and other +hash based structures may misbehave! +

+In the case of listwrapper above whenever the wrapper +object is in a dictionary the wrapped list must not change +to avoid anomalies. Don't do this unless you are prepared +to think hard about the requirements and the consequences +of not meeting them correctly. You've been warned! +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 10 10:08:40 1997 by +aaron watters +

+ +


+

6.19. How the heck do you make an array in Python?

+["this", 1, "is", "an", "array"] +

+Lists are arrays in the C or Pascal sense of the word (see question +6.16). The array module also provides methods for creating arrays +of fixed types with compact representations (but they are slower to +index than lists). Also note that the Numerics extensions and others +define array-like structures with various characteristics as well. +

+To get Lisp-like lists, emulate cons cells +

+

+    lisp_list = ("like",  ("this",  ("example", None) ) )
+
+using tuples (or lists, if you want mutability). Here the analogue +of lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1]. +Only do this if you're sure you really need to (it's usually a lot +slower than using Python lists). +

+Think of Python lists as mutable heterogeneous arrays of +Python objects (say that 10 times fast :) ). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:08:27 1997 by +aaron watters +

+ +


+

6.20. Why doesn't list.sort() return the sorted list?

+In situations where performance matters, making a copy of the list +just to sort it would be wasteful. Therefore, list.sort() sorts +the list in place. In order to remind you of that fact, it does +not return the sorted list. This way, you won't be fooled into +accidentally overwriting a list when you need a sorted copy but also +need to keep the unsorted version around. +

+As a result, here's the idiom to iterate over the keys of a dictionary +in sorted order: +

+

+	keys = dict.keys()
+	keys.sort()
+	for key in keys:
+		...do whatever with dict[key]...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 2 17:01:52 1999 by +Fred L. Drake, Jr. +

+ +


+

6.21. How do you specify and enforce an interface spec in Python?

+An interfaces specification for a module as provided +by languages such as C++ and java describes the prototypes +for the methods and functions of the module. Many feel +that compile time enforcement of interface specifications +help aid in the construction of large programs. Python +does not support interface specifications directly, but many +of their advantages can be obtained by an appropriate +test discipline for components, which can often be very +easily accomplished in Python. There is also a tool, PyChecker, +which can be used to find problems due to subclassing. +

+A good test suite for a module can at +once provide a regression test and serve as a module interface +specification (even better since it also gives example usage). Look to +many of the standard libraries which often have a "script +interpretation" which provides a simple "self test." Even +modules which use complex external interfaces can often +be tested in isolation using trivial "stub" emulations of the +external interface. +

+An appropriate testing discipline (if enforced) can help +build large complex applications in Python as well as having interface +specifications would do (or better). Of course Python allows you +to get sloppy and not do it. Also you might want to design +your code with an eye to make it easily tested. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 23 03:05:29 2002 by +Neal Norwitz +

+ +


+

6.22. Why do all classes have the same type? Why do instances all have the same type?

+The Pythonic use of the word "type" is quite different from +common usage in much of the rest of the programming language +world. A "type" in Python is a description for an object's operations +as implemented in C. All classes have the same operations +implemented in C which sometimes "call back" to differing program +fragments implemented in Python, and hence all classes have the +same type. Similarly at the C level all class instances have the +same C implementation, and hence all instances have the same +type. +

+Remember that in Python usage "type" refers to a C implementation +of an object. To distinguish among instances of different classes +use Instance.__class__, and also look to 4.47. Sorry for the +terminological confusion, but at this point in Python's development +nothing can be done! +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 1 12:35:47 1997 by +aaron watters +

+ +


+

6.23. Why isn't all memory freed when Python exits?

+Objects referenced from Python module global name spaces are +not always deallocated when Python exits. +

+This may happen if there are circular references (see question +4.17). There are also certain bits of memory that are allocated +by the C library that are impossible to free (e.g. a tool +like Purify will complain about these). +

+But in general, Python 1.5 and beyond +(in contrast with earlier versions) is quite agressive about +cleaning up memory on exit. +

+If you want to force Python to delete certain things on deallocation +use the sys.exitfunc hook to force those deletions. For example +if you are debugging an extension module using a memory analysis +tool and you wish to make Python deallocate almost everything +you might use an exitfunc like this one: +

+

+  import sys
+
+
+  def my_exitfunc():
+       print "cleaning up"
+       import sys
+       # do order dependant deletions here
+       ...
+       # now delete everything else in arbitrary order
+       for x in sys.modules.values():
+            d = x.__dict__
+            for name in d.keys():
+                 del d[name]
+
+
+  sys.exitfunc = my_exitfunc
+
+Other exitfuncs can be less drastic, of course. +

+(In fact, this one just does what Python now already does itself; +but the example of using sys.exitfunc to force cleanups is still +useful.) +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 29 09:46:26 1998 by +GvR +

+ +


+

6.24. Why no class methods or mutable class variables?

+The notation +

+

+    instance.attribute(arg1, arg2)
+
+usually translates to the equivalent of +

+

+    Class.attribute(instance, arg1, arg2)
+
+where Class is a (super)class of instance. Similarly +

+

+    instance.attribute = value
+
+sets an attribute of an instance (overriding any attribute of a class +that instance inherits). +

+Sometimes programmers want to have +different behaviours -- they want a method which does not bind +to the instance and a class attribute which changes in place. +Python does not preclude these behaviours, but you have to +adopt a convention to implement them. One way to accomplish +this is to use "list wrappers" and global functions. +

+

+   def C_hello():
+         print "hello"
+
+
+   class C:
+        hello = [C_hello]
+        counter = [0]
+
+
+    I = C()
+
+Here I.hello[0]() acts very much like a "class method" and +I.counter[0] = 2 alters C.counter (and doesn't override it). +If you don't understand why you'd ever want to do this, that's +because you are pure of mind, and you probably never will +want to do it! This is dangerous trickery, not recommended +when avoidable. (Inspired by Tim Peter's discussion.) +

+In Python 2.2, you can do this using the new built-in operations +classmethod and staticmethod. +See http://www.python.org/2.2/descrintro.html#staticmethods +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 15:59:37 2001 by +GvR +

+ +


+

6.25. Why are default values sometimes shared between objects?

+It is often expected that a function CALL creates new objects for default +values. This is not what happens. Default values are created when the +function is DEFINED, that is, there is only one such object that all +functions refer to. If that object is changed, subsequent calls to the +function will refer to this changed object. By definition, immutable objects +(like numbers, strings, tuples, None) are safe from change. Changes to mutable +objects (like dictionaries, lists, class instances) is what causes the +confusion. +

+Because of this feature it is good programming practice not to use mutable +objects as default values, but to introduce them in the function. +Don't write: +

+

+	def foo(dict={}):  # XXX shared reference to one dict for all calls
+	    ...
+
+but: +
+	def foo(dict=None):
+		if dict is None:
+			dict = {} # create a new dict for local namespace
+
+See page 182 of "Internet Programming with Python" for one discussion +of this feature. Or see the top of page 144 or bottom of page 277 in +"Programming Python" for another discussion. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 16 07:03:35 1997 by +Case Roole +

+ +


+

6.26. Why no goto?

+Actually, you can use exceptions to provide a "structured goto" +that even works across function calls. Many feel that exceptions +can conveniently emulate all reasonable uses of the "go" or "goto" +constructs of C, Fortran, and other languages. For example: +

+

+   class label: pass # declare a label
+   try:
+        ...
+        if (condition): raise label() # goto label
+        ...
+   except label: # where to goto
+        pass
+   ...
+
+This doesn't allow you to jump into the middle of a loop, but +that's usually considered an abuse of goto anyway. Use sparingly. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Sep 10 07:16:44 1997 by +aaron watters +

+ +


+

6.27. How do you make a higher order function in Python?

+You have two choices: you can use default arguments and override +them or you can use "callable objects." For example suppose you +wanted to define linear(a,b) which returns a function f where f(x) +computes the value a*x+b. Using default arguments: +

+

+     def linear(a,b):
+         def result(x, a=a, b=b):
+             return a*x + b
+         return result
+
+Or using callable objects: +

+

+     class linear:
+        def __init__(self, a, b):
+            self.a, self.b = a,b
+        def __call__(self, x):
+            return self.a * x + self.b
+
+In both cases: +

+

+     taxes = linear(0.3,2)
+
+gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2. +

+The defaults strategy has the disadvantage that the default arguments +could be accidentally or maliciously overridden. The callable objects +approach has the disadvantage that it is a bit slower and a bit +longer. Note however that a collection of callables can share +their signature via inheritance. EG +

+

+      class exponential(linear):
+         # __init__ inherited
+         def __call__(self, x):
+             return self.a * (x ** self.b)
+
+On comp.lang.python, zenin@bawdycaste.org points out that +an object can encapsulate state for several methods in order +to emulate the "closure" concept from functional programming +languages, for example: +

+

+    class counter:
+        value = 0
+        def set(self, x): self.value = x
+        def up(self): self.value=self.value+1
+        def down(self): self.value=self.value-1
+
+
+    count = counter()
+    inc, dec, reset = count.up, count.down, count.set
+
+Here inc, dec and reset act like "functions which share the +same closure containing the variable count.value" (if you +like that way of thinking). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Sep 25 08:38:35 1998 by +Aaron Watters +

+ +


+

6.28. Why do I get a SyntaxError for a 'continue' inside a 'try'?

+This is an implementation limitation, +caused by the extremely simple-minded +way Python generates bytecode. The try block pushes something on the +"block stack" which the continue would have to pop off again. The +current code generator doesn't have the data structures around so that +'continue' can generate the right code. +

+Note that JPython doesn't have this restriction! +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 22 15:01:07 1998 by +GvR +

+ +


+

6.29. Why can't raw strings (r-strings) end with a backslash?

+More precisely, they can't end with an odd number of backslashes: +the unpaired backslash at the end escapes the closing quote character, +leaving an unterminated string. +

+Raw strings were designed to ease creating input for processors (chiefly +regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose. +

+If you're trying to build Windows pathnames, note that all Windows system calls accept forward slashes too: +

+

+    f = open("/mydir/file.txt") # works fine!
+
+If you're trying to build a pathname for a DOS command, try e.g. one of +

+

+    dir = r"\this\is\my\dos\dir" "\\"
+    dir = r"\this\is\my\dos\dir\ "[:-1]
+    dir = "\\this\\is\\my\\dos\\dir\\"
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jul 13 20:50:20 1998 by +Tim Peters +

+ +


+

6.30. Why can't I use an assignment in an expression?

+Many people used to C or Perl complain that they want to be able to +use e.g. this C idiom: +

+

+    while (line = readline(f)) {
+        ...do something with line...
+    }
+
+where in Python you're forced to write this: +

+

+    while 1:
+        line = f.readline()
+        if not line:
+            break
+        ...do something with line...
+
+This issue comes up in the Python newsgroup with alarming frequency +-- search Deja News for past messages about assignment expression. +The reason for not allowing assignment in Python expressions +is a common, hard-to-find bug in those other languages, +caused by this construct: +

+

+    if (x = 0) {
+        ...error handling...
+    }
+    else {
+        ...code that only works for nonzero x...
+    }
+
+Many alternatives have been proposed. Most are hacks that save some +typing but use arbitrary or cryptic syntax or keywords, +and fail the simple criterion that I use for language change proposals: +it should intuitively suggest the proper meaning to a human reader +who has not yet been introduced with the construct. +

+The earliest time something can be done about this will be with +Python 2.0 -- if it is decided that it is worth fixing. +An interesting phenomenon is that most experienced Python programmers +recognize the "while 1" idiom and don't seem to be missing the +assignment in expression construct much; it's only the newcomers +who express a strong desire to add this to the language. +

+One fairly elegant solution would be to introduce a new operator +for assignment in expressions spelled ":=" -- this avoids the "=" +instead of "==" problem. It would have the same precedence +as comparison operators but the parser would flag combination with +other comparisons (without disambiguating parentheses) as an error. +

+Finally -- there's an alternative way of spelling this that seems +attractive but is generally less robust than the "while 1" solution: +

+

+    line = f.readline()
+    while line:
+        ...do something with line...
+        line = f.readline()
+
+The problem with this is that if you change your mind about exactly +how you get the next line (e.g. you want to change it into +sys.stdin.readline()) you have to remember to change two places +in your program -- the second one hidden at the bottom of the loop. +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 18 00:57:41 1999 by +Andrew Dalke +

+ +


+

6.31. Why doesn't Python have a "with" statement like some other languages?

+Basically, because such a construct would be terribly ambiguous. Thanks to Carlos Ribeiro for the following remarks: +

+Some languages, such as Object Pascal, Delphi, and C++, use static types. So it is possible to know, in an unambiguous way, what member is being assigned in a "with" clause. This is the main point - the compiler always knows the scope of every variable at compile time. +

+Python uses dynamic types. It is impossible to know in advance which +attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This would make it impossible to know, from a simple reading, what attribute is being referenced - a local one, a global one, or a member attribute. +

+For instance, take the following snippet (it is incomplete btw, just to +give you the idea): +

+

+   def with_is_broken(a):
+      with a:
+         print x
+
+The snippet assumes that "a" must have a member attribute called "x". +However, there is nothing in Python that guarantees that. What should +happen if "a" is, let us say, an integer? And if I have a global variable named "x", will it end up being used inside the with block? As you see, the dynamic nature of Python makes such choices much harder. +

+The primary benefit of "with" and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of: +

+

+    function(args).dict[index][index].a = 21
+    function(args).dict[index][index].b = 42
+    function(args).dict[index][index].c = 63
+
+would become: +

+

+    ref = function(args).dict[index][index]
+    ref.a = 21
+    ref.b = 42
+    ref.c = 63
+
+This also has the happy side-effect of increasing execution speed, since name bindings are resolved at run-time in Python, and the second method only needs to perform the resolution once. If the referenced object does not have a, b and c attributes, of course, the end result is still a run-time exception. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 11 14:32:58 2002 by +Steve Holden +

+ +


+

6.32. Why are colons required for if/while/def/class?

+The colon is required primarily to enhance readability (one of the +results of the experimental ABC language). Consider this: +

+

+    if a==b
+        print a
+
+versus +

+

+    if a==b:
+        print a
+
+Notice how the second one is slightly easier to read. Notice further how +a colon sets off the example in the second line of this FAQ answer; it's +a standard usage in English. Finally, the colon makes it easier for +editors with syntax highlighting. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:22:57 2002 by +Matthias Urlichs +

+ +


+

6.33. Can't we get rid of the Global Interpreter Lock?

+The Global Interpreter Lock (GIL) is often seen as a hindrance to +Python's deployment on high-end multiprocessor server machines, +because a multi-threaded Python program effectively only uses +one CPU, due to the insistence that (almost) all Python code +can only run while the GIL is held. +

+Back in the days of Python 1.5, Greg Stein actually implemented +a comprehensive patch set ("free threading") +that removed the GIL, replacing it with +fine-grained locking. Unfortunately, even on Windows (where locks +are very efficient) this ran ordinary Python code about twice as +slow as the interpreter using the GIL. On Linux the performance +loss was even worse (pthread locks aren't as efficient). +

+Since then, the idea of getting rid of the GIL has occasionally +come up but nobody has found a way to deal with the expected slowdown; +Greg's free threading patch set has not been kept up-to-date for +later Python versions. +

+This doesn't mean that you can't make good use of Python on +multi-CPU machines! You just have to be creative with dividing +the work up between multiple processes rather than multiple +threads. +

+

+It has been suggested that the GIL should be a per-interpreter-state +lock rather than truly global; interpreters then wouldn't be able +to share objects. Unfortunately, this isn't likely to happen either. +

+It would be a tremendous amount of work, because many object +implementations currently have global state. E.g. small ints and +small strings are cached; these caches would have to be moved to the +interpreter state. Other object types have their own free list; these +free lists would have to be moved to the interpreter state. And so +on. +

+And I doubt that it can even be done in finite time, because the same +problem exists for 3rd party extensions. It is likely that 3rd party +extensions are being written at a faster rate than you can convert +them to store all their global state in the interpreter state. +

+And finally, once you have multiple interpreters not sharing any +state, what have you gained over running each interpreter +in a separate process? +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:34:01 2003 by +GvR +

+ +


+

7. Using Python on non-UNIX platforms

+ +
+

7.1. Is there a Mac version of Python?

+Yes, it is maintained by Jack Jansen. See Jack's MacPython Page: +

+

+  http://www.cwi.nl/~jack/macpython.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Fri May 4 09:33:42 2001 by +GvR +

+ +


+

7.2. Are there DOS and Windows versions of Python?

+Yes. The core windows binaries are available from http://www.python.org/windows/. There is a plethora of Windows extensions available, including a large number of not-always-compatible GUI toolkits. The core binaries include the standard Tkinter GUI extension. +

+Most windows extensions can be found (or referenced) at http://www.python.org/windows/ +

+Windows 3.1/DOS support seems to have dropped off recently. You may need to settle for an old version of Python one these platforms. One such port is WPY +

+WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2. +Also contains a GUI package that offers portability between Windows +(not DOS) and Unix, and native look and feel on both. +ftp://ftp.python.org/pub/python/wpy/. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jun 2 20:21:57 1998 by +Mark Hammond +

+ +


+

7.3. Is there an OS/2 version of Python?

+Yes, see http://www.python.org/download/download_os2.html. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 7 11:33:16 1999 by +GvR +

+ +


+

7.4. Is there a VMS version of Python?

+Jean-François Piéronne has ported 2.1.3 to OpenVMS. It can be found at +<http://vmspython.dyndns.org/>. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 19 15:40:38 2002 by +Skip Montanaro +

+ +


+

7.5. What about IBM mainframes, or other non-UNIX platforms?

+I haven't heard about these, except I remember hearing about an +OS/9 port and a port to Vxworks (both operating systems for embedded +systems). If you're interested in any of this, go directly to the +newsgroup and ask there, you may find exactly what you need. For +example, a port to MPE/iX 5.0 on HP3000 computers was just announced, +see http://www.allegro.com/software/. +

+On the IBM mainframe side, for Z/OS there's a port of python 1.4 that goes with their open-unix package, formely OpenEdition MVS, (http://www-1.ibm.com/servers/eserver/zseries/zos/unix/python.html). On a side note, there's also a java vm ported - so, in theory, jython could run too. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Nov 18 03:18:39 2002 by +Bruno Jessen +

+ +


+

7.6. Where are the source or Makefiles for the non-UNIX versions?

+The standard sources can (almost) be used. Additional sources can +be found in the platform-specific subdirectories of the distribution. +

+ +Edit this entry / +Log info +

+ +


+

7.7. What is the status and support for the non-UNIX versions?

+I don't have access to most of these platforms, so in general I am +dependent on material submitted by volunteers. However I strive to +integrate all changes needed to get it to compile on a particular +platform back into the standard sources, so porting of the next +version to the various non-UNIX platforms should be easy. +(Note that Linux is classified as a UNIX platform here. :-) +

+Some specific platforms: +

+Windows: all versions (95, 98, ME, NT, 2000, XP) are supported, +all python.org releases come with a Windows installer. +

+MacOS: Jack Jansen does an admirable job of keeping the Mac version +up to date (both MacOS X and older versions); +see http://www.cwi.nl/~jack/macpython.html +

+For all supported platforms, see http://www.python.org/download/ +(follow the link to "Other platforms" for less common platforms) +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:34:24 2002 by +GvR +

+ +


+

7.8. I have a PC version but it appears to be only a binary. Where's the library?

+If you are running any version of Windows, then you have the wrong distribution. The FAQ lists current Windows versions. Notably, Pythonwin and wpy provide fully functional installations. +

+But if you are sure you have the only distribution with a hope of working on +your system, then... +

+You still need to copy the files from the distribution directory +"python/Lib" to your system. If you don't have the full distribution, +you can get the file lib<version>.tar.gz from most ftp sites carrying +Python; this is a subset of the distribution containing just those +files, e.g. ftp://ftp.python.org/pub/python/src/lib1.4.tar.gz. +

+Once you have installed the library, you need to point sys.path to it. +Assuming the library is in C:\misc\python\lib, the following commands +will point your Python interpreter to it (note the doubled backslashes +-- you can also use single forward slashes instead): +

+

+        >>> import sys
+        >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
+        >>>
+
+For a more permanent effect, set the environment variable PYTHONPATH, +as follows (talking to a DOS prompt): +

+

+        C> SET PYTHONPATH=C:\misc\python\lib
+
+

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 16:28:27 1997 by +Ken Manheimer +

+ +


+

7.9. Where's the documentation for the Mac or PC version?

+The documentation for the Unix version also applies to the Mac and +PC versions. Where applicable, differences are indicated in the text. +

+ +Edit this entry / +Log info +

+ +


+

7.10. How do I create a Python program file on the Mac or PC?

+Use an external editor. On the Mac, BBEdit seems to be a popular +no-frills text editor. I work like this: start the interpreter; edit +a module file using BBedit; import and test it in the interpreter; +edit again in BBedit; then use the built-in function reload() to +re-read the imported module; etc. In the 1.4 distribution +you will find a BBEdit extension that makes life a little easier: +it can tell the interpreter to execute the current window. +See :Mac:Tools:BBPy:README. +

+Regarding the same question for the PC, Kurt Wm. Hemr writes: "While +anyone with a pulse could certainly figure out how to do the same on +MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows. +Not only can you easily resave and "reload()" from Python after making +changes, but since WinNot auto-copies to the clipboard any text you +select, you can simply select the entire procedure (function) which +you changed in WinNot, switch to QWPython, and shift-ins to reenter +the changed program unit." +

+If you're using Windows95 or Windows NT, you should also know about +PythonWin, which provides a GUI framework, with an mouse-driven +editor, an object browser, and a GUI-based debugger. See +

+       http://www.python.org/ftp/python/pythonwin/
+
+for details. +

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 10:04:25 1997 by +GvR +

+ +


+

7.11. How can I use Tkinter on Windows 95/NT?

+Starting from Python 1.5, it's very easy -- just download and install +Python and Tcl/Tk and you're in business. See +

+

+  http://www.python.org/download/download_windows.html
+
+One warning: don't attempt to use Tkinter from PythonWin +(Mark Hammond's IDE). Use it from the command line interface +(python.exe) or the windowless interpreter (pythonw.exe). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:32:48 1998 by +GvR +

+ +


+

7.12. cgi.py (or other CGI programming) doesn't work sometimes on NT or win95!

+Be sure you have the latest python.exe, that you are using +python.exe rather than a GUI version of python and that you +have configured the server to execute +

+

+     "...\python.exe -u ..."
+
+for the cgi execution. The -u (unbuffered) option on NT and +win95 prevents the interpreter from altering newlines in the +standard input and output. Without it post/multipart requests +will seem to have the wrong length and binary (eg, GIF) +responses may get garbled (resulting in, eg, a "broken image"). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jul 30 10:48:02 1997 by +aaron watters +

+ +


+

7.13. Why doesn't os.popen() work in PythonWin on NT?

+The reason that os.popen() doesn't work from within PythonWin is due to a bug in Microsoft's C Runtime Library (CRT). The CRT assumes you have a Win32 console attached to the process. +

+You should use the win32pipe module's popen() instead which doesn't depend on having an attached Win32 console. +

+Example: +

+ import win32pipe
+ f = win32pipe.popen('dir /c c:\\')
+ print f.readlines()
+ f.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 31 15:34:09 1997 by +Bill Tutt +

+ +


+

7.14. How do I use different functionality on different platforms with the same program?

+Remember that Python is extremely dynamic and that you +can use this dynamism to configure a program at run-time to +use available functionality on different platforms. For example +you can test the sys.platform and import different modules based +on its value. +

+

+   import sys
+   if sys.platform == "win32":
+      import win32pipe
+      popen = win32pipe.popen
+   else:
+      import os
+      popen = os.popen
+
+(See FAQ 7.13 for an explanation of why you might want to +do something like this.) Also you can try to import a module +and use a fallback if the import fails: +

+

+    try:
+         import really_fast_implementation
+         choice = really_fast_implementation
+    except ImportError:
+         import slower_implementation
+         choice = slower_implementation
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:39:06 1997 by +aaron watters +

+ +


+

7.15. Is there an Amiga version of Python?

+Yes. See the AmigaPython homepage at http://www.bigfoot.com/~irmen/python.html. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 14 06:53:32 1998 by +Irmen de Jong +

+ +


+

7.16. Why doesn't os.popen()/win32pipe.popen() work on Win9x?

+There is a bug in Win9x that prevents os.popen/win32pipe.popen* from working. The good news is there is a way to work around this problem. +The Microsoft Knowledge Base article that you need to lookup is: Q150956. You will find links to the knowledge base at: +http://www.microsoft.com/kb. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 25 10:45:38 1999 by +Bill Tutt +

+ +


+

8. Python on Windows

+ +
+

8.1. Using Python for CGI on Microsoft Windows

+** Setting up the Microsoft IIS Server/Peer Server +

+On the Microsoft IIS +server or on the Win95 MS Personal Web Server +you set up python in the same way that you +would set up any other scripting engine. +

+Run regedt32 and go to: +

+HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap +

+and enter the following line (making any specific changes that your system may need) +

+.py :REG_SZ: c:\<path to python>\python.exe -u %s %s +

+This line will allow you to call your script with a simple reference like: +http://yourserver/scripts/yourscript.py +provided "scripts" is an "executable" directory for your server (which +it usually is by default). +The "-u" flag specifies unbuffered and binary mode for stdin - needed when working with binary data +

+In addition, it is recommended by people who would know that using ".py" may +not be a good idea for the file extensions when used in this context +(you might want to reserve *.py for support modules and use *.cgi or *.cgp +for "main program" scripts). +However, that issue is beyond this Windows FAQ entry. +

+

+** Apache configuration +

+In the Apache configuration file httpd.conf, add the following line at +the end of the file: +

+ScriptInterpreterSource Registry +

+Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin directory. +

+

+** Netscape Servers: +Information on this topic exists at: +http://home.netscape.com/comprod/server_central/support/fasttrack_man/programs.htm#1010870 +

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 27 12:25:54 2002 by +Gerhard Häring +

+ +


+

8.2. How to check for a keypress without blocking?

+Use the msvcrt module. This is a standard Windows-specific extensions +in Python 1.5 and beyond. It defines a function kbhit() which checks +whether a keyboard hit is present; also getch() which gets one +character without echo. Plus a few other goodies. +

+(Search for "keypress" to find an answer for Unix as well.) +

+ +Edit this entry / +Log info + +/ Last changed on Mon Mar 30 16:21:46 1998 by +GvR +

+ +


+

8.3. $PYTHONPATH

+In MS-DOS derived environments, a unix variable such as $PYTHONPATH is +set as PYTHONPATH, without the dollar sign. PYTHONPATH is useful for +specifying the location of library files. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 11 00:41:26 1998 by +Gvr +

+ +


+

8.4. dedent syntax errors

+The FAQ does not recommend using tabs, and Guido's Python Style Guide recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default; see +

+

+    http://www.python.org/doc/essays/styleguide.html
+
+Under any editor mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools -> Options -> Tabs, and for file type "Default" set "Tab size" and "Indent size" to 4, and select the "Insert spaces" radio button. +

+If you suspect mixed tabs and spaces are causing problems in leading whitespace, run Python with the -t switch or, run Tools/Scripts/tabnanny.py to check a directory tree in batch mode. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 12 15:04:14 2001 by +Steve Holden +

+ +


+

8.5. How do I emulate os.kill() in Windows?

+Use win32api: +

+

+    def kill(pid):
+        """kill function for Win32"""
+        import win32api
+        handle = win32api.OpenProcess(1, 0, pid)
+        return (0 != win32api.TerminateProcess(handle, 0))
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 8 18:55:06 1998 by +Jeff Bauer +

+ +


+

8.6. Why does os.path.isdir() fail on NT shared directories?

+The solution appears to be always append the "\\" on +the end of shared drives. +

+

+  >>> import os
+  >>> os.path.isdir( '\\\\rorschach\\public')
+  0
+  >>> os.path.isdir( '\\\\rorschach\\public\\')
+  1
+
+[Blake Winton responds:] +I've had the same problem doing "Start >> Run" and then a +directory on a shared drive. If I use "\\rorschach\public", +it will fail, but if I use "\\rorschach\public\", it will +work. For that matter, os.stat() does the same thing (well, +it gives an error for "\\\\rorschach\\public", but you get +the idea)... +

+I've got a theory about why this happens, but it's only +a theory. NT knows the difference between shared directories, +and regular directories. "\\rorschach\public" isn't a +directory, it's _really_ an IPC abstraction. This is sort +of lended credence to by the fact that when you're mapping +a network drive, you can't map "\\rorschach\public\utils", +but only "\\rorschach\public". +

+[Clarification by funkster@midwinter.com] +It's not actually a Python +question, as Python is working just fine; it's clearing up something +a bit muddled about Windows networked drives. +

+It helps to think of share points as being like drive letters. +Example: +

+        k: is not a directory
+        k:\ is a directory
+        k:\media is a directory
+        k:\media\ is not a directory
+
+The same rules apply if you substitute "k:" with "\\conky\foo": +
+        \\conky\foo  is not a directory
+        \\conky\foo\ is a directory
+        \\conky\foo\media is a directory
+        \\conky\foo\media\ is not a directory
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sun Jan 31 08:44:48 1999 by +GvR +

+ +


+

8.7. PyRun_SimpleFile() crashes on Windows but not on Unix

+I've seen a number of reports of PyRun_SimpleFile() failing +in a Windows port of an application embedding Python that worked +fine on Unix. PyRun_SimpleString() works fine on both platforms. +

+I think this happens because the application was compiled with a +different set of compiler flags than Python15.DLL. It seems that some +compiler flags affect the standard I/O library in such a way that +using different flags makes calls fail. You need to set it for +the non-debug multi-threaded DLL (/MD on the command line, or can be set via MSVC under Project Settings->C++/Code Generation then the "Use rum-time library" dropdown.) +

+Also note that you can not mix-and-match Debug and Release versions. If you wish to use the Debug Multithreaded DLL, then your module _must_ have an "_d" appended to the base name. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Nov 17 17:37:07 1999 by +Mark Hammond +

+ +


+

8.8. Import of _tkinter fails on Windows 95/98

+Sometimes, the import of _tkinter fails on Windows 95 or 98, +complaining with a message like the following: +

+

+  ImportError: DLL load failed: One of the library files needed
+  to run this application cannot be found.
+
+It could be that you haven't installed Tcl/Tk, but if you did +install Tcl/Tk, and the Wish application works correctly, +the problem may be that its installer didn't +manage to edit the autoexec.bat file correctly. It tries to add a +statement that changes the PATH environment variable to include +the Tcl/Tk 'bin' subdirectory, but sometimes this edit doesn't +quite work. Opening it with notepad usually reveals what the +problem is. +

+(One additional hint, noted by David Szafranski: you can't use +long filenames here; e.g. use C:\PROGRA~1\Tcl\bin instead of +C:\Program Files\Tcl\bin.) +

+ +Edit this entry / +Log info + +/ Last changed on Wed Dec 2 22:32:41 1998 by +GvR +

+ +


+

8.9. Can't extract the downloaded documentation on Windows

+Sometimes, when you download the documentation package to a Windows +machine using a web browser, the file extension of the saved file +ends up being .EXE. This is a mistake; the extension should be .TGZ. +

+Simply rename the downloaded file to have the .TGZ extension, and +WinZip will be able to handle it. (If your copy of WinZip doesn't, +get a newer one from http://www.winzip.com.) +

+ +Edit this entry / +Log info + +/ Last changed on Sat Nov 21 13:41:35 1998 by +GvR +

+ +


+

8.10. Can't get Py_RunSimpleFile() to work.

+This is very sensitive to the compiler vendor, version and (perhaps) +even options. If the FILE* structure in your embedding program isn't +the same as is assumed by the Python interpreter it won't work. +

+The Python 1.5.* DLLs (python15.dll) are all compiled +with MS VC++ 5.0 and with multithreading-DLL options (/MD, I think). +

+If you can't change compilers or flags, try using Py_RunSimpleString(). +A trick to get it to run an arbitrary file is to construct a call to +execfile() with the name of your file as argument. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 13 10:58:14 1999 by +GvR +

+ +


+

8.11. Where is Freeze for Windows?

+("Freeze" is a program that allows you to ship a Python program +as a single stand-alone executable file. It is not a compiler, +your programs don't run any faster, but they are more easily +distributable (to platforms with the same OS and CPU). Read the +README file of the freeze program for more disclaimers.) +

+You can use freeze on Windows, but you must download the source +tree (see http://www.python.org/download/download_source.html). +This is recommended for Python 1.5.2 (and betas thereof) only; +older versions don't quite work. +

+You need the Microsoft VC++ 5.0 compiler (maybe it works with +6.0 too). You probably need to build Python -- the project files +are all in the PCbuild directory. +

+The freeze program is in the Tools\freeze subdirectory of the source +tree. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 17 18:47:24 1999 by +GvR +

+ +


+

8.12. Is a *.pyd file the same as a DLL?

+Yes, .pyd files are dll's. But there are a few differences. If you +have a DLL named foo.pyd, then it must have a function initfoo(). You +can then write Python "import foo", and Python will search for foo.pyd +(as well as foo.py, foo.pyc) and if it finds it, will attempt to call +initfoo() to initialize it. You do not link your .exe with foo.lib, +as that would cause Windows to require the DLL to be present. +

+Note that the search path for foo.pyd is PYTHONPATH, not the same as +the path that Windows uses to search for foo.dll. Also, foo.pyd need +not be present to run your program, whereas if you linked your program +with a dll, the dll is required. Of course, foo.pyd is required if +you want to say "import foo". In a dll, linkage is declared in the +source code with __declspec(dllexport). In a .pyd, linkage is defined +in a list of available functions. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Nov 23 02:40:08 1999 by +Jameson Quinn +

+ +


+

8.13. Missing cw3215mt.dll (or missing cw3215.dll)

+Sometimes, when using Tkinter on Windows, you get an error that +cw3215mt.dll or cw3215.dll is missing. +

+Cause: you have an old Tcl/Tk DLL built with cygwin in your path +(probably C:\Windows). You must use the Tcl/Tk DLLs from the +standard Tcl/Tk installation (Python 1.5.2 comes with one). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 11 00:54:13 1999 by +GvR +

+ +


+

8.14. How to make python scripts executable:

+[Blake Coverett] +

+Win2K: +

+The standard installer already associates the .py extension with a file type +(Python.File) and gives that file type an open command that runs the +interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to +make scripts executable from the command prompt as 'foo.py'. If you'd +rather be able to execute the script by simple typing 'foo' with no +extension you need to add .py to the PATHEXT environment variable. +

+WinNT: +

+The steps taken by the installed as described above allow you do run a +script with 'foo.py', but a long time bug in the NT command processor +prevents you from redirecting the input or output of any script executed in +this way. This is often important. +

+An appropriate incantation for making a Python script executable under WinNT +is to give the file an extension of .cmd and add the following as the first +line: +

+

+    @setlocal enableextensions & python -x %~f0 %* & goto :EOF
+
+Win9x: +

+[Due to Bruce Eckel] +

+

+  @echo off
+  rem = """
+  rem run python on this bat file. Needs the full path where
+  rem you keep your python files. The -x causes python to skip
+  rem the first line of the file:
+  python -x c:\aaa\Python\\"%0".bat %1 %2 %3 %4 %5 %6 %7 %8 %9
+  goto endofpython
+  rem """
+
+
+  # The python program goes here:
+
+
+  print "hello, Python"
+
+
+  # For the end of the batch file:
+  rem = """
+  :endofpython
+  rem """
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Nov 30 10:25:17 1999 by +GvR +

+ +


+

8.15. Warning about CTL3D32 version from installer

+The Python installer issues a warning like this: +

+

+  This version uses CTL3D32.DLL whitch is not the correct version.
+  This version is used for windows NT applications only.
+
+[Tim Peters] +This is a Microsoft DLL, and a notorious +source of problems. The msg means what it says: you have the wrong version +of this DLL for your operating system. The Python installation did not +cause this -- something else you installed previous to this overwrote the +DLL that came with your OS (probably older shareware of some sort, but +there's no way to tell now). If you search for "CTL3D32" using any search +engine (AltaVista, for example), you'll find hundreds and hundreds of web +pages complaining about the same problem with all sorts of installation +programs. They'll point you to ways to get the correct version reinstalled +on your system (since Python doesn't cause this, we can't fix it). +

+David A Burton has written a little program to fix this. Go to +http://www.burtonsys.com/download.html and click on "ctl3dfix.zip" +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 26 15:42:00 2000 by +GvR +

+ +


+

8.16. How can I embed Python into a Windows application?

+Edward K. Ream <edream@tds.net> writes +

+When '##' appears in a file name below, it is an abbreviated version number. For example, for Python 2.1.1, ## will be replaced by 21. +

+Embedding the Python interpreter in a Windows app can be summarized as +follows: +

+1. Do _not_ build Python into your .exe file directly. On Windows, +Python must be a DLL to handle importing modules that are themselves +DLL's. (This is the first key undocumented fact.) Instead, link to +python##.dll; it is typically installed in c:\Windows\System. +

+You can link to Python statically or dynamically. Linking statically +means linking against python##.lib The drawback is that your app won't +run if python##.dll does not exist on your system. +

+General note: python##.lib is the so-called "import lib" corresponding +to python.dll. It merely defines symbols for the linker. +

+Borland note: convert python##.lib to OMF format using Coff2Omf.exe +first. +

+Linking dynamically greatly simplifies link options; everything happens +at run time. Your code must load python##.dll using the Windows +LoadLibraryEx() routine. The code must also use access routines and +data in python##.dll (that is, Python's C API's) using pointers +obtained by the Windows GetProcAddress() routine. Macros can make +using these pointers transparent to any C code that calls routines in +Python's C API. +

+2. If you use SWIG, it is easy to create a Python "extension module" +that will make the app's data and methods available to Python. SWIG +will handle just about all the grungy details for you. The result is C +code that you link _into your .exe file_ (!) You do _not_ have to +create a DLL file, and this also simplifies linking. +

+3. SWIG will create an init function (a C function) whose name depends +on the name of the extension module. For example, if the name of the +module is leo, the init function will be called initleo(). If you use +SWIG shadow classes, as you should, the init function will be called +initleoc(). This initializes a mostly hidden helper class used by the +shadow class. +

+The reason you can link the C code in step 2 into your .exe file is that +calling the initialization function is equivalent to importing the +module into Python! (This is the second key undocumented fact.) +

+4. In short, you can use the following code to initialize the Python +interpreter with your extension module. +

+

+    #include "python.h"
+    ...
+    Py_Initialize();  // Initialize Python.
+    initmyAppc();  // Initialize (import) the helper class. 
+    PyRun_SimpleString("import myApp") ;  // Import the shadow class.
+
+5. There are two problems with Python's C API which will become apparent +if you use a compiler other than MSVC, the compiler used to build +python##.dll. +

+Problem 1: The so-called "Very High Level" functions that take FILE * +arguments will not work in a multi-compiler environment; each compiler's +notion of a struct FILE will be different. From an implementation +standpoint these are very _low_ level functions. +

+Problem 2: SWIG generates the following code when generating wrappers to +void functions: +

+

+    Py_INCREF(Py_None);
+    _resultobj = Py_None;
+    return _resultobj;
+
+Alas, Py_None is a macro that expands to a reference to a complex data +structure called _Py_NoneStruct inside python##.dll. Again, this code +will fail in a mult-compiler environment. Replace such code by: +

+

+    return Py_BuildValue("");
+
+It may be possible to use SWIG's %typemap command to make the change +automatically, though I have not been able to get this to work (I'm a +complete SWIG newbie). +

+6. Using a Python shell script to put up a Python interpreter window +from inside your Windows app is not a good idea; the resulting window +will be independent of your app's windowing system. Rather, you (or the +wxPythonWindow class) should create a "native" interpreter window. It +is easy to connect that window to the Python interpreter. You can +redirect Python's i/o to _any_ object that supports read and write, so +all you need is a Python object (defined in your extension module) that +contains read() and write() methods. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 31 16:29:34 2002 by +Victor Kryukov +

+ +


+

8.17. Setting up IIS 5 to use Python for CGI

+In order to set up Internet Information Services 5 to use Python for CGI processing, please see the following links: +

+http://www.e-coli.net/pyiis_server.html (for Win2k Server) +http://www.e-coli.net/pyiis.html (for Win2k pro) +

+ +Edit this entry / +Log info + +/ Last changed on Fri Mar 22 22:05:51 2002 by +douglas savitsky +

+ +


+

8.18. How do I run a Python program under Windows?

+This is not necessarily quite the straightforward question it appears +to be. If you are already familiar with running programs from the +Windows command line then everything will seem really easy and +obvious. If your computer experience is limited then you might need a +little more guidance. Also there are differences between Windows 95, +98, NT, ME, 2000 and XP which can add to the confusion. You might +think of this as "why I pay software support charges" if you have a +helpful and friendly administrator to help you set things up without +having to understand all this yourself. If so, then great! Show them +this page and it should be a done deal. +

+Unless you use some sort of integrated development environment (such +as PythonWin or IDLE, to name only two in a growing family) then you +will end up typing Windows commands into what is variously referred +to as a "DOS window" or "Command prompt window". Usually you can +create such a window from your Start menu (under Windows 2000 I use +"Start | Programs | Accessories | Command Prompt"). You should be +able to recognize when you have started such a window because you will +see a Windows "command prompt", which usually looks like this: +

+

+    C:\>
+
+The letter may be different, and there might be other things after it, +so you might just as easily see something like: +

+

+    D:\Steve\Projects\Python>
+
+depending on how your computer has been set up and what else you have +recently done with it. Once you have started such a window, you are +well on the way to running Python programs. +

+You need to realize that your Python scripts have to be processed by +another program, usually called the "Python interpreter". The +interpreter reads your script, "compiles" it into "Python bytecodes" +(which are instructions for an imaginary computer known as the "Python +Virtual Machine") and then executes the bytecodes to run your +program. So, how do you arrange for the interpreter to handle your +Python? +

+First, you need to make sure that your command window recognises the +word "python" as an instruction to start the interpreter. If you have +opened a command window, you should try entering the command: +

+

+    python
+
+and hitting return. If you then see something like: +

+

+    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
+    Type "help", "copyright", "credits" or "license" for more information.
+    >>>
+
+then this part of the job has been correctly managed during Python's +installation process, and you have started the interpreter in +"interactive mode". That means you can enter Python statements or +expressions interactively and have them executed or evaluated while +you wait. This is one of Python's strongest features, but it takes a +little getting used to. Check it by entering a few expressions of your +choice and seeing the results... +

+

+    >>> print "Hello"
+    Hello
+    >>> "Hello" * 3
+    HelloHelloHello
+
+When you want to end your interactive Python session, enter a +terminator (hold the Ctrl key down while you enter a Z, then hit the +"Enter" key) to get back to your Windows command prompt. You may also +find that you have a Start-menu entry such as "Start | Programs | +Python 2.2 | Python (command line)" that results in you seeing the +">>>" prompt in a new window. If so, the window will disappear after +you enter the terminator -- Windows runs a single "python" command in +the window, which terminates when you terminate the interpreter. +

+If the "python" command, instead of displaying the interpreter prompt ">>>", gives you a message like +

+

+    'python' is not recognized as an internal or external command,
+    operable program or batch file.
+
+or +

+

+    Bad command or filename
+
+then you need to make sure that your computer knows where to find the +Python interpreter. To do this you will have to modify a setting +called the PATH, which is a just list of directories where Windows +will look for programs. Rather than just enter the right command every +time you create a command window, you should arrange for Python's +installation directory to be added to the PATH of every command window +as it starts. If you installed Python fairly recently then the command +

+

+    dir C:\py*
+
+will probably tell you where it is installed. Alternatively, perhaps +you made a note. Otherwise you will be reduced to a search of your +whole disk ... break out the Windows explorer and use "Tools | Find" +or hit the "Search" button and look for "python.exe". Suppose you +discover that Python is installed in the C:\Python22 directory (the +default at the time of writing) then you should make sure that +entering the command +

+

+    c:\Python22\python
+
+starts up the interpreter as above (and don't forget you'll need a +"CTRL-Z" and an "Enter" to get out of it). Once you have verified the +directory, you need to add it to the start-up routines your computer +goes through. For older versions of Windows the easiest way to do +this is to edit the C:\AUTOEXEC.BAT file. You would want to add a line +like the following to AUTOEXEC.BAT: +

+

+    PATH C:\Python22;%PATH%
+
+For Windows NT, 2000 and (I assume) XP, you will need to add a string +such as +

+

+    ;C:\Python22
+
+to the current setting for the PATH environment variable, which you +will find in the properties window of "My Computer" under the +"Advanced" tab. Note that if you have sufficient privilege you might +get a choice of installing the settings either for the Current User or +for System. The latter is preferred if you want everybody to be able +to run Python on the machine. +

+If you aren't confident doing any of these manipulations yourself, ask +for help! At this stage you may or may not want to reboot your system +to make absolutely sure the new setting has "taken" (don't you love +the way Windows gives you these freqeuent coffee breaks). You probably +won't need to for Windows NT, XP or 2000. You can also avoid it in +earlier versions by editing the file C:\WINDOWS\COMMAND\CMDINIT.BAT +instead of AUTOEXEC.BAT. +

+You should now be able to start a new command window, enter +

+

+    python
+
+at the "C:>" (or whatever) prompt, and see the ">>>" prompt that +indicates the Python interpreter is reading interactive commands. +

+Let's suppose you have a program called "pytest.py" in directory +"C:\Steve\Projects\Python". A session to run that program might look +like this: +

+

+    C:\> cd \Steve\Projects\Python
+    C:\Steve\Projects\Python> python pytest.py
+
+Because you added a file name to the command to start the interpreter, +when it starts up it reads the Python script in the named file, +compiles it, executes it, and terminates (so you see another "C:\>" +prompt). You might also have entered +

+

+    C:\> python \Steve\Projects\Python\pytest.py
+
+if you hadn't wanted to change your current directory. +

+Under NT, 2000 and XP you may well find that the installation process +has also arranged that the command +

+

+    pytest.py
+
+(or, if the file isn't in the current directory) +

+

+    C:\Steve\Projects\Python\pytest.py
+
+will automatically recognize the ".py" extension and run the Python +interpreter on the named file. Using this feature is fine, but some +versions of Windows have bugs which mean that this form isn't exactly +equivalent to using the interpreter explicitly, so be careful. Easier +to remember, for now, that +

+

+    python C:\Steve\Projects\Python\pytest.py
+
+works pretty close to the same, and redirection will work (more) +reliably. +

+The important things to remember are: +

+1. Start Python from the Start Menu, or make sure the PATH is set +correctly so Windows can find the Python interpreter. +

+

+    python
+
+should give you a '>>>" prompt from the Python interpreter. Don't +forget the CTRL-Z and ENTER to terminate the interpreter (and, if you +started the window from the Start Menu, make the window disappear). +

+2. Once this works, you run programs with commands: +

+

+    python {program-file}
+
+3. When you know the commands to use you can build Windows shortcuts +to run the Python interpreter on any of your scripts, naming +particular working directories, and adding them to your menus, but +that's another lessFAQ. Take a look at +

+

+    python --help
+
+if your needs are complex. +

+4. Interactive mode (where you see the ">>>" prompt) is best used +not for running programs, which are better executed as in steps 2 +and 3, but for checking that individual statements and expressions do +what you think they will, and for developing code by experiment. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Aug 20 16:19:53 2002 by +GvR +

+ +


+Python home / +Python FAQ Wizard 1.0.3 / +Feedback to GvR +

Python Powered
+ + --- python2.7-2.7.6.orig/debian/PVER-dbg.README.Debian.in +++ python2.7-2.7.6/debian/PVER-dbg.README.Debian.in @@ -0,0 +1,58 @@ +Contents of the @PVER@-dbg package +------------------------------------- + +For debugging python and extension modules, you may want to add the contents +of /usr/share/doc/@PVER@/gdbinit (found in the @PVER@-dev package) to your +~/.gdbinit file. + +@PVER@-dbg contains two sets of packages: + + - debugging symbols for the standard @PVER@ build. When this package + is installed, gdb will automatically load up the debugging symbols + from it when debugging @PVER@ or one of the included extension + modules. + + - a separate @PVER@-dbg binary, configured --with-pydebug, enabling the + additional debugging code to help debug memory management problems. + +For the latter, all extension modules have to be recompiled to +correctly load with an pydebug enabled build. + + +Debian and Ubuntu specific changes to the debug interpreter +----------------------------------------------------------- +The python2.4 and python2.5 packages in Ubuntu feisty are modified to +first look for extension modules under a different name. + + normal build: foo.so + debug build: foo_d.so foo.so + +This naming schema allows installation of the extension modules into +the same path (The naming is directly taken from the Windows builds +which already uses this naming scheme). + +See https://wiki.ubuntu.com/PyDbgBuilds for more information. + + +Using the python-dbg builds +--------------------------- + + * Call the python-dbg or the pythonX.Y-dbg binaries instead of the + python or pythonX.Y binaries. + + * Debugging a third party extension requires the availabilty of the + extension built for the debug interpreter. For an extension `foo' + make sure that the `python-foo-dbg' package is installed, or else + the interpreter falls back to the extension for the normal build. + The error on fallback is expected. + + * Properties of the debug build are described in + /usr/share/doc/@PVER@/SpecialBuilds.txt.gz. + The debug interpreter is built with Py_DEBUG defined. + + * From SpecialBuilds.txt: This is what is generally meant by "a debug + build" of Python. Py_DEBUG implies LLTRACE, Py_REF_DEBUG, + Py_TRACE_REFS, and PYMALLOC_DEBUG (if WITH_PYMALLOC is enabled). + In addition, C assert()s are enabled (via the C way: by not defining + NDEBUG), and some routines do additional sanity checks inside + "#ifdef Py_DEBUG" blocks. --- python2.7-2.7.6.orig/debian/PVER-dbg.overrides.in +++ python2.7-2.7.6/debian/PVER-dbg.overrides.in @@ -0,0 +1,11 @@ +@PVER@-dbg binary: package-name-doesnt-match-sonames +@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink + +# no, it's not unusual +@PVER@-dbg binary: unusual-interpreter + +# just the gdb debug file +@PVER@-dbg binary: python-script-but-no-python-dep + +# pointless lintian ... +@PVER@-dbg binary: hardening-no-fortify-functions --- python2.7-2.7.6.orig/debian/PVER-dbg.postinst.in +++ python2.7-2.7.6/debian/PVER-dbg.postinst.in @@ -0,0 +1,19 @@ +#! /bin/sh + +set -e + +if [ "$1" = configure ]; then + files=$(dpkg -L lib@PVER@-dbg | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + if [ -n "$files" ]; then + @PVER@ -E -S /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + @PVER@ -E -S -O /usr/lib/@PVER@/py_compile.py $files + fi + else + echo >&2 "@PVER@-dbg: can't get files for byte-compilation" + fi +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/PVER-dbg.prerm.in +++ python2.7-2.7.6/debian/PVER-dbg.prerm.in @@ -0,0 +1,28 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + rm -f /usr/lib/debug/usr/bin/@PVER@-gdb.py[co] + rm -f /usr/lib/debug/usr/lib/lib@PVER@.so.1.0-gdb.py[co] + dpkg -L lib@PVER@-dbg \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + upgrade) + dpkg -L lib@PVER@-dbg \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-api.in @@ -0,0 +1,13 @@ +Document: @PVER@-api +Title: Python/C API Reference Manual (v@VER@) +Author: Guido van Rossum +Abstract: This manual documents the API used by C (or C++) programmers who + want to write extension modules or embed Python. It is a + companion to *Extending and Embedding the Python Interpreter*, + which describes the general principles of extension writing but + does not document the API functions in detail. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/c-api/index.html +Files: /usr/share/doc/@PVER@/html/c-api/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-dist.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-dist.in @@ -0,0 +1,13 @@ +Document: @PVER@-dist +Title: Distributing Python Modules (v@VER@) +Author: Greg Ward +Abstract: This document describes the Python Distribution Utilities + (``Distutils'') from the module developer's point-of-view, describing + how to use the Distutils to make Python modules and extensions easily + available to a wider audience with very little overhead for + build/release/install mechanics. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/distutils/index.html +Files: /usr/share/doc/@PVER@/html/distutils/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-ext.in @@ -0,0 +1,16 @@ +Document: @PVER@-ext +Title: Extending and Embedding the Python Interpreter (v@VER@) +Author: Guido van Rossum +Abstract: This document describes how to write modules in C or C++ to extend + the Python interpreter with new modules. Those modules can define + new functions but also new object types and their methods. The + document also describes how to embed the Python interpreter in + another application, for use as an extension language. Finally, + it shows how to compile and link extension modules so that they + can be loaded dynamically (at run time) into the interpreter, if + the underlying operating system supports this feature. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/extending/index.html +Files: /usr/share/doc/@PVER@/html/extending/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-inst.in @@ -0,0 +1,12 @@ +Document: @PVER@-inst +Title: Installing Python Modules (v@VER@) +Author: Greg Ward +Abstract: This document describes the Python Distribution Utilities + (``Distutils'') from the end-user's point-of-view, describing how to + extend the capabilities of a standard Python installation by building + and installing third-party Python modules and extensions. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/install/index.html +Files: /usr/share/doc/@PVER@/html/install/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-lib.in @@ -0,0 +1,15 @@ +Document: @PVER@-lib +Title: Python Library Reference (v@VER@) +Author: Guido van Rossum +Abstract: This library reference manual documents Python's standard library, + as well as many optional library modules (which may or may not be + available, depending on whether the underlying platform supports + them and on the configuration choices made at compile time). It + also documents the standard types of the language and its built-in + functions and exceptions, many of which are not or incompletely + documented in the Reference Manual. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/library/index.html +Files: /usr/share/doc/@PVER@/html/library/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-new.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-new.in @@ -0,0 +1,10 @@ +Document: @PVER@-new +Title: What's new in Python @VER@ +Author: A.M. Kuchling +Abstract: This documents lists new features and changes worth mentioning + in Python @VER@. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/whatsnew/@VER@.html +Files: /usr/share/doc/@PVER@/html/whatsnew/@VER@.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-ref.in @@ -0,0 +1,18 @@ +Document: @PVER@-ref +Title: Python Reference Manual (v@VER@) +Author: Guido van Rossum +Abstract: This reference manual describes the syntax and "core semantics" of + the language. It is terse, but attempts to be exact and complete. + The semantics of non-essential built-in object types and of the + built-in functions and modules are described in the *Python + Library Reference*. For an informal introduction to the language, + see the *Python Tutorial*. For C or C++ programmers, two + additional manuals exist: *Extending and Embedding the Python + Interpreter* describes the high-level picture of how to write a + Python extension module, and the *Python/C API Reference Manual* + describes the interfaces available to C/C++ programmers in detail. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/reference/index.html +Files: /usr/share/doc/@PVER@/html/reference/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python2.7-2.7.6/debian/PVER-doc.doc-base.PVER-tut.in @@ -0,0 +1,13 @@ +Document: @PVER@-tut +Title: Python Tutorial (v@VER@) +Author: Guido van Rossum, Fred L. Drake, Jr., editor +Abstract: This tutorial introduces the reader informally to the basic + concepts and features of the Python language and system. It helps + to have a Python interpreter handy for hands-on experience, but + all examples are self-contained, so the tutorial can be read + off-line as well. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/tutorial/index.html +Files: /usr/share/doc/@PVER@/html/tutorial/*.html --- python2.7-2.7.6.orig/debian/PVER-doc.overrides.in +++ python2.7-2.7.6/debian/PVER-doc.overrides.in @@ -0,0 +1,2 @@ +# this is referenced by the html docs +@PVER@-doc binary: extra-license-file --- python2.7-2.7.6.orig/debian/PVER-examples.overrides.in +++ python2.7-2.7.6/debian/PVER-examples.overrides.in @@ -0,0 +1,2 @@ +# don't care about permissions of the example files +@PVER@-examples binary: executable-not-elf-or-script --- python2.7-2.7.6.orig/debian/PVER-minimal.README.Debian.in +++ python2.7-2.7.6/debian/PVER-minimal.README.Debian.in @@ -0,0 +1,152 @@ +Contents of the @PVER@-minimal package +----------------------------------------- + +@PVER@-minimal consists of a minimum set of modules which may be needed +for python scripts used during the boot process. If other packages +are needed in these scripts, don't work around the missing module, but +file a bug report against this package. The modules in this package +are: + + __builtin__ builtin + __future__ module + _abcoll module + _bisect extension + _bytesio extension + _codecs builtin + _collections extension + _fileio extension + _functools extension + _hashlib extensionx + _heapq extension + _io extension + _locale extension + _md5 extension + _random extension + _sha extension + _sha256 extension + _sha512 extension + _socket extension + _sre builtin + _ssl extensionx + _struct extension + _symtable builtin + _sysconfigdata module + _types builtin + _warnings builtin + _weakref extension + _weakrefset module + abc module + atexit module + ConfigParser module + StringIO module + UserDict module + cPickle extension + cStringIO extension + array extension + base64 module + binascii extension + bisect module + cmath extension + codecs module + collections module + compileall module + copy module + copy_reg module + dis module + errno builtin + exceptions builtin + fcntl extension + fnmatch module + functools module + gc builtin + genericpath module + getopt module + glob module + grp extension + hashlib module + heapq module + imp builtin + inspect module + io module + itertools extension + keyword module + linecache module + logging package + marshal builtin + math extension + md5 module + opcode module + operator extension + optparse module + os module + pickle module + platform module + popen2 module + posix builtin + posixpath module + pkgutil module + pwd builtin + py_compile module + random module + re module + repr module + runpy module + select extension + sha module + shutil module + signal builtin + socket module + spwd extension + sre module + sre_compile module + sre_constants module + sre_parse module + ssl module + stat module + string module + strop extension + struct module + subprocess module + sys builtin + syslog extension + sysconfig module + tempfile module + textwrap module + time extension + token module + thread builtin + token module + tokenize module + traceback module + types module + unicodedata extension + weakref module + warnings module + zipimport extension + zlib extension + +Included are as well the codecs and stringprep modules, and the encodings +modules for all encodings except the multibyte encodings and the bz2 codec. + +The following modules are excluded, their import is guarded from the +importing module: + + Used in Excluded + ------------ ------------------------------------ + os nt ntpath os2 os2emxpath mac macpath + riscos riscospath riscosenviron + optparse gettext + pickle doctest + subprocess threading + +This list was derived by looking at the modules in the perl-base package, +then adding python specific "core modules". + +TODO's +------ + +- time.strptime cannot be used. The required _strptime module is not + included in the -minimal package yet. _strptime, locale, _locale and + calendar have to be added. + +- modules used very often in the testsuite: copy, cPickle, operator. --- python2.7-2.7.6.orig/debian/PVER-minimal.postinst.in +++ python2.7-2.7.6/debian/PVER-minimal.postinst.in @@ -0,0 +1,78 @@ +#! /bin/sh + +set -e + +if [ ! -f /etc/@PVER@/sitecustomize.py ]; then + cat <<-EOF + # Empty sitecustomize.py to avoid a dangling symlink +EOF +fi + +case "$1" in + configure) + # Create empty directories in /usr/local + if [ ! -e /usr/local/lib/@PVER@ ]; then + mkdir -p /usr/local/lib/@PVER@ 2> /dev/null || true + chmod 2775 /usr/local/lib/@PVER@ 2> /dev/null || true + chown root:staff /usr/local/lib/@PVER@ 2> /dev/null || true + fi + localsite=/usr/local/lib/@PVER@/dist-packages + if [ ! -e $localsite ]; then + mkdir -p $localsite 2> /dev/null || true + chmod 2775 $localsite 2> /dev/null || true + chown root:staff $localsite 2> /dev/null || true + fi + + if which update-binfmts >/dev/null; then + update-binfmts --import @PVER@ + fi + + ;; +esac + +if [ "$1" = configure ]; then + if ls -L /usr/lib/@PVER@/sitecustomize.py >/dev/null 2>&1; then + filt='cat' + else + filt='fgrep -v sitecustomize.py' + fi + files=$(dpkg -L lib@PVER@-minimal \ + | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p' | $filt) + if [ -n "$files" ]; then + @PVER@ -E -S /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + @PVER@ -E -S -O /usr/lib/@PVER@/py_compile.py $files + fi + else + echo >&2 "@PVER@-minimal: can't get files for byte-compilation" + fi + bc=no + if [ -z "$2" ] || dpkg --compare-versions "$2" lt 2.7-9 \ + || [ -f /var/lib/python/@PVER@_installed ]; then + bc=yes + fi + if grep -sq '^unsupported-versions[^#]*@PVER@' /usr/share/python/debian_defaults + then + # FIXME: byte compile anyway? + bc=no + fi + if [ "$bc" = yes ]; then + # new installation or installation of first version with hook support + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Linking and byte-compiling packages for runtime @PVER@..." + fi + version=$(dpkg -s @PVER@-minimal | awk '/^Version:/ {print $2}') + for hook in /usr/share/python/runtime.d/*.rtinstall; do + [ -x $hook ] || continue + $hook rtinstall @PVER@ "$2" "$version" + done + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi + fi +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/PVER-minimal.postrm.in +++ python2.7-2.7.6/debian/PVER-minimal.postrm.in @@ -0,0 +1,21 @@ +#! /bin/sh + +set -e + +if [ "$1" = "remove" ]; then + + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi +fi + +if [ "$1" = "purge" ]; then + for d in `find /usr/lib/@PVER@ -depth -type d -empty 2> /dev/null`; do \ + while rmdir $d 2> /dev/null; do d=`dirname $d`; done; \ + done +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/PVER-minimal.preinst.in +++ python2.7-2.7.6/debian/PVER-minimal.preinst.in @@ -0,0 +1,39 @@ +#!/bin/sh + +set -e + +syssite=/usr/lib/@PVER@/site-packages +oldsite=/usr/lib/@PVER@/old-site-packages +localsite=/usr/local/lib/@PVER@/dist-packages +syslink=../../${localsite#/usr/*} + +case "$1" in + install) + if [ -z "$2" ] && [ -d $syssite ] && [ ! -h $syssite ]; then + echo "new installation of @PVER@-minimal; $syssite is a directory" + echo "which is expected a symlink to $localsite." + echo "please find the package shipping files in $syssite and" + echo "file a bug report to ship these in /usr/lib/@PVER@/dist-packages instead" + echo "aborting installation of @PVER@-minimal" + exit 1 + fi + + # remember newly installed runtime + mkdir -p /var/lib/python + touch /var/lib/python/@PVER@_installed + ;; + upgrade) + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/PVER-minimal.prerm.in +++ python2.7-2.7.6/debian/PVER-minimal.prerm.in @@ -0,0 +1,36 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Unlinking and removing bytecode for runtime @PVER@" + fi + for hook in /usr/share/python/runtime.d/*.rtremove; do + [ -x $hook ] || continue + $hook rtremove @PVER@ || continue + done + + if which update-binfmts >/dev/null; then + update-binfmts --package @PVER@ --remove @PVER@ /usr/bin/@PVER@ + fi + + localsite=/usr/local/lib/@PVER@/dist-packages + [ -d $localsite ] && rmdir $localsite 2>/dev/null || true + [ -d $(dirname $localsite) ] \ + && rmdir $(dirname $localsite) 2>/dev/null || true + ;; + upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/PVER.desktop.in +++ python2.7-2.7.6/debian/PVER.desktop.in @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=Python (v@VER@) +Comment=Python Interpreter (v@VER@) +Exec=/usr/bin/@PVER@ +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=true +Type=Application +Categories=Development; +StartupNotify=true +NoDisplay=true --- python2.7-2.7.6.orig/debian/PVER.menu.in +++ python2.7-2.7.6/debian/PVER.menu.in @@ -0,0 +1,4 @@ +?package(@PVER@):needs="text" section="Applications/Programming"\ + title="Python (v@VER@)"\ + icon="/usr/share/pixmaps/@PVER@.xpm"\ + command="/usr/bin/python@VER@" --- python2.7-2.7.6.orig/debian/PVER.overrides.in +++ python2.7-2.7.6/debian/PVER.overrides.in @@ -0,0 +1,14 @@ +# idlelib images +@PVER@ binary: image-file-in-usr-lib + +# yes, we have to +@PVER@ binary: depends-on-python-minimal + +@PVER@ binary: desktop-command-not-in-package +@PVER@ binary: menu-command-not-in-package + +# license file referred by the standard library +@PVER@ binary: extra-license-file + +# no, not useless +@PVER@ binary: manpage-has-useless-whatis-entry --- python2.7-2.7.6.orig/debian/PVER.postinst.in +++ python2.7-2.7.6/debian/PVER.postinst.in @@ -0,0 +1,41 @@ +#! /bin/sh + +set -e + +case "$1" in + configure) + files=$(dpkg -L lib@PVER@-stdlib | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + if [ -n "$files" ]; then + @PVER@ -E -S /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + @PVER@ -E -S -O /usr/lib/@PVER@/py_compile.py $files + fi + else + echo >&2 "@PVER@: can't get files for byte-compilation" + fi + + # Create empty directories in /usr/local + if [ ! -e /usr/local/lib/python@VER@ ]; then + mkdir -p /usr/local/lib/python@VER@ 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@ 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@ 2> /dev/null || true + fi + if [ ! -e /usr/local/lib/python@VER@/site-packages ]; then + mkdir -p /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + fi + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/PVER.prerm.in +++ python2.7-2.7.6/debian/PVER.prerm.in @@ -0,0 +1,22 @@ +#! /bin/sh + +set -e + +case "$1" in + remove|upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +rmdir /usr/local/lib/python@VER@/site-packages 2>/dev/null && \ + rmdir /usr/local/lib/python@VER@ 2>/dev/null || \ + true + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/PVER.pycentral.in +++ python2.7-2.7.6/debian/PVER.pycentral.in @@ -0,0 +1,4 @@ +[@PVER@] +runtime: @PVER@ +interpreter: /usr/bin/@PVER@ +prefix: /usr/lib/@PVER@ --- python2.7-2.7.6.orig/debian/README.Debian.in +++ python2.7-2.7.6/debian/README.Debian.in @@ -0,0 +1,8 @@ +The documentation for this package is in /usr/share/doc/@PVER@/. + +A draft of the "Debian Python Policy" can be found in + + /usr/share/doc/python + +Sometime it will be moved to /usr/share/doc/debian-policy in the +debian-policy package. --- python2.7-2.7.6.orig/debian/README.PVER.in +++ python2.7-2.7.6/debian/README.PVER.in @@ -0,0 +1,95 @@ + + Python @VER@ for Debian + --------------------- + +This is Python @VER@ packaged for Debian. + +This document contains information specific to the Debian packages of +Python @VER@. + + + + [TODO: This document is not yet up-to-date with the packages.] + +Currently, it features those two main topics: + + 1. Release notes for the Debian packages: + 2. Notes for developers using the Debian Python packages: + +Release notes and documentation from the upstream package are installed +in /usr/share/doc/@PVER@/. + +There's a mailing list for discussion of issues related to Python on Debian +systems: debian-python@lists.debian.org. The list is not intended for +general Python problems, but as a forum for maintainers of Python-related +packages and interested third parties. + + + +1. Release notes for the Debian packages: + + +Results of the regression test: +------------------------------ + +The package does successfully run the regression tests for all included +modules. Seven packages are skipped since they are platform-dependent and +can't be used with Linux. + + +2. Notes for developers using the Debian python packages: + +See the draft of the Debian Python policy in /usr/share/doc/python. + +distutils can be found in the @PVER@-dev package. Development files +like the python library or Makefiles can be found in the @PVER@-dev +package in /usr/lib/@PVER@/config. Therefore, if you need to install +a pure python extension, you only need @PVER@. On the other hand, to +install a C extension, you need @PVER@-dev. + +a) Locally installed Python add-ons + + /usr/local/lib/@PVER@/site-packages/ + /usr/local/lib/site-python/ (version-independent modules) + +b) Python add-ons packaged for Debian + + /usr/lib/@PVER@/site-packages/ + /usr/lib/site-python/ (version-independent modules) + +Note that no package must install files directly into /usr/lib/@PVER@/ +or /usr/local/lib/@PVER@/. Only the site-packages directory is allowed +for third-party extensions. + +Use of the new `package' scheme is strongly encouraged. The `ni' interface +is obsolete in python 1.5. + +Header files for extensions go into /usr/include/@PVER@/. + + +Installing extensions for local use only: +---------------------------------------- + +Consider using distutils ... + +Most extensions use Python's Makefile.pre.in. Note that Makefile.pre.in +by default will install files into /usr/lib/, not into /usr/local/lib/, +which is not allowed for local extensions. You'll have to change the +Makefile accordingly. Most times, "make prefix=/usr/local install" will +work. + + +Packaging python extensions for Debian: +-------------------------------------- + +Maintainers of Python extension packages should read + + /usr/share/doc/python/python-policy.txt.gz + + + + + 03/09/98 + Gregor Hoffleit + +Last change: 2001-12-14 --- python2.7-2.7.6.orig/debian/README.Tk +++ python2.7-2.7.6/debian/README.Tk @@ -0,0 +1,8 @@ +Tkinter documentation can be found at + + http://www.pythonware.com/library/index.htm + +more specific: + + http://www.pythonware.com/library/tkinter/introduction/index.htm + http://www.pythonware.com/library/tkinter/an-introduction-to-tkinter.pdf --- python2.7-2.7.6.orig/debian/README.dbm +++ python2.7-2.7.6/debian/README.dbm @@ -0,0 +1,72 @@ + + Python and dbm modules on Debian + -------------------------------- + +This file documents the configuration of the dbm modules for Debian. It +gives hints at the preferred use of the dbm modules. + + +The preferred way to access dbm databases in Python is the anydbm module. +dbm databases behave like mappings (dictionaries). + +Since there exist several dbm database formats, we choose the following +layout for Python on Debian: + + * creating a new database with anydbm will create a Berkeley DB 2.X Hash + database file. This is the standard format used by libdb starting + with glibc 2.1. + + * opening an existing database with anydbm will try to guess the format + of the file (using whichdb) and then load it using one of the bsddb, + bsddb1, gdbm or dbm (only if the python-gdbm package is installed) + or dumbdbm modules. + + * The modules use the following database formats: + + - bsddb: Berkeley DB 2.X Hash (as in libc6 >=2.1 or libdb2) + - bsddb1: Berkeley DB 1.85 Hash (as in libc6 >=2.1 or libdb2) + - gdbm: GNU dbm 1.x or ndbm + - dbm: " (nearly the same as the gdbm module for us) + - dumbdbm: a hand-crafted format only used in this module + + That means that all usual formats should be readable with anydbm. + + * If you want to create a database in a format different from DB 2.X, + you can still directly use the specified module. + + * I.e. bsddb is the preferred module, and DB 2.X is the preferred format. + + * Note that the db1hash and bsddb1 modules are Debian specific. anydbm + and whichdb have been modified to support DB 2.X Hash files (see + below for details). + + + +For experts only: +---------------- + +Although bsddb employs the new DB 2.X format and uses the new Sleepycat +DB 2 library as included with glibc >= 2.1, it's still using the old +DB 1.85 API (which is still supported by DB 2). + +A more recent version 1.1 of the BSD DB module (available from +http://starship.skyport.net/robind/python/) directly uses the DB 2.X API. +It has a richer set of features. + + +On a glibc 2.1 system, bsddb is linked with -ldb, bsddb1 is linked with +-ldb1 and gdbm as well as dbm are linked with -lgdbm. + +On a glibc 2.0 system (e.g. potato for m68k or slink), bsddb will be +linked with -ldb2 while bsddb1 will be linked with -ldb (therefore +python-base here depends on libdb2). + + +db1hash and bsddb1 nearly completely identical to dbhash and bsddb. The +only difference is that bsddb is linked with the real DB 2 library, while +bsddb1 is linked with an library which provides compatibility with legacy +DB 1.85 databases. + + + July 16, 1999 + Gregor Hoffleit --- python2.7-2.7.6.orig/debian/README.idle-PVER.in +++ python2.7-2.7.6/debian/README.idle-PVER.in @@ -0,0 +1,14 @@ + + The Python IDLE package for Debian + ---------------------------------- + +This package contains Python @VER@'s Integrated DeveLopment Environment, IDLE. + +IDLE is included in the Python @VER@ upstream distribution (Tools/idle) and +depends on Tkinter (available as @PVER@-tk package). + +I have written a simple man page. + + + 06/16/1999 + Gregor Hoffleit --- python2.7-2.7.6.orig/debian/README.maintainers.in +++ python2.7-2.7.6/debian/README.maintainers.in @@ -0,0 +1,88 @@ + +Hints for maintainers of Debian packages of Python extensions +------------------------------------------------------------- + +Most of the content of this README can be found in the Debian Python policy. +See /usr/share/doc/python/python-policy.txt.gz. + +Documentation Tools +------------------- + +If your package ships documentation produced in the Python +documentation format, you can generate it at build-time by +build-depending on @PVER@-dev, and you will find the +templates, tools and scripts in /usr/lib/@PVER@/doc/tools -- +adjust your build scripts accordingly. + + +Makefile.pre.in issues +---------------------- + +Python comes with a `universal Unix Makefile for Python extensions' in +/usr/lib/@PVER@/config/Makefile.pre.in (with Debian, this is included +in the python-dev package), which is used by most Python extensions. + +In general, packages using the Makefile.pre.in approach can be packaged +simply by running dh_make or by using one of debhelper's rules' templates +(see /usr/doc/debhelper/examples/). Makefile.pre.in works fine with e.g. +"make prefix=debian/tmp/usr install". + +One glitch: You may be running into the problem that Makefile.pre.in +doesn't try to create all the directories when they don't exist. Therefore, +you may have to create them manually before "make install". In most cases, +the following should work: + + ... + dh_installdirs /usr/lib/@PVER@ + $(MAKE) prefix=debian/tmp/usr install + ... + + +Byte-compilation +---------------- + +For speed reasons, Python internally compiles source files into a byte-code. +To speed up subsequent imports, it tries to save the byte-code along with +the source with an extension .pyc (resp. pyo). This will fail if the +libraries are installed in a non-writable directory, which may be the +case for /usr/lib/@PVER@/. + +Not that .pyc and .pyo files should not be relocated, since for debugging +purposes the path of the source for is hard-coded into them. + +To precompile files in batches after installation, Python has a script +compileall.py, which compiles all files in a given directory tree. The +Debian version of compileall has been enhanced to support incremental +compilation and to feature a ddir (destination dir) option. ddir is +used to compile files in debian/usr/lib/python/ when they will be +installed into /usr/lib/python/. + + +Currently, there are two ways to use compileall for Debian packages. The +first has a speed penalty, the second has a space penalty in the package. + +1.) Compiling and removing .pyc files in postinst/prerm: + + Use dh_python(1) from the debhelper packages to add commands to byte- + compile on installation and to remove the byte-compiled files on removal. + Your package has to build-depend on: debhelper (>= 4.1.67), python. + + In /usr/share/doc/@PVER@, you'll find sample.postinst and sample.prerm. + If you set the directory where the .py files are installed, these + scripts will install and remove the .pyc and .pyo files for your + package after unpacking resp. before removing the package. + +2.) Compiling the .pyc files `out of place' during installation: + + As of 1.5.1, compileall.py allows you to specify a faked installation + directory using the "-d destdir" option, so that you can precompile + the files in their temporary directory + (e.g. debian/tmp/usr/lib/python2.1/site-packages/PACKAGE). + + + + 11/02/98 + Gregor Hoffleit + + +Last modified: 2007-10-14 --- python2.7-2.7.6.orig/debian/README.python +++ python2.7-2.7.6/debian/README.python @@ -0,0 +1,153 @@ + + Python 2.x for Debian + --------------------- + +This is Python 2.x packaged for Debian. + +This document contains information specific to the Debian packages of +Python 2.x. + + + + [TODO: This document is not yet up-to-date with the packages.] + + + + + + +Currently, it features those two main topics: + + 1. Release notes for the Debian packages: + 2. Notes for developers using the Debian Python packages: + +Release notes and documentation from the upstream package are installed +in /usr/share/doc/python/. + +Up-to-date information regarding Python on Debian systems is also +available as http://www.debian.org/~flight/python/. + +There's a mailing list for discussion of issues related to Python on Debian +systems: debian-python@lists.debian.org. The list is not intended for +general Python problems, but as a forum for maintainers of Python-related +packages and interested third parties. + + + +1. Release notes for the Debian packages: + + +Results of the regression test: +------------------------------ + +The package does successfully run the regression tests for all included +modules. Seven packages are skipped since they are platform-dependent and +can't be used with Linux. + + +Noteworthy changes since the 1.4 packages: +----------------------------------------- + +- Threading support enabled. +- Tkinter for Tcl/Tk 8.x. +- New package python-zlib. +- The dbmmodule was dropped. Use bsddb instead. gdbmmodule is provided + for compatibility's sake. +- python-elisp adheres to the new emacs add-on policy; it now depends + on emacsen. python-elisp probably won't work correctly with emacs19. + Refer to /usr/doc/python-elisp/ for more information. +- Remember that 1.5 has dropped the `ni' interface in favor of a generic + `packages' concept. +- Python 1.5 regression test as additional package python-regrtest. You + don't need to install this package unless you don't trust the + maintainer ;-). +- once again, modified upstream's compileall.py and py_compile.py. + Now they support compilation of optimized byte-code (.pyo) for use + with "python -O", removal of .pyc and .pyo files where the .py source + files are missing (-d) and finally the fake of a installation directory + when .py files have to be compiled out of place for later installation + in a different directory (-i destdir, used in ./debian/rules). +- The Debian packages for python 1.4 do call + /usr/lib/python1.4/compileall.py in their postrm script. Therefore + I had to provide a link from /usr/lib/python1.5/compileall.py, otherwise + the old packages won't be removed completely. THIS IS A SILLY HACK! + + + +2. Notes for developers using the Debian python packages: + + +Embedding python: +---------------- + +The files for embedding python resp. extending the python interpreter +are included in the python-dev package. With the configuration in the +Debian GNU/Linux packages of python 1.5, you will want to use something +like + + -I/usr/include/python1.5 (e.g. for config.h) + -L/usr/lib/python1.5/config -lpython1.5 (... -lpthread) + (also for Makefile.pre.in, Setup etc.) + +Makefile.pre.in automatically gets that right. Note that unlike 1.4, +python 1.5 has only one library, libpython1.5.a. + +Currently, there's no shared version of libpython. Future version of +the Debian python packages will support this. + + +Python extension packages: +------------------------- + +According to www.python.org/doc/essays/packages.html, extension packages +should only install into /usr/lib/python1.5/site-packages/ (resp. +/usr/lib/site-python/ for packages that are definitely version independent). +No extension package should install files directly into /usr/lib/python1.5/. + +But according to the FSSTND, only Debian packages are allowed to use +/usr/lib/python1.5/. Therefore Debian Python additionally by default +searches a second hierarchy in /usr/local/lib/. These directories take +precedence over their equivalents in /usr/lib/. + +a) Locally installed Python add-ons + + /usr/local/lib/python1.5/site-packages/ + /usr/local/lib/site-python/ (version-independent modules) + +b) Python add-ons packaged for Debian + + /usr/lib/python1.5/site-packages/ + /usr/lib/site-python/ (version-independent modules) + +Note that no package must install files directly into /usr/lib/python1.5/ +or /usr/local/lib/python1.5/. Only the site-packages directory is allowed +for third-party extensions. + +Use of the new `package' scheme is strongly encouraged. The `ni' interface +is obsolete in python 1.5. + +Header files for extensions go into /usr/include/python1.5/. + + +Installing extensions for local use only: +---------------------------------------- + +Most extensions use Python's Makefile.pre.in. Note that Makefile.pre.in +by default will install files into /usr/lib/, not into /usr/local/lib/, +which is not allowed for local extensions. You'll have to change the +Makefile accordingly. Most times, "make prefix=/usr/local install" will +work. + + +Packaging python extensions for Debian: +-------------------------------------- + +Maintainers of Python extension packages should read README.maintainers. + + + + + 03/09/98 + Gregor Hoffleit + +Last change: 07/16/1999 --- python2.7-2.7.6.orig/debian/README.source +++ python2.7-2.7.6/debian/README.source @@ -0,0 +1,7 @@ +The source tarball is lacking the files Lib/profile.py and Lib/pstats.py, +which Debian considers to have a license non-suitable for main (the use +of these modules limited to python). + +The package uses quilt to apply / unapply patches. +See /usr/share/doc/quilt/README.source. The series file is generated +during the build. --- python2.7-2.7.6.orig/debian/_sysconfigdata.py +++ python2.7-2.7.6/debian/_sysconfigdata.py @@ -0,0 +1,6 @@ +import sys + +if hasattr(sys, 'gettotalrefcount'): + from _sysconfigdata_d import * +else: + from _sysconfigdata_nd import * --- python2.7-2.7.6.orig/debian/argparse.egg-info +++ python2.7-2.7.6/debian/argparse.egg-info @@ -0,0 +1,8 @@ +Metadata-Version: 1.0 +Name: argparse +Version: 1.2.1 +Summary: Python command-line parsing library +Author: Steven Bethard +Author-email: steven.bethard@gmail.com +License: Python Software Foundation License +Platform: any --- python2.7-2.7.6.orig/debian/changelog +++ python2.7-2.7.6/debian/changelog @@ -0,0 +1,3560 @@ +python2.7 (2.7.6-8ubuntu0.4) trusty-security; urgency=medium + + * SECURITY UPDATE: integer overflow in the PyString_DecodeEscape + function + - debian/patches/CVE-2017-1000158.patch: fix this integer overflow + in Objects/stringobject.c. + - CVE-2017-1000158 + + -- Leonidas S. Barbosa Mon, 20 Nov 2017 12:39:42 -0300 + +python2.7 (2.7.6-8ubuntu0.3) trusty-security; urgency=medium + + * SECURITY UPDATE: StartTLS stripping attack + - debian/patches/CVE-2016-0772.patch: raise an error when + STARTTLS fails in Lib/smtplib.py. + - CVE-2016-0772 + * SECURITY UPDATE: use of HTTP_PROXY flag supplied by attacker in CGI + scripts (aka HTTPOXY attack) + - debian/patches/CVE-2016-1000110-pre.patch: prefer lower_case + proxy environment variables over UPPER_CASE or Mixed_Case ones. + - debian/patches/CVE-2016-1000110.patch: if running as CGI + script, forget HTTP_PROXY in Lib/urllib.py, add test to + Lib/test/test_urllib.py, add documentation. + - CVE-2016-1000110 + * SECURITY UPDATE: Integer overflow when handling zipfiles + - debian/patches/CVE-2016-5636-pre.patch: check for negative size + in Modules/zipimport.c + - debian/patches/CVE-2016-5636.patch: check for too large value in + Modules/zipimport.c + - CVE-2016-5636 + * SECURITY UPDATE: CRLF injection vulnerability in the + HTTPConnection.putheader + - debian/patches/CVE-2016-5699.patch: disallow newlines in + putheader() arguments when not followed by spaces or tabs in + Lib/httplib.py, add tests in Lib/test/test_httplib.py + - CVE-2016-5699 + + -- Steve Beattie Tue, 25 Oct 2016 15:38:32 -0700 + +python2.7 (2.7.6-8ubuntu0.2) trusty-security; urgency=medium + + * SECURITY UPDATE: denial of service in multiple servers + - debian/patches/CVE-2013-1752-httplib-2.patch: limit amount of headers + in Lib/httplib.py, added test to Lib/test/test_httplib.py. + - debian/patches/CVE-2013-1752-poplib.patch: limit maximum line length + in Lib/poplib.py, added test to Lib/test/test_poplib.py. + - debian/patches/CVE-2013-1752-smtplib.patch: limit amount read from + the network in Lib/smtplib.py, added test to + Lib/test/test_smtplib.py. + - CVE-2013-1752 + * SECURITY UPDATE: denial of service via xmlrpc gzip-compressed + HTTP bodies + - debian/patches/CVE-2013-1753.patch: add default limit in + Lib/xmlrpclib.py, added test to Lib/test/test_xmlrpc.py. + - CVE-2013-1753 + * SECURITY UPDATE: arbitrary memory read via idx argument + - debian/patches/CVE-2014-4616.patch: reject negative idx values in + Modules/_json.c, added test to Lib/json/tests/test_decode.py. + - CVE-2014-4616 + * SECURITY UPDATE: code execution or file disclosure via CGIHTTPServer + - debian/patches/CVE-2014-4650.patch: url unquote path in + Lib/CGIHTTPServer.py, added test to Lib/test/test_httpservers.py. + - CVE-2014-4650 + * SECURITY UPDATE: information disclosure via buffer function + - debian/patches/CVE-2014-7185.patch: avoid overflow in + Objects/bufferobject.c, added test to Lib/test/test_buffer.py. + - CVE-2014-7185 + + -- Marc Deslauriers Mon, 22 Jun 2015 10:51:39 -0400 + +python2.7 (2.7.6-8) unstable; urgency=medium + + * Update to 20140322, taken from the 2.7 branch. + * Install updated idle icons. LP: #1295969. + * Update the ssl.match_hostname backport: Change behavior of + ``ssl.match_hostname()`` to follow RFC 6125, for security reasons. + It now doesn't match multiple wildcards nor wildcards inside IDN fragments. + Closes: #740255. + + -- Matthias Klose Sat, 22 Mar 2014 14:31:54 +0100 + +python2.7 (2.7.6-7) unstable; urgency=medium + + * Include test data for test_imghdr test. + + -- Matthias Klose Wed, 26 Feb 2014 01:16:47 +0100 + +python2.7 (2.7.6-6) unstable; urgency=high + + * Update to 20140225, taken from the 2.7 branch. + - CVE-2014-1912. Fix issue 20246, buffer overflow in socket.recvfrom_into. + * Build without ffi on or1k. Closes: #738519. + * Allow loading of extensions in the sqlite module. Closes: #739555. + * Update autopkg tests (Martin Pitt): + - Don't fail if apport is not installed. + - Call su with explicit shell, as nobody has nologin as default shell now. + - Only use $SUDO_USER if that user actually exists in the testbed. + - Drop obsolete chowning of $TMPDIR and $ADTTMP; with current autopkgtest + $TMPDIR has appropriate permissions, and $ADTTMP is not being used. + + -- Matthias Klose Tue, 25 Feb 2014 10:51:27 +0100 + +python2.7 (2.7.6-5) unstable; urgency=medium + + * Update to 20140111, taken from the 2.7 branch. + * Build-depend on net-tools, required for the test_uuid test. + * Build-depend on the default Tcl/Tk. + * Add two new autopkg tests to run the failing tests. + + -- Matthias Klose Sat, 11 Jan 2014 14:52:11 +0100 + +python2.7 (2.7.6-4) unstable; urgency=medium + + * Update to 20131230, taken from the 2.7 branch. + * Disable sphinx refcounting extension, removed in sphinx-1.2. + Closes: #733404. + + -- Matthias Klose Mon, 30 Dec 2013 15:17:09 +0100 + +python2.7 (2.7.6-3) unstable; urgency=low + + * Update to 20131206, taken from the 2.7 branch. + * Disable the test_uuid autopkg test, hanging, missing entropy? + * Drop python dependency in libpython2.7-dbg. + * Revert patch from http://bugs.python.org/issue19352 as it completely breaks + unittest discovery on Debian/Ubuntu. LP: #1255505. + + -- Matthias Klose Fri, 06 Dec 2013 20:35:22 +0100 + +python2.7 (2.7.6-2) unstable; urgency=low + + * Update to 20131121, taken from the 2.7 branch. + * Fix test support when the running kernel doesn't handle port reuse. + * Build-depend on libdb-dev (<< 1:6.0) instead of a specific db version. + + -- Matthias Klose Fri, 22 Nov 2013 13:06:15 +0100 + +python2.7 (2.7.6-1) unstable; urgency=low + + * Python 2.7.6 release. + * Update to 20131119, taken from the 2.7 branch. + * For autopkg tests, only run the separate tests when defined. + * Don't run the curses autopkg test. + * Disable running the testsuite on mipsn32(el) and mips64(el), + requested by YunQiang Su. Closes: #719057. + + -- Matthias Klose Tue, 19 Nov 2013 11:45:31 +0100 + +python2.7 (2.7.5-8) unstable; urgency=medium + + * Update to 20130917, taken from the 2.7 branch. + - Fix SSL module to handle NULL bytes inside subjectAltNames general + names (CVE-2013-4238). Closes: #719566. + * Don't run the curses autopkg test. + * Set Multi-Arch attributes for binary packages. + * Fix multiarch include header for sparc64. Closes: #714802, #715063. + + -- Matthias Klose Tue, 17 Sep 2013 15:47:45 +0200 + +python2.7 (2.7.5-7) unstable; urgency=low + + * Update to 20130803, taken from the 2.7 branch. + * Update package descriptions (Filipus Klutiero). Closes: #715801. + * Fix multiarch include header for sparc64. Closes: #715063. + * Move removal of the sitecustomize.py file into the libpython-minimal + postrm. Closes: #709964. + + -- Matthias Klose Sun, 04 Aug 2013 11:56:52 +0200 + +python2.7 (2.7.5-6) unstable; urgency=low + + * Update to 20130613, taken from the 2.7 branch. + * Refresh patches. + * Don't run consistency check for cross builds. + * Really skip byte compile of non-existing sitecustomize.py. + * Fix the multiarch header file for mips64 (YunQiang Su). Closes: #710374. + + -- Matthias Klose Thu, 13 Jun 2013 13:06:51 +0200 + +python2.7 (2.7.5-5) unstable; urgency=low + + * Update to 20130602, taken from the 2.7 branch. + * Fix possible abuse of ssl.match_hostname() for denial of service + using certificates with many wildcards (CVE-2013-2099). Closes: #709066. + * Don't try to byte-compile sitecustomize.py if the target of the + symlink doesn't exist anymore. Closes: #709157. + * Handle byte compilation in python2.7{-minimal,}, byte removal in + libpython2.7{-minimal,-stdlib}. Closes: #709964. + * Backport patch to fix issue #13146, possible race conditions when writing + .pyc/.pyo files in py_compile.py (Barry Warsaw). LP: #1058884. + * Fix issue #17988, internal error in regular expression engine on 32bit + targets (closes: #710315). + + -- Matthias Klose Sun, 02 Jun 2013 15:11:19 +0200 + +python2.7 (2.7.5-4) unstable; urgency=low + + * Move the libc dependency of -minimal from Depends to Pre-Depends. + Closes: #708831. + * Disable the test_io test on armel, armhf, mips, mipsel. Hangs the + buildds. + + -- Matthias Klose Mon, 20 May 2013 12:21:06 +0200 + +python2.7 (2.7.5-3) unstable; urgency=high + + * Fix the multiarch header file for ppc64. Closes: #708641. + + -- Matthias Klose Sat, 18 May 2013 20:18:38 +0200 + +python2.7 (2.7.5-2) unstable; urgency=low + + * Only run the _multiprocessing build check on linux targets. + + -- Matthias Klose Wed, 15 May 2013 22:09:30 +0200 + +python2.7 (2.7.5-1) unstable; urgency=low + + * Python 2.7.5 release. + * Set the platinclude dir back to the non-multiarch include path, + where the multiarch pyconfig.h compatibility header is found. + * Fix issue #17703: Fix a regression where an illegal use of Py_DECREF() + after interpreter finalization can cause a crash. + * Issue #17754, setting LANG and LC_ALL for the compiler call in ctypes/util. + * Issue #17761, platform._parse_release_file doesn't close the + /etc/lsb-release file, and doesn't know about 'Ubuntu'. + * Fix autopkg tests. + * Re-enable lto and pgo optimized builds, accidentally disabled for the + last upload. + * more autopkg test fixes. + * Link the ctypes extension with the shared libffi library. + * Fix a distutils test with the deb install layout. + * Move lib2to3 library into libpython2.7-stdlib. Closes: #705078. + * Don't set yet any Multi-Arch: attributes in Debian. + + -- Matthias Klose Wed, 15 May 2013 15:02:13 +0200 + +python2.7 (2.7.4-2) experimental; urgency=low + + * Idle updates: + - Issue #17657: Show full Tk version in IDLE's about dialog. + - Issue #17613: Prevent traceback when removing syntax colorizer. + - Issue #1207589: Backwards-compatibility patch for right-click menu. + - Issue #16887: Now accepts Cancel in tabify/untabify dialog box. + - Issue #14254: Now handles readline correctly across shell restarts. + - Issue #17614: No longer raises exception when quickly closing a file. + - Issue #6698: Now opens just an editor window when configured to do so. + - Issue #8900: Using keyboard shortcuts in IDLE to open a file no longer + raises an exception. + - Issue #6649: Fixed missing exit status. + * Build a libpython2.7-testsuite package. LP: #301629. + * Add autopkg tests to run the installed testsuite in normal and debug + mode. + * Re-enable running the tests during the build. + * Add the io and _io modules to libpython2.7-minimal. + * Backport ssl.CertificateError as well. Closes: #626539. LP: #1166344. + * Don't ship an uncompress python man page. Closes: #705079. + + -- Matthias Klose Thu, 11 Apr 2013 00:44:48 +0200 + +python2.7 (2.7.4-1ubuntu4) raring; urgency=low + + * Build a libpython2.7-testsuite package. LP: #301629. + * Add autopkg tests to run the installed testsuite in normal and debug + mode. + * Re-enable running the tests during the build. + * Idle updates: + - Issue #17657: Show full Tk version in IDLE's about dialog. + - Issue #17613: Prevent traceback when removing syntax colorizer. + - Issue #1207589: Backwards-compatibility patch for right-click menu. + - Issue #16887: Now accepts Cancel in tabify/untabify dialog box. + - Issue #14254: Now handles readline correctly across shell restarts. + - Issue #17614: No longer raises exception when quickly closing a file. + - Issue #6698: Now opens just an editor window when configured to do so. + - Issue #8900: Using keyboard shortcuts in IDLE to open a file no longer + raises an exception. + - Issue #6649: Fixed missing exit status. + + -- Matthias Klose Tue, 09 Apr 2013 17:53:02 +0200 + +python2.7 (2.7.4-1ubuntu3) raring; urgency=low + + * Add the io and _io modules to libpython2.7-minimal. LP: #1165172. + * Add missing import for the ssl module. LP: #1166644. + + -- Matthias Klose Tue, 09 Apr 2013 12:11:12 +0200 + +python2.7 (2.7.4-1ubuntu2) raring; urgency=low + + * Backport ssl.CertificateError as well. Closes: #626539. LP: #1166344. + + -- Matthias Klose Mon, 08 Apr 2013 20:59:52 +0200 + +python2.7 (2.7.4-1ubuntu1) raring; urgency=low + + * Merge with Debian; remaining changes: + - Build-depend on python:any instead of python. + + -- Matthias Klose Sat, 06 Apr 2013 17:45:49 +0200 + +python2.7 (2.7.4-1) experimental; urgency=low + + * Python 2.7.4 release. + - Issue #17550: Fix the --enable-profiling configure switch. + - Issue #15801 (again): With string % formatting, relax the type check + for a mapping such that any type with a __getitem__ can be used on the + right hand side. + - Issue #17625: In IDLE, close the replace dialog after it is used. + - Issue #17531: Fix tests that thought group and user ids were always + the int type. Also, always allow -1 as a valid group and user id. + - Issue 17538: Document XML vulnerabilties + * Byte-compile files in libpython2.7-dbg. + * libpython2.7-minimal: Break earlier python2.7-minimal versions. + Closes: #704084. LP: #1157687. + * Call python with -E -S for the byte compilation. + + -- Matthias Klose Sat, 06 Apr 2013 16:38:57 +0200 + +python2.7 (2.7.4~rc1-4) experimental; urgency=low + + * Fix byte-compiliation/-removal for the split-out library packages. + LP: #1160944. + + -- Matthias Klose Sat, 30 Mar 2013 12:51:58 +0100 + +python2.7 (2.7.4~rc1-3) experimental; urgency=low + + * Fix webbrowser update. Closes: #703872. LP: #1159636. + + -- Matthias Klose Mon, 25 Mar 2013 14:33:50 +0100 + +python2.7 (2.7.4~rc1-2) experimental; urgency=low + + * Backport webbrowser updates from 3.3. Closes: #700429. + * Build again using db-5.1 instead of db-5.3. + + -- Matthias Klose Sun, 24 Mar 2013 18:27:57 +0100 + +python2.7 (2.7.4~rc1-1) experimental; urgency=low + + * Python 2.7.4 release candidate 1. + - Issue #10211: Buffer objects expose the new buffer interface internally. + - Issue #10212: cStringIO and struct.unpack support new buffer objects. + - Issue #12098: multiprocessing on Windows now starts child processes + using the same sys.flags as the current process. + - Issue #8862: Fixed curses cleanup when getkey is interrputed by a signal. + - Issue #9090: When a socket with a timeout fails with EWOULDBLOCK or + EAGAIN, retry the select() loop instead of bailing out. + - Issue #1285086: Get rid of the refcounting hack and speed up + urllib.unquote(). + - Issue #17368: Fix an off-by-one error in the Python JSON decoder + that caused a failure while decoding empty object literals when + object_pairs_hook was specified. + - Issue #17477: Update the bsddb module to pybsddb 5.3.0, supporting + db-5.x, and dropping support for db-4.1 and db-4.2. + - Issue #17192: Update the ctypes module's libffi to v3.0.13. This + specifically addresses a stack misalignment issue on x86 and issues on + some more recent platforms. + - Issue #11420: make test suite pass with -B/DONTWRITEBYTECODE set. + - Issue #17299: Add test coverage for cPickle with file objects + and general IO objects. + - Issue #11963: remove human verification from test_parser and + test_subprocess. + - Issue #16004: Add `make touch`. + - Issue #17047: remove doubled words in docs and docstrings + * Rework the sysconfigdata patch into something upstreamable. + + -- Matthias Klose Sun, 24 Mar 2013 01:56:36 +0100 + +python2.7 (2.7.3-16ubuntu2) raring; urgency=low + + * Update to 20130315, taken from the 2.7 branch. + - Issue #1285086: Get rid of the refcounting hack and speed + up urllib.unquote(). + - Issue #17368: Fix an off-by-one error in the Python JSON decoder + that caused a failure while decoding empty object literals when + object_pairs_hook was specified. + - Issue #17299: Add test coverage for cPickle with file objects and general + IO objects. + - Issue #11963: Remove human verification from test_parser and + test_subprocess. + - Issue #16004: Add `make touch`. + - Issue #17412: Update 2.7 Doc/make.bat to also use sphinx-1.0.7. + - Issue #17047: Remove doubled words in docs and docstrings. + * Revert the patch for Issue #1159051, handling corrupted gzip files + with unexpected EOF. LP: #1116079. + + -- Matthias Klose Fri, 15 Mar 2013 12:20:10 -0700 + +python2.7 (2.7.3-16ubuntu1) raring; urgency=low + + * Merge with Debian; remaining changes: + - Build-depend on python:any instead of python. + * Update symbols files. + + -- Matthias Klose Fri, 08 Mar 2013 14:30:55 +0800 + +python2.7 (2.7.3-16) experimental; urgency=low + + * Update to 20130308, taken from the 2.7 branch. + - Issue #10156: In the interpreter's initialization phase, unicode globals + are now initialized dynamically as needed. + - Issue #16975: Fix error handling bug in the escape-decode decoder. + - Issue #9290: In IDLE the sys.std* streams now implement io.TextIOBase + interface and support all mandatory methods and properties. + - Issue #13454: Fix a crash when deleting an iterator created by + itertools.tee() if all other iterators were very advanced before. + - Issue #3754: fix typo in pthread AC_CACHE_VAL. + - Issue #17029: Let h2py search the multiarch system include directory. + - Issue #16445: Fixed potential segmentation fault when deleting an + exception message. + - Issue #17275: Corrected class name in init error messages of the + C version of BufferedWriter and BufferedRandom. + - Issue #7963: Fixed misleading error message that issued when object is + called without arguments. + - Issue #5308: Raise ValueError when marshalling too large object (a + sequence with size >= 2**31), instead of producing illegal marshal data. + - Issue #17043: The unicode-internal decoder no longer read past the end of + input buffer. + - Issue #16979: Fix error handling bugs in the unicode-escape-decode + decoder. + - Issue #17278: Fix a crash in heapq.heappush() and heapq.heappop() when + the list is being resized concurrently. + - Issue #17018: Make Process.join() retry if os.waitpid() fails with EINTR. + - Issue #14720: sqlite3: Convert datetime microseconds correctly. + - Issue #17225: JSON decoder now counts columns in the first line starting + with 1, as in other lines. + - Issue #7842: backported fix for py_compile.compile() syntax error + handling. + - Issue #13153: Tkinter functions now raise TclError instead of ValueError + when a unicode argument contains non-BMP character. + - Issue #9669: Protect re against infinite loops on zero-width matching in + non-greedy repeat. + - Issue #13169: The maximal repetition number in a regular expression + has been increased from 65534 to 2147483647 (on 32-bit platform) or + 4294967294 (on 64-bit). + - Issue #11311: StringIO.readline(0) now returns an empty string + as all other file-like objects. + - Issue #16800: tempfile.gettempdir() no longer left temporary files when + the disk is full. Original patch by Amir Szekely. + - Issue #13555: cPickle now supports files larger than 2 GiB. + - Issue #17052: unittest discovery should use self.testLoader. + - Issue #4591: Uid and gid values larger than 2**31 are supported now. + - Issue #17141: random.vonmisesvariate() no more hangs for large kappas. + - Issue #17149: Fix random.vonmisesvariate to always return results in + the range [0, 2*math.pi]. + - Issue #1470548: XMLGenerator now works with UTF-16 and UTF-32 encodings. + - Issue #6975: os.path.realpath() now correctly resolves multiple nested + symlinks on POSIX platforms. + - Issue #17156: pygettext.py now correctly escapes non-ascii characters. + - Issue #7358: cStringIO.StringIO now supports writing to and reading from + a stream larger than 2 GiB on 64-bit systems. + - IDLE was displaying spurious SystemExit tracebacks when running scripts + that terminated by raising SystemExit (i.e. unittest and turtledemo). + - Issue #10355: In SpooledTemporaryFile class mode and name properties and + xreadlines method now work for unrolled files. encoding and newlines + - Issue #16686: Fixed a lot of bugs in audioop module. + - Issue #17073: Fix some integer overflows in sqlite3 module. + - Issue #6083: Fix multiple segmentation faults occured when + PyArg_ParseTuple parses nested mutating sequence. + - Issue #5289: Fix ctypes.util.find_library on Solaris. + - Issue #17106: Fix a segmentation fault in io.TextIOWrapper when an + underlying stream or a decoder produces data of an unexpected type (i.e. + when io.TextIOWrapper initialized with text stream or use bytes-to-bytes + codec). + - Issue #13994: Add compatibility alias in distutils.ccompiler for + distutils.sysconfig.customize_compiler. + - Issue #15633: httplib.HTTPResponse is now mark closed when the server + sends less than the advertised Content-Length. + - Issue #15881: Fixed atexit hook in multiprocessing. + - Issue #14340: Upgrade the embedded expat library to version 2.1.0. + - Issue #11159: SAX parser now supports unicode file names. + - Issue #6972: The zipfile module no longer overwrites files outside of + its destination path when extracting malicious zip files. + - Issue #17049: Localized calendar methods now return unicode if a locale + includes an encoding and the result string contains month or weekday (was + regression from Python 2.6). + - Issue #4844: ZipFile now raises BadZipfile when opens a ZIP file with an + incomplete "End of Central Directory" record. + - Issue #15505: `unittest.installHandler` no longer assumes SIGINT handler + is set to a callable object. + - Issue #17051: Fix a memory leak in os.path.isdir() on Windows. + - Issue #12268: The io module file object write methods no longer abort + early when a write system calls is interrupted (EINTR). + - Issue #17249: convert a test in test_capi to use unittest and reap + threads. + - We now run both test_email.py and test_email_renamed.py when running the + test_email regression test. test_email_renamed contains some tests that + test_email does not. + - Issue #17041: Fix testing when Python is configured with the + --without-doc-strings option. + - Issue #5033: Fix building of the sqlite3 extension module when the + SQLite library version has "beta" in it. + - Issue #17228: Fix building without pymalloc. + - Issue #17086: Backport the patches from the 3.3 branch to cross-build + the package. + - Issue #16406: combine the pages for uploading and registering to PyPI. + - Issue #16403: Document how distutils uses the maintainer field in + PKG-INFO. + - Issue #16695: Document how glob handles filenames starting with a dot. + - Issue #8890: Stop advertising an insecure practice by replacing uses + of the /tmp directory with better alternatives in the documentation. + - Issue #17203: add long option names to unittest discovery docs. + * python2.7-dbg, libpython2.7-dbg: Drop dependency on python. + * python2.7-dbg: Make gdb (not gdb-minimal) a recommendation. + * python2.7: Replace python2.7-minimal (<< 2.7.3-7). Closes: #702005. + * Build the _md5, _sha1, _sha256 and _sha512 extension modules. + * Fix multiarch include for AArch64. + + -- Matthias Klose Fri, 08 Mar 2013 09:54:59 +0800 + +python2.7 (2.7.3-15) experimental; urgency=low + + * Update to 20130124, taken from the 2.7 branch. + - Issue #14850: Now a charmap decoder treats U+FFFE as "undefined mapping" + in any mapping, not only in a Unicode string. + - Issue #11461: Fix the incremental UTF-16 decoder. + - Issue #1159051: GzipFile now raises EOFError when reading a corrupted + file with truncated header or footer. + - Issue #16992: On Windows in signal.set_wakeup_fd, validate the file + descriptor argument. + - Issue #15861: tkinter now correctly works with lists and tuples + containing strings with whitespaces, backslashes or unbalanced braces. + - Issue #10527: Use poll() instead of select() for multiprocessing pipes. + - Issue #9720: zipfile now writes correct local headers for files larger + than 4 GiB. + - Issue #16829: IDLE printing no longer fails if there are spaces or other + special characters in the file path. + - Issue #13899: \A, \Z, and \B now correctly match the A, Z, and B literals + when used inside character classes (e.g. '[\A]'). + - Issue #16398: Optimize deque.rotate() so that it only moves pointers + and doesn't touch the underlying data with increfs and decrefs. + - Issue #15109: Fix regression in sqlite3's iterdump method where it would + die with an encoding error if the database contained string values + containing non-ASCII. + - Issue #15545: Fix regression in sqlite3's iterdump method where it was + failing if the connection used a row factory (such as sqlite3.Row) that + produced unsortable objects. + - Issue #16953: Fix socket module compilation on platforms with + HAVE_BROKEN_POLL. + - Issue #16836: Enable IPv6 support even if IPv6 is disabled on the + build host. + - Issue #15539: Fix a number of bugs in Tools/scripts/pindent.py. + * Backport cross-build support from python3.3. LP: #873007. + * Add pyconfig.h compatibility headers. Closes: #695667. LP: #1094246. + + -- Matthias Klose Thu, 24 Jan 2013 14:57:08 +0100 + +python2.7 (2.7.3-14) experimental; urgency=low + + * Update to 20130105, taken from the 2.7 branch. + - Issue #16367: Fix FileIO.readall() on Windows for files larger than 2 GB. + - Issue #15516: Fix a bug in PyString_FromFormat where it failed + to properly ignore errors from a __int__() method. + - Issue #16839: Fix a segfault when calling unicode() on a classic class + early in interpreter initialization. + - Issue #16761: Calling ``int()`` and ``long()`` with *base* argument only + now raises TypeError. + - Issue #16828: Fix error incorrectly raised by bz2.compress(''). + LP: #1090043. + - Issue #16819: IDLE method completion now correctly works for unicode + literals. + - Issue 10527: make multiprocessing use poll() instead of select() + if available. + - Issue #16485: Now file descriptors are closed if file header patching + failed on closing an aifc file. + - Issue #12065: connect_ex() on an SSL socket now returns the original + errno when the socket's timeout expires (it used to return None). + - Issue #16504: IDLE now catches SyntaxErrors raised by tokenizer. + - Issue #16702: test_urllib2_localnet tests now correctly ignores proxies + for localhost tests. + - Issue #16713: Fix the parsing of tel url with params using urlparse + module. + - Issue #16443: Add docstrings to regular expression match objects. + - Issue #8853: Allow port to be of type long for socket.getaddrinfo(). + - Issue #16597: In buffered and text IO, call close() on the underlying + stream if invoking flush() fails. + - Issue #15701: Fix HTTPError info method call to return the headers + information. + - Issue #14958: Change IDLE systax highlighting to recognize all string + and byte literals currently supported in Python 2.7. + - Issue #15324: Fix regrtest parsing of --fromfile and --randomize options. + - Issue #16618: Add more regression tests for glob. + - Issue #13094: add "Why do lambdas defined in a loop with different values + all return the same result?" programming FAQ. + * python-config --help returns with an exit value 0. LP: #1093860. + * Update package description for the -dbg packages. Closes: #696616. + + -- Matthias Klose Sat, 05 Jan 2013 17:22:13 +0100 + +python2.7 (2.7.3-13) experimental; urgency=low + + * Update to 20121220, taken from the 2.7 branch. + - Issue #16646: ftplib.FTP.makeport() might lose socket error details. + - Issue #16298: In HTTPResponse.read(), close the socket when there is no + Content-Length and the incoming stream is finished. + * Filter out -D_FORTIFY_SOURCE for the debug builds. Meaningless. + * Install the _sysconfigdata.py and python-config.sh from both shared + builds, but don't link extensions against the shared python library. + Closes: #695979. + * Fix python2.7-dbg-config symlink. LP: #1091615. + * During purge, check for existance of /etc/python2.7 before trying + to remove it. Closes: #696023. + * python2.7-dev, libpython2.7-dev: Drop the dependency on libssl-dev. + * debian/patches/sys-multiarch.diff: Expose multiarch tuple as + sys._multiarch (Barry Warsaw). Closes: #695958. + Note: Usage of sysconfig.get_config_var('MULTIARCH') is preferred. + + -- Matthias Klose Thu, 20 Dec 2012 16:57:49 +0100 + +python2.7 (2.7.3-12) experimental; urgency=low + + * Fix typo in pkgconfig file. Closes: #695671, LP: #1088988. + + -- Matthias Klose Mon, 10 Dec 2012 19:10:32 +0100 + +python2.7 (2.7.3-11) experimental; urgency=low + + * Update to 20121210, taken from the 2.7 branch. + - Issue #16602: When a weakref's target was part of a long deallocation + chain, the object could remain reachable through its weakref even though + its refcount had dropped to zero. + - Issue #16588: Silence unused-but-set warnings in Python/thread_pthread. + - Issue #16248: Disable code execution from the user's home directory by + tkinter when the -E flag is passed to Python. Patch by Zachary Ware. + - Issue #16628: Fix a memory leak in ctypes.resize(). + - Issue #13614: Fix setup.py register failure with invalid rst in + description. + - Issue #10182: The re module doesn't truncate indices to 32 bits anymore. + - Issue #16573: In 2to3, treat enumerate() like a consuming call, so + superfluous list() calls aren't added to filter(), map(), and zip() + which are directly passed enumerate(). + - Issue #16476: Fix json.tool to avoid including trailing whitespace. + - Issue #16549: Add tests for json.tools. + - Issue #15990: Improve argument/parameter documentation. + * Use _sysconfigdata.py in distutils.sysconfig. + * Fix distutils.sysconfig.get_{config_h,makefile}_filename for multiarch. + * Backport ssl.match_hostname from Python3. Closes: #626539. + + -- Matthias Klose Mon, 10 Dec 2012 16:06:41 +0100 + +python2.7 (2.7.3-10) experimental; urgency=low + + * Update to 20121128, taken from the 2.7 branch. + - Issue #9011: Fix hacky AST code that modified the CST when compiling + a negated numeric literal. + - Issue #16306: Fix multiple error messages when unknown command line + parameters where passed to the interpreter. + - Issue #15379: Fix passing of non-BMP characters as integers for the + charmap decoder (already working as unicode strings). + - Issue #16453: Fix equality testing of dead weakref objects. + - Issue #9535: Fix pending signals that have been received but not yet + handled by Python to not persist after os.fork() in the child process. + - Issue #15001: fix segfault on "del sys.modules['__main__']". + - Issue #5057: the peepholer no longer optimizes subscription on unicode + literals (e.g. u'foo'[0]) in order to produce compatible pyc files + between narrow and wide builds. + - Issue #8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) + now raises an error. + - Issue #14700: Fix buggy overflow checks for large width and precision + in string formatting operations. + - Issue #16345: Fix an infinite loop when ``fromkeys`` on a dict subclass + received a nonempty dict from the constructor. + - Issue #6074: Ensure cached bytecode files can always be updated by the + user that created them, even when the source file is read-only. + - Issue #14783: Improve int() and long() docstrings and switch docstrings + for unicode(), slice(), range(), and xrange() to use multi-line + signatures. + - Issue #16030: Fix overflow bug in computing the `repr` of an xrange + object with large start, step or length. + - Issue #16029: Fix overflow bug occurring when pickling xranges with large + start, step or length. + - Issue #16037: Limit httplib's _read_status() function to work around + broken HTTP servers and reduce memory usage (backport of a 3.2 fix). + - Issue #13992: The trashcan mechanism is now thread-safe. This eliminates + sporadic crashes in multi-thread programs when several long deallocator + chains ran concurrently and involved subclasses of built-in container + types. + - Issue #15801: Make sure mappings passed to '%' formatting are actually + subscriptable. + - Issue #15604: Update uses of PyObject_IsTrue() to check for and handle + errors correctly. + - Issue #15897: zipimport.c doesn't check return value of fseek(). + - Issue #16369: Global PyTypeObjects not initialized with PyType_Ready(...). + - Issue #15033: Fix the exit status bug when modules invoked using + -m switch, return the proper failure return value (1). + - Issue #1160: Fix compiling large regular expressions on UCS2 builds. + - Issue #14313: zipfile now raises NotImplementedError when the compression + type is unknown. + - Issue #16408: Fix file descriptors not being closed in error conditions + in the zipfile module. + - Issue #16327: The subprocess module no longer leaks file descriptors + used for stdin/stdout/stderr pipes to the child when fork() fails. + - Issue #14396: Handle the odd rare case of waitpid returning 0 when not + expected in subprocess.Popen.wait(). + - Issue #16411: Fix a bug where zlib.decompressobj().flush() might try + to access previously-freed memory. + - Issue #16350: zlib.decompressobj().decompress() now accumulates data from + successive calls after EOF in unused_data, instead of only saving the + argument to the last call. decompressobj().flush() now correctly sets + unused_data and unconsumed_tail. A bug in the handling of MemoryError + when setting the unconsumed_tail attribute has also been fixed. + - Issue #12759: sre_parse now raises a proper error when the name + of the group is missing. + - Issue #16152: fix tokenize to ignore whitespace at the end of the code + when no newline is found. + - Issue #1207589: Add Cut/Copy/Paste items to IDLE right click + Context Menu. + - Issue #16230: Fix a crash in select.select() when one the lists changes + size while iterated on. + - Issue #16228: Fix a crash in the json module where a list changes size + while it is being encoded. + - Issue #14897: Enhance error messages of struct.pack and struct.pack_into. + - Issue #12890: cgitb no longer prints spurious

tags in text + mode when the logdir option is specified. + - Issue #14398: Fix size truncation and overflow bugs in the bz2 module. + - Issue #5148: Ignore 'U' in mode given to gzip.open() and gzip.GzipFile(). + - Issue #16220: wsgiref now always calls close() on an iterable response. + - Issue #16461: Wave library should be able to deal with 4GB wav files, + and sample rate of 44100 Hz. + - Issue #16176: Properly identify Windows 8 via platform.platform(). + - Issue #15756: subprocess.poll() now properly handles errno.ECHILD to + return a returncode of 0 when the child has already exited or cannot + be waited on. + - Issue #12376: Pass on parameters in TextTestResult.__init__ super call. + - Issue #15222: Insert blank line after each message in mbox mailboxes. + - Issue #16013: Fix CSV Reader parsing issue with ending quote characters. + - Issue #15421: fix an OverflowError in Calendar.itermonthdates() after + datetime.MAXYEAR. + - Issue #15970: xml.etree.ElementTree now serializes correctly the + empty HTML elements 'meta' and 'param'. + - Issue #15676: Now "mmap" check for empty files before doing the + offset check. + - Issue #15340: Fix importing the random module when /dev/urandom cannot + be opened. This was a regression caused by the hash randomization patch. + - Issue #15841: The readable(), writable() and seekable() methods of + io.BytesIO and io.StringIO objects now raise ValueError when the object + has been closed. + - Issue #16112: platform.architecture does not correctly escape argument to + /usr/bin/file. + - Issue #12776,#11839: call argparse type function (specified by + add_argument) only once. Before, the type function was called twice in + the case where the default was specified and the argument was given as + well. This was especially problematic for the FileType type, as a + default file would always be opened, even if a file argument was + specified on the command line. + - Issue #15906: Fix a regression in argparse caused by the preceding change, + when action='append', type='str' and default=[]. + - Issue #13370: Ensure that ctypes works on Mac OS X when Python is + compiled using the clang compiler + - Issue #15544: Fix Decimal.__float__ to work with payload-carrying NaNs. + - Issue #15199: Fix JavaScript's default MIME type to + application/javascript. + - Issue #15477: In cmath and math modules, add workaround for platforms + whose system-supplied log1p function doesn't respect signs of zeros. + - Issue #15908: Fix misbehaviour of the sha1 module when called on data + larger than 2**32 bytes. + - Issue #15910: Fix misbehaviour of _md5 and sha1 modules when "updating" + on data larger than 2**32 bytes. + - Fix the leak of a dict in the time module when used in an embedded + interpreter that is repeatedly initialized and shutdown and reinitialized. + - Issue #12268: File readline, readlines and read or readall methods + no longer lose data when an underlying read system call is interrupted + within an io module object. IOError is no longer raised due to a read + system call returning EINTR from within these methods. + - Issue #16012: Fix a regression in pyexpat. The parser's UseForeignDTD() + method doesn't require an argument again. + - Issue #16559: Add more tests for the json module, including some from the + official test suite at json.org. + - Issue #16274: Fix test_asyncore on Solaris. + - Issue #15040: Close files in mailbox tests for PyPy compatibility. + - Issue #15802: Fix test logic in TestMaildir.test_create_tmp. + - Issue #15765: Extend a previous fix to Solaris and OpenBSD for quirky + getcwd() behaviour (issue #9185) to NetBSD as well. + - Issue #15615: Add some tests for the json module's handling of invalid + input data. + - Issue #15923: fix a mistake in asdl_c.py that resulted in a TypeError + after 2801bf875a24 (see #15801). + - Issue #11715: Fix multiarch detection without having Debian development + tools (dpkg-dev) installed. + - Issue #15819: Make sure we can build Python out-of-tree from a readonly + source directory. (Somewhat related to Issue #9860.) + - Issue #15822: Ensure 2to3 grammar pickles are properly installed. + - Issue #13301: use ast.literal_eval() instead of eval() + in Tools/i18n/msgfmt.py. + - Issue #16400: Update the description of which versions of a given package + PyPI displays. + - Issue #15677: Document that zlib and gzip accept a compression level + of 0 to mean 'no compression'. + - Issue #8040: added a version switcher to the documentation. + - Issue #16115: Improve subprocess.Popen() documentation around args, + shell, and executable arguments. + - Issue #15979: Improve timeit documentation. + - Issue #16036: Improve documentation of built-in int()'s signature and + arguments. + - Issue #15935: Clarification of argparse docs, re: add_argument() type and + default arguments. + - Issue #13769: Document the effect of ensure_ascii to the return type + of JSON decoding functions. + - Issue #14880: Fix kwargs notation in csv.reader, + .writer & .register_dialect. + - Issue #14674: Add a discussion of the json module's standard compliance. + * Clarify location of the gdbinit file. LP: #975676. + * Fix traceback for missing distutils wininst .exe files. LP: #1081155. + * Backport python3.3 multiarch packaging changes (Riku Voipio), and fix + multiarch issues discovered after the backport. + Closes: #683755. + * Use a shell implementation for the python-config script. + + -- Matthias Klose Thu, 29 Nov 2012 20:18:20 +0100 + +python2.7 (2.7.3-5) unstable; urgency=low + + * Enable verbose build for the sharedmods target. + * Fix issue #15847: allow args to be a tuple in parse_args. Closes: #686583. + * Fix issue #15340: Fix importing the random module when /dev/urandom cannot + be opened. Regression caused by the hash randomization patch. + * Don't use `-n' anymore to start idle in the desktop/menu files, not + needed anymore for multiseat installations. + + -- Matthias Klose Sun, 09 Sep 2012 16:54:26 +0200 + +python2.7 (2.7.3-4) unstable; urgency=low + + * Follwup for issue #9374. Restore the removed attributes in the + urlparse module. + * Update symbols files. + * Disable test_subprocess on the Hurd buildds. + * Call dh_movefiles with --srcdir. Closes: #685543. + + -- Matthias Klose Sun, 26 Aug 2012 12:24:31 +0200 + +python2.7 (2.7.3-3) unstable; urgency=low + + * Update to 20120814, taken from the 2.7 branch. Posix relevant patches: + - Issue #15041: Update "see also" list in tkinter documentation. + - Issue #14579: Fix error handling bug in the utf-16 decoder. + - Issue #15368: An issue that caused bytecode generation to be + non-deterministic when using randomized hashing (-R) has been fixed. + - Issue #15567: Fix NameError when running threading._test + - Issue #15424: Add a __sizeof__ implementation for array objects. + - Issue #13052: Fix IDLE crashing when replace string in Search/Replace + dialog ended with '\'. + - Issue #15538: Fix compilation of the getnameinfo() / getaddrinfo() + emulation code. + - Issue #9803: Don't close IDLE on saving if breakpoint is open. + - Issue #12288: Consider '0' and '0.0' as valid initialvalue + for tkinter SimpleDialog. + - Issue #15489: Add a __sizeof__ implementation for BytesIO objects. + - Issue #15469: Add a __sizeof__ implementation for deque objects. + - Issue #15487: Add a __sizeof__ implementation for buffered I/O objects. + - Issue #15512: Add a __sizeof__ implementation for parser. + - Issue #15402: An issue in the struct module that caused sys.getsizeof to + return incorrect results for struct.Struct instances has been fixed. + - Issue #15232: when mangle_from is True, email.Generator now correctly + mangles lines that start with 'From ' that occur in a MIME preamble + or epilog. + - Issue #13922: argparse no longer incorrectly strips '--'s that appear + after the first one. + - Issue #12353: argparse now correctly handles null argument values. + - Issue #14635: telnetlib will use poll() rather than select() when possible + to avoid failing due to the select() file descriptor limit. + - Issue #6056: Make multiprocessing use setblocking(True) on the + sockets it uses. + - Issue #15630: Add an example for "continue" stmt in the tutorial. + - Issue #15250: Document that filecmp.dircmp compares files shallowly. + * Fortified build. + * Python/import.c: Don't export isdir(). + * Modules/socketmodule.c: Don't export netdb_lock. + * Add breaks for vim-{nox,gtk,gnome,athena}. Closes: #682034. + * Don't ship python2.pc, should be shipped with python-dev instead. + Closes: #684612. + + -- Matthias Klose Tue, 14 Aug 2012 17:55:32 +0200 + +python2.7 (2.7.3-2) unstable; urgency=low + + * Update to 20120713, taken from the 2.7 branch. + - Issue #15033: Fix the exit status bug when modules invoked using -m swith, + return the proper failure return value (1). + - Issue #12268: File readline, readlines and read() methods no longer lose + data when an underlying read system call is interrupted. IOError is no + longer raised due to a read system call returning EINTR from within these + methods. + - Issue #13512: Create ~/.pypirc securely (CVE-2011-4944). + - Issue #7719: Make distutils ignore ``.nfs*`` files instead of choking + later on. + - Issue #10053: Don't close FDs when FileIO.__init__ fails. + - Issue #15247: FileIO now raises an error when given a file descriptor + pointing to a directory. + - Issue #14591: Fix bug in Random.jumpahead that could produce an invalid + Mersenne Twister state on 64-bit machines. + - Issue #5346: Preserve permissions of mbox, MMDF and Babyl mailbox + files on flush(). + - Issue #15219: Fix a reference leak when hashlib.new() is called with + invalid parameters. + - Issue #9559: If messages were only added, a new file is no longer + created and renamed over the old file when flush() is called on an + mbox, MMDF or Babyl mailbox. + - Issue #14653: email.utils.mktime_tz() no longer relies on system + mktime() when timezone offest is supplied. + - Issue #15101: Make pool finalizer avoid joining current thread. + - Issue #15054: A bug in tokenize.tokenize that caused string literals + with 'b' and 'br' prefixes to be incorrectly tokenized has been fixed. + - Issue #15036: Mailbox no longer throws an error if a flush is done + between operations when removing or changing multiple items in mbox, + MMDF, or Babyl mailboxes. + - Issue #15043: test_gdb is now skipped entirely if gdb security settings + block loading of the gdb hooks + - Issue #13557: Clarify effect of giving two different namespaces to exec or + execfile(). + * Don't build the _hashlib and _ssl extensions as a builtin, but as + extensions. Closes: #680930. + * Backport issue #13150: sysconfig no longer parses the Makefile and config.h + files when imported, instead doing it at build time. This makes importing + sysconfig faster and reduces Python startup time by 20%. + * python2.7: Add a break for python-virtualenv (<< 1.7.1.2-2~). + * Don't run the test_gdb test on mips/mipsel, not even in debug mode. + * For lto builds, use -g instead of -g1; filter out lto flags in the + installed Makefile. Closes: #681348. + + -- Matthias Klose Fri, 13 Jul 2012 05:03:43 +0200 + +python2.7 (2.7.3-1) unstable; urgency=low + + * Python 2.7.3 release. + * Update to 20120615, taken from the 2.7 branch. + * The wininst-* files cannot be built within Debian from the included + sources, needing a zlib mingw build, which the zlib maintainer isn't + going to provide. Closes: #639407. + * Let pydoc handle dist-packages the same as site-packages. + Closes: #671021. + * python2.7-doc: Fix underscore.js symlink. Closes: #671795, #676339. + * Do not italicize punctuation in python(1) manual page (Matt Kraai). + Closes: #579269. + * Build _heapq as a builtin (and move it to -minimal). + + -- Matthias Klose Fri, 15 Jun 2012 15:26:21 +0200 + +python2.7 (2.7.3~rc2-2.1) unstable; urgency=low + + * Non-maintainer upload (with maintainer's permission). + * Disable testsuite on GNU/kFreeBSD. (Closes: #669281) + + -- Robert Millan Sun, 22 Apr 2012 22:04:26 +0200 + +python2.7 (2.7.3~rc2-2) unstable; urgency=low + + * Use xdg-open/gvfs-open in Lib/webbrowser.py (Michael Vogt). + LP: #971311. + * Add a paragraph about python-foo-dbg packages to README.debug. + LP: #872050. + * Disable some tests (no feedback from porters): + - test_socket on hurd-i386. + - test_io on amd64. + - test_signal on kfreebsd-*. Closes: #654783. + - test_threading on sparc. + * Tighten build dependency on libexpat-dev. Closes: #665346. + * Build-depend on db-5.1, don't care about testsuite regressions on + some esoteric ports. If packages rely on threaded applications or + transactions, please use the python-bsddb3 package. + Closes: #621374. + * Don't ship the python2 and python2-config symlinks, move these + to the python-minimal and python-dev packages. Closes: #663874. + * Remove PVER-doc.doc-base.PVER-doc.in. Closes: #656763. + * Update symbols files. + * Avoid runtime path for the sqlite extension. + * CVE-2011-4944, distutils creates ~/.pypirc insecurely. Closes: #650555. + * Fix issue #14505, file descriptor leak when deallocating file objects + created with PyFile_FromString(). Closes: #664529. + + -- Matthias Klose Thu, 05 Apr 2012 15:47:03 +0200 + +python2.7 (2.7.3~rc2-1) unstable; urgency=low + + * Python 2.7.3 release candidate 2. + * Build-depend on expat >= 2.1~. + + -- Matthias Klose Wed, 21 Mar 2012 05:21:47 +0100 + +python2.7 (2.7.3~rc1-1) unstable; urgency=low + + * Python 2.7.3 release candidate 1. + * Update to 20120309, taken from the 2.7 branch. + * Fix dangling libpython.a symlink. Closes: #660231. + + -- Matthias Klose Fri, 09 Mar 2012 19:28:43 +0100 + +python2.7 (2.7.2-13) unstable; urgency=low + + * Update to 20120120, taken from the 2.7 branch. + * Remove patch integrated upstream (issue9054.diff). + * Backport Issue #9189 to distutils/sysconfig.py as well. + Closes: #656118. + * Disable test_io on kfreebsd again. Closes: #654783. + * Disable test_bsddb3 tests on kfreebsd again. + + -- Matthias Klose Fri, 20 Jan 2012 16:33:47 +0100 + +python2.7 (2.7.2-12) unstable; urgency=low + + * Run the tests with a script command which doesn't exit immediatly + when stdin is /dev/null (Colin Watson). + + -- Matthias Klose Fri, 13 Jan 2012 11:04:31 +0100 + +python2.7 (2.7.2-11) unstable; urgency=low + + * Don't run the test_site tests when $HOME doesn't exist. + + -- Matthias Klose Wed, 11 Jan 2012 09:19:00 +0100 + +python2.7 (2.7.2-10) unstable; urgency=low + + * Update to 20120110, taken from the 2.7 branch. + * Overwrite some lintian warnings: + - The -dbg interpreters are not unusual. + - The -gdb.py files don't need a python dependency. + - lintian can't handle a whatis entry starting with one word on the line. + * Fix test failures related to distutils debian installation layout. + * Add build-arch/build-indep targets. + * Regenerate Setup and Makefiles after correcting Setup.local. + * profiled-build.diff: Pass PY_CFLAGS instead of CFLAGS for the profiled + build. + * Pass dpkg-buildflags to the build process, and build third party + extensions with these flags. + * Add support to build using -flto (and -g1) on some architectures. + * Disable pgo builds for some architectures (for now, keep just + amd64 armel armhf i386 powerpc ppc64). + * Build-depend on libgdbm-dev to build and run the gdbm tests. + * Build-depend on xvfb to run the tkinter tests. + * python2.7: Provide python2.7-argparse and python-argparse. + * Don't run test_threading on mips/mipsel. + * Run the test_gdb test for the debug build only. + * Add build conflict to python-cxx-dev (pydoc test failures). + * Disable test_ssl certificate check, certificate expired on python.org. + + -- Matthias Klose Tue, 10 Jan 2012 16:44:56 +0100 + +python2.7 (2.7.2-9) unstable; urgency=low + + * Update to 20111217, taken from the 2.7 branch. + + -- Matthias Klose Sat, 17 Dec 2011 17:36:27 +0100 + +python2.7 (2.7.2-8) unstable; urgency=low + + * Update to 20111130, taken from the 2.7 branch. + * New patch, ctypes-arm, allow for ",hard-float" after libc6 in ldconfig -p + output (Loic Minier). LP: #898172. + * debian/rules: Define DPKG_VARS (Alban Browaeys). Closes: #647419). + * Add python-config man page (Johann Felix Soden). Closes: #650181). + + -- Matthias Klose Wed, 30 Nov 2011 19:16:23 +0100 + +python2.7 (2.7.2-7) unstable; urgency=low + + * Adjust patches for removed Lib/plat-linux3. + * Add build conflict to libncurses5-dev, let configure search for + ncurses headers in /usr/include/ncursesw too. + + -- Matthias Klose Wed, 05 Oct 2011 11:30:16 +0200 + +python2.7 (2.7.2-6) unstable; urgency=low + + * Update to 20111004, taken from the 2.7 branch. + * Use the ncursesw include directory when linking with ncursesw. + * Rebuild with libreadline not linked with libncurses*. Closes: #643816. + * Fix typos in the multiprocessing module. Closes: #643856. + + -- Matthias Klose Tue, 04 Oct 2011 16:09:29 +0200 + +python2.7 (2.7.2-5) unstable; urgency=low + + * Update to 20110816, taken from the 2.7 branch. + - Fix issue#12752. LP: #824734. + * Don't run test_threading on the kfreebsd-i386 buildd. + + -- Matthias Klose Tue, 16 Aug 2011 08:33:31 +0200 + +python2.7 (2.7.2-4) unstable; urgency=low + + * Update to 20110803, taken from the 2.7 branch. + * Fix build on s390x. Closes: #636033. + * Use linux-any for some build dependencies. Closes: #634809. + * Revert previous change to treat Linux 3.x as Linux 2. Use the + plat-linux3 directory instead. + + -- Matthias Klose Wed, 03 Aug 2011 12:36:05 +0200 + +python2.7 (2.7.2-3) unstable; urgency=low + + * Update to 20110709, taken from the 2.7 branch. + * Make the conflict against python-profiler a versioned conflict. + * Don't run the bsddb3 tests on kfreebsd-i386. + * Don't add the bsddb multilib path, if already in the standard lib path. + * Treat Linux 3.x as Linux 2. Closes: #633015. + * Assume working semaphores on Linux, don't rely on running kernel + for the check. Closes: #631188. + + -- Matthias Klose Sat, 09 Jul 2011 13:19:47 +0200 + +python2.7 (2.7.2-2) unstable; urgency=low + + * Update to 20110628, taken from the 2.7 branch. + * Add profile/pstats to the python2.7 package, update debian copyright. + * Don't run the bsddb3 tests on kfreebsd-amd64. + * Don't run the benchmark on hurd-i386. + + -- Matthias Klose Tue, 28 Jun 2011 23:05:21 +0200 + +python2.7 (2.7.2-1) unstable; urgency=low + + * Python 2.7.2 release. + + -- Matthias Klose Sun, 12 Jun 2011 21:04:24 +0200 + +python2.7 (2.7.2~rc1-2) unstable; urgency=medium + + * Set pyexpat dummy version string. + + -- Matthias Klose Tue, 31 May 2011 12:05:56 +0200 + +python2.7 (2.7.2~rc1-1) unstable; urgency=low + + * Python 2.7.2 release candidate 1. + * Update libpython symbols file for m68k (Thorsten Glaser). Closes: #627458. + * Apply proposed patch for issue #670664. LP: #357067. + + -- Matthias Klose Mon, 30 May 2011 06:44:23 +0200 + +python2.7 (2.7.1-9) unstable; urgency=low + + * Update to 20110520, taken from the 2.7 branch. + + -- Matthias Klose Fri, 20 May 2011 13:43:12 +0200 + +python2.7 (2.7.1-8) unstable; urgency=low + + * Keep the ssl.PROTOCOL_SSLv2 module constant , just raise an exception + when trying to create a PySSL object. Closes: #623423. + + -- Matthias Klose Wed, 20 Apr 2011 12:31:03 +0200 + +python2.7 (2.7.1-7) unstable; urgency=low + + * Update to 20110419, taken from the 2.7 branch. + * Build without OpenSSL v2 support. Closes: #620581. + * Force linking the curses module against libncursesw. Closes: #622064. + * Link libpython with --whole-archive. Closes: #614711. + * Re-enable running the testsuite during the build. + + -- Matthias Klose Tue, 19 Apr 2011 17:36:56 +0200 + +python2.7 (2.7.1-6) unstable; urgency=low + + * Update to 20110307, taken from the 2.7 branch. + * Disable the profile guided build on ia64, sparc. + + -- Matthias Klose Mon, 07 Mar 2011 02:19:02 +0100 + +python2.7 (2.7.1-5) experimental; urgency=low + + * Update to 20110224, taken from the 2.7 branch. + * Update patches. + * Re-enable profile guided build. + + -- Matthias Klose Thu, 24 Feb 2011 06:01:42 +0100 + +python2.7 (2.7.1-4) experimental; urgency=low + + * Update to 20110119, taken from the 2.7 branch. + + -- Matthias Klose Wed, 19 Jan 2011 04:21:14 +0100 + +python2.7 (2.7.1-3) experimental; urgency=low + + * Do not run test_multiprocessing when running the testsuite. + Fails on armel and powerpc on some buildds. + + -- Matthias Klose Fri, 24 Dec 2010 01:46:55 +0100 + +python2.7 (2.7.1-2) experimental; urgency=low + + * Update to 20101222, taken from the 2.7 branch. + * Re-enable the distutils-sysconfig.diff patch, apparently + lost when updating the patches for 2.7. + * Disable the profiled builds on all architectures. + + -- Matthias Klose Wed, 22 Dec 2010 15:39:48 +0100 + +python2.7 (2.7.1-1) experimental; urgency=low + + * Python 2.7.1 release. + + -- Matthias Klose Sun, 28 Nov 2010 12:05:23 +0100 + +python2.7 (2.7.1~rc1-2) experimental; urgency=low + + * Move the pyconfig.h file into the -min package, required by sysconfig. + Closes: #603237. + + -- Matthias Klose Sun, 14 Nov 2010 09:40:09 +0100 + +python2.7 (2.7.1~rc1-1) experimental; urgency=low + + * Python 2.7.1 release candidate 1. + * Move the Makefile into the -min package, required by sysconfig. + Closes: #603237. + + -- Matthias Klose Sun, 14 Nov 2010 00:33:48 +0100 + +python2.7 (2.7-9) experimental; urgency=low + + * Update to 20101016, taken from the 2.7 branch. + + -- Matthias Klose Sat, 16 Oct 2010 12:46:57 +0200 + +python2.7 (2.7-8) experimental; urgency=low + + * Disabled the profiled build on armel. + + -- Matthias Klose Thu, 23 Sep 2010 15:06:06 +0200 + +python2.7 (2.7-7) experimental; urgency=low + + * Update to 20100922, taken from the 2.7 branch. + * Update GNU/Hurd patches (Pino Toscano). Closes: #597419. + + -- Matthias Klose Wed, 22 Sep 2010 20:35:24 +0200 + +python2.7 (2.7-6) experimental; urgency=low + + * Update to 20100915, taken from the 2.7 branch. + - Fix issue #9729, Unconnected SSLSocket.{send,recv} raises TypeError + (Andrew Bennetts). LP: #637821. + * Add copyright information for expat, libffi and zlib. Addresses: #596276. + * Apply proposed fix for issue 9054, configure --with-system-expat. + * Provide Lib/plat-gnukfreebsd[78] (Jakub Wilk). Addresses: #593818. + + -- Matthias Klose Wed, 15 Sep 2010 17:43:18 +0200 + +python2.7 (2.7-5) experimental; urgency=low + + * Update to 20100829, taken from the 2.7 branch. + * Don't configure --with-system-expat, segfaults the interpreter in the + testsuite. + * Disable more tests on hppa and hurd-i386, which fail on the buildds. + + -- Matthias Klose Sun, 29 Aug 2010 16:22:37 +0200 + +python2.7 (2.7-4) experimental; urgency=low + + * Update to 20100822, taken from the 2.7 branch. + * Fixed in previous 2.7 uploads: Multiple integer overflows in audioop.c + in the audioop module (CVE-2010-1634). + * Fix some lintian warnings. + * Configure --with-system-expat. + + -- Matthias Klose Mon, 23 Aug 2010 13:03:40 +0200 + +python2.7 (2.7-3) experimental; urgency=low + + * Update to 20100807, taken from the 2.7 branch. + * Move '/usr/local/.../dist-packages' before '/usr/lib/.../dist-packages' + in sys.path. Adresses: #588342. + * Fix detection of ffi.h header file. Closes: #591408. + * python2-7-dev: Depend on libssl-dev. LP: #611845. + + -- Matthias Klose Sat, 07 Aug 2010 21:28:04 +0200 + +python2.7 (2.7-2) experimental; urgency=low + + * Complete debug-build.diff, some parts lost in quilt conversion. + * Move the pkgconfig file into the -dev package. + + -- Matthias Klose Tue, 06 Jul 2010 21:07:48 +0200 + +python2.7 (2.7-1) experimental; urgency=low + + * Python 2.7 release. + * Update to 20100706, taken from the trunk. + * Update symbols files. + + -- Matthias Klose Tue, 06 Jul 2010 07:21:23 +0200 + +python2.7 (2.7~rc2-3) experimental; urgency=low + + * Update to 20100703, taken from the trunk. + * Move the _weakrefset module, not extension to -minimal. Closes: #587568. + * Move the sysconfig module to -minimal. Closes: #586113. + * Move the shutil module to python2.6-minimal. Addresses: #587628. + + -- Matthias Klose Sat, 03 Jul 2010 13:27:36 +0200 + +python2.7 (2.7~rc2-2) experimental; urgency=low + + * Fix applying plat-linux2* patches. + * Use the profiled build on armel, sparc and sparc64. + + -- Matthias Klose Tue, 29 Jun 2010 08:04:59 +0200 + +python2.7 (2.7~rc2-1) experimental; urgency=low + + * Python 2.7 release candidate 2. + * Update to 20100628, taken from the trunk. + * Merge packaging changes from python2.6 (2.6.5+20100628-1). + + -- Matthias Klose Tue, 29 Jun 2010 00:57:00 +0200 + +python2.7 (2.7~b1-2) experimental; urgency=low + + * Update to 20100508, taken from the trunk. + + -- Matthias Klose Sat, 08 May 2010 17:34:07 +0200 + +python2.7 (2.7~b1-1) experimental; urgency=low + + * Python 2.7 beta1. + * Update to 20100420, taken from the trunk. + * Update libpython symbols files. + * Apply proposed patch for issue #7332, segfaults in + PyMarshal_ReadLastObjectFromFile in import_submodule. + * Don't build-depend on locales on avr32. Closes: #575144. + + -- Matthias Klose Tue, 20 Apr 2010 23:53:42 +0200 + +python2.7 (2.7~a4-1) experimental; urgency=low + + * Python 2.7 alpha4. + * Update to 20100316, taken from the trunk. + * Point distutils.sysconfig to the system installation. Closes: #573363. + + -- Matthias Klose Tue, 16 Mar 2010 15:45:07 +0100 + +python2.7 (2.7~a3-1) experimental; urgency=low + + * Python 2.7 alpha3. + + -- Matthias Klose Tue, 16 Feb 2010 03:04:01 +0100 + +python2.7 (2.7~a2-1) experimental; urgency=low + + * Python 2.7 alpha2. + + -- Matthias Klose Sat, 16 Jan 2010 14:49:59 +0100 + +python2.6 (2.6.5+20100628-1) unstable; urgency=low + + * Update to 20100614, taken from the 2.6 release branch (r82337). + * Apply plat-linux2- patch for alpha, hppa, mips, mipsel, sparc + and sparc64. + + -- Matthias Klose Mon, 28 Jun 2010 21:26:43 +0200 + +python2.6 (2.6.5+20100626-1) unstable; urgency=low + + * Update to 20100614, taken from the 2.6 release branch (r82245). + * Update libpython symbols files. Closes: #587012. + * Move the logging package and the runpy module to python2.6-minimal. + + -- Matthias Klose Sat, 26 Jun 2010 14:29:41 +0200 + +python2.6 (2.6.5+20100616-1) unstable; urgency=medium + + * Update to 20100614, taken from the 2.6 release branch (r81601). + * Reapply the backport for issue #8233, lost in the conversion to + quilt. + * Disable the profiled build on alpha. + * Make pydoc more robust not to fail on exceptions other than import + exceptions. + * posixmodule: Add flags for statvfs.f_flag to constant list. + + -- Matthias Klose Wed, 16 Jun 2010 07:56:40 +0200 + +python2.6 (2.6.5+20100529-1) unstable; urgency=low + + * Update to 20100529, taken from the 2.6 release branch (r81601). + - Fix issue #5753, CVE-2008-5983 python: untrusted python modules + search path. Closes: #572010. + * Convert internal dpatch system to quilt. + * Build the ossaudio extension on GNU/kFreeBSD. Closes: #574696. + + -- Matthias Klose Sat, 29 May 2010 15:07:51 +0200 + +python2.6 (2.6.5-2) unstable; urgency=low + + * Update libpython symbols files. + * debian/patches/issue8032.dpatch: Update to version from the + trunk. + * Fix issue #8329: Don't return the same lists from select.select + when no fds are changed. + * Fix issue #8310: Allow dis to examine new style classes. + * Fix issues #8279: Fix test_gdb failures. + * Fix issue #8233: When run as a script, py_compile.py optionally + takes a single argument `-`. + * Apply proposed patch for issue #7332, segfaults in + PyMarshal_ReadLastObjectFromFile in import_submodule. + * Don't build-depend on locales on avr32. Closes: #575144. + + -- Matthias Klose Tue, 20 Apr 2010 19:41:36 +0200 + +python2.6 (2.6.5-1ubuntu6) lucid; urgency=low + + * Fix applying patch for issue #8310. + + -- Matthias Klose Fri, 16 Apr 2010 14:20:35 +0200 + +python2.6 (2.6.5-1ubuntu5) lucid; urgency=low + + * Fix issue #8329: Don't return the same lists from select.select + when no fds are changed. + * Fix issue #8310: Allow dis to examine new style classes. + + -- Matthias Klose Thu, 15 Apr 2010 01:21:07 +0200 + +python2.6 (2.6.5-1ubuntu4) lucid; urgency=low + + * debian/patches/issue8032.dpatch: Update to version from the + trunk. Upload for beta2 to avoid apport errors. + - Handle PyFrameObject's: LP: #543624, #548723. + - Detect cycles in object reference graph and add extra + protection: LP: #544823, LP: #552356. + + -- Matthias Klose Thu, 01 Apr 2010 22:53:06 +0200 + +python2.6 (2.6.5-1ubuntu3) lucid; urgency=low + + * debian/patches/issue8140.dpatch: Incomplete patch; regenerate. + * debian/patches/issue8032.dpatch: Update to v4: + - Add support for PySetObject (set/frozenset). + - Add support for PyBaseExceptionObject (BaseException). + - Fix a signed vs unsigned char issue that led to exceptions + in gdb for PyStringObject instances. + - Handle the case of loops in the object reference graph. + - Unit tests for all of the above. + + -- Matthias Klose Wed, 31 Mar 2010 18:52:32 +0200 + +python2.6 (2.6.5-1ubuntu2) lucid; urgency=low + + * Disable profiled build on powerpc. + + -- Matthias Klose Sat, 20 Mar 2010 15:17:18 +0100 + +python2.6 (2.6.5-1ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.5-1). + + -- Matthias Klose Sat, 20 Mar 2010 03:57:17 +0100 + +python2.6 (2.6.5-1) unstable; urgency=low + + * Python 2.6.5 final release. + * Fix issue #4961: Inconsistent/wrong result of askyesno function in + tkMessageBox with Tcl8.5. LP: #462950. + * Issue #8154, fix segfault with os.execlp('true'). LP: #418848. + * Apply proposed patch for issue #8032, gdb7 hooks for debugging. + + -- Matthias Klose Fri, 19 Mar 2010 00:12:55 +0100 + +python2.6 (2.6.5~rc2-2) unstable; urgency=low + + * Add copyright notices for the readline and _ssl extensions. + Closes: #573866. + * Backport issue #8140: Extend compileall to compile single files. + Add -i option. + * Backport issue #6949, build _bsddb extension with db-4.8.x. + + -- Matthias Klose Tue, 16 Mar 2010 03:02:21 +0100 + +python2.6 (2.6.5~rc2-1) unstable; urgency=low + + * Python 2.6.5 release candidate 2. + - Replace the Monty Python audio test file. Closes: #568674. + * Fix build failure on sparc64. Closes: #570845. + + -- Matthias Klose Thu, 11 Mar 2010 16:50:03 +0100 + +python2.6 (2.6.5~rc2-0ubuntu1) lucid; urgency=low + + * Python 2.6.5 release candidate 2. + + -- Matthias Klose Thu, 11 Mar 2010 13:30:19 +0100 + +python2.6 (2.6.4-6ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.4-6). + + -- Matthias Klose Tue, 16 Feb 2010 01:08:50 +0100 + +python2.6 (2.6.4-6) unstable; urgency=low + + * Update to 20100215, taken from the 2.6 release branch. + * python2.6-minimal: Skip moving syssite contents to new location, if + /usr/local/lib/python2.6 cannot be written. Closes: #569532. LP: #338227. + * libpython2.6: Fix symlink in /usr/lib/python2.6/config. LP: #521050. + + -- Matthias Klose Mon, 15 Feb 2010 22:12:18 +0100 + +python2.6 (2.6.4-5ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.4-5). + + -- Matthias Klose Sun, 31 Jan 2010 22:31:41 +0100 + +python2.6 (2.6.4-5) unstable; urgency=low + + * Update to 20100131, taken from the 2.6 release branch. + - Fix typo in os.execvp docstring. Closes: #558764. + * distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment and if --user option is not present. LP: #476005. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present, without changing the install prefix. + LP: #510211. + + -- Matthias Klose Sun, 31 Jan 2010 21:16:51 +0100 + +python2.6 (2.6.4-4ubuntu1) lucid; urgency=low + + * Update to 20100122, taken from the 2.6 release branch. + - Fix DoS via XML document with malformed UTF-8 sequences (CVE_2009_3560). + Closes: #566233. + - Fix typo in os.execvp docstring. Closes: #558764. + * python2.6-doc: Fix searching in local documentation. LP: #456025. + * Update locale module from the trunk. LP: #223281. + * Merge with Debian (2.6.4-4). + + -- Matthias Klose Fri, 22 Jan 2010 11:37:29 +0100 + +python2.6 (2.6.4-4) unstable; urgency=low + + * Update to 20100122, taken from the 2.6 release branch. + - Fix DoS via XML document with malformed UTF-8 sequences (CVE_2009_3560). + Closes: #566233. + * Hurd fixes (Pino Toscano). Closes: #565693: + - hurd-broken-poll.dpatch: ported from 2.5. + - hurd-disable-nonworking-constants.dpatch: disable a few constants from + the public API whose C counterparts are not implemented, so using them + either always blocks or always fails (caused issues in the test suite). + - Exclude the profiled build for hurd. + - Disable four blocking tests from the test suite. + + -- Matthias Klose Fri, 22 Jan 2010 11:10:41 +0100 + +python2.6 (2.6.4-3) unstable; urgency=low + + * Disable the profiled build on s390, mips, mipsel. + * Fix symbol files for kfreebsd-amd64 and sparc64. + + -- Matthias Klose Sat, 16 Jan 2010 16:12:17 +0100 + +python2.6 (2.6.4-2) unstable; urgency=low + + * Update to 20100116, taken from the 2.6 release branch. + * Fix bashism in makesetup shell script. Closes: #530170, #530171. + * Fix build issues on avr (Bradley Smith). Closes: #528439. + - Configure --without-ffi. + - Don't run lengthly tests. + * locale.py: Update locale aliases from the 2.7 branch. + + -- Matthias Klose Sat, 16 Jan 2010 11:05:12 +0100 + +python2.6 (2.6.4-1) experimental; urgency=low + + * Python 2.6.4 final release. + - Issue #7120: logging: Removed import of multiprocessing which is causing + crash in GAE. + - Issue #7149: fix exception in urllib when detecting proxy settings + on OSX. + - Issue #7115: Fixed the extension module builds that is failing when + using paths in the extension name instead of dotted names. LP: #449734. + - Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" + environment. + - Issue #7052: Removed nonexisting NullHandler from logging.__all__. + - Issue #7039: Fixed distutils.tests.test_sysconfig when running on + installation with no build. + - Issue #7019: Raise ValueError when unmarshalling bad long data, instead + of producing internally inconsistent Python longs. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present. + + -- Matthias Klose Tue, 27 Oct 2009 01:22:21 +0100 + +python2.6 (2.6.4~rc1-1) experimental; urgency=low + + * Python 2.6.4 release candidate 1. + - Issue #7052: Removed nonexisting NullHandler from logging.__all__. + - Issue #7039: Fixed distutils.tests.test_sysconfig when running on + installation with no build. + - Issue #7019: Raise ValueError when unmarshalling bad long data, instead + of producing internally inconsistent Python longs. + - Issue #7068: Fixed the partial renaming that occured in r72594. + - Issue #7042: Fix test_signal (test_itimer_virtual) failure on OS X 10.6. + * Remove the conflict with python-setuptools (fixed in issue #7068). + * Build _hashlib as a builtin. + * python2.6-doc: Don't compress the sphinx inventory. + * python2.6-doc: Fix jquery.js symlink. + + -- Matthias Klose Sat, 10 Oct 2009 10:21:02 +0200 + +python2.6 (2.6.3-1) experimental; urgency=low + + * Final Python 2.6.3 release. + - Issue #5329: Fix os.popen* regression from 2.5 with commands as a + sequence running through the shell. + - Issue #6990: Fix threading.local subclasses leaving old state around + after a reference cycle GC which could be recycled by new locals. + - Issue #6790: Make it possible again to pass an `array.array` to + `httplib.HTTPConnection.send`. + - Issue #6922: Fix an infinite loop when trying to decode an invalid + UTF-32 stream with a non-raising error handler like "replace" or + "ignore". + - Issue #1590864: Fix potential deadlock when mixing threads and fork(). + - Issue #6844: Do not emit DeprecationWarnings when accessing a "message" + attribute on exceptions that was set explicitly. + - Issue #6236, #6348: Fix various failures in the `io` module under AIX + and other platforms, when using a non-gcc compiler. Patch by egreen. + - Issue #6851: Fix urllib.urlopen crash on secondairy threads on OSX 10.6 + - Issue #6947: Fix distutils test on windows. Patch by Hirokazu Yamamoto. + - Issue #4606: Passing 'None' if ctypes argtype is set to POINTER(...) + does now always result in NULL. + - Issue #5042: ctypes Structure sub-subclass does now initialize + correctly with base class positional arguments. + - Issue #6938: Fix a TypeError in string formatting of a multiprocessing + debug message. + - Issue #6944: Fix a SystemError when socket.getnameinfo() was called + with something other than a tuple as first argument. + - Issue #6980: Fix ctypes build failure on armel-linux-gnueabi with + -mfloat-abi=softfp. + * python2.6-dbg: Don't create debug subdirectory in /usr/local. No + separate debug directory needed anymore. + * Run the benchmark with -C 2 -n 5 -w 4 on all architectures. + * Build-depend on the versioned db4.x-dev to avoid unexpected updates + for anydbm databases. + + -- Matthias Klose Sat, 03 Oct 2009 13:19:56 +0200 + +python2.6 (2.6.2-3) experimental; urgency=low + + * Update to 20090919, taken from the 2.6 release branch. + * Add a conflict to python-setuptools (<< 0.6c9-3), C extension + builds broken. + * Add new symbols for update from the branch. + + -- Matthias Klose Sat, 19 Sep 2009 10:36:34 +0200 + +python2.6 (2.6.2-2) experimental; urgency=low + + * Symbol _Py_force_double@Base is i386 only. Closes: #534208. + + -- Matthias Klose Tue, 23 Jun 2009 06:14:40 +0200 + +python2.6 (2.6.2-1) experimental; urgency=low + + * Final Python 2.6.2 release. + - Update Doc/tools/sphinxext/download.html. Closes: #526797. + * Update to 20090621, taken from the 2.6 release branch. + + * Address issues when working with PYTHONUSERBASE and non standard prefix + (pointed out by Larry Hastings): + - distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment. + - site.addusersitepackages(): Add USER_BASE/.../dist-packages to sys.path. + * Always use the `unix_prefix' scheme for setup.py install in a virtualenv + setup. LP: #339904. + * Don't make the setup.py install options --install-layout=deb and --prefix + conflict with each other. + * distutils: Always install into `/usr/local/lib/python2.6/dist-packages' + if an option `--prefix=/usr/local' is present (except for virtualenv + and PYTHONUSERBASE installations). LP: #362570. + * Always use `site-packages' as site directory name in virtualenv. + + * Do not add /usr/lib/pythonXY.zip on sys.path. + * Add symbols files for libpython2.6 and python2.6-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python2.6-minimal to avoid a warning on + startup. + * Build a shared library configured --with-pydebug. LP: #322580. + * Fix some lintian warnings. + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * Move the bdist_wininst files into the -dev package (only needed to build + windows installers). + * Document changes to the site directory name in the installation manual. + * Fix issue #1113244: Py_XINCREF, Py_DECREF, Py_XDECREF: Add + `do { ... } while (0)' to avoid compiler warnings. Closes: #516956. + * debian/pyhtml2devhelp.py: update for python 2.6 (Marc Deslauriers). + * debian/rules: re-enable documentation files for devhelp. LP: #338791. + * python2.6-doc: Depend on libjs-jquery, use jquery.js from this package. + Closes: #523482. + + -- Matthias Klose Sun, 21 Jun 2009 16:12:15 +0200 + +python2.6 (2.6.1-3) experimental; urgency=low + + * Update to 20090318, taken from the 2.6 release branch. + * Use the information in /etc/lsb-release for platform.dist(). + * Update installation schemes: LP: #338395. Closes: #520278. + - When the --prefix option is used for setup.py install, Use the + `unix_prefix' scheme. + - Use the `deb_system' scheme if --install-layout=deb is specified. + - Use the the `unix_local' scheme if neither --install-layout=deb + nor --prefix is specified. + - The options --install-layout=deb and --prefix are exclusive. + * Don't fail installation/removal if directories in /usr/local cannot + be created. LP: #338227. + * Don't try to move away the site-packages directory. There never was a + python2.6 upload using site-packages. Closes: #518780. + * Fix build failure on mips/mipsel. Closes: #519386. + + -- Matthias Klose Wed, 18 Mar 2009 22:17:20 +0100 + +python2.6 (2.6.1-2) experimental; urgency=low + + * Move libpython2.6.a into the python2.6-dev package. + * Move idlelib into the idle-python2.6 package. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-1) experimental; urgency=low + + * New upstream version, upload to experimental. + * Update to 20090225, taken from the 2.6 release branch. + * Don't build-depend on locales on armel, hppa, ia64 and mipsel; package is + currently not installable. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-0ubuntu9) jaunty; urgency=low + + * Don't build pyexpat, _elementtree and _ctypes as builtin extensions, + third party packages make too many assumptions about these not built + as builtins. + + -- Matthias Klose Tue, 24 Feb 2009 16:34:27 +0100 + +python2.6 (2.6.1-0ubuntu8) jaunty; urgency=low + + * Link the shared libpython with $(MODLIBS). + + -- Matthias Klose Sun, 22 Feb 2009 16:38:49 +0100 + +python2.6 (2.6.1-0ubuntu7) jaunty; urgency=low + + * Update to 20090222, taken from the 2.6 release branch. + + -- Matthias Klose Sun, 22 Feb 2009 10:35:29 +0100 + +python2.6 (2.6.1-0ubuntu6) jaunty; urgency=low + + * Don't build the gdbm extension from the python2.6 source. + * Build the dbm extension using libdb. + * Don't build-depend on locales on sparc (currently not installable), only + needed by the testsuite. + * Update to 20090219, taken from the 2.6 release branch. + + -- Matthias Klose Thu, 19 Feb 2009 12:43:20 +0100 + +python2.6 (2.6.1-0ubuntu5) jaunty; urgency=low + + * Add build dependency on libdb-dev. + + -- Matthias Klose Mon, 16 Feb 2009 13:34:41 +0100 + +python2.6 (2.6.1-0ubuntu4) jaunty; urgency=low + + * Disable the profiled build on all architectures. + + -- Matthias Klose Mon, 16 Feb 2009 11:18:51 +0100 + +python2.6 (2.6.1-0ubuntu3) jaunty; urgency=low + + * Disable the profiled build on armel as well. + + -- Matthias Klose Sun, 15 Feb 2009 10:38:02 +0100 + +python2.6 (2.6.1-0ubuntu2) jaunty; urgency=low + + * Don't use the profiled build on amd64, lpia and sparc (GCC + PR profile/38292). + + -- Matthias Klose Sat, 14 Feb 2009 14:09:34 +0100 + +python2.6 (2.6.1-0ubuntu1) jaunty; urgency=low + + * Update to 20090211, taken from the 2.6 release branch. + + -- Matthias Klose Fri, 13 Feb 2009 12:51:00 +0100 + +python2.6 (2.6.1-0ubuntu1~ppa1) jaunty; urgency=low + + * Python 2.6.1 release. + * Update to 20081206, taken from the 2.6 release branch. + * Ensure that all extensions from the -minimal package are statically + linked into the interpreter. + * Include expat, _elementtree, datetime, bisect, _bytesio, _locale, + _fileio in -minimal to link these extensions statically. + + -- Matthias Klose Fri, 05 Dec 2008 20:43:51 +0100 + +python2.6 (2.6-0ubuntu1~ppa5) intrepid; urgency=low + + * Test build + + -- Matthias Klose Fri, 14 Nov 2008 10:14:38 +0100 + +python2.6 (2.6-0ubuntu1~ppa4) intrepid; urgency=low + + * Do not build the bsddb3 module from this source, but recommend the + python-bsddb3 package (will be a dependency after python-bsddb3 is in + the archive). + * For locally installed packages, create a directory + /usr/local/lib/python2.6/dist-packages. This is the default for + installations done with distutils and setuptools. Third party stuff + packaged within the distribution goes to /usr/lib/python2.6/dist-packages. + There is no /usr/lib/python2.6/site-packages in the file system and + on sys.path. No package within the distribution must not install + anything in this location. + * Place the gdbm extension into the python2.6 package. + * distutils: Add an option --install-layout=deb, which + - installs into $prefix/dist-packages instead of $prefix/site-packages. + - doesn't encode the python version into the egg name. + + -- Matthias Klose Sat, 25 Oct 2008 11:12:24 +0000 + +python2.6 (2.6-0ubuntu1~ppa3) intrepid; urgency=low + + * Build-depend on libdb4.6-dev, instead of libdb-dev (4.7). Test suite + hangs in the bsddb tests. + + -- Matthias Klose Wed, 22 Oct 2008 11:05:13 +0200 + +python2.6 (2.6-0ubuntu1~ppa2) intrepid; urgency=low + + * Update to 20081021, taken from the 2.6 release branch. + * Fix typos and section names in doc-base files. LP: #273344. + * Build a new package libpython2.6. + * For locally installed packages, create a directory + /usr/local/lib/python2.6/system-site-packages, which is symlinked + from /usr/lib/python2.6/site-packages. Third party stuff packaged + within the distribution goes to /usr/lib/python2.6/dist-packages. + + -- Matthias Klose Tue, 21 Oct 2008 18:09:31 +0200 + +python2.6 (2.6-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 release. + * Update to current branch 20081009. + + -- Matthias Klose Thu, 09 Oct 2008 14:28:26 +0200 + +python2.6 (2.6~b3-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta3 release. + + -- Matthias Klose Sun, 24 Aug 2008 01:34:54 +0000 + +python2.6 (2.6~b2-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta2 release. + + -- Matthias Klose Thu, 07 Aug 2008 16:45:56 +0200 + +python2.6 (2.6~b1-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta1 release. + + -- Matthias Klose Tue, 15 Jul 2008 12:57:20 +0000 + +python2.6 (2.6~a3-0ubuntu1~ppa2) hardy; urgency=low + + * Test build + + -- Matthias Klose Thu, 29 May 2008 18:08:48 +0200 + +python2.6 (2.6~a3-0ubuntu1~ppa1) hardy; urgency=low + + * Python 2.6 alpha3 release. + * Update to current trunk 20080523. + + -- Matthias Klose Thu, 22 May 2008 17:37:46 +0200 + +python2.5 (2.5.2-5) unstable; urgency=low + + * Backport new function signal.set_wakeup_fd from the trunk. + Background: http://bugzilla.gnome.org/show_bug.cgi?id=481569 + + -- Matthias Klose Wed, 30 Apr 2008 12:05:10 +0000 + +python2.5 (2.5.2-4) unstable; urgency=low + + * Update to 20080427, taken from the 2.5 release branch. + - Fix issues #2670, #2682. + * Disable running pybench on the hppa buildd (ftbfs). + * Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, + CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + * Support parallel= in DEB_BUILD_OPTIONS (see #209008). + + -- Matthias Klose Sun, 27 Apr 2008 10:40:51 +0200 + +python2.5 (2.5.2-3) unstable; urgency=medium + + * Update to 20080416, taken from the 2.5 release branch. + - Fix CVE-2008-1721, integer signedness error in the zlib extension module. + - Fix urllib2 file descriptor happens byte-at-a-time, reverting + a fix for excessively large memory allocations when calling .read() + on a socket object wrapped with makefile(). + * Disable some regression tests on some architectures: + - arm: test_compiler, test_ctypes. + - armel: test_compiler. + - hppa: test_fork1, test_wait3. + - m68k: test_bsddb3, test_compiler. + * Build-depend on libffi-dev instead of libffi4-dev. + * Fix CVE-2008-1679, integer overflows in the imageop module. + + -- Matthias Klose Wed, 16 Apr 2008 23:37:46 +0200 + +python2.5 (2.5.2-2) unstable; urgency=low + + * Use site.addsitedir() to add directories in /usr/local to sys.path. + Addresses: #469157, #469818. + + -- Matthias Klose Sat, 08 Mar 2008 16:11:23 +0100 + +python2.5 (2.5.2-1) unstable; urgency=low + + * Python 2.5.2 release. + * Merge from Ubuntu: + - Move site customization into sitecustomize.py, don't make site.py + a config file. Addresses: #309719, #413172, #457361. + - Move site.py to python2.4-minimal, remove `addbuilddir' from site.py, + which is unnecessary for installed builds. + - python2.5-dev: Recommend libc-dev instead of suggesting it. LP: #164909. + - Fix issue 961805, Tk Text.edit_modified() fails. LP: #84720. + + -- Matthias Klose Thu, 28 Feb 2008 23:18:52 +0100 + +python2.5 (2.5.1-7) unstable; urgency=low + + * Update to 20080209, taken from the 2.5 release branch. + * Build the _bsddb extension with db-4.5 again; 4.6 is seriously + broken when used with the _bsddb extension. + * Do not run pybench on arm and armel. + * python2.5: Provide python2.5-wsgiref. + * Fix a pseudo RC report with duplicated attributes in the control + file. Closes: #464307. + + -- Matthias Klose Sun, 10 Feb 2008 00:22:57 +0100 + +python2.5 (2.5.1-6) unstable; urgency=low + + * Update to 20080102, taken from the 2.5 release branch. + - Only define _BSD_SOURCE on OpenBSD systems. Closes: #455400. + * Fix handling of packages in linecache.py (Kevin Goodsell). LP: #70902. + * Bump debhelper to v5. + * Register binfmt for .py[co] files. + * Use absolute paths when byte-compiling files. Addresses: #453346. + Closes: #413566, LP: #177722. + * CVE-2007-4965, http://bugs.python.org/issue1179: + Multiple integer overflows in the imageop module in Python 2.5.1 and + earlier allow context-dependent attackers to cause a denial of service + (application crash) and possibly obtain sensitive information (memory + contents) via crafted arguments to (1) the tovideo method, and unspecified + other vectors related to (2) imageop.c, (3) rbgimgmodule.c, and other + files, which trigger heap-based buffer overflows. + Patch prepared by Stephan Herrmann. Closes: #443333, LP: #163845. + * Register info docs when doing source only uploads. LP: #174786. + * Remove deprecated value from categories in desktop file. LP: #172874. + * python2.5-dbg: Don't include the gdbm and _tkinter extensions, now provided + in separate packages. + * Provide a symlink changelog -> NEWS. Closes: #439271. + * Fix build failure on hurd, working around poll() on systems on which it + returns an error on invalid FDs. Closes: #438914. + * Configure --with-system-ffi on all architectures. Closes: #448520. + * Fix version numbers in copyright and README files (Dan O'Huiginn). + Closes: #446682. + * Move some documents from python2.5 to python2.5-dev. + + -- Matthias Klose Wed, 02 Jan 2008 22:22:19 +0100 + +python2.5 (2.5.1-5) unstable; urgency=low + + * Build the _bsddb extension with db-4.6. + + -- Matthias Klose Fri, 17 Aug 2007 00:39:35 +0200 + +python2.5 (2.5.1-4) unstable; urgency=low + + * Update to 20070813, taken from the 2.5 release branch. + * Include plat-mac/plistlib.py (plat-mac is not in sys.path by default. + Closes: #435826. + * Use emacs22 to build the documentation in info format. Closes: #434969. + * Build-depend on db-dev (>= 4.6). Closes: #434965. + + -- Matthias Klose Mon, 13 Aug 2007 22:22:44 +0200 + +python2.5 (2.5.1-3) unstable; urgency=high + + * Support mixed-endian IEEE floating point, as found in the ARM old-ABI + (Aurelien Jarno). Closes: #434905. + + -- Matthias Klose Fri, 27 Jul 2007 20:01:35 +0200 + +python2.5 (2.5.1-2) unstable; urgency=low + + * Update to 20070717, taken from the 2.5 release branch. + * Fix reference count for sys.pydebug variable. Addresses: #431393. + * Build depend on libbluetooth-dev instead of libbluetooth2-dev. + + -- Matthias Klose Tue, 17 Jul 2007 14:09:47 +0200 + +python2.5 (2.5.1-1) unstable; urgency=low + + * Python-2.5.1 release. + * Build-depend on gcc-4.1 (>= 4.1.2-4) on alpha, powerpc, s390, sparc. + * Merge from Ubuntu: + - Add debian/patches/subprocess-eintr-safety.dpatch (LP: #87292): + - Create and use wrappers around read(), write(), and os.waitpid() in the + subprocess module which retry the operation on an EINTR (which happens + if e. g. an alarm was raised while the system call was in progress). + It is incredibly hard and inconvenient to sensibly handle this in + applications, so let's fix this at the right level. + - Patch based on original proposal of Peter <85>strand + in http://python.org/sf/1068268. + - Add two test cases. + - Change the interpreter to build and install python extensions + built with the python-dbg interpreter with a different name into + the same path (by appending `_d' to the extension name). The debug build + of the interpreter tries to first load a foo_d.so or foomodule_d.so + extension, then tries again with the normal name. + - When trying to import the profile and pstats modules, don't + exit, add a hint to the exception pointing to the python-profiler + package, don't exit. + - Keep the module version in the .egg-info name, only remove the + python version. + - python2.5-dbg: Install Misc/SpecialBuilds.txt, document the + debug changes in README.debug. + * Update to 20070425, taken from the 2.5 release branch. + + -- Matthias Klose Wed, 25 Apr 2007 22:12:50 +0200 + +python2.5 (2.5-6) unstable; urgency=medium + + * webbrowser.py: Recognize other browsers: www-browser, x-www-browser, + iceweasel, iceape. + * Move pyconfig.h from the python2.5-dev into the python2.5 package; + required by builds for pure python modules without having python2.5-dev + installed (matching the functionality in python2.4). + * Move the unicodedata module into python2.5-minimal; allows byte compilation + of UTF8 encoded files. + * Do not install anymore outdated debhelper sample scripts. + * Install Misc/SpecialBuilds.txt as python2.5-dbg document. + + -- Matthias Klose Wed, 21 Feb 2007 01:17:12 +0100 + +python2.5 (2.5-5) unstable; urgency=high + + * Do not run the python benchmark on m68k. Timer problems. + Fixes FTBFS on m68k. + * Update to 20061209, taken from the 2.5 release branch. + - Fixes building the library reference in info format. + + -- Matthias Klose Sat, 9 Dec 2006 13:40:48 +0100 + +python2.5 (2.5-4) unstable; urgency=medium + + * Update to 20061203, taken from the 2.5 release branch. + - Fixes build failures on knetfreebsd and the hurd. Closes: #397000. + * Clarify README about distutils. Closes: #396394. + * Move python2.5-config to python2.5-dev. Closes: #401451. + * Cleanup build-conflicts. Addresses: #394512. + + -- Matthias Klose Sun, 3 Dec 2006 18:22:49 +0100 + +python2.5 (2.5-3.1) unstable; urgency=low + + * Non-maintainer upload. + * python2.5-minimal depends on python-minimal (>= 2.4.4-1) because it's the + first version which lists python2.5 as an unsupported runtime (ie a + runtime that is available but for which modules are not auto-compiled). + And being listed there is required for python-central to accept the + installation of python2.5-minimal. Closes: #397006 + + -- Raphael Hertzog Wed, 22 Nov 2006 15:41:06 +0100 + +python2.5 (2.5-3) unstable; urgency=medium + + * Update to 20061029 (2.4.4 was released on 20061019), taken from + the 2.5 release branch. We do not want to have regressions in + 2.5 compared to the 2.4.4 release. + * Don't run pybench on m68k, fails in the calibration loop. Closes: #391030. + * Run the installation/removal hooks. Closes: #383292, #391036. + + -- Matthias Klose Sun, 29 Oct 2006 11:35:19 +0100 + +python2.5 (2.5-2) unstable; urgency=medium + + * Update to 20061003, taken from the 2.5 release branch. + * On arm and m68k, don't run the pybench in debug mode. + * Fix building the source within exec_prefix (Alexander Wirt). + Closes: #385336. + + -- Matthias Klose Tue, 3 Oct 2006 10:08:36 +0200 + +python2.5 (2.5-1) unstable; urgency=low + + * Python 2.5 release. + * Update to 20060926, taken from the 2.5 release branch. + * Run the Python benchmark during the build, compare the results + of the static and shared builds. + * Fix invalid html in python2.5.devhelp.gz. + * Add a python2.5 console entry to the menu (hidden by default). + * python2.5: Suggest python-profiler. + + -- Matthias Klose Tue, 26 Sep 2006 02:36:11 +0200 + +python2.5 (2.5~c1-1) unstable; urgency=low + + * Python 2.5 release candidate 1. + * Update to trunk 20060818. + + -- Matthias Klose Sat, 19 Aug 2006 19:21:05 +0200 + +python2.5 (2.5~b3-1) unstable; urgency=low + + * Build the _ctypes module for m68k-linux. + + -- Matthias Klose Fri, 11 Aug 2006 18:19:19 +0000 + +python2.5 (2.5~b3-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta3 release. + * Update to trunk 20060811. + * Rebuild the documentation. + * Fix value of sys.exec_prefix in the debug build. + * Do not build the library reference in info format; fails to build. + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 6%. + * Install the statically linked version of the interpreter as + python2.5-static for now. + * Link the shared libpython with -O1. + + -- Matthias Klose Thu, 10 Aug 2006 14:04:48 +0000 + +python2.5 (2.4.3+2.5b2-3) unstable; urgency=low + + * Disable the testsuite on s390; don't care about "minimally configured" + buildd's. + + -- Matthias Klose Sun, 23 Jul 2006 11:45:03 +0200 + +python2.5 (2.4.3+2.5b2-2) unstable; urgency=low + + * Update to trunk 20060722. + * Merge idle-lib from idle-python2.5 into python2.5. + * Merge lib-tk from python-tk into python2.5. + * Tkinter.py: Suggest installation of python-tk package on failed + import of the _tkinter extension. + * Don't run the testsuite for the debug build on alpha. + * Don't run the test_compiler test on m68k. Just takes too long. + * Disable building ctypes on m68k (requires support for closures). + + -- Matthias Klose Sat, 22 Jul 2006 22:26:42 +0200 + +python2.5 (2.4.3+2.5b2-1) unstable; urgency=low + + * Python 2.5 beta2 release. + * Update to trunk 20060716. + * When built on a buildd, do not run the following test which try to + access the network: test_codecmaps_cn, test_codecmaps_hk, test_codecmaps_jp, + test_codecmaps_kr, test_codecmaps_tw, test_normalization. + * When built on a buildd, do not run tests requiring missing write permissions: + test_ossaudiodev. + + -- Matthias Klose Sun, 16 Jul 2006 02:53:50 +0000 + +python2.5 (2.4.3+2.5b2-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta2 release. + + -- Matthias Klose Thu, 13 Jul 2006 17:16:52 +0000 + +python2.5 (2.4.3+2.5b1-1ubuntu2) edgy; urgency=low + + * Fix python-dev dependencies. + * Update to trunk 20060709. + + -- Matthias Klose Sun, 9 Jul 2006 18:50:32 +0200 + +python2.5 (2.4.3+2.5b1-1ubuntu1) edgy; urgency=low + + * Python 2.5 beta1 release. + * Update to trunk 20060623. + * Merge changes from the python2.4 packages. + * python2.5-minimal: Add _struct. + + -- Matthias Klose Fri, 23 Jun 2006 16:04:46 +0200 + +python2.5 (2.4.3+2.5a1-1) experimental; urgency=low + + * Update to trunk 20060409. + * Run testsuite for debug build as well. + * Build-depend on gcc-4.1. + + -- Matthias Klose Sun, 9 Apr 2006 22:27:05 +0200 + +python2.5 (2.4.3+2.5a1-0ubuntu1) dapper; urgency=low + + * Python 2.5 alpha1 release. + * Drop integrated patches. + * Add build dependencies on libsqlite3-dev and libffi4-dev. + * Add (build-)dependency on mime-support, libgpmg1 (test suite). + * Build using the system FFI. + * python2.5 provides python2.5-ctypes and python2.5-pysqlite2, + python2.5-elementtree. + * Move hashlib.py to python-minimal. + * Lib/hotshot/pstats.py: Error out on missing profile/pstats modules. + + -- Matthias Klose Wed, 5 Apr 2006 14:56:15 +0200 + +python2.4 (2.4.3-8ubuntu1) edgy; urgency=low + + * Resynchronize with Debian unstable. Remaining changes: + - Apply langpack-gettext patch. + - diff.gz contains pregenerated html and info docs. + - Build the -doc package from this source. + + -- Matthias Klose Thu, 22 Jun 2006 18:39:57 +0200 + +python2.4 (2.4.3-8) unstable; urgency=low + + * Remove python2.4's dependency on python-central. On installation of + the runtime, call hooks /usr/share/python/runtime.d/*.rtinstall. + On removal, call hooks /usr/share/python/runtime.d/*.rtremove. + Addresses: #372658. + * Call the rtinstall hooks only, if it's a new installation, or the first + installation using the hooks. Adresses: #373677. + + -- Matthias Klose Sun, 18 Jun 2006 00:56:13 +0200 + +python2.4 (2.4.3-7) unstable; urgency=medium + + * Reupload, depend on python-central (>= 0.4.15). + * Add build-conflict on python-xml. + + -- Matthias Klose Wed, 14 Jun 2006 18:56:57 +0200 + +python2.4 (2.4.3-6) medium; urgency=low + + * idle-python2.4: Remove the old postinst and prerm scripts. + * Name the runtime correctly in python2.4-minimal's installation + scripts. + + -- Matthias Klose Mon, 12 Jun 2006 17:39:56 +0000 + +python2.4 (2.4.3-5) unstable; urgency=low + + * python2.4-prerm: Handle the case, when python-central is not installed. + * idle-python2.4: Depend on python-tk instead of python2.4-tk. + + -- Matthias Klose Fri, 9 Jun 2006 05:17:17 +0200 + +python2.4 (2.4.3-4) unstable; urgency=low + + * SVN update up to 2006-06-07 + * Use python-central. + * Don't build the -tk and -gdbm packages from this source; now built + from the python-stdlib-extensions source. + * Remove leftover build dependency on libgmp3-dev. + * Do not build-depend on libbluetooth1-dev and libgpmg1-dev on + hurd-i386, kfreebsd-i386, kfreebsd-amd64. Closes: #365830. + * Do not run the test_tcl test; hangs for unknown reasons on at least + the following buildds: vivaldi(m68k), goedel (alpha), mayer (mipsel). + And no virtual package to file bug reports for the buildds ... + Closes: #364419. + * Move the Makefile from python2.4-dev to python2.4. Closes: #366473. + * Fix typo in pdb(1). Closes: #365772. + * New autoconf likes the mandir in /usr/share instead of /usr; work + with both locations. Closes: #367618. + + -- Matthias Klose Wed, 7 Jun 2006 21:37:20 +0200 + +python2.4 (2.4.3-3) unstable; urgency=low + + * SVN update up to 2006-04-21 + * Update locale aliases from /usr/share/X11/locale/locale.alias. + * Start idle with option -n from the desktop menu, so that the program + can be started in parallel. + * Testsuite related changes only: + - Add build dependencies mime-support, libgpmg1 (needed by test cases). + - Run the testsuite with bsddb, audio and curses resources enabled. + - Re-run the failed tests in verbose mode. + - Run the test suite for the debug build as well. + - Build depend on netbase, needed by test_socketmodule. + - Build depend on libgpmg1, needed by test_curses. + - On the buildds do not run the tests needing the network resource. + * Update python logo. + * Check for the availability of the profile and pstats modules when + importing hotshot.pstats. Closes: #334067. + * Don't build the -doc package from the python2.4 source. + * Set OPT in the installed Makefile to -O2. + + -- Matthias Klose Fri, 21 Apr 2006 19:58:43 +0200 + +python2.4 (2.4.3-2) unstable; urgency=low + + * Add (build-)dependency on mime-support. + + -- Matthias Klose Tue, 4 Apr 2006 22:21:41 +0200 + +python2.4 (2.4.3-1) unstable; urgency=low + + * Python 2.4.3 release. + + -- Matthias Klose Thu, 30 Mar 2006 23:42:37 +0200 + +python2.4 (2.4.3-0ubuntu1) dapper; urgency=low + + * Python 2.4.3 release. + - Fixed a bug that the gb18030 codec raises RuntimeError on encoding + surrogate pair area on UCS4 build. Ubuntu: #29289. + + -- Matthias Klose Thu, 30 Mar 2006 10:57:32 +0200 + +python2.4 (2.4.2+2.4.3c1-0ubuntu1) dapper; urgency=low + + * SVN update up to 2006-03-25 (2.4.3 candidate 1). + - Regenerate the documentation. + + -- Matthias Klose Mon, 27 Mar 2006 12:03:05 +0000 + +python2.4 (2.4.2-1ubuntu3) dapper; urgency=low + + * SVN update up to 2006-03-04 + - Regenerate the documentation. + - map.mmap(-1, size, ...) can return anonymous memory again on Unix. + Ubuntu #26201. + * Build-depend on libncursesw5-dev, ncursesw5 is preferred for linking. + Provides UTF-8 compliant curses bindings. + * Fix difflib where certain patterns of differences were making difflib + touch the recursion limit. + + -- Matthias Klose Sat, 4 Mar 2006 21:38:24 +0000 + +python2.4 (2.4.2-1ubuntu2) dapper; urgency=low + + * SVN update up to 2006-01-17 + - pwd is now a builtin module, remove it from python-minimal. + - Regenerate the documentation. + * python2.4-tk: Suggest tix instead of tix8.1. + * Move config/Makefile from the -dev package into the runtime package + to be able to use the bdist_wininst distutils command. Closes: #348335. + + -- Matthias Klose Tue, 17 Jan 2006 11:02:24 +0000 + +python2.4 (2.4.2-1ubuntu1) dapper; urgency=low + + * Temporarily remove build dependency on lsb-release. + + -- Matthias Klose Sun, 20 Nov 2005 17:40:18 +0100 + +python2.4 (2.4.2-1build1) dapper; urgency=low + + * Rebuild (openssl-0.9.8). + + -- Matthias Klose Sun, 20 Nov 2005 15:27:24 +0000 + +python2.4 (2.4.2-1) unstable; urgency=low + + * Python 2.4.2 release. + + -- Matthias Klose Thu, 29 Sep 2005 01:49:28 +0200 + +python2.4 (2.4.1+2.4.2rc1-1) unstable; urgency=low + + * Python 2.4.2 release candidate 1. + * Fix "Fatal Python error" from cStringIO's writelines. + Patch by Andrew Bennetts. + + -- Matthias Klose Thu, 22 Sep 2005 10:33:22 +0200 + +python2.4 (2.4.1-5) unstable; urgency=low + + * CVS update up to 2005-09-14 + - Regenerate the html and info docs. + * Add some more locale aliases. + * Fix substitution pf python version in README.python2.4-minimal. + Closes: #327487. + * On m68k, build using -O2 (closes: #326903). + * On Debian, don't configure --with-fpectl, which stopped working with + glibc-2.3.5. + + -- Matthias Klose Wed, 14 Sep 2005 17:32:56 +0200 + +python2.4 (2.4.1-4) unstable; urgency=low + + * CVS update up to 2005-09-04 + - teTeX 3.0 related fixes (closes: #322407). + - Regenerate the html and info docs. + * Add entry for IDLE in the Gnome menus. + * Don't build-depend on libbluetooth-dev on the Hurd (closes: #307037). + * Reenable the cthreads patch for the Hurd (closes: #307052). + + -- Matthias Klose Sun, 4 Sep 2005 18:31:42 +0200 + +python2.4 (2.4.1-3) unstable; urgency=low + + * Synchronise with Ubuntu: + - Build a python2.4-minimal package. + + -- Matthias Klose Tue, 12 Jul 2005 00:23:10 +0000 + +python2.4 (2.4.1-2ubuntu3) breezy; urgency=low + + * CVS update up to 2005-07-07 + * Regenerate the documentation. + + -- Matthias Klose Thu, 7 Jul 2005 09:21:28 +0200 + +python2.4 (2.4.1-2ubuntu2) breezy; urgency=low + + * CVS update up to 2005-06-15 + * Regenerate the documentation. + * Synchronize with Debian. Ubuntu 10485. + * idle-python2.4 enhances python2.4. Ubuntu 11562. + * README.Debian: Fix reference to the doc directory (closes: #311677). + + -- Matthias Klose Wed, 15 Jun 2005 08:56:57 +0200 + +python2.4 (2.4.1-2ubuntu1) breezy; urgency=low + + * Update build dependencies: + db4.2-dev -> db4.3-dev, + libreadline4-dev -> libreadline5-dev. + * python2.4-dev: Add missing templates to generate HTML docs. Ubuntu 11531. + + -- Matthias Klose Sun, 29 May 2005 00:01:05 +0200 + +python2.4 (2.4.1-2) unstable; urgency=low + + * Add the debug symbols for the python2.4, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. + * Add gdbinit example to doc directory. + + -- Matthias Klose Thu, 5 May 2005 11:12:32 +0200 + +python2.4 (2.4.1-1ubuntu2) breezy; urgency=low + + * Add the debug symbols for the python2.4, python2.4-minimal, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. Ubuntu 10261, + * Add gdbinit example to doc directory. + * For os.utime, use utimes(2), correctly working with glibc-2.3.5. + Ubuntu 10294. + + -- Matthias Klose Thu, 5 May 2005 09:06:07 +0200 + +python2.4 (2.4.1-1ubuntu1) breezy; urgency=low + + * Reupload as 2.4.1-1ubuntu1. + + -- Matthias Klose Thu, 14 Apr 2005 10:46:32 +0200 + +python2.4 (2.4.1-1) unstable; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 19:42:03 +0200 + +python2.4 (2.4.1-0) hoary; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 16:35:34 +0200 + +python2.4 (2.4+2.4.1rc2-2) unstable; urgency=low + + * Add the valgrind support file to /etc/python2.4 + * Build the -dbg package with -DPy_USING_MEMORY_DEBUGGER. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * Fix two typos in python(1). Addresses: #300124. + + -- Matthias Klose Sat, 19 Mar 2005 21:50:14 +0100 + +python2.4 (2.4+2.4.1rc2-1) unstable; urgency=low + + * Python 2.4.1 release candidate 2. + * Build-depend on libbluetooth1-dev. + + -- Matthias Klose Sat, 19 Mar 2005 00:57:14 +0100 + +python2.4 (2.4dfsg-2) unstable; urgency=low + + * CVS update up to 2005-03-03 + + -- Matthias Klose Thu, 3 Mar 2005 22:22:16 +0100 + +python2.4 (2.4dfsg-1ubuntu4) hoary; urgency=medium + + * Move exception finalisation later in the shutdown process - this + fixes the crash seen in bug #1165761, taken from CVS. + * codecs.StreamReader: Reset codec when seeking. Ubuntu #6972. + * Apply fix for SF1124295, fixing an obscure bit of Zope's security machinery. + * distutils: Don't add standard library dirs to library_dirs + and runtime_library_dirs. On amd64, runtime paths pointing to /usr/lib64 + aren't recognized by dpkg-shlibdeps, and the packages containing these + libraries aren't added to ${shlibs:Depends}. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * os.py: Avoid using items() in environ.update(). Fixes #1124513. + * Python/pythonrun.c: + * Build depend on locales, generate the locales needed for the + testsuite. + * Add build dependency on libbluetooth1-dev, adding some bluetooth + functionality to the socket module. + * Lib/test/test_sundry.py: Don't fail on import of profile & pstats, + which are separated out to the python-profiler package. + * Fix typos in manpage. + + -- Matthias Klose Tue, 29 Mar 2005 13:35:53 +0200 + + +python2.4 (2.4dfsg-1ubuntu3) hoary; urgency=low + + * debian/patches/langpack-gettext.dpatch: + - langpack support for python-gettext added + + -- Michael Vogt Tue, 1 Mar 2005 13:13:36 +0100 + +python2.4 (2.4dfsg-1ubuntu2) hoary; urgency=low + + * Revert 'essential' status on python2.4-minimal. This status on + on python-minimal is sufficient (Ubuntu #6392). + + -- Matthias Klose Wed, 9 Feb 2005 23:09:42 +0100 + +python2.4 (2.4dfsg-1ubuntu1) hoary; urgency=low + + * Resyncronise with Debian. + * Mark the python2.4-minimal package as 'essential'. + + -- Matthias Klose Wed, 9 Feb 2005 13:31:09 +0100 + +python2.4 (2.4dfsg-1) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Remove the profile.py and pstats.py modules from the source package, + not having a DFSG conforming license. The modules can be found in + the python2.x-profile package in the non-free section. + Addresses: #293932. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7ubuntu1) hoary; urgency=low + + * Fix the name of the python-dbg man page. + * Resyncronise with Debian. + * Move more modules to -minimal (new code in copy.py requires these): + dis, inspect, opcode, token, tokenize. + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-6) unstable; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Apply the pydebug-path patch. The package was already built in -5. + + -- Matthias Klose Fri, 4 Feb 2005 22:15:13 +0100 + +python2.4 (2.4-5) unstable; urgency=high + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + * CVS updates of the release24-maint branch upto 2005-02-04. + + -- Matthias Klose Fri, 4 Feb 2005 08:12:10 +0100 + +python2.4 (2.4-4) unstable; urgency=medium + + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Remove /usr/bin/smtpd.py (closes: #291049). + + -- Matthias Klose Mon, 17 Jan 2005 23:54:37 +0100 + +python2.4 (2.4-3ubuntu6) hoary; urgency=low + + * Use old-style dpatches instead of dpatch-run. + + -- Tollef Fog Heen Mon, 7 Feb 2005 15:58:05 +0100 + +python2.4 (2.4-3ubuntu5) hoary; urgency=low + + * Actually apply the patch as well (add to list of patches in + debian/rules) + + -- Tollef Fog Heen Sun, 6 Feb 2005 15:12:58 +0100 + +python2.4 (2.4-3ubuntu4) hoary; urgency=low + + * Add nb_NO and nn_NO locales to Lib/locale.py + + -- Tollef Fog Heen Sun, 6 Feb 2005 14:33:05 +0100 + +python2.4 (2.4-3ubuntu3) hoary; urgency=low + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + + -- Matthias Klose Wed, 2 Feb 2005 09:08:20 +0000 + +python2.4 (2.4-3ubuntu2) hoary; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Add operator and copy to the -minimal package. + + -- Matthias Klose Mon, 17 Jan 2005 23:19:47 +0100 + +python2.4 (2.4-3ubuntu1) hoary; urgency=low + + * Resynchronise with Debian. + * python2.4: Depend on the very same version of python2.4-minimal. + * Docment, that time.strptime currently cannot be used, if the + python-minimal package is installed without the python package. + + -- Matthias Klose Sun, 9 Jan 2005 19:35:48 +0100 + +python2.4 (2.4-3) unstable; urgency=medium + + * Build the fpectl module. + * Updated to CVS release24-maint 20050107. + + -- Matthias Klose Sat, 8 Jan 2005 19:05:21 +0100 + +python2.4 (2.4-2ubuntu5) hoary; urgency=low + + * Updated to CVS release24-maint 20050102. + * python-minimal: + - os.py: Use dict instead of UserDict, remove UserDict from -minimal. + - add pickle, threading, needed for subprocess module. + - optparse.py: conditionally import gettext, if not available, + define _ as the identity function. Patch taken from the trunk. + Avoids import of _locale, locale, gettext, copy, repr, itertools, + collections, token, tokenize. + - Add a build check to make sure that the minimal module list is + closed under dependency. + * Fix lintian warnings. + + -- Matthias Klose Sun, 2 Jan 2005 22:00:14 +0100 + +python2.4 (2.4-2ubuntu4) hoary; urgency=low + + * Add UserDict.py to the -minimal package, since os.py needs it. + + -- Colin Watson Thu, 30 Dec 2004 20:41:28 +0000 + +python2.4 (2.4-2ubuntu3) hoary; urgency=low + + * Add os.py and traceback.py to the -minimal package, get the list + of modules from the README. + + -- Matthias Klose Mon, 27 Dec 2004 08:20:45 +0100 + +python2.4 (2.4-2ubuntu2) hoary; urgency=low + + * Add compileall.py and py_compile.py to the -minimal package, not + just to the README ... + + -- Matthias Klose Sat, 25 Dec 2004 22:24:56 +0100 + +python2.4 (2.4-2ubuntu1) hoary; urgency=low + + * Separate the interpreter and a minimal subset of modules into + a python2.4-minimal package. See the README.Debian.gz in this + package. + * Move site.py to python2.4-minimal as well. + * Add documentation files for devhelp. + + -- Matthias Klose Sun, 19 Dec 2004 22:47:32 +0100 + +python2.4 (2.4-2) unstable; urgency=medium + + * Updated patch for #283108. Thanks to Jim Meyering. + + -- Matthias Klose Fri, 3 Dec 2004 17:00:16 +0100 + +python2.4 (2.4-1) unstable; urgency=low + + * Final 2.4 release. + * Flush stdout/stderr if closed (SF #1074011). + + -- Matthias Klose Wed, 1 Dec 2004 07:54:34 +0100 + +python2.4 (2.3.97-2) unstable; urgency=low + + * Don't run test_tcl, hanging on the buildds. + + -- Matthias Klose Fri, 19 Nov 2004 23:48:42 +0100 + +python2.4 (2.3.97-1) unstable; urgency=low + + * Python 2.4 Release Candidate 1. + + -- Matthias Klose Fri, 19 Nov 2004 21:27:02 +0100 + +python2.4 (2.3.96-1) experimental; urgency=low + + * Updated to CVS release24-maint 20041113. + * Build the docs in info format again. + + -- Matthias Klose Sat, 13 Nov 2004 21:21:10 +0100 + +python2.4 (2.3.95-2) experimental; urgency=low + + * Move distutils package from the python2.4-dev into the python2.4 + package. + + -- Matthias Klose Thu, 11 Nov 2004 22:56:14 +0100 + +python2.4 (2.3.95-1) experimental; urgency=low + + * Python 2.4 beta2 release. + + -- Matthias Klose Thu, 4 Nov 2004 23:43:47 +0100 + +python2.4 (2.3.94-1) experimental; urgency=low + + * Python 2.4 beta1 release. + + -- Matthias Klose Sat, 16 Oct 2004 08:33:57 +0200 + +python2.4 (2.3.93-1) experimental; urgency=low + + * Python 2.4 alpha3 release. + + -- Matthias Klose Fri, 3 Sep 2004 21:53:47 +0200 + +python2.4 (2.3.92-1) experimental; urgency=low + + * Python 2.4 alpha2 release. + + -- Matthias Klose Thu, 5 Aug 2004 23:53:18 +0200 + +python2.4 (2.3.91-1) experimental; urgency=low + + * Python 2.4 alpha1 release. + Highlights: http://www.python.org/2.4/highlights.html + + -- Matthias Klose Fri, 9 Jul 2004 17:38:54 +0200 + +python2.4 (2.3.90-1) experimental; urgency=low + + * Package HEAD branch (pre alpha ..). + + -- Matthias Klose Mon, 14 Jun 2004 23:19:57 +0200 + +python2.3 (2.3.4-1) unstable; urgency=medium + + * Final Python 2.3.4 Release. + * In the API docs, fix signature of PyModule_AddIntConstant (closes: #250826). + * locale.getdefaultlocale: don't fail with empty environment variables. + Closes: #249816. + * Include distutils/command/wininst.exe in -dev package (closes: #249006). + * Disable cthreads on the Hurd (Michael Banck). Closes: #247211. + * Add a note to pygettext(1), that this program is deprecated in favour + of xgettext, which now includes support for Python as well. + Closes: #246332. + + -- Matthias Klose Fri, 28 May 2004 22:59:42 +0200 + +python2.3 (2.3.3.91-1) unstable; urgency=low + + * Python 2.3.4 Release Candidate 1. + * Do not use the default namespace for attributes. Patch taken from the + 2.3 maintenance branch. + The xmllib module is obsolete. Use xml.sax instead. + * http://python.org/sf/945642 - fix nonblocking i/o with ssl socket. + + -- Matthias Klose Thu, 13 May 2004 21:24:52 +0200 + +python2.3 (2.3.3-7) unstable; urgency=low + + * Add a workaround for GNU libc nl_langinfo()'s returning NULL. + Closes: #239237. + Patch taken from 2.3 maintenance branch. + * threading.py: Remove calls to currentThread() in _Condition methods that + were side-effect. Side-effects were deemed unnecessary and were causing + problems at shutdown time when threads were catching exceptions at start + time and then triggering exceptions trying to call currentThread() after + gc'ed. Masked the initial exception which was deemed bad. + Closes: #195812. + * Properly support normalization of empty unicode strings. Closes: #239986. + Patch taken from 2.3 maintenance branch. + * README.maintainers: Add section where to find the documentation tools. + * Fix crash in pyexpat module (closes: #229281). + * For the Hurd, set the interpreters recursion limit to 930. + * Do not try to byte-compile the test files on installation; this + currently breaks the Hurd install. + + -- Matthias Klose Sat, 1 May 2004 07:50:46 +0200 + +python2.3 (2.3.3-6) unstable; urgency=low + + * Don't build the unversioned python{,-*} packages anymore. Now + built from the python-defaults package. + * Update to the proposed python-policy: byte-compile using -E. + * Remove python-elisp's dependency on emacs20 (closes: #232785). + * Don't build python-elisp from the python2.3 source anymore, + get it from python-mode.sf.net as a separate source package. + * python2.3-dev suggests libc-dev (closes: #231091). + * get LDSHARED and CCSHARED (like, CC, CXX, CPP, CFLAGS) from + the environment + * Set CXX in installed config/Makefile (closes: #230273). + + -- Matthias Klose Tue, 24 Feb 2004 07:07:51 +0100 + +python2.3 (2.3.3-5) unstable; urgency=low + + * Build-depend on libdb4.2-dev, instead of libdb4.1-dev. According + to the docs the file format is compatible. + + -- Matthias Klose Mon, 12 Jan 2004 10:37:45 +0100 + +python2.3 (2.3.3-4) unstable; urgency=low + + * Fix broken _bsddb module. setup.py picked up the wrong library. + + -- Matthias Klose Sun, 4 Jan 2004 11:30:00 +0100 + +python2.3 (2.3.3-3) unstable; urgency=low + + * Fix typo in patch (closes: #224797, #226064). + + -- Matthias Klose Sun, 4 Jan 2004 09:23:21 +0100 + +python2.3 (2.3.3-2) unstable; urgency=medium + + * Lib/email/Charset: use locale unaware function to lower case of locale + name (closes: #224797). + * Update python-mode to version from python-mode.sf.net. Fixes highlighting + problems (closes: #223520). + * Backport from mainline: Add IPV6_ socket options from RFCs 3493 and 3542. + + -- Matthias Klose Fri, 2 Jan 2004 14:03:26 +0100 + +python2.3 (2.3.3-1) unstable; urgency=low + + * New upstream release. + * Copy the templates, tools and scripts from the Doc dir in the source + to /usr/share/lib/python2.3/doc in the python2.3-dev package. Needed + for packages building documentation like python does (closes: #207337). + + -- Matthias Klose Fri, 19 Dec 2003 10:57:39 +0100 + +python2.3 (2.3.2.91-1) unstable; urgency=low + + * New upstream version (2.3.3 release candidate). + * Update python-mode.el (closes: #158811, #159630). + Closing unreproducible report (closes: #159628). + + -- Matthias Klose Sat, 6 Dec 2003 14:41:14 +0100 + +python2.3 (2.3.2-7) unstable; urgency=low + + * Put the conflict in the correct direction. python2.3 (2.3.2-6) doesn't + conflict with python (<= 2.3.2-5) but python (2.3.2-6) conflicts with + python2.3 (<= 2.3.2-5) (thanks to Brian May). Really closes #221791. + + -- Matthias Klose Fri, 21 Nov 2003 00:20:02 +0100 + +python2.3 (2.3.2-6) unstable; urgency=low + + * Add conflicts with older python{,2.3} packages to fix overwrite + errors (closes: #221791). + + -- Matthias Klose Thu, 20 Nov 2003 07:24:36 +0100 + +python2.3 (2.3.2-5) unstable; urgency=low + + * Updated to CVS release23-maint 20031119. + * Re-upgrade the dependency of python2.3 on python (>= 2.3) to + a dependency (closes: #221523). + + -- Matthias Klose Wed, 19 Nov 2003 00:30:27 +0100 + +python2.3 (2.3.2-4) unstable; urgency=low + + * Don't build-depend on latex2html (moved to non-free), but keep + the prebuilt docs in debian/patches (closes: #221347). + * Fix typos in the library reference (closes: #220510, #220954). + * Fix typo in python-elisp's autoloading code (closes: #220308). + * Update proposed python policy: private modules can be installed + into /usr/lib/ (arch dependent) and into /usr/share/ + (arch independent). + + -- Matthias Klose Tue, 18 Nov 2003 00:41:39 +0100 + +python2.3 (2.3.2-3) unstable; urgency=low + + * Downgrade the dependency of python2.3 on python (>= 2.3) to + a recommendation. + * Fix path to interpreter in binfmt file. + * Fix segfault in unicodedata module (closes: #218697). + * Adjust python-elisp autoload code (closes: #219821). + + -- Matthias Klose Sun, 9 Nov 2003 19:43:37 +0100 + +python2.3 (2.3.2-2) unstable; urgency=medium + + * Fix broken doc link (closes: #214217). + * Disable wrongly detected large file support for GNU/Hurd. + * Really fix the FTBFS for the binary-indep target (closes: #214303). + + -- Matthias Klose Mon, 6 Oct 2003 07:54:58 +0200 + +python2.3 (2.3.2-1) unstable; urgency=low + + * New upstream version. + * Fix a FTBFS for the binary-indep target. + + -- Matthias Klose Sat, 4 Oct 2003 10:20:15 +0200 + +python2.3 (2.3.1-3) unstable; urgency=low + + * Fix names of codec packages in recommends. + * On alpha compile using -mieee (see #212912). + + -- Matthias Klose Sun, 28 Sep 2003 10:48:12 +0200 + +python2.3 (2.3.1-2) unstable; urgency=low + + * Update python policy draft (closes: #128911, #163785). + * Re-add os.fsync function (closes: #212672). + * Let python2.3-doc conflict with older python2.3 versions (closes: #211882). + * Add recommends for pythonX.Y-japanese-codecs, pythonX.Y-iconvcodec, + pythonX.Y-cjkcodecs, pythonX.Y-korean-codecs (closes: #207161). + * Generate binfmt file (closes: #208005). + * Add IPPROTO_IPV6 option to the socketmodule (closes: #206569). + * Bugs reported against python2.2 and fixed in python2.3: + - Crashes in idle (closes: #186887, #200084). + + -- Matthias Klose Sat, 27 Sep 2003 11:21:47 +0200 + +python2.3 (2.3.1-1) unstable; urgency=low + + * New upstream version (bug fix release). + + -- Matthias Klose Wed, 24 Sep 2003 11:27:43 +0200 + +python2.3 (2.3-4) unstable; urgency=high + + * Disable check for utimes function, which is broken in glibc-2.3.2. + Packages using distutils had '1970/01/01-01:00:01' timestamps in files. + * Bugs fixed by making python2.3 the default python version: + - Canvas.scan_dragto() takes a 3rd optional parmeter "gain". + Closes: #158168. + - New command line parsing module (closes: #38628). + - compileall.py allows compiling single files (closes: #139971). + * Bugs reported for 2.2 and fixed in 2.3: + - Idle does save files with ASCII characters (closes: #179313). + - imaplib support for prefix-quoted strings (closes: #150485). + - posixpath includes getctime (closes: #173827). + - pydoc has support for keywords (closes: #186775). + * Bugs reported for 2.1 and fixed in 2.3: + - Fix handling of "#anchor" URLs in urlparse (closes: #147844). + - Fix readline if C stdin is not a tty, even if sys.stdin is. + Closes: #131810. + * Updated to CVS release23-maint 20030810 (fixing memory leaks in + array and socket modules). + * pydoc's usage output uses the basename of the script. + * Don't explicitely remove /etc/python2.3 on purge (closes: #202864). + * python conflicts with python-xmlbase (closes: #204773). + * Add dependency python (>= 2.3) to python2.3, so make sure the + unversioned names can be used. + + -- Matthias Klose Sun, 10 Aug 2003 09:27:52 +0200 + +python2.3 (2.3-3) unstable; urgency=medium + + * Fix shlibs file. + + -- Matthias Klose Fri, 8 Aug 2003 08:45:12 +0200 + +python2.3 (2.3-2) unstable; urgency=medium + + * Make python2.3 the default python version. + + -- Matthias Klose Tue, 5 Aug 2003 22:13:22 +0200 + +python2.3 (2.3-1) unstable; urgency=low + + * Python 2.3 final release. + + -- Matthias Klose Wed, 30 Jul 2003 08:12:28 +0200 + +python2.3 (2.2.107-1rc2) unstable; urgency=medium + + * Python 2.3 release candidate 2. + * Don't compress .txt files referenced by the html docs (closes: #200298). + * Include the email/_compat* files (closes: #200349). + + -- Matthias Klose Fri, 25 Jul 2003 07:08:09 +0200 + +python2.3 (2.2.106-2beta2) unstable; urgency=medium + + * Python 2.3 beta2 release, updated to CVS 20030704. + - Fixes AssertionError in httplib (closed: #192452). + - Fixes uncaught division by zero in difflib.py (closed: #199287). + * Detect presence of setgroups(2) at configure time (closes: #199839). + * Use default gcc on arm as well. + + -- Matthias Klose Sat, 5 Jul 2003 10:21:33 +0200 + +python2.3 (2.2.105-1beta2) unstable; urgency=low + + * Python 2.3 beta2 release. + - Includes merged idle fork. + - Fixed socket.setdefaulttimeout(). Closes: #189380. + - socket.ssl works with _socketobj. Closes: #196082. + * Do not link libtix to the _tkinter module. It's loaded via + 'package require tix' at runtime. python2.3-tkinter now + suggests tix8.1 instead. + * On arm, use gcc-3.2 to build. + * Add -fno-strict-aliasing rules to OPT to avoid warnings + "dereferencing type-punned pointer will break strict-aliasing rules", + when building with gcc-3.3. + + -- Matthias Klose Mon, 30 Jun 2003 00:19:32 +0200 + +python2.3 (2.2.104-1beta1.1) unstable; urgency=low + + * Non-maintainer upload with maintainer consent. + * debian/control (Build-Depends): s/libgdbmg1-dev/libgdbm-dev/. + + -- James Troup Wed, 4 Jun 2003 02:24:27 +0100 + +python2.3 (2.2.104-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030514. + - build the current documentation. + * Reenable Tix support. + + -- Matthias Klose Wed, 14 May 2003 07:38:57 +0200 + +python2.3 (2.2.103-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030506. + - updated due to build problems on mips/mipsel. + - keep the 2.3b1 documentation (doc build problems with cvs). + + -- Matthias Klose Wed, 7 May 2003 06:26:39 +0200 + +python2.3 (2.2.102-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release. + + -- Matthias Klose Sat, 3 May 2003 22:45:16 +0200 + +python2.3 (2.2.101-1exp1) unstable; urgency=medium + + * Python 2.3 alpha2 release, updated to CVS 20030321. + * Tkinter: Catch exceptions thrown for undefined substitutions in + events (needed for tk 8.4.2). + + -- Matthias Klose Fri, 21 Mar 2003 21:32:14 +0100 + +python2.3 (2.2.100-1exp1) unstable; urgency=low + + * Python 2.3 alpha2 release, updated to CVS 20030221. + + -- Matthias Klose Fri, 21 Feb 2003 19:37:17 +0100 + +python2.3 (2.2.99-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030123. + - should fix the testsuite (and package build) failure on alpha. + * Remove build dependency on libexpat1-dev. Merge the python2.3-xmlbase + package into python2.3 (closes: #177739). + + -- Matthias Klose Thu, 23 Jan 2003 22:48:12 +0100 + +python2.3 (2.2.98-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030117. + * Build using libdb4.1. + + -- Matthias Klose Sat, 18 Jan 2003 00:14:01 +0100 + +python2.3 (2.2.97-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030109. + * Build-Depend on g++ (>= 3:3.2). + * Python package maintainers: please wait uploading python dependent + packages until python2.2 and python2.1 are compiled using gcc-3.2. + + -- Matthias Klose Thu, 9 Jan 2003 23:56:42 +0100 + +python2.3 (2.2.96-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release (not exactly the tarball, but taken from + CVS 20030101). + - Includes support for linking with threaded tk8.4 (closes: #172714). + * Install and register whatsnew document (closes: #173859). + * Properly unregister info documentation. + + -- Matthias Klose Wed, 1 Jan 2003 17:38:54 +0100 + +python2.3 (2.2.95-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021212. + - data in unicodedate module is up to date (closes: #171061). + * Fix idle packaging (closes: #170394). + * Configure using unicode UCS-4 (closes: #171062). + This change breaks compatibility with binary modules, but what do you + expect from experimental packages ... Please recompile dependent packages. + * Don't strip binaries for now. + + -- Matthias Klose Thu, 12 Dec 2002 21:42:27 +0100 + +python2.3 (2.2.94-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021120. + * Remove outdated README.dbm. + * Depend on tk8.4. + * python-elisp: Install emacsen install file with mode 644 (closes: #167718). + + -- Matthias Klose Thu, 21 Nov 2002 01:04:51 +0100 + +python2.3 (2.2.93-1exp1) unstable; urgency=medium + + * Experimental packages from CVS 021015. + * Build a static library libpython2.3-pic.a. + * Enable large file support for the Hurd (closes: #164602). + + -- Matthias Klose Tue, 15 Oct 2002 21:06:27 +0200 + +python2.3 (2.2.92-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020922. + * Fix build error on ia64 (closes: #161234). + * Build depend on gcc-3.2-3.2.1-0pre2 to fix build error on arm. + + -- Matthias Klose Sun, 22 Sep 2002 18:30:28 +0200 + +python2.3 (2.2.91-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020906. + * idle-python2.3: Fix conflict (closes: #159267). + * Fix location of python-mode.el (closes: #159564, #159619). + * Use tix8.1. + * Apply fix for distutils/ccompiler problem (closes: #159288). + + -- Matthias Klose Sat, 7 Sep 2002 09:55:07 +0200 + +python2.3 (2.2.90-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020820. + * Don't build python2.3-elisp, but put the latest version into + python-elisp. + + -- Matthias Klose Thu, 22 Aug 2002 21:52:04 +0200 + +python2.2 (2.2.1-6) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-07-23. + * Enable IPv6 support (closes: #152543). + * Add python2.2-tk suggestion for python2.2 (pydoc -g). + * Fix from SF patch #527518: proxy config with user+pass authentication. + * Point pydoc to the correct location of the docs (closes: #147579). + * Remove '*.py[co]' files, when removing the python package, + not when purging (closes: #147130). + * Update to new py2texi.el version (Milan Zamazal). + + -- Matthias Klose Mon, 29 Jul 2002 23:11:32 +0200 + +python2.2 (2.2.1-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-05-03. + * Build the info docs (closes: #145653). + + -- Matthias Klose Fri, 3 May 2002 22:35:46 +0200 + +python2.2 (2.2.1-4) unstable; urgency=high + + * Fix indentation errors introduced in last upload (closes: #143809). + + -- Matthias Klose Sun, 21 Apr 2002 01:00:14 +0200 + +python2.2 (2.2.1-3) unstable; urgency=high + + * Add Build-Conflicts: tcl8.0-dev, tk8.0-dev, tcl8.2-dev, tk8.2-dev. + Closes: #143534 (build a working _tkinter module, on machines, where + 8.0's tk.h gets included). + * CVS updates of the release22-maint branch upto 2002-04-20. + + -- Matthias Klose Sat, 20 Apr 2002 09:22:37 +0200 + +python2.2 (2.2.1-2) unstable; urgency=low + + * Forgot to copy the dlmodule patch from the 2.1.3 package. Really + closes: #141681. + + -- Matthias Klose Sat, 13 Apr 2002 01:28:05 +0200 + +python2.2 (2.2.1-1) unstable; urgency=high + + * Final 2.2.1 release. + * According to report #131813, the python interpreter is much faster on some + architectures, when beeing linked statically with the python library (25%). + Gregor and me tested on i386, m68k and alpha, but we could not reproduce + such a speedup (generally between 5% and 10%). But we are linking the + python executable now statically ... + * Build info docs from the tex source, merge the python-doc-info + package into the python-doc package. + * Always build the dl module. Failure in case of + sizeof(int)!=sizeof(long)!=sizeof(void*) + is delayed until dl.open is called. Closes: #141681. + + -- Matthias Klose Thu, 11 Apr 2002 00:19:19 +0200 + +python2.2 (2.2.0.92-0) unstable; urgency=low + + * Package CVS sources, omit cvs-updates.dpatch (closes: #140977). + + -- Matthias Klose Wed, 3 Apr 2002 08:20:52 +0200 + +python2.2 (2.2-6) unstable; urgency=medium + + * Update to python-2.2.1 release candidate 2 (final release scheduled + for April 10). + * Enable dl module (closes: #138992). + * Build doc files with python binary from package (closes: #139657). + * Build _tkinter module with BLT and Tix support. + * python2.2-elisp: Conflict with python2-elisp (closes: #138970). + * string.split docs updated in python-2.2.1 (closes: #129272). + + -- Matthias Klose Mon, 1 Apr 2002 13:52:36 +0200 + +python2.2 (2.2-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 20020310 (aproaching + the first 2.2.1 release candidate). + * Stolen from HEAD: check argument of locale.nl_langinfo (closes: #137371). + + -- Matthias Klose Fri, 15 Mar 2002 01:05:59 +0100 + +python2.2 (2.2-4) unstable; urgency=medium + + * Include test/{__init__.py,README,pystone.py} in package (closes: #129013). + * Fix python-elisp conflict (closes: #129046). + * Don't compress stylesheets (closes: #133179). + * CVS updates of the release22-maint branch upto 20020310. + + -- Matthias Klose Sun, 10 Mar 2002 23:32:28 +0100 + +python2.2 (2.2-3) unstable; urgency=medium + + * Updates from the CVS python22-maint branch up to 20020107. + webbrowser.py: properly escape url's. + * The Hurd does not have large file support: disabled. + + -- Matthias Klose Mon, 7 Jan 2002 21:55:57 +0100 + +python2.2 (2.2-2) unstable; urgency=medium + + * CVS updates of the release22-maint branch upto 20011229. Fixes: + - Include TCP_CORK flag in plat-linux2 headers (fixes: #84340). + - Update CDROM.py module (fixes: #125785). + * Add missing chunk of the GNU/Hurd patch (therefore urgency medium). + * Send anonymous password when using anonftp (closes: #126814). + + -- Matthias Klose Sat, 29 Dec 2001 20:18:26 +0100 + +python2.2 (2.2-1) unstable; urgency=low + + * New upstream version: 2.2. + * Bugs fixed upstream: + - Docs for os.kill reference the signal module for constants. + - Documentation strings in the tutorial end with a period (closes: #94770). + - Tk: grid_location method moved from Grid to Misc (closes: #98338). + - mhlib.SubMessage.getbodytext takes decode parameter (closes: #31876). + - Strings in modules are locale aware (closes: #51444). + - Printable 8-bit characters in strings are correctly printed + (closes: #64354). + - Dictionary can be updated with abstract mapping object (closes: #46566). + * Make site.py a config files. + + -- Matthias Klose Sat, 22 Dec 2001 00:51:46 +0100 + +python2.2 (2.1.99c1-1) unstable; urgency=low + + * New upstream version: 2.2c1 (release candidate). + * Do not provide python2.2-base anymore. + * Install correct README.Debian for python2.2 package. Include hint + where to find Makefile.pre.in. + * Suggest installation of python-ssl. + * Remove idle config files on purge. + * Remove empty /usr/lib/python2.2 directory on purge. + + -- Matthias Klose Sat, 15 Dec 2001 17:56:27 +0100 + +python2.2 (2.1.99beta2-1) unstable; urgency=high + + * debian/rules: Reflect removal of regrtest package (closes: #122278). + Resulted in build failures on all architectures. + * Build -doc package from source. + + -- Matthias Klose Sat, 8 Dec 2001 00:38:41 +0100 + +python2.2 (2.1.99beta2-0.1) unstable; urgency=low + + * Non maintainer upload. + * New upstream version (this is 2.2beta2). + * Do not build the python-regrtest package anymore; keep the test framework + components test/regrtest.py and test/test_support.py in the python + package (closes: #119408). + + -- Gregor Hoffleit Tue, 27 Nov 2001 09:53:26 +0100 + +python2.2 (2.1.99beta1-4) unstable; urgency=low + + * Configure with --with-fpectl (closes: #118125). + * setup.py: Remove broken check for _curses_panel module (#116081). + * idle: Move config-* files to /etc and mark as conffiles (#106390). + * Move idle packages to section `devel'. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-3) unstable; urgency=low + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * README.Debian: point to draft of python-policy in the python package. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-2) unstable; urgency=medium + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * Rename package python2.2-base to python2.2. + + -- Matthias Klose Wed, 24 Oct 2001 23:00:50 +0200 + +python2.2 (2.1.99beta1-1) unstable; urgency=low + + * New upstream version (beta). Call the package version 2.1.99beta1-1. + * New maintainer until the final 2.2 release. + * Updated the debian patches. + + -- Matthias Klose Sat, 20 Oct 2001 18:56:26 +0200 + +python2.1 (2.1.1-1.2) unstable; urgency=low + + * Really remove the python alternative. + + -- Matthias Klose Sat, 20 Oct 2001 15:16:56 +0200 + +python2.1 (2.1.1-1.1) unstable; urgency=low + + * README FOR PACKAGE MAINTAINERS: It is planned to remove the python2-XXX + packages from unstable and move on to python2.1. + If you repackage/adapt your modules for python2.1, don't build + python2-XXX and python2.1-XXX packages from the same source package, + so that the python2-XXX package can be removed without influencing the + python2.1-XXX package. + + See the debian-python mailing list at http://lists.debian.org/devel.html + for details and the current discussion and a draft for a debian-python + policy (August to October 2001). + + * Remove alternative for /usr/bin/python. The python-base package now + provides the default python version. + + * Regenerate control file to fix build dependencies (closes: #116190). + * Remove alternative for /usr/bin/{python,pydoc}. + * Provide a libpython2.1.so symlink in /usr/lib/python2.1/config, + so that the shared library is found when -L/usr/lib/python2.1/config + is specified. + * Conflict with old package versions, where /usr/bin/python is a real + program (closes: #115943). + * python2.1-elisp conflicts with python-elisp (closes: #115895). + * We now have 2.1 (closes: #96851, #107849, #110243). + + -- Matthias Klose Fri, 19 Oct 2001 17:34:41 +0200 + +python2.1 (2.1.1-1) unstable; urgency=low + + * Incorporated Matthias' modifications. + + -- Gregor Hoffleit Thu, 11 Oct 2001 00:16:42 +0200 + +python2.1 (2.1.1-0.2) unstable; urgency=low + + * New upstream 2.1.1. + * GPL compatible licence (fixes #84080, #102949, #110643). + * Fixed upstream (closes: #99692, #111340). + * Build in separate build directory. + * Split Debian patches into debian/patches directory. + * Build dependencies: Add libgmp3-dev, libexpat1-dev, tighten + debhelper dependency. + * debian/rules: Updated a "bit". + * python-elisp: Remove custom dependency (closes: #87783), + fix emacs path (closes: #89712), remove emacs19 dependency (#82694). + * Mention distutils in python-dev package description (closes: #108170). + * Update README.Debian (closes: #85430). + * Run versioned python in postinsts (closes: #113349). + * debian/sample.{postinst,prerm}: Change to version independent scripts. + * Use '/usr/bin/env python2.1' as interpreter for all python scripts. + * Add libssl-dev to Build-Conflicts. + * python-elisp: Add support for emacs21 (closes: #98635). + * Do not compress .py files in doc directories. + * Don't link explicitely with libc. + + -- Matthias Klose Wed, 3 Oct 2001 09:53:08 +0200 + +python2.1 (2.1.1-0.1) unstable; urgency=low + + * New upstream version (CVS branch release21-maint, will become 2.1.1): + This CVS branch will be released as 2.1.1 under a GPL compatible + license. + + -- Gregor Hoffleit Wed, 27 Jun 2001 22:47:58 +0200 + +python2 (2.1-0.1) unstable; urgency=low + + * Fixed Makefile.pre.in. + * Fixed the postinst files in order to use 2.1 (instead of 2.0). + * Mention the immanent release of 2.0.1 and 2.1.1, with a GPL + compatible license. + + -- Gregor Hoffleit Sun, 17 Jun 2001 21:05:25 +0200 + +python2 (2.1-0) unstable; urgency=low + + * New upstream version. + * Experimental packages. + + -- Gregor Hoffleit Thu, 10 May 2001 00:20:04 +0200 + +python2 (2.0-7) unstable; urgency=low + + * Rebuilt with recent tcl8.3-dev/tk8.3-dev in order to fix a + dependency problem with python2-tk (closes: #87793, #92962). + * Change postinst to create and update /usr/local/lib/python2.0 and + site-python with permissions and owner as mandated by policy: + 2775 and root:staff (closes: #89047). + * Fix to compileall.py: A superfluous argument made compileall without + options fail (cf. #92990 for python). + * Move the distutils module into python2-dev. It needs Makefile.pre.in + in order to work (closes: #89900). + * Remove build-dependency on libgdbm2-dev (which isn't built anyway). + * Add a build-dependency on libdb2-dev (cf. #90220 for python). + + -- Gregor Hoffleit Sat, 14 Apr 2001 21:07:51 +0200 + +python2 (2.0-6) unstable; urgency=low + + * Remove python-zlib package; merge it into python-base. + * Mark that README.python2 is not yet updated. + + -- Gregor Hoffleit Wed, 21 Feb 2001 12:34:18 +0100 + +python2 (2.0-5) unstable; urgency=low + + * Recompile with tcl/tk8.3 (closes: #82088). + * Modifications to README.why-python2 (closes: #82116). + * Add menu hint to idle2 menu entry. + * idle2 is renamed idle-python2 and now build correctly (closes: #82218). + * Add build-dependency on autoconf (closes: #85339). + * Build bsddbmodule as shared module (Modules/Setup.config.in), + and link libpython2.so with -lm in Makefile (closes: #86027). + * various cleanups in debian/rules, e.g. removing dh_suidregister. + * Make pdb available as /usr/bin/pdb-python2 in python2-dev + (cf. #79870 in python-base). + * Remove libgmp3 from build-dependencies, since we currently can't + build the mpzmodule for Python2 due to license problems. + + -- Gregor Hoffleit Sun, 18 Feb 2001 00:12:17 +0100 + +python2 (2.0-4) unstable; urgency=low + + * control: make python2-elisp conflict with python-elisp (it doesn't + make sense to have both of them installed, does it ?) + * include build-depend on libxmltok1-dev. + * again, build with tcl/tk8.0. + + -- Gregor Hoffleit Wed, 10 Jan 2001 23:37:01 +0100 + +python2 (2.0-3) unstable; urgency=low + + * Modules/Setup.in: Added a missing \ that made _tkinter be built + incorrectly. + * rules: on the fly, change all '#!' python scripts to use python2. + + -- Gregor Hoffleit Wed, 13 Dec 2000 20:07:24 +0100 + +python2 (2.0-2) unstable; urgency=low + + * Aaargh. Remove conflicts/provides/replaces on python-base to make + parallel installation of python-base and python2-base possible. + * Install examples into /usr/share/doc/python2 (not python) and fix + symlink to python2.0 (thanks to Rick Younie for + pointing out this). + * Rename man page to python2.1. + + -- Gregor Hoffleit Wed, 13 Dec 2000 09:31:05 +0100 + +python2 (2.0-1) unstable; urgency=low + + * New upstream version. Initial release for python2. + + -- Gregor Hoffleit Mon, 11 Dec 2000 22:39:46 +0100 --- python2.7-2.7.6.orig/debian/changelog.shared +++ python2.7-2.7.6/debian/changelog.shared @@ -0,0 +1,3 @@ + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 5%. --- python2.7-2.7.6.orig/debian/compat +++ python2.7-2.7.6/debian/compat @@ -0,0 +1 @@ +5 --- python2.7-2.7.6.orig/debian/control +++ python2.7-2.7.6/debian/control @@ -0,0 +1,213 @@ +Source: python2.7 +Section: python +Priority: optional +Maintainer: Ubuntu Core Developers +XSBC-Original-Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5), quilt, autoconf, lsb-release, sharutils, + libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), + tk-dev, blt-dev (>= 2.4z), libssl-dev, + zlib1g-dev, libbz2-dev, + libexpat1-dev, + libbluetooth-dev [linux-any], + locales [!armel !avr32 !hppa !ia64 !mipsel], + libsqlite3-dev, libffi-dev (>= 3.0.5) [!or1k !avr32], + libgpm2 [linux-any], + mime-support, netbase, net-tools, bzip2, + libdb-dev (<< 1:6.0), libgdbm-dev, python:any, help2man, + gcc (>= 4:4.8) [amd64 armel armhf i386 x32 kfreebsd-any hurd-any], + xvfb, xauth +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, python2.7-xml, python-xml, autoconf2.13, python-cxx-dev +Standards-Version: 3.9.5 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg2.7-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg2.7-debian +XS-Testsuite: autopkgtest + +Package: python2.7 +Architecture: any +Multi-Arch: allowed +Priority: standard +Depends: python2.7-minimal (= ${binary:Version}), libpython2.7-stdlib (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: python2.7-doc, binutils +Conflicts: python-profiler (<= 2.7.1-2) +Breaks: python-virtualenv (<< 1.7.1.2-2~), vim-nox (<< 2:7.3.547-4), vim-gtk (<< 2:7.3.547-4), vim-gnome (<< 2:7.3.547-4), vim-athena (<< 2:7.3.547-4) +Replaces: python-profiler (<= 2.7.1-2), python2.7-minimal (<< 2.7.3-7~) +Description: Interactive high-level object-oriented language (version 2.7) + Python is a high-level, interactive, object-oriented language. Its 2.7 version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: libpython2.7-stdlib +Architecture: any +Multi-Arch: same +Priority: standard +Depends: libpython2.7-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Provides: python2.7-cjkcodecs, python2.7-ctypes, python2.7-elementtree, python2.7-celementtree, python2.7-wsgiref, python2.7-profiler, python2.7-argparse, python-argparse +Replaces: python2.7 (<< 2.7.5-0~) +Description: Interactive high-level object-oriented language (standard library, version 2.7) + Python is a high-level, interactive, object-oriented language. Its 2.7 version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains Python 2.7's standard library. It is normally not + used on its own, but as a dependency of python2.7. + +Package: python2.7-minimal +Architecture: any +Multi-Arch: allowed +Priority: standard +Pre-Depends: ${shlibs:Pre-Depends} +Depends: libpython2.7-minimal (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Recommends: python2.7 +Suggests: binfmt-support +Replaces: python2.7 (<< 2.7.1~rc1-2~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version 2.7) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/python2.7-minimal/README.Debian for a list of the modules + contained in this package. + +Package: libpython2.7-minimal +Architecture: any +Multi-Arch: same +Priority: standard +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: libpython2.7-stdlib +Replaces: python2.7 (<< 2.7.4-2), python2.7-minimal (<< 2.7.3-10), libpython2.7-stdlib (<< 2.7.4-2) +Breaks: python2.7-minimal (<< 2.7.4~rc1-1~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version 2.7) + This package contains some essential modules. It is normally not + used on it's own, but as a dependency of python2.7-minimal. + +Package: libpython2.7 +Architecture: any +Multi-Arch: same +Section: libs +Priority: standard +Pre-Depends: multiarch-support +Depends: libpython2.7-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: python2.7 (<< 2.6) +Description: Shared Python runtime library (version 2.7) + Python is a high-level, interactive, object-oriented language. Its 2.7 version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: python2.7-examples +Architecture: all +Depends: python2.7 (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v2.7) + Examples, Demos and Tools for Python (v2.7). These are files included in + the upstream Python distribution (v2.7). + +Package: python2.7-dev +Architecture: any +Multi-Arch: allowed +Depends: python2.7 (= ${binary:Version}), libpython2.7-dev (= ${binary:Version}), libpython2.7 (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Recommends: libc6-dev | libc-dev +Replaces: python2.7 (<< 2.7-3) +Description: Header files and a static library for Python (v2.7) + Header files, a static library and development tools for building + Python (v2.7) modules, extending the Python interpreter or embedding + Python (v2.7) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: libpython2.7-dev +Section: libdevel +Architecture: any +Multi-Arch: same +Pre-Depends: multiarch-support +Depends: libpython2.7-stdlib (= ${binary:Version}), libpython2.7 (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Replaces: python2.7 (<< 2.7-3), python2.7-dev (<< 2.7.3-10), python2.7-minimal (<< 2.7.3-10) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v2.7) + Header files, a static library and development tools for building + Python (v2.7) modules, extending the Python interpreter or embedding + Python (v2.7) in applications. + . + Maintainers of Python packages should read README.maintainers. + . + This package contains development files. It is normally not + used on it's own, but as a dependency of python2.7-dev. + +Package: libpython2.7-testsuite +Section: libdevel +Architecture: all +Depends: libpython2.7-stdlib (>= ${binary:Version}), ${misc:Depends} +Suggests: python-gdbm, python-tk +Description: Testsuite for the Python standard library (v2.7) + The complete testsuite for the Python standard library. Note that + a subset is found in the libpython2.7-stdlib package, which should + be enough for other packages to use (please do not build-depend + on this package, but file a bug report to include additional + testsuite files in the libpython2.7-stdlib package). + +Package: idle-python2.7 +Architecture: all +Depends: python2.7, python-tk (>= 2.6~a3), python2.7-tk, ${misc:Depends} +Enhances: python2.7 +Replaces: python2.7 (<< 2.6.1-2) +Description: IDE for Python (v2.7) using Tkinter + IDLE is an Integrated Development Environment for Python (v2.7). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: python2.7-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: python2.7 +Description: Documentation for the high-level object-oriented language Python (v2.7) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v2.7). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python2.7 + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: python2.7-dbg +Section: debug +Architecture: any +Multi-Arch: allowed +Priority: extra +Depends: python2.7 (= ${binary:Version}), libpython2.7-dbg (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version 2.7) + The package holds two things: + . + - A Python interpreter configured with --pydebug. Dynamically loaded modules + are searched as _d.so first. Third party extensions need a separate + build to be used by this interpreter. + - Debug information for standard python interpreter and extensions. + . + See the README.debug for more information. + +Package: libpython2.7-dbg +Section: debug +Architecture: any +Multi-Arch: same +Priority: extra +Pre-Depends: multiarch-support +Depends: libpython2.7-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python2.7-gdbm-dbg, python2.7-tk-dbg +Replaces: python2.7-dbg (<< 2.7.3-10) +Description: Debug Build of the Python Interpreter (version 2.7) + The package holds two things: + . + - Extensions for a Python interpreter configured with --pydebug. + - Debug information for standard python extensions. + . + See the README.debug for more information. + --- python2.7-2.7.6.orig/debian/control.in +++ python2.7-2.7.6/debian/control.in @@ -0,0 +1,212 @@ +Source: @PVER@ +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5), quilt, autoconf, lsb-release, sharutils, + libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), + tk-dev, blt-dev (>= 2.4z), libssl-dev, + zlib1g-dev, libbz2-dev, + libexpat1-dev, + libbluetooth-dev [linux-any], + locales [!armel !avr32 !hppa !ia64 !mipsel], + libsqlite3-dev, libffi-dev (>= 3.0.5) [!or1k !avr32], + libgpm2 [linux-any], + mime-support, netbase, net-tools, bzip2, + libdb-dev (<< 1:6.0), libgdbm-dev, python@bd_qual@, help2man, + gcc (>= 4:4.8) [amd64 armel armhf i386 x32 kfreebsd-any hurd-any], + xvfb, xauth +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, @PVER@-xml, python-xml, autoconf2.13, python-cxx-dev +Standards-Version: 3.9.5 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg@VER@-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg@VER@-debian +XS-Testsuite: autopkgtest + +Package: @PVER@ +Architecture: any +Multi-Arch: allowed +Priority: @PRIO@ +Depends: @PVER@-minimal (= ${binary:Version}), lib@PVER@-stdlib (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: @PVER@-doc, binutils +Conflicts: python-profiler (<= 2.7.1-2) +Breaks: python-virtualenv (<< 1.7.1.2-2~), vim-nox (<< 2:7.3.547-4), vim-gtk (<< 2:7.3.547-4), vim-gnome (<< 2:7.3.547-4), vim-athena (<< 2:7.3.547-4) +Replaces: python-profiler (<= 2.7.1-2), @PVER@-minimal (<< 2.7.3-7~) +Description: Interactive high-level object-oriented language (version @VER@) + Python is a high-level, interactive, object-oriented language. Its @VER@ version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: lib@PVER@-stdlib +Architecture: any +Multi-Arch: same +Priority: @PRIO@ +Depends: lib@PVER@-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Provides: @PVER@-cjkcodecs, @PVER@-ctypes, @PVER@-elementtree, @PVER@-celementtree, @PVER@-wsgiref, @PVER@-profiler, @PVER@-argparse, python-argparse +Replaces: @PVER@ (<< 2.7.5-0~) +Description: Interactive high-level object-oriented language (standard library, version @VER@) + Python is a high-level, interactive, object-oriented language. Its @VER@ version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains Python @VER@'s standard library. It is normally not + used on its own, but as a dependency of python@VER@. + +Package: @PVER@-minimal +Architecture: any +Multi-Arch: allowed +Priority: @MINPRIO@ +Pre-Depends: ${shlibs:Pre-Depends} +Depends: lib@PVER@-minimal (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Recommends: @PVER@ +Suggests: binfmt-support +Replaces: @PVER@ (<< 2.7.1~rc1-2~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version @VER@) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/@PVER@-minimal/README.Debian for a list of the modules + contained in this package. + +Package: lib@PVER@-minimal +Architecture: any +Multi-Arch: same +Priority: @MINPRIO@ +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: lib@PVER@-stdlib +Replaces: @PVER@ (<< 2.7.4-2), @PVER@-minimal (<< 2.7.3-10), lib@PVER@-stdlib (<< 2.7.4-2) +Breaks: @PVER@-minimal (<< 2.7.4~rc1-1~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version @VER@) + This package contains some essential modules. It is normally not + used on it's own, but as a dependency of @PVER@-minimal. + +Package: lib@PVER@ +Architecture: any +Multi-Arch: same +Section: libs +Priority: @PRIO@ +Pre-Depends: multiarch-support +Depends: lib@PVER@-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 2.6) +Description: Shared Python runtime library (version @VER@) + Python is a high-level, interactive, object-oriented language. Its @VER@ version + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: @PVER@-examples +Architecture: all +Depends: @PVER@ (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v@VER@) + Examples, Demos and Tools for Python (v@VER@). These are files included in + the upstream Python distribution (v@VER@). + +Package: @PVER@-dev +Architecture: any +Multi-Arch: allowed +Depends: @PVER@ (= ${binary:Version}), lib@PVER@-dev (= ${binary:Version}), lib@PVER@ (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Recommends: libc6-dev | libc-dev +Replaces: @PVER@ (<< 2.7-3) +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: lib@PVER@-dev +Section: libdevel +Architecture: any +Multi-Arch: same +Pre-Depends: multiarch-support +Depends: lib@PVER@-stdlib (= ${binary:Version}), lib@PVER@ (= ${binary:Version}), libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 2.7-3), @PVER@-dev (<< 2.7.3-10), @PVER@-minimal (<< 2.7.3-10) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + . + This package contains development files. It is normally not + used on it's own, but as a dependency of @PVER@-dev. + +Package: lib@PVER@-testsuite +Section: libdevel +Architecture: all +Depends: lib@PVER@-stdlib (>= ${binary:Version}), ${misc:Depends} +Suggests: python-gdbm, python-tk +Description: Testsuite for the Python standard library (v@VER@) + The complete testsuite for the Python standard library. Note that + a subset is found in the lib@PVER@-stdlib package, which should + be enough for other packages to use (please do not build-depend + on this package, but file a bug report to include additional + testsuite files in the lib@PVER@-stdlib package). + +Package: idle-@PVER@ +Architecture: all +Depends: @PVER@, python-tk (>= 2.6~a3), @PVER@-tk, ${misc:Depends} +Enhances: @PVER@ +Replaces: @PVER@ (<< 2.6.1-2) +Description: IDE for Python (v@VER@) using Tkinter + IDLE is an Integrated Development Environment for Python (v@VER@). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: @PVER@-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: @PVER@ +Description: Documentation for the high-level object-oriented language Python (v@VER@) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v@VER@). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python@VER@ + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: @PVER@-dbg +Section: debug +Architecture: any +Multi-Arch: allowed +Priority: extra +Depends: @PVER@ (= ${binary:Version}), lib@PVER@-dbg (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version @VER@) + The package holds two things: + . + - A Python interpreter configured with --pydebug. Dynamically loaded modules + are searched as _d.so first. Third party extensions need a separate + build to be used by this interpreter. + - Debug information for standard python interpreter and extensions. + . + See the README.debug for more information. + +Package: lib@PVER@-dbg +Section: debug +Architecture: any +Multi-Arch: same +Priority: extra +Pre-Depends: multiarch-support +Depends: lib@PVER@-stdlib (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: @PVER@-gdbm-dbg, @PVER@-tk-dbg +Replaces: @PVER@-dbg (<< 2.7.3-10) +Description: Debug Build of the Python Interpreter (version @VER@) + The package holds two things: + . + - Extensions for a Python interpreter configured with --pydebug. + - Debug information for standard python extensions. + . + See the README.debug for more information. + --- python2.7-2.7.6.orig/debian/control.stdlib +++ python2.7-2.7.6/debian/control.stdlib @@ -0,0 +1,16 @@ +Package: @PVER@-tk +Architecture: any +Depends: @PVER@ (= ${Source-Version}), ${shlibs:Depends} +Suggests: tix +XB-Python-Version: @VER@ +Description: Tkinter - Writing Tk applications with Python (v@VER@) + A module for writing portable GUI applications with Python (v@VER@) using Tk. + Also known as Tkinter. + +Package: @PVER@-gdbm +Architecture: any +Depends: @PVER@ (= ${Source-Version}), ${shlibs:Depends} +Description: GNU dbm database support for Python (v@VER@) + GNU dbm database module for Python. Install this if you want to + create or read GNU dbm database files with Python. + --- python2.7-2.7.6.orig/debian/copyright +++ python2.7-2.7.6/debian/copyright @@ -0,0 +1,732 @@ +This package was put together by Klee Dienes from +sources from ftp.python.org:/pub/python, based on the Debianization by +the previous maintainers Bernd S. Brentrup and +Bruce Perens. Current maintainer is Matthias Klose . + +It was downloaded from http://python.org/ + +Copyright: + +Upstream Author: Guido van Rossum and others. + +License: + +The following text includes the Python license and licenses and +acknowledgements for incorporated software. The licenses can be read +in the HTML and texinfo versions of the documentation as well, after +installing the pythonx.y-doc package. Licenses for files not licensed +under the Python Licenses are found at the end of this file. + + +Python License +============== + +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations (now Zope +Corporation, see http://www.zope.com). In 2001, the Python Software +Foundation (PSF, see http://www.python.org/psf/) was formed, a +non-profit organization created specifically to own Python-related +Intellectual Property. Zope Corporation is a sponsoring member of +the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.2 2.1.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2.1 2.2 2002 PSF yes + 2.2.2 2.2.1 2002 PSF yes + 2.2.3 2.2.2 2003 PSF yes + 2.3 2.2.2 2002-2003 PSF yes + 2.3.1 2.3 2002-2003 PSF yes + 2.3.2 2.3.1 2002-2003 PSF yes + 2.3.3 2.3.2 2002-2003 PSF yes + 2.3.4 2.3.3 2004 PSF yes + 2.3.5 2.3.4 2005 PSF yes + 2.4 2.3 2004 PSF yes + 2.4.1 2.4 2005 PSF yes + 2.4.2 2.4.1 2005 PSF yes + 2.4.3 2.4.2 2006 PSF yes + 2.5 2.4 2006 PSF yes + 2.5.1 2.5 2007 PSF yes + 2.5.2 2.5.1 2008 PSF yes + 2.5.3 2.5.2 2008 PSF yes + 2.6 2.5 2008 PSF yes + 2.6.1 2.6 2008 PSF yes + 2.6.2 2.6.1 2009 PSF yes + 2.6.3 2.6.2 2009 PSF yes + 2.6.4 2.6.3 2009 PSF yes + 2.6.5 2.6.4 2010 PSF yes + 2.7 2.6 2010 PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python +alone or in any derivative version, provided, however, that PSF's +License Agreement and PSF's notice of copyright, i.e., "Copyright (c) +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Licenses and Acknowledgements for Incorporated Software +======================================================= + +Mersenne Twister +---------------- + +The `_random' module includes code based on a download from +`http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html'. The +following are the verbatim comments from the original code: + + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Any feedback is very welcome. + http://www.math.keio.ac.jp/matumoto/emt.html + email: matumoto@math.keio.ac.jp + + +Sockets +------- + +The `socket' module uses the functions, `getaddrinfo', and +`getnameinfo', which are coded in separate source files from the WIDE +Project, `http://www.wide.ad.jp/about/index.html'. + + Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + FOR GAI_ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON GAI_ANY THEORY OF LIABILITY, WHETHER + IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN GAI_ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + + +Floating point exception control +-------------------------------- + +The source for the `fpectl' module includes the following notice: + + --------------------------------------------------------------------- + / Copyright (c) 1996. \ + | The Regents of the University of California. | + | All rights reserved. | + | | + | Permission to use, copy, modify, and distribute this software for | + | any purpose without fee is hereby granted, provided that this en- | + | tire notice is included in all copies of any software which is or | + | includes a copy or modification of this software and in all | + | copies of the supporting documentation for such software. | + | | + | This work was produced at the University of California, Lawrence | + | Livermore National Laboratory under contract no. W-7405-ENG-48 | + | between the U.S. Department of Energy and The Regents of the | + | University of California for the operation of UC LLNL. | + | | + | DISCLAIMER | + | | + | This software was prepared as an account of work sponsored by an | + | agency of the United States Government. Neither the United States | + | Government nor the University of California nor any of their em- | + | ployees, makes any warranty, express or implied, or assumes any | + | liability or responsibility for the accuracy, completeness, or | + | usefulness of any information, apparatus, product, or process | + | disclosed, or represents that its use would not infringe | + | privately-owned rights. Reference herein to any specific commer- | + | cial products, process, or service by trade name, trademark, | + | manufacturer, or otherwise, does not necessarily constitute or | + | imply its endorsement, recommendation, or favoring by the United | + | States Government or the University of California. The views and | + | opinions of authors expressed herein do not necessarily state or | + | reflect those of the United States Government or the University | + | of California, and shall not be used for advertising or product | + \ endorsement purposes. / + --------------------------------------------------------------------- + + +Cookie management +----------------- + +The `Cookie' module contains the following notice: + + Copyright 2000 by Timothy O'Malley + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software + and its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Timothy O'Malley not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR + ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +Execution tracing +----------------- + +The `trace' module contains the following notice: + + portions copyright 2001, Autonomous Zones Industries, Inc., all rights... + err... reserved and offered to the public under the terms of the + Python 2.2 license. + Author: Zooko O'Whielacronx + http://zooko.com/ + mailto:zooko@zooko.com + + Copyright 2000, Mojam Media, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1999, Bioreason, Inc., all rights reserved. + Author: Andrew Dalke + + Copyright 1995-1997, Automatrix, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. + + Permission to use, copy, modify, and distribute this Python software and + its associated documentation for any purpose without fee is hereby + granted, provided that the above copyright notice appears in all copies, + and that both that copyright notice and this permission notice appear in + supporting documentation, and that the name of neither Automatrix, + Bioreason or Mojam Media be used in advertising or publicity pertaining + to distribution of the software without specific, written prior + permission. + + +UUencode and UUdecode functions +------------------------------- + +The `uu' module contains the following notice: + + Copyright 1994 by Lance Ellinghouse + Cathedral City, California Republic, United States of America. + All Rights Reserved + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Lance Ellinghouse + not be used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Modified by Jack Jansen, CWI, July 1995: + - Use binascii module to do the actual line-by-line conversion + between ascii and binary. This results in a 1000-fold speedup. The C + version is still 5 times faster, though. + - Arguments more compliant with python standard + + +XML Remote Procedure Calls +-------------------------- + +The `xmlrpclib' module contains the following notice: + + The XML-RPC client interface is + + Copyright (c) 1999-2002 by Secret Labs AB + Copyright (c) 1999-2002 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, + and will comply with the following terms and conditions: + + Permission to use, copy, modify, and distribute this software and + its associated documentation for any purpose and without fee is + hereby granted, provided that the above copyright notice appears in + all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Secret Labs AB or the author not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD + TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- + ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR + BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + OF THIS SOFTWARE. + +Licenses for Software linked to +=============================== + +Note that the choice of GPL compatibility outlined above doesn't extend +to modules linked to particular libraries, since they change the +effective License of the module binary. + + +GNU Readline +------------ + +The 'readline' module makes use of GNU Readline. + + The GNU Readline Library is free software; you can redistribute it + and/or modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2, or (at + your option) any later version. + + On Debian systems, you can find the complete statement in + /usr/share/doc/readline-common/copyright'. A copy of the GNU General + Public License is available in /usr/share/common-licenses/GPL-2'. + + +OpenSSL +------- + +The '_ssl' module makes use of OpenSSL. + + The OpenSSL toolkit stays under a dual license, i.e. both the + conditions of the OpenSSL License and the original SSLeay license + apply to the toolkit. Actually both licenses are BSD-style Open + Source licenses. Note that both licenses are incompatible with + the GPL. + + On Debian systems, you can find the complete license text in + /usr/share/doc/openssl/copyright'. + + +Files with other licenses than the Python License +------------------------------------------------- + +Files: Lib/profile.py Lib/pstats.py +Copyright: Disney Enterprises, Inc. All Rights Reserved. +License: # Licensed to PSF under a Contributor Agreement + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied. See the License for the specific language + overning permissions and limitations under the License. + + On Debian systems, the Apache 2.0 license can be found in + /usr/share/common-licenses/Apache-2.0. + +Files: Modules/zlib/* +Copyright: (C) 1995-2010 Jean-loup Gailly and Mark Adler +License: This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + If you use the zlib library in a product, we would appreciate *not* receiving + lengthy legal documents to sign. The sources are provided for free but without + warranty of any kind. The library has been entirely written by Jean-loup + Gailly and Mark Adler; it does not include third-party code. + +Files: Modules/_ctypes/libffi/* +Copyright: Copyright (C) 1996-2009 Red Hat, Inc and others. +License: Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + Documentation: + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 2, or (at your option) any + later version. A copy of the license is included in the + section entitled ``GNU General Public License''. + +Files: Modules/expat/* +Copyright: Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper + Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers +License: Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Files: Misc/python-mode.el +Copyright: Copyright (C) 1992,1993,1994 Tim Peters +License: This software is provided as-is, without express or implied + warranty. Permission to use, copy, modify, distribute or sell this + software, without fee, for any purpose and by any individual or + organization, is hereby granted, provided that the above copyright + notice and this paragraph appear in all copies. + +Files: PC/_subprocess.c +Copyright: Copyright (c) 2004 by Fredrik Lundh + Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com + Copyright (c) 2004 by Peter Astrand +License: + * Permission to use, copy, modify, and distribute this software and + * its associated documentation for any purpose and without fee is + * hereby granted, provided that the above copyright notice appears in + * all copies, and that both that copyright notice and this permission + * notice appear in supporting documentation, and that the name of the + * authors not be used in advertising or publicity pertaining to + * distribution of the software without specific, written prior + * permission. + * + * THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Files: PC/winsound.c +Copyright: Copyright (c) 1999 Toby Dickenson +License: * Permission to use this software in any way is granted without + * fee, provided that the copyright notice above appears in all + * copies. This software is provided "as is" without any warranty. + */ + +/* Modified by Guido van Rossum */ +/* Beep added by Mark Hammond */ +/* Win9X Beep and platform identification added by Uncle Timmy */ --- python2.7-2.7.6.orig/debian/depgraph.py +++ python2.7-2.7.6/debian/depgraph.py @@ -0,0 +1,199 @@ +#! /usr/bin/python + +# Copyright 2004 Toby Dickenson +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +import sys, getopt, colorsys, imp, md5 + +class pydepgraphdot: + + def main(self,argv): + opts,args = getopt.getopt(argv,'',['mono']) + self.colored = 1 + for o,v in opts: + if o=='--mono': + self.colored = 0 + self.render() + + def fix(self,s): + # Convert a module name to a syntactically correct node name + return s.replace('.','_') + + def render(self): + p,t = self.get_data() + + # normalise our input data + for k,d in p.items(): + for v in d.keys(): + if not p.has_key(v): + p[v] = {} + + f = self.get_output_file() + + f.write('digraph G {\n') + #f.write('concentrate = true;\n') + #f.write('ordering = out;\n') + f.write('ranksep=1.0;\n') + f.write('node [style=filled,fontname=Helvetica,fontsize=10];\n') + allkd = p.items() + allkd.sort() + for k,d in allkd: + tk = t.get(k) + if self.use(k,tk): + allv = d.keys() + allv.sort() + for v in allv: + tv = t.get(v) + if self.use(v,tv) and not self.toocommon(v,tv): + f.write('%s -> %s' % ( self.fix(k),self.fix(v) ) ) + self.write_attributes(f,self.edge_attributes(k,v)) + f.write(';\n') + f.write(self.fix(k)) + self.write_attributes(f,self.node_attributes(k,tk)) + f.write(';\n') + f.write('}\n') + + def write_attributes(self,f,a): + if a: + f.write(' [') + f.write(','.join(a)) + f.write(']') + + def node_attributes(self,k,type): + a = [] + a.append('label="%s"' % self.label(k)) + if self.colored: + a.append('fillcolor="%s"' % self.color(k,type)) + else: + a.append('fillcolor=white') + if self.toocommon(k,type): + a.append('peripheries=2') + return a + + def edge_attributes(self,k,v): + a = [] + weight = self.weight(k,v) + if weight!=1: + a.append('weight=%d' % weight) + length = self.alien(k,v) + if length: + a.append('minlen=%d' % length) + return a + + def get_data(self): + t = eval(sys.stdin.read()) + return t['depgraph'],t['types'] + + def get_output_file(self): + return sys.stdout + + def use(self,s,type): + # Return true if this module is interesting and should be drawn. Return false + # if it should be completely omitted. This is a default policy - please override. + if s=='__main__': + return 0 + #if s in ('os','sys','time','__future__','types','re','string'): + if s in ('sys'): + # nearly all modules use all of these... more or less. They add nothing to + # our diagram. + return 0 + if s.startswith('encodings.'): + return 0 + if self.toocommon(s,type): + # A module where we dont want to draw references _to_. Dot doesnt handle these + # well, so it is probably best to not draw them at all. + return 0 + return 1 + + def toocommon(self,s,type): + # Return true if references to this module are uninteresting. Such references + # do not get drawn. This is a default policy - please override. + # + if s=='__main__': + # references *to* __main__ are never interesting. omitting them means + # that main floats to the top of the page + return 1 + #if type==imp.PKG_DIRECTORY: + # # dont draw references to packages. + # return 1 + return 0 + + def weight(self,a,b): + # Return the weight of the dependency from a to b. Higher weights + # usually have shorter straighter edges. Return 1 if it has normal weight. + # A value of 4 is usually good for ensuring that a related pair of modules + # are drawn next to each other. This is a default policy - please override. + # + if b.split('.')[-1].startswith('_'): + # A module that starts with an underscore. You need a special reason to + # import these (for example random imports _random), so draw them close + # together + return 4 + return 1 + + def alien(self,a,b): + # Return non-zero if references to this module are strange, and should be drawn + # extra-long. the value defines the length, in rank. This is also good for putting some + # vertical space between seperate subsystems. This is a default policy - please override. + # + return 0 + + def label(self,s): + # Convert a module name to a formatted node label. This is a default policy - please override. + # + return '\\.\\n'.join(s.split('.')) + + def color(self,s,type): + # Return the node color for this module name. This is a default policy - please override. + # + # Calculate a color systematically based on the hash of the module name. Modules in the + # same package have the same color. Unpackaged modules are grey + t = self.normalise_module_name_for_hash_coloring(s,type) + return self.color_from_name(t) + + def normalise_module_name_for_hash_coloring(self,s,type): + if type==imp.PKG_DIRECTORY: + return s + else: + i = s.rfind('.') + if i<0: + return '' + else: + return s[:i] + + def color_from_name(self,name): + n = md5.md5(name).digest() + hf = float(ord(n[0])+ord(n[1])*0xff)/0xffff + sf = float(ord(n[2]))/0xff + vf = float(ord(n[3]))/0xff + r,g,b = colorsys.hsv_to_rgb(hf, 0.3+0.6*sf, 0.8+0.2*vf) + return '#%02x%02x%02x' % (r*256,g*256,b*256) + + +def main(): + pydepgraphdot().main(sys.argv[1:]) + +if __name__=='__main__': + main() + + + --- python2.7-2.7.6.orig/debian/dh_doclink +++ python2.7-2.7.6/debian/dh_doclink @@ -0,0 +1,28 @@ +#! /bin/sh + +pkg=`echo $1 | sed 's/^-p//'` +target=$2 + +ln -sf $target debian/$pkg/usr/share/doc/$pkg + +f=debian/$pkg.postinst.debhelper +if [ ! -e $f ] || [ "`grep -c '^# dh_doclink' $f`" -eq 0 ]; then +cat >> $f <> $f < /dev/null`; do \ + while rmdir $$d 2> /dev/null; do d=`dirname $$d`; done; \ +done + +exit 0 --- python2.7-2.7.6.orig/debian/idle-PVER.1.in +++ python2.7-2.7.6/debian/idle-PVER.1.in @@ -0,0 +1,104 @@ +.TH IDLE 1 "21 September 2004" +.SH NAME +\fBIDLE\fP \- An Integrated DeveLopment Environment for Python +.SH SYNTAX +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] [ \fIfile\fP ...] +.PP +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] ( \fI-c cmd\fP | \fI-r file\fP ) [ \fIarg\fP ...] +.PP +.B idle [ \fI-dins\fP ] [ \fI-t title\fP ] - [ \fIarg\fP ...] +.SH DESCRIPTION +This manual page documents briefly the +.BR idle +command. +This manual page was written for Debian +because the original program does not have a manual page. +For more information, refer to IDLE's help menu. +.PP +.B IDLE +is an Integrated DeveLopment Environment for Python. IDLE is based on +Tkinter, Python's bindings to the Tk widget set. Features are 100% pure +Python, multi-windows with multiple undo and Python colorizing, a Python +shell window subclass, a debugger. IDLE is cross-platform, i.e. it works +on all platforms where Tk is installed. +.LP +.SH OPTIONS +.TP +.B \-h +.PD +Print this help message and exit. +.TP +.B \-n +.PD +Run IDLE without a subprocess (see Help/IDLE Help for details). +.PP +The following options will override the IDLE 'settings' configuration: +.TP +.B \-e +.PD +Open an edit window. +.TP +.B \-i +.PD +Open a shell window. +.PP +The following options imply -i and will open a shell: +.TP +.B \-c cmd +.PD +Run the command in a shell, or +.TP +.B \-r file +.PD +Run script from file. +.PP +.TP +.B \-d +.PD +Enable the debugger. +.TP +.B \-s +.PD +Run $IDLESTARTUP or $PYTHONSTARTUP before anything else. +.TP +.B \-t title +.PD +Set title of shell window. +.PP +A default edit window will be bypassed when -c, -r, or - are used. +.PP +[arg]* and [file]* are passed to the command (-c) or script (-r) in sys.argv[1:]. +.SH EXAMPLES +.TP +idle +.PD +Open an edit window or shell depending on IDLE's configuration. +.TP +idle foo.py foobar.py +.PD +Edit the files, also open a shell if configured to start with shell. +.TP +idle -est "Baz" foo.py +.PD +Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell +window with the title "Baz". +.TP +idle -c "import sys; print sys.argv" "foo" +.PD +Open a shell window and run the command, passing "-c" in sys.argv[0] +and "foo" in sys.argv[1]. +.TP +idle -d -s -r foo.py "Hello World" +.PD +Open a shell window, run a startup script, enable the debugger, and +run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in +sys.argv[1]. +.TP +echo "import sys; print sys.argv" | idle - "foobar" +.PD +Open a shell window, run the script piped in, passing '' in sys.argv[0] +and "foobar" in sys.argv[1]. +.SH SEE ALSO +python(1). +.SH AUTHORS +Various. --- python2.7-2.7.6.orig/debian/idle-PVER.menu.in +++ python2.7-2.7.6/debian/idle-PVER.menu.in @@ -0,0 +1,5 @@ +?package(idle-@PVER@):needs="X11" section="Applications/Programming"\ + title="IDLE (Python v@VER@)"\ + icon="/usr/share/pixmaps/@PVER@.xpm"\ + command="/usr/bin/idle-@PVER@" \ + hints="Environments" --- python2.7-2.7.6.orig/debian/idle-PVER.overrides.in +++ python2.7-2.7.6/debian/idle-PVER.overrides.in @@ -0,0 +1,3 @@ +# icon in dependent package +idle-@PVER@ binary: menu-icon-missing +idle-@PVER@ binary: image-file-in-usr-lib --- python2.7-2.7.6.orig/debian/idle-PVER.postinst.in +++ python2.7-2.7.6/debian/idle-PVER.postinst.in @@ -0,0 +1,32 @@ +#! /bin/sh +# +# postinst script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +set -e + +DIRLIST="/usr/lib/python@VER@/idlelib" + +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + + for i in $DIRLIST ; do + @PVER@ /usr/lib/@PVER@/compileall.py -q $i + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config + then + @PVER@ -O /usr/lib/@PVER@/compileall.py -q $i + fi + done + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; + +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/idle-PVER.postrm.in +++ python2.7-2.7.6/debian/idle-PVER.postrm.in @@ -0,0 +1,11 @@ +#! /bin/sh + +set -e + +if [ "$1" = "purge" ]; then + rm -rf /etc/idle-@PVER@ +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/idle-PVER.prerm.in +++ python2.7-2.7.6/debian/idle-PVER.prerm.in @@ -0,0 +1,17 @@ +#! /bin/sh +# +# sample prerm script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +set -e + +PACKAGE=`basename $0 .prerm` + +dpkg --listfiles $PACKAGE | + awk '$0~/\.py$/ {print $0"c\n" $0"o"}' | + xargs rm -f >&2 + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/idle-icons.tgz.uue +++ python2.7-2.7.6/debian/idle-icons.tgz.uue @@ -0,0 +1,409 @@ +begin-base64 644 idle-icons.tgz +H4sIAFSWLVMAA+19CTxW2/f3MWVoQCJJSBKRWZmnKCQ0q1QqFUVRKlOGUDRQ +GlWGpFIaSIZMGUMkYyoyl4TMQ5H97nUep+u63fF/39/v/37evtfuPOc55+y9 +1tprrb3W2odrbWmzw8Z6m7TB9n17D0hb47MtsguldlnvJP49yGAsVFCAo+wi +RZmxR4CcjKwcISsnt2ihgpyc7KKFhIysgqycIiEk8y/S8Ls4eMBh634hIcJy +3559f3Tfn13/fxRLDZYoKW/lIDiIgWOE3vYjepZHllgeWboDf3BDWTIoVwHl +yaPniqhwEcpRQgWaqFgdlWigUi1UroMql6DXS1GpPqpaht4tR1WrUO0qVLcC +Na5F781Q8wbUsgW1WqC2ragd/2xHDYc07YM0DoRoOISpHwxXP3hDzfGOmlOU +qvN9DbeYxbt8FlsdX2rto2Ptp73HX9s2UG/fWa2955c5Bhu43VH3iF969JHe +sWT7C7GhoaF+1+6FhYWFh4dHRETcvHkzMjLy7t279+7du3///oMHDx4+fBgb +GxsfH5+QkPDkyZPk5OTU1NS0tLSnT5+iuiDUcBX1XkVtkajrAepOuJ30PCKl +ODyzJjqj+Hp2XXp6ekZGRlZWVk5OTm5ubl5eXn5+fmFh4YsXL4qKil6+fFlc +XFxSUlJdXf3u3buampra2lrUW1pW96m+vr6hoaGxsbGpqen9+/cfPnxobm7+ ++PFjS0tLW1tbe3v758+f0VDrp46ezs7Orq6u7u7unp6evr6+/v7+gYGBwcHB +L1++fP36dWhoaHh4+Nu3byMjIwih/7aG/H+E2V8Y6QjiOCEJJ2ATBEszcVpo +huN7w4uSm6YKbEjkYL288MjIMOc0X9NLWha8Ajr7b5mEydt+ipyhu9901rH1 +2Y9nZN8qEtRZu/v8mdk7inUW7Kaf/EnetzhsmrVOosXWHtPpsvYTgltaDphy +czMa7m7hjQzg5hOzzLags0gXmmTyOLLces6eUzzzJzRFc2lnXvA/wnL9sn2j +8SpVIT5+/W5T9uszZn9W+pJOx+DDzDKNf3YZs0mYuMyEI4Nh9TJe9EanPFbI +5841eL7CMFBEZyf71YX2gXsTOegmHw3XfsTSVe/FclnLdL6CWTFj/LPFakfv +iTxpTrDnV3PuLeblIFT/28L/if8GrH+4/tvt3fUvjvFn67/8QpnfrP+Kcj/X +//8E/EyNl05m42PDHycb6OuuJMDx4cYxAf9rsn2OMD5M2LZsqS4iwWo2UI2/ +YbXTX38AH/XJtiR/jwZBMEoZ6Gqv1s+9sKbgZOAWXrfhlC3PqiLDZm+3FY4U +9Y324X59a1KSaVK02IY4tis7OMrvTfzKPHVnvVZT+JpEu+KdLPtnSylc0bvq +V27BIh369d3wsPHJshajVQxPa5OdnJS/qr8cSnnpFHDHXOpSwQ4dRm0ORrrB +p29sFl59sTPdUi7ISDRdZlKWjMcXV43Ql6Hqy26uvLN690FuZj34MN9bAd8W +a6B/u6zFQcVbP1DEYOrsE+FiJzJjb1lfudV1rzXpQat3eWufc6qxL44j7k4t +tVLgOz1hdtyG+2uj1I84c6TdgU9rdKb66QqfJcJL8OX3sw4lv9ubMFEp2Ph2 +Gevrdnw25VRuY5fjpGz8j9oUDh2W2cPu9z4PDH1zE2Tx0blummf51iQ9U4T/ +9JIbJSx2SvxTjjP44u70GaOh8wsMycAbk6OaQEAuw7STghptbURra0et+1dG +/VJHNT66zQ/f3LNOD1Zt6fXjOlWcfNhh9boHMvRHc7bFmEl61HbggbRkeCdN +8Erhen4tVF5H8qlzXEzJXgbpzdWpLv2SQixJUgbX8t6+rUq4wOaVbLf1Kf1T +Vl8sBGHyIbpL0ZVYAOqb5WNjXlebb0p15lZyc7UW55+wdu2DLSai4pzrJ0xa +XDbN59vb9lu1QcZBwjwfNjyER5xul+dUc+U05AbUppX4a7pPYFlxvouXw/uN +jQpT4c7lV40cF7D0PAk3nYvanHY1v1pwaaKZWd5O+RmeSZddPIKOcW7/IMGT +EJ/mSseyYg2bluo07zdGgcQ5vwoF+QulLZb7nWYQDt9y2QnTinxGwjk1TjE9 +U2UHGyO9p5ZQOrfFbINzfmL7PcpuswtuNmcU0Cxq3lfDmLn1aW3jl0q97em1 +TzXdjVnz5Ii8boek4+mk0D2wKryxucZxNbVyT8xHFSGDR5IF0wafTRbij9+w +5ekED7enm5mJrLBsbr1AqxBjZaF5MqEb76d3cA6CauXuo5tJp/r0yNDwlxtL +6a6+kJm2Y1/uXUNPVtlJhMWtMgW2bMJJ/Spd+vXFAx1oMd2h1Oq9CVXtHybO +u6p++PNrWaFQk9smIcOrLNnUrt6ZT0hKViczEzGvby5jbte8Ozn6ibgMvRHd +B7r1t1aWXShg/Uyiu4RIMmaNNk5+d0mazkLFNoEubLPmgWN0BXKpz/YuehF0 +ysegcO3eqIrdcRu+Pvx4qEVMZ/bAQ1/QilMu2S0OSg82MRArzLfULrN0Gapf +PL/Pi9l1z3CcbyR91uz2tpI5bCmJlwve739iLqz98pvbXS3RMqD40P0lW1aE +VV41CjRIl/Hnd+qZQFy8lBBPbNI8uHs7A4deqPSlqppbs7akDVduXz3/guHN +0tKVYIuxW542aC65bio2jW26dOmF1Ec6tecdrrw6oUN3Uu9KqFp+c88X183T +Btyb541IfBR991DuJnYhcx30zBwstzrsUNm+fwc+EDglVFggI7tAXna1jLKK +zEIVWTkJGTkVGZnD7nM5f/WA7T5L651Ov//ABOHg++DnDPSMdR/oWBz973jZ +/734wfovL/cfzv8Xysv/Zv2XV/i5/v8nQMv/hQghYqAb5/+u30sAOP/X3eG+ +bds2lCKCUuaitHnoqRhKlUDp4ihDAmVKoqwFKFsK5UijLDmUI4NyZVGeHBQL +8hWgXlCwEEoGGWooWxO9UEIvlFGRCipSRS9VUaE6eqmGitVQCVlKKNFEpZpQ +UCjDP9pQVniliyr1yOICWV94pY/eGqIqQ6gyVBtBoaHGBBWsR0XmqNYUVZlD +xaF+JWpYhRpWo8Y1UH1owj/roAbxYT2UIT5uRC2b0KfN6NMWVGWLavejpl1U +YWIbVCXsLmvaB2naX9Hcf1XjQDBUKA6EajjgnzCNg9ehVHHohvqhCPVDN9UP +31I7fFv98G01x0iyeHGXrF/cU3W+r+r8QNUF/0SrukaruMaoHHmkciRW5chj +Fbc4Zbd4ZfcEZfdE3R0eujuP6u70WrzLm1bvWGztq2Ptp7P7hM7ukzp7TkPh +wwb/BGjbntG2DdTae05r73mtfRfWu11d4hS+2O2BsscTJc8UpaOp1kcvrvW6 +re31xDYo2e7CI7tL8ZrHM0zP5piee77nepH1jdLr168/evTo8ePH34sgUP7o +8kSdjx9mlqWnp2dmZo4rczx//rygoOC3xY7S0tKysrLy8vKKiopXr15VVla+ +fv36LQ4lqqp+VQfpeom6i1FPOequQN2vUG8FGqhGg+9eNbSXN3x+1dhR3dT6 +9n17eVPn2489bz721tXV/UHR5NOnT62trd9LJx0dHejrp5aO3k8dvWMLKL29 +vf9WDYWW//fQ8n+wCYJlhGhm5dePDsvwmvBGfPWg/9Ys+6oN9St9OGaren5y +tq16JXElybbEOa5bYcq6HG/e6Y+qrBZc0jUpic9RMYi+bnhocm2L622pi3Gn +5a2LXOad2SS9r+Zee7XfHnNxk1cKrHNVHO5UHE6Mvvjo1m6uF1EWLt2MQQV8 +kedW19ouTrKtVtoj4PLsRMWJcM+1Vkx3T1+UWPv4sn3q6VW3i65qneB++GjV +rlU3VXyaE+MKVRWuKO6rmqYhMD0wpsJ+9eRbpy9ErZM+VGPsksX9YsYt/b3P +XVfoWq//eEV5+tSa5YPBN3c+t9x1/ahYSbvn6tMb4g+tD9747NSV2TNvRLIJ +a7n6ty7gi7oz3/zJsxFrxlm7ls+QfsXalXHjSM22mubyoFXNU9qSV3zqmxSt +0tmgdvBJ5w5j6Ua1A35zHNJXTOCt4KT3FTjcVpk1WY3/HP+Si6yvCpSDhAaf +Hc3ilGMRPEwQ6aqL0tN1uFZzfnh1cm/qKtY5++7RHZu+mn8qix8DEV07SeK8 +UKZPT7pjueqp9K1z/NdY3N4SEODBZTlhGseX8EV3XXuMnbY7ahsoWXiW6bLy +rSa0TzYK3RRd2ZFecpO73ntqzjX9SSVek6XOd3oGsT0W49hYVdfwQvWkh6ce +d0fhjJyper2mXhMlXM/QMU6WrGtWu2wrv1w8yOCogLDfki7dG+JLVKwZWJq0 +1lyZGZc0eaFzrQwDq7C3iMpuDvEkIfoLHELR2rKXlkxbJp1o0VO5csU0zyix +fp+F/lpV58MNJe73Tj05/3Z5X9FU7TaZxSE7QpyK11bJ5FYrvHIoXynZceZK +M3MOY5mWC8OFZTbST+xWnuO6aWhoJMNfLFFumqs/2ytkmlkYgyw9e/U9bTq6 +/1BB5sfr/380/1dYpLjwN+v/Qvmf6/9/Aj/I/4Wgkfn/nE+3Eoi/mv+zSkL+ +b1WTun6Z0fYd0zRsPeO1ri9YXWN0ZgJnmYEC3YpT0bJS5rwH5WNLLmvPtSi9 +3Kk/zzKMgY4728lMcMW82bJJl328gxsZvCbKRmzzVPDOibhAv3jjho9D9lWt +DYVdtxOq62UDYpW/CA70a9Z+Kfry8skFrWPTpoUVvfBZOr9F4ZM+o2Ku+t0t +Rfn8Fy+KQp5eb9ep9rJHbeNZfRF8Oqy3rZU/156f+YyR6Ll8ES2coPjoEKok +CDZIzwddcZiy6AUJwSPeJkOu7DOJjLMvr/lBVl9dLwPpzRur85AsXWv8SkLy +4n3AAo9wgHC/JZlLE04kCD7I9GW8OM08zCR5Tua8doPEKpluw0YAHWT777/W +M3tlWMjwnlrimpzbE02cOeG08v7aqIpPFtG3AM9acW618s60sCQAX1gi4LJ1 +dS7Bcjyr3o7X47IuQebCRBikYXO1jAFTGCLuAdqGv1wgEbWua7XKuznbiZUV +9fpkSWTm5aFZXEJ5Ch59gINy/B4eoqevd3fyzubeyDsLoMg3TxTg7JxHsNF1 +86649qGl7vEWpYv5lnJBp7aFyt4KA3jQQYzx+DFjGGSg7V96ykg0NrJf4Vx6 +TMsWcL9yWY/uwa0splbFGtdFZ084I+ohJmJIgoA1vKdnhsVkEtOlCosAxsYa +VkKfnwfJ6x8JyW17ofDinDEUb65YX2ep9Hm5naVz+BNg/lAwObuONVC82Rxy +WCXY+Pa55rMz1AKMGr88IWGimXNA0Ch33jn+ekYnG0fAayvdu/uvAR9GPBM3 +bXFUtZyn3C3idFHH+0FWKWBlv8v5PTItMc0cSs775N6QsF7YqHin8jCJp19E +095HPTRlph+YTLBu3p4RRpJXHy1zLF/GcOdHZbZZEyblxMvcKXVeA+DW2guQ +SubW73x73rCKROpmV3fJY0RqH8/n+ZK6C1Jnlq42m7VgfQIhUFjPIbDaxujY +2eP5HPUa9T1LUy89y2a8K0gWnnZU2mwHNMa+bFjljk5/HbwQIUYsJnGPg48X +EG22cBEg6LbY+hI6cb+SDFbetybXHyUAcl8VkFhvtULMl5XO28h8fUbxUNdS +h/TiYnu6PE4X2Z0DFhyT2Y5bh0wxZr7JIeTV9XZbSDeU1tjDHgEC2+ew3wV9 +Y6rbz0R/Z1p6RZTmN8tYutftaKS1ixCZ2uWowCZ0NmKlH2OZ4U2ji8YMCopr +1kVVTMga6nj69dOBlzMmORhPenPDM28bsfJtfZiXwKW7t2etKnX91tdaiYa5 +LBx6Ty8KcWbTmp9zpCNt6Evz0+H9HB4OX4U4IiTml+/2oa8b6njxocj4qSBd +8W6TF8RW6eJawL4Yi/tFYsuNhOavCoxwKi2fxCqhbvhAVdXNXYzRg/96bFgG +/3GVIF0vecWi5HcCJkpGa60U2NUYfTlXF6yau3R5wDsofRA+JAo7TwDYeNge +G79EJjnJE1IHai5tGRkZ0jY5V79NhevMuRNW0loCqVvurrqzLCFrhW3c5cLC +4a7cT/PT4/Ys2jfydc8hFv2bkfveff26J3Z92wIXl8iHm27wz37ucRbAyUOf +SoKnoB9w6NDaeSYuUPzL2stwPKvDRJRuwoS9NY/fEJ+ru77Qe7Z5ncw51J+W +tZjwaJbf5368Ma6SIJSkzqbPuL/2/oTIBwICaQ4taOVwJEe6Tk7rTadukRyV +NYcyh4LVjrx//lKzNm2yXbN/reAkgdDnA+FuO431b7PzmBmtFLeUkVXmOfCE +IMyldj+i2+y2/jyd2e6aRO2e8wxiH3zO3z7YrZaT9O7z/i/fcuXbIjyqozYx +1ylZHjPF4XgPe7uyy9rH5bwzAfJ880i4OHsL8KzdnUzCxojZUKShy6zNIUSD +nyNcrWaqSF9fXBw3N0Hki7gtEPISVy5VCsqumkBo3Zm2g+ARe+Nz5nJzjMv2 +VKLHaOEO9k+7QpyG7YOnpFuqHP6cM51OwMXo/i2T2Hlccq4HerLY2eWv6dA/ +3D61ZKevjlZhj04JuAENl29iAVtSfI+1OqxsmRdKEIOuxreL51qxiMrLeZxe +sevhrg/EQncOokRESQOwV8F4OaCvl0ViMd+5WwvXs5zX8ZwrsV1HVEhlltO1 +ximLzC8XPlK/ah1ttynSKeTg1ZJIMWIavVlW7EatyDuZN/i1elYvxRq+5s7q +hvXm5mL5fjndBpPnCZ08URRys9Zsc9F87+jk/UqRyaq2dLoXQqpmTbm9kvDy +WrS3Oomp7pBLqoagnJAA82B7Qmul5iBxx72eXuD8pOkrN+o7Ge4OGoqWyt/8 +8sUCCQbC8av1sGv4SkXFTWmSbEQfvVm+/TXwCKffpBJxWeXcbMnab5cKamRX +mT8caE9gD7BV0I060jyL8GhoWLfZc9Vz1vnabHQKvn30vXN91YwEdb1tpay3 +lT4DLOlnPneRRJa4cUxA4/37EusI4lpRgKbGtRmJHT7TL15q4dNI+shDnDHe +CAvU13eHByd/PildvH2/8qzENIBGcqcQoZ9XZqa04ox31mDLKR0bl5nNW5wN +qu1iXrs1+O17mrPlWUyF8+fqfOXZhIVL8g1AlqWOyZH+N3Ukel4ePgg4HTCH +Y7+y6FN9RvVZbPVuQZM8u768IsHDAxlic/N0np0kXnU8/yw1UjOiQb8rzlAE +L7kbJqfbX716fEZh4Kzdz9UjxJ/REcMjjfR2jHpN+8v5lm8i4eRErsEbd8x1 +yztTYAuVy4kTOC+v3m0PODtFS7FyREOWOCi5JCWjuXCnh+Nwf/uyS0T1XqOV +14u75QgtNf99nKJPHPgOGGhrr+IiPDa7dwkTHoZ9TecuSQsOnCwW99m7kt5X +4dt9t+5jlzy0vlVuiZzDORKi0zpx4qS8c/nuiLc1hNM91Zj4L1c/fxD/Kyj9 +h+t/iooKv4n/FX6+//MfAa3+h+eC6CcIeOcnURAKfqniKE0GinzPZKGYV6QC +hbo8E1SxmCzIGaHqZej5SlS7EpVthqrbhw1QYCvZid7uQBU2UGN7bYfaLFDH +Ac39V9UPRag5RakciYUC2E6vxVbHdXaf3HDwJBS37C4td7xi6Hpz8ZEoJc8U +bc84LZ+UXecS9gWlLPLK0PDN0j2VY3kpfVvwi60hxYdu5B66+eLg7VLspa5d +uxYREYFDbxx54jUUVfuj5mDUFo7e30XtsaEJhcFPSh5kV8YVvLuSUR9b8jE7 +O7uwsBDHpcWVNdXV1ehrZVNTU1tbG/raAiWlzr7e3l403D/wdRjjvzUZtPqT +Ga3+BHNCMI94mB318vY5dtzX7/i6datPBZw5e2r1alOTS8tPXDFbZ2BmuNpw +3TITQ5NlF1ebmN41vbjMUG150FXfdV7nn5xbt3zZjdjlq5cbGqiqZ8adNDTL +CD99/tSDS/cu3jQxUL/4ON/rpX9xYP3LynVvq9+FpIVHRCw/3XDa1OB9VFV+ +wlH/zs7rN9QMTA5dS35UGBx7pF53rkFmo98U/moOQxuRT+WBpsqO1Rs/FFxS +3f2eT92pNyLwrldjyOtl3gFcN0Tn00kFzW3jLNwcc+jjah0j08AdV5ZsndEi +Md1oTe2SzU8i2NayX+jm35ZRL/5R1++r2NajcX5CF/17wyQvTDu1Jj/23Hmt +Fk+f3MAHI+941zP0lU6XFjO06NuwsvdN2IWTNf73WOaa5W+6u/aOa3dvtIjY +poE1rJf63nGLKKyO7Kzbqjdxzuqj+/nXPPBbv6nDe/0jh/csk7gFNRz1S64z +MAsvmJ4TRz9p3zmR8+cZh3KwRGeutbGLf5GR7Vd9zHvhnYaSNfXLXoZkZDvo +MXXzPba9JCZL7zxbf23pljuBafulrJIUCh688Mwa7D6RcoJez0edW6L2I72/ +kp7C0s1OZ3SPL9tN0A+GSC3NDpthc83J4qhnk48dE+NEpU4Gh1LO82+9OjZN +yJo430PoKnNckEXmkdlWeVr0Cmxnq+aIfIicOFns2cItJ6X9OeYQ6yTPpNMx +rx6xuzFvaIX9WXG/Tfv9pB+uyNvGLDVBXIeFOGOnR88iZJ1+OtF0aqHe8q6I +dYej71tVnZyx34CeawW/dXrwIp5pbCvn3nn0TuKdp+n1iSvTuZgm6POYehCL +NPJOGHQ8WZnPHbNgng/XTFOtDMap+nXppywELDzCT00tzZ/nsjLzhPUZnfqC +nZK37HIm8JkWizNO8jjRRMc0SSideOJz0WRuwMWVrJIPBoWzLvCbr2i9H8pn +Pe8OvRiH5FIXnoK7EQ80PHXZ+oLqJG8nygndv3xyAocWx+kruqcPVmdK8HCK +KRz2uT+1LsnjrF+gigd78Yp6g6ndkbtFY0RfPGYT+eL23ON0p9hl9pTbhZdX +xszN7AvzfhauMGn35Rs8FiF3WliMlq+KSpeo3rysM3rr4+s7TfWYboo2PDgo +XqD6ouiErdXeSOY884zLX2L0ZDJuV4u8OCQTt12SQ/5Yfms4PXHPN9pMP7Zr +6ukLgYySmUfeMWyZy7o1gz58/l0tDrM5wp3rKhPfnlTMiq4ukHE4ye3HfYYp +jq/oRJfk+zrv6W75oqt5Zw3IRNokmNVvUNRh07JRj8vn8lode5C96n3cc4N8 +i5DCJp4gnefbjEOy8pVDb9vsXHM3V2qo7XGlm77Q/843rH68/v8n63+ysrIK +P6j/yf5c//8T+EH9D8QuQ9b/mAPnZhN/tf7HGQH1P8e3FeYuRqvfzEA7tbQ2 +M4gJhR/1ENKZPF+eo/zjkkc7k921ymxzOBSTry9/7PfoyoOoN5bLYkXfxd+R +Sn5TaibI4hsWad/+1ixduG2JuISGI4twN7/THJWUY55Vmmnf+iZNf3BAe1NC +c+g5l8/BBzq+CTytHTjSXF1SfODqpekD/f297u8keT4vXSI6wMX1cCjfhuVV +ib0NoNDq2mWMz/aKUJJb4b44rrJRxQBeA1IP2e5KYvc+SALknQ1Kd8dtuB8f +1dpSdtskVEPdXlgNMNzz8ovUu3fVAadTpZisbDd5TJeSBpiYBJwCKPB+rkl1 +Gfj8Luv4em1dVyPLGDNJnokryELNnBUmAPYS8obkpeVk9WeZAxr5NjTQwRUE +BUnd3sGuxtwAQa7TZHccB8kyE1dMne8xEr6wpTU0lCP7WVMJoF9eAvAcslJI +2FebdmQo/uFDsprw7bggtjWM4a6A4UNpadUvg3qSpllk8Xwbfh146tn7gkvS +W9LMH+7KiI9/lgNocaDVOw4eRFdNMzJtTyfEA9g8pTYlObSU3tSlVUQbnM2S +ggGzSo4yTeSRNBOaNtSUf26eSQhLDllC7OOklds4c7IBWiuUla+TEHTLiz18 +aD/KcvJezq6l6tLf9iZ217nAXufUzQ8P28Or1YWF1Wmz6L31CpgkpqeUJl4C +TD8bQCLagVZxs695CTAxZy4Ild9VdE35QHaKJ4kGFQWtoOOApfu7vZjZBdQc +O1tuu/YfH2C5KkBMIR4bBVlc5Hk4qBU7PEuN4aWfG1kCvBxJsrnWMT1218sQ +dRfRDzsC8l/sCBisYzhWs66D8666R4yC+pH3zy9IrHugwDvoM0Xw2ZcrAL4u +HY8pWvRF7JMAHLI8Jn0sNzc/YHF6ySutRpfqReKjffA5Ep0s/Y/vb3wzZ6R3 +3rHEyiJONzcbg8BpNMx60ZiWtqfywabkQ7ZWH0lEisz+ZPrpzblb/Ze31MTq +mbS/kbMduBy6YGPg3upE+8Znk+3T4AW1u4aBRaGa7iPDTgZJbt++9rVWzr0T +BVgWWBSsevhz9ZPtuYNHpi9wXnPCtJ2OicRRBrJ294iROU+9Tm+By63G7h5+ +N7ZHSwKOfbQZGf7S0/xyem4ni/+zGhfpOYDGGwEWjtIbORcqeyzY/8EpnT1n +MsflUiWXyDqPiqh1DzenXokkq9/LdZdZneRZsOGx1VmW+RZm9yILC71JBGh8 +9VTS0Sp+cXXRvpqUL292Ga10Vj+QuWXkaA+QeKDZ34Njyrq5fgsMApXucp5J +33pDhC5TyXxabmJIlp5Bg9VSLRahOySsP6Vc26I/dSLfS2k36X28uT1y6wym +HggSOXgIYLjyCAnjKeU539rUM28xd57kO11wccHGeJugPIbLDA5JgSSSVJ74 +xJPVahY53QbvRP56Ef03pBXomalkLn1muTVovxjdGy/zs3kZ3fandNlLOOV2 +LiUh7E7irOOjTFXVgY7ap+5opHbkUOOz0zMX7Z3Eom8EcO1Znla7qDabLKkI +KGealFUwoVVRxFV+wtM8xbGrIeekgcEEKPgnJjaRYJkS+QDAU/mSFJKTb4If +j5R5ol29jjDpNUw8S3wrm8lJNffMV3qmxjKzREiMpYYsSQflVQLWVTOzvsZ9 +T5feLPnsjQejSIwna45dQ0vjOZrC8lwkLXfT2mcz3FdxSXS/O/zFuro68bCd +Y4tAuvRuhecx/Wu29kcJLJV+qJjfw2zZZMqixhpyivGMupDw0Y7S0szU/Ii1 +dHdvhD0n0esgtXPGJJuu4+wSetq+iE6vW4yh+CijoYFpt/2Zebv1uzdwfvZy +sp+U0eD8Zdhj4TPH+vVGNaHuaU49H7Am5GbLNM1Spg8Y2nzqbX7q151lDIPa +p5+dAXCkjtRnHWcX1LCx3ZSw913SwVaHJLIcX5qk4hQ39ejS0xN4/a+wJyd6 +8In5c832rOckoWMxqB7GxKa9zadweg/9JxlBxln8gHtt4qZmqwHn6zTiHYP9 +szqTVI49CB22fMRslrtGujyMEJFyH5E/oGXKsTFzXqiQs4XNtBJWCS3duQEC +6s69H8/6GnNsEvp0Zp6VIeusD3qZ2WtWGWwLvCCykEMWxZF2K/pgO9OJZgsf +g/lVHwfux3CumLnUJ2pdbEr1uy1BzGLaRwOZUj8OFlxhF2A10TJoaH0YdTcp +2U/KPDLSat+83TZtHz92TA8JLzEyMpPEKwunsvKbNwZTV+j7BgRESazQ0bGx +0WcpOTZZYu3g0Lo1OywtLYf7Hu5LjSP9fX9c3J01HssLMyeCnF7d39jSMmnW +BAaX7PospQAxlsn8RJ5WIuu9CQqeTXXd6XuVp4v1eajY0X9mEMuUlfn2OubR +o/iF4YuPS226e3/u3TvWe1pbt2dcfSHZ2dWVz1bnIyDi8OJFcLBuqNuVq0Md +7lzvm7c83byKa8YT0lf2uw7HbMiIWku8JU3sTeCFHJGK0kc0T7bDUovDqEjH +Q2ze4mihTSy3yFUpOA/KlEvCyZL6iTv0D0hnNWcby6p4OzH+iALWK4ns0Zqa +T1NS4i5Yfft65oxTj++Jk+z8jo2Tw/taFy9ufjmv1ErEj0naoEycPlfX1XXE +1SD//sbLaPpTxx1sdeEXIpnszVOOqBYV9BAiFr7JnKFzurTdPBglSRhpMTG+ +4JXoZlJ+I/Ge7vIW8jXgLnPRsmKOhyyL0zMr39Pv0u5R4pSYcDTX6Vy+JR9f +Jr/KOyPuMBWui5VHN69T06yq1S6xt7e2XveQzabS6lnu/ZgQK7n+gidaLYmR +H09K97d7hVc8DIyqaSemvI63rcI/j2J7ugHxezfFbMs5wS1R4y4okJ4rbWIX +/6wrSWid1ulA3rRv/Y0Bta5l/UObEztfLMKxwJH+9dra1nfkFrGYxLhJfeGa +I/mioLH5a99D+yUHFafpKTktiCShf4/15dqw2G/B57hyh3ID5J98eP+tWdPW +VtfLKyvL6K5Nve5zHknB0JqG3NzQ5tk+PjNmMLNP5VR37CwLnSo71CWvojKV +08l5pG2Xru5EnpShvXo+S26UWMU5f7tXyRAteqonz/tC5pqNjfHOXzo8vq17 +YKfk1GZmbX1A/my+gprNAjGLBMUnz5nUZ/VvPNfe25P3cPHinQH2sU4WHr55 +VsNDtX6+zs4jXQEfrdwCHitUCHhYfTiY09Ntb+FsaLjzQ6qLrqJiezsDg3zu +Xs9v555Y3Hr61LnvY0ktCvGNTHIuE5UN/biAJ+1l9ZP6el3ds2eDgi5cuNtD +lB/FdG3gKCpQJ7bOmcbsr2Xu32r6XnfQt6dboF6iwc1iOOv4pk0piQ+KMjlz +WCbmODkNin9wEuh3cXFxNi5yl31qTsfr/vVxPE/lseNRx8Jo3vee5IOKx4/b +aJHbqh5Cwfscx7RM3XWAyjscDNpztqRPkBCboCj4ZWrEG5uFBQtKN3i8qm90 +KN6aHOomsG+ficmiReHsGo4dqaHomq+Vzal1DE30zCKeXJIXM7T18/Pzd05j +pHtPFqznzW2HJa8oeIubU0O2H9c8Y5ta/x6zbi9hjuM3tm4JSJl0arsW24nd ++/WEM7zCi202LhR8uJ5rWlP7cofOOmn3GTOXNTU21tc3hL8aDqkUGvzwwUQj +hiexmiE78WDfur4ipfJcd8kuzWn80weSa7/1hAobrsj8dPSoFzMXl19KanDw +k53KSnkRVjG9vXbS03m399vk2gYHBOyzuqy3wKri7pqotffleHl7mJjTGWz0 +pPU/Risol4mxxs3lV1W2juPiKrNPt5Tq7H/VkugmzVhbtcf2bCf/k5z5AQUL +Nlm7dju1cjed5azgj96e6z9L9ZDYAeLTUHymwZk7gfRCFjaf16zkmDaDv60x +a0++oeXEtiUzBTtaXYKOXgjIynzP79Gzd+/WrY4X326oYMsjI83lhif8AYfs +ld2GISpmYhZiW/nIQsHiaxP3XPtZPLkxyuvcBCbnpGXrpmoIpW8IK1u64BXb +5WCLC3lrWBtz+oTs3UZyTp471yW55ciOcwyJGnsVti1ffSdVaq9WTHv5nYaG +K3zhR4+Wlt6dH7Nzop558qGmvKJgXd0AwVjCI39VY1/+Zds9rjZtX8weVsi9 +YZ7QPdXNzm73p8O19qL8s2xX0Uk63jg7UBFx+3YEwHJXqMrBT+V3Vm1M2F/e +MzJUR2idXZBx3XUS3V1upcwVbVeOLd0qoLsq8pmxbXv7xvhIznsBL/e5LdZt +en/hjJb0681hPIxM0WF9zsbR2W8/Qqxp/kR4t3a8JG+fu5nY80KxBWFuAT58 +1y5JEF8Y/emszTozZDPNpa5zcMY9Tunxj0u/vUTinPy6L0pLvVblLtp7736w +k+Lqg9McvvZC/jJv7v31sTtfXFGUklpKLmmRdcSXE5enMlvUsvNUvHei62fP +b0XdKXROdEoMAnQm6eFqHVaxbjfe7PdIHnobp6srK1vrtky3qeWJW2rflzeK +VwXSeW4W0mlefHumVCl8blt2mdWVK/F75wrLXQ1VCzLuNDwTUXZ/41LdxzZv +BEe0dFdvCr5iqFtetXGzsW7vs5kXLjAw2Ai9Ev/YU3XqKbuMa+0Z5rqUFB5v +PnYhphUTGYU1n3WEWd3rCs/dpvwh56DYeqEVjAlhdN0cI1OfJD/9tvDsfoU5 +mavOcyR2fJovKSI8X9zvhLDwp7amxrnL4vcdXxqienttiBUO26dv6HXevIeb +3+5LN2Q7E6d4aHG+nFPD/Fhr9ms2sdrp3nHmChbKSgwRE/M80zNYBxPZa/21 +7c3uZn9zSPJjPRYYEjJxuq+v0a2vzsLhMbIPKjwY6jgDs11WBgcv1vH1Hf52 +LtD32HF19Vq3q4f1htv34QX5cAd4kLu13NeTeLJnng0MdOxDBdJOtcPlGzjC +hc7s1gJ4cAi9cputdI+zkZeN8SJD6/urh2O6mTJuHPOu1bbvFCqco5RRuUjK +P++NsoyMxma1jp6E1RvS9vFNnnkrODiDgztud4X/rJT1Wz/MfGTjTEwsstJ1 +uB4RdklRal7VuoOCcY3x2/hqelWHgu3vPuX68A3haED9kzLBO2lirpMyc9js +Ye/3b+fb5jHl7sny8uLfcdp/f0nRtvquImMtTpcT+dkueg8379BepGh/2XZh +VpYjKpu+pXOtkZdnQr6veoz0WzyitIfrt75jk2cutHndGbVlNnvdw8kHk5Zd +giTRoG3yhUoHISvd2aYsHYrBz+nM2M+4zxNCTb7cFTVFTulPR3I2cs2cGaPk +/qEwCOdu1YkZA/aHPpy28PJadlFy/SNLv6jW64uPT5mlUl6c3ii21iruntC8 +ec+6o2VqXIuL03PyLl4cBDiysxvr7tkTVLWzg26hklbgFH4lu7p0z/LV+0jc +v8htsc+9m0xK9+83iSike32JnYWB2YPrDHv69sHEmLOytRUXlLdZenNvWJ3N +ZrvXeBkg2fUJ+VJN4lPBkSx1jRmZsoynNk9ZGL3j/kXlzJoQzUIr2/f2m9fO +CxQx1t9k7nikMUdz+aN6usE6Yod875QpKUJcXLHWZbeWX114MyK6Tlj4NYMC +n2hqjGy8uarqMb7YoAU1WV75NnZn1qWkDfnfuPTVeYQeNRnUHNy6b8tawLH0 +/Q7nXSxFlI4JnWccDp9cVeSj5njJ9/a8c9Jpb1o+1m1OZS6cmtPZIR49adcu +/0Pmm+ahOELAKIqp3E7Nv5qTPkuW8YQAj+TTkdzSTjcZI7HN35j5pD2X3Ls6 +vJjpJjtPZ1hYreBVi11VxI5P6p1PLReJ5TdlKK4mfv7WxU8QP6r/Sllv/5cL +nX9c/1VYqCg7vv4rv/Dn/u9/CnQEMyEkxIGPjMRHeoI4RMCvf9LOxegIYjMD +ga/DfSxEJAtBHGOE67RzKyaCkJoMMwznQkTkXIK4OJW6H5/j+zSUqPuFCCv8 +7Ad9ghAjaK+ZapHjM9IIof89Cj3IH8LDg3aA/+Ar/E96ejr+BpE/BEK0A/wH +X9Fe+7fD/5EnnXDGQrj72rEQ7F7y8gHkaQBCg3Ysg/LySkqd5H2+gwHItwdf +9sLnzPgEgM/l5eF8IMDX15c8h68JZvLqoC55XV6pE+73Rd6j5/IB+H58XVd3 +kHauCff7BuBQ02v0fJB2XR96gXPc/yC+DsD3aNL6p53r95D3+/oGeNO+6KH6 +Hxw9x+ND9740mnSBvlH6e+E6jX7k6zvo2wt9wDmtqo8G9XH/FL94BMyCLsiH +1j8NAwTtfiyAAHyHI4iL6h+Nypfqn7yX+KX/AfzDQrvfFyQ4MBhg5zGm/4FB +8jLc70s+j8jL3/sfoF0elT9+nnb5l/5plwnmw6OgXSaGBdPd6xg8NPGp4JjG +gBsdTZd+t9GN3jf2Oc3fae64IQ+CDjcG3JhxY8dNEIGec4zqOqXnHr+n5v8D +PbcDVcb32nkcZ4aZcLRzRF5Yw90DUIC8kibhjm+Sx6J0Dxg0AUV1R70moILu +Ab36oHnupIYE4HPQJRMluB95m8D9Afq6JuTz3rrQH5553L87OSceBClrR4Jw +E8R8woQzjLY/AnUP82hjH+8PRieTccwzdKMNw81yCXH9oCZx67AGEeWsTsS6 +qRJeu/SIU3sWE+f3aRNX92sRyZ4qxH0PA+KK5zYi4bId8SxgGVF8Yw8hloYI +yUxEyD5DhGY2IhSfI0KtCBHmLxCxuBwRy94iYkUtIg7gtqYBERubEbG9DhHb +2hBx7do1IikpiSjLiiaOdiEirhMROTk5xPPnz4mioiKipKSEqKioIN6+fUu8 +e/eO6Hj/mijrRkRdXR3x4cMHoqWlhfj8+TPR2/GJaPyCiK6uLqKvr4/48uUL +MTIy8idC+4mf+P8bP/41vtEFYOxXYmLwWwvi5Gc5Pl7uaVOn8kh+vyoqKi0l +JS4uJSYiIiqOZvFOn849TVKSi+pBXApfBojDXWjmDLhBUpJj9LqUvJi4tAh0 +LyaKD4gfbuDmnsr5/bqIqLSomLgYfh7oEsA3zEG/ECklL01BYiILMxIQoPUw +bSonB5fkaP/S0lIi0mgyPSsLvo5v4B29gQfR+scQk0YT6elZaddJGqdN5eBA +Y/pHTIz09LLCY27gJK+T/UuLwnVG+smyo6TJ8cEI+DoSEZXHfYhLIzbogJWF +mXkCHR3dJDkYAa7TIhncP9uvbkAgBrguJi4vJSUtLy7P/qsb8PXpfKP9i0uJ +4+sSU9iYRm+A6zN4Z8kR3/uXpwVYJGbDDZT8oH9RMfyDu5CWJ5kgR6Dkj/tH +5BxKy0vjPtgkJGgkfL8+itExpkhIkCRM+n5dDIbAMy8tLi8tJiXBTjIxWYKg +ruNJx53jfuSRPOZjtDeC+HX/8mOGkZYSF/3lOu4ffyEGfcgDifLSWBHHXIf+ +sQJIYynKy4uJYl0WFBQTG9//KMQQ9I7J+FX/Y6+LiWB1lSZ+uQ7ykZYevUlM +XkQI6xpB/Lh/eVGSFGLsdTFx8pI0cCUmJPXry6Pzi/VHimRbaNzlsf3Ly0uJ +io+7TEj/GvLjLiOU7j7I7qFZh+Ox9H8nnnP/QfthLOdBaI6L50bjFLoxBI6N +U3YsJW47ahC+1nrE5f2LicdH9YjoK27Eojwce5QgQr8SEWsbaLGFIz5GRUUR +sbGxREpKClGRfpu4imOPaBxjZGdnE/n5+WSMUVNTQzQ11BLv378n2traiO6u +DjKW6O/v/xlH/MRP/C8ALFRTRj9PmTKFm3Yk/53MC8sxfOKaMmXyFG7+qWws +LJwC+JyHj5d3Bq/ARDbWmcxwzj19xgx870S2qfhfAYKdh59PgINRYCK+AS9m +nOzcvHwCTIx8nKNfcPHw8wvQ00/gwzfPnMTCzMWNR2Kip2dkoKObMJOVlZuH +X4Cfg4meEb4QYJvKja/zQM8CHAx0uH8ufMKPz5imMzIw4PHheV5MADzCgc/x ++AI8vDOmwxMzMP14fH7ycW4Bkj92DC4Mbm7ylHDHOZ3a2HyQjvgx6Ihf54P4 +OUKQlg9C9c+CoNWNAB5z//GUQGUJsskJYxoT8eeZ6r+F3+P+jwD0TsSNW1BQ +cDY+QhPBTZSVlRXCBfjDbFhSxEzcpuE2maBJ8N/kiWG030l/8X6QKyyPfLgJ +hYaGrmtoaEju6Oj4gPPe5tbW1ob29vb3+Fjb29vb0dnZ2VRdXR2Tm5t7EgeQ +EmpqatKjPPGO9sNK0OTwd+QHcw0L81QcpM/BR5DVlD9+5Dt4N27cqLkQA3+e +WVlZGYBzdgR/NKW5uRnh9Re9evUKFRYWIvhbJ+Xl5Qiuw2+T4Hz/HfzREsxr +fWlpaUhGRoa7jo4OhGUwT2Dy03HjHKUF5pVttMHnyaPXeHCbBffa2trKDw4O +fsWfJf8G/TOwvF/Onj1bAfpYtGiRKNCH6SLpf/78OXry5AnC9KHExESSbhxH +oA8fPqDi4mJUUlJC3gfPwC/G4O+b8DOhMTExRxISEo5s2bJFz8vLy8TOzk7X +39/fFJs70AZ5lsT06dPl/fz8NsjJyYHseHV1dcWg379Lf09PD8Lxz9k5c+Yo +Yhn6f/r0CaWnp3+X88uXL9GbN29IOvH8kLTD57q6OlRVVUWeA09Ua2pqIo9Y +53q7uroGsd4N4T4/fv36FcFfj6moqHjS2NhYi8f6AvdhPs9he1PENPjDs3+X +/r6+PhjrewP6qQY8UA3mhGpAP8UH9Zlq43mhGqb5e8Nz/r2N/R7aP6E/Kyvr +FJ5HYawT3sBDZmYmST/ox9u3b8k5qK+vJ8+BRrAJbMPksaysjGxgGzAfcIR5 +A9uBZwoKCkj6YQ6x/SOYB9pf6PkF+HwIfz8M17ENy/0d+nEcjISEhEj9V1JS +EgU9hgb0v3jxAiUnJyM85ygpKYm0YZA/zAeOr8kGtOfl5ZG28vr1a/Iz8AA+ +APQN7ATmCGiL/4zQjrcIaRYhpJCPM6IchCQyEJJKR2jlc4Tuvkeor7+/DNsK +/9+hPy0t7ayIiIgijvv9sb+E+SB5AHpB5iBX4AfmAmiHzzD3ODcgG3wGmYO8 +gV7QA+AF6Ab5wxyHtyGk+wohrVKEVF8itKgQ52N5mIdshOZjHkRTERJOQsi/ +GqHh4eFrf4d++CvXVAP6qUbNBdX+iZ2AHYC+rKtBaOlrhBZXYPkDD3gOFhYg +JId52FuJUP8wQjtLEJJJI1Wq86/SPzAwALp8CqflwlgXvIEHPA+/4QVoAT0C +Gn/EB8gdZA5zBHoD+g9+F+d3JEEmmP5lVTQedMoR0sC0qmAeFLHe2L2m0W9d +hpBIym/LW39EP14zEOX/Qf/hb2ZBGz8nlJ6DXGEuQK9ANyg+wMZBz0DvwS6o +I9gFYFU9QsaYB0Os/0sqaTyoFyOk/ILGgwy2BclMhMSe/n36sS8+O3fuXEU8 +D/5gZ+BbfsQH6Prv6RfIH67DukD+3TDsZ8ZibRO2UeDhHUIGmAc9zEN0O/or +6MLtyu/Rj3NwhNeZXzXggWoUHz+akx/xMTQ0hEqeBKObroboir0murhPiyRi +wweE1jQitKIOoeXAw5tRe8Y6o0bZcz7NnsEniabR7HlBCs2mscct/D368Tyf +UlBQEMb+3BvoBz0ZzwfoPej1eD4oXkDXQY9qCx+j24fV0I2D6ijkgAbJA2BT +C0LrR3kwrUXICNOk/2aMPQMPo/YsBT4J+9S52CfNxjwIJtJ8K4bnj+gXFhb+ +rv94jYd1/jfzAfYL6wE1F2APcE7xAPRjv4fSL1miKCc1dOuwOgrHPARjHgBb +sf80xzyYYTpWN9B4oOwZeKDsGXySbC6WexZC4sADlr/QE2z/eWQ3RT+iH/t7 +Uv+xrflDPAQ2R/FB8QI8wHrwe7oF9IOfjPPURg9cVNFdzMNNzMN1Bxr9BzoQ +smjFPHxEaN17mj2DTzKs+sWegQfKnoEHyp7BJ4klk90MjKcf7AzWF/hlaqoB +D1Qbz8ePbITiBZDgroweuaqgB86q6I4j5uGQOurr/IQqv9J42IJ52NiMeRhj +z4aj9qxdRvNJSi9o6zPlk+ZhHuYk/9AvkfTj+P6UoqKiMI5RvIF+8ItwBJ0B +HiDmoXiB72CtpeIyuAbrLcQMgCQPZRTvpoxiMA/3MQ+RmIeUoH2ot6PlLzmb +FsynLZ4TJcqeR2OMeWk/ph/8BaX/KioqojAXVAN7BbqBNqCd4gV8P/h7yGvA +b8JaBWsbIO2oEnqCeYhzU0HRrqroHuZhvD1fwD7prK02OrVHB/laL0ZeuxYj +d0tddPLgBlRTWUzyMDbGkBqNMX6PfuzvSf3H9PhDPAF0Af1AE9AN9gB0U3MC +Pn5sfAzrL/AI+p/lq4FSMQ+JmIfHRzAP2BbAnoGH8FEegkZ5OAM87NZBx60w +Dzt1kZulHskDAHySypgYQzHnx/oPPgPWMIgjqAY8jG1j5+SP7OTbt2+oOGQr +yvBahFI8MQ/YFmIxDw9H7Rl80vWDGih4vwa6bKeJzu/VQgE22ugk5uEY5uEo +5uEI5gEwPsbYXPZj/wP0Y10g9R/rtTfwAvrwI15+jw+KF3j2Y0ksyvRehNIx +D8mYB9KeMQ/gkyh7DsM+6dp+TXTJTgudwzz4Yx5OYB58sB557qD93in4JO0x +MUZs64/9P9BP6b+qqqoo0EC1fzIn374No/qMKyjn1GL01EsJJY/a86Mx9hwx +ysPVUR4CsR7579FGftY0HgBkjIHXZyPcgpvJ9beA+C1mwJzj9fcsznsU8Tz4 +w3oA8h/Lxx/xMp4POIJNjc+xfoTK7AffYwyw59Oj9jwOfxj/AP0wHjTwpVQD +Pqj2P50TAPikx25/wZ4xDz/wM7+HGSAn7A9J/cfrqzfwAT4ReAA/AzEZxDew +Pr179470OxAL/YgXoBvWBvBVEAtBPAr5AADs+eWtg2j4K843bhz6bs9UjBE0 +as9nsC38XfrnzJnzXf+puQC5QzwPDfJ0iPsh3gF6IL8HeoEHWAtgnaD4gBwG +eAB/CnoIayGMkX1SF5XeBvr70fOIQ7/EGIdoMQbYM/ikK47Lgfy/nH9B39jf +k/qPafEHe6ZiMSoHhiPEDMAD6APQDrT+SLeAP7gf7oW4DuYC5AE2Tdoznoex +9nxnnD0XJoTC2Ff/Kv3ALPAADWyBakA/1ag5GW8jf8VOQKfgCH2Cb30RvA2l ++Gjh9ZkWY8D6HHVkMUo4twtVFcSj/r6+stOnT//l+gPQj+f61MKFC4Xr6+u9 +gQ+QP4wHdQXQffL/d4XlDvUFoO1HvMC9sA6D3sMaDbYC90MeCd9BjAR9AC8/ +AGb/Sw3M19+t/8DDlP6rqamJUvMBcgf7A/2laqGwxgLdcI2q7VB8AL1AP1Xz +BVuBI9gD2AjYw3h7h/7G5h5ga8TfrL+N1X+ck/iPzgcpFPA5IEOQHzn/WKeB +3h/pF5X3wnyBrYDeA51wBB0C3sbqFsgD7k9JSQkUERFZ+Pjx4wCY939CP6Xz +lB1QbSzGfv937YSyDeoIegQ5A8gF/DHMHVXfwDTNJ/76/sWMUX0n9R/L0Bto +onIpmF9qDYL6JegwfAcypeI1kDXInFoHwQ4ofwWxKegPxNpgB/A8zCfIHXww +pn0kIiLCm5eXV+vixYvh2dnZHwnang/zX6Ufxh0b/4AcKdmC3QIN4BNBNjA2 +8AbyAtsAvuAIMqaeoeqJ8AzIFOzn0aNH6MGDBygyMhI9fPiQ1B3oLzU19aOC +gsImBwcHV0x7Jv7uOEHb9/ir+zdk/EbFP9geSf8P9kbZL8w3yAvkDXIGHQA/ +AUf4HmwC9JvSK7AD6l7gD/iHOtZYfYTP0C/MEcgE1nPML/x/ScBvMv1F2r/T +P1ZXx+rwWN0eq/N/x07Az4AvAoD+QE4EDWgHvkJDQ6HGGEZPT/93af9OPxX/ +Y3l7Aw+UX/wRH3/Ey3g+4DrMDRVDwL4O6D3oEsgc6z6CP9LyD+T+K/rH6j/o +xfg19p/MCTS4H3QJdB3OwS8D7dT+yL1794L/B7ST9I/Nf/Ha40/lX8AHVe8H +/wG+DtajvzIn0IBvqjafk5NDnoPOUPsH2AfcZmBg+J/Q/p3+sevi2BhmbGzz +V+cEGtwPekPFfOA7gReKdhyf3vqH+v4b+oEWbF+k/uP12xt4oPLf3+OFqnlS ++3cwN1QdjqoHwZyBL4K9BNiDAl6AdjzGP/Ezf0j/2PoPlUv90ZxAfA/xD5zD +ugYNdAuOQCf4XZAB2CvoO9APdoD1MeJfpJ2kf2z9E/sJf5h3qP8AD7B2gjzB +/4EewHoEMob1CeoNIHuYB6q+C/MA5+DzYQ0BPxYXF0fmQJjnf5t2kn4q1/o9 +Pf+Rvo/VeyrWgbkA3kHOwCPoOtajERwjfMRzBesq379MO2AqQXsH4f9mgzHg +vYff/W2vvwPkgReXpwQxTDCjEU2CqCMIzU7aEX/6l48Mo0e60SPxLx3pxvX/ +f4t+99Ejoh3pRo8Mo0fm0SP76FFw9Kg5enQfPSLakQ6Ov/69HSGSJw8O4u8A +3u+hfhOIifiDWBHPtCdu+bj1j8sX4Rx2VMbXA38PMBbv7NmzZczNzQ137Nix +Asf7utjnaxO0184g5oYX2b7rKfT9bhChQw0I6b+i7bFBLRj2FOSyEDIvQuhV +N0nLH9EAvPIzMTEt8vT0tMc2PQj+DMecfdjftmC/1Ib90luce4UfOnRoN46B +dfH9srgJ43ijY1cTbZ8MaqGwz6c6Wsst70HoZRdCmtnk+J//YPxZ2IffwGMO +jt1Pp941oernozH/CG492OeWYb+ZBB3DninsN8I+F+yvQE0carEVvQgVd/+l +vV5B8NNHjx7dev78+bVAA8ROkD/A+gh+HdYi8NUQy0KcAtfgM2Djx1/2C2GP +B/Y7oaYN+ztQk4c9tj8bH3KAgwcP7nVxcdlN5feQA8G4EEeDTKicB+KmsYD9 +sg3NtP0+2Ct73Pmj0sWv0DFOH8jxx777MP6dB5AJrF/t79+i215ryTqm/2gN +cFs7Qls+0fZNVzXQ9n2p9wfG6iPsD8E+oxo+VvxaJwVhTfH29t566dKltWPf +w4D5h/dMgBZYf5KDbMkaGNSDoSZPjQ9t8yfavifst5H6+Jq21wZ7PKCPsEcF +e52wT7i+gHw0jxof1vHDhw/vPXLkyO6x+91UPAtHiK0fuC0ma4lQz4U64tjx +Ye8V9o/XjdNHrdE9Gtjrgz0m0EeJVJp/oMaH+GfsXun4/XegBRA9uj9x4xCt +Htvb8Ql5dv2aBtDHteP0UXN0z1R+VB/H7dOR4x87dmxrUFDQ2rF0wNig53AE +wH4b1FRhfwFqwvGX7P50z/DTV4T2Y1rUS2h7bWATsN85dnyIK5ycnPa6u7vv +Hrv3StWzQRYAqK/DXtP90f0+2GeCeijoI+wxwd6G1+j+kut2Wrt41JqkgdTH +4l/2vsePP34vePweMMx/xnFNcr8L9oqgpgm1cUofoS4O+yuwN0HucY2Of8Ry +CTnW0jH6qF746/mHmMzPz2/rtWvX1lI1TIjPgW+gBWQAx9Ib1uS+IexXQV01 +arS2HTq6vwA2AfsjsFfosUP3uwwAY3007N2O1X+wLWdn573Y/++m9gcgL4Dc +DmQCvgdk0fvxDXp+zpTcJ4D6dPRofT1ijE3APtPJ0X0y91EaAKQ+4nHNcase ++LX9j83Pxu+zjN27Azn92Z5RWeZDco8F9uq8MQ1uo3uNY/Ab/wfjnzx5cmtI +SMhaoAH8PuQeVF5NvTdI1aLAH8E1AOzfPnD+xSZ+pI9jdO2H/h9ibFdX171e +Xl67gUeqLg1+F9Y+8P+gCyAP0EWq5kfZxOeGctTe8ArbxDh9tNH+vlf2R+NT +dcHx9f7xdf7xcwNzkXPWFHU2laOOxle/6KPDL/p41W09DP9H678g9HP69Omt +YWFha8l3i/BaC3kVyBp0kaqjgVwoXwnzA7Lp+fgWFV3fg554aZPvAlD6GO60 +BD26YIdam6oR+uP4RxBucHNz2+vj47Mb5gJkDzEIjAmyp3IfkDkcQf7Uu40g +j/FrMmC0NluK+fmz+E9w7DNja89UfeT3as3j54Zax6l3K3Hf8N4z45+ND2P6 ++/tvvXHjxlrSZ4++uwk6D3MB8gB/QO2RUDpA1ZApfcDrxLCNjc0urMsHcIwE +v/QFOf+f5VTk+HjtJeUPnyl9p+oXlM5DPAB0UXpIvSNCHfFa9XXBggUu27Zt +C8X5eTtBSwX+DIJja/zja22/NzcwB+AX4BmgBWQBcgKfCXQ+ffoU/lTFX9mj +IO3/1KlTW69fv752bK3pR7RQn6n9IdAHiBEhTgJ/Ae8lPnr06DpByxX+Ckj/ +R/kf6A9q8iB7mAPg6Ud0wDlV44V4Gd7hB5vBPFz7G2N/H398DWt8TWKsTOAI ++gZzDrIGvkFny8rKbv3NscnxYZwTJ06Q/v9HdFBxMPVeFdR+IC6EmhO1p/gP +xybHh3Go9Rd0CcagYnDwedS+JPBJ7XtAXpKQkEC9J/hPx/7O/1+pgYKfoexw +dI1sLygo8CNo9ZN/CvhdE45/2MC+/sy//S6GBT006+h+9bu30P7sd3bH/u7u ++GfH//2Vv/F7u0IkTVo/4CYqKkrw93gIDg5eHBoa+jg8PLw/IiLi882bNwNv +3br1K79z7969DtzHvrt375Lf43sYsa83wOtt2v3790m7pdYwmGds06/GPg/7 +aRkZGVBnHcJ91EVGRvbCO+Ogg6CvD3AOsqqK9h6UJo6vrzaQXSVQz8O9oNMQ +w1HxDJVXgj/Z0kLLmSA+LcVhjULur+JjIj4+nhyL2uun9tgoX7S1nZYDJ3T/ +Zhnuwy0efBPYEdBK/X5HcUoEOruPFhtuH82dIH+E/BVyBchVZHCuFITpgv+T +D+TkQDvoP4x7x82AjHF6cA52tZfWB+TikHtB7gd5H+SdSjjvhBo1FSuA3wJA +DgPxYuwFe7KPsWgdotV0oI4AORv4dqgTwzyBbwIkH9Mj4y2I9yDWg1gTYl3I +N+5d8yP7gJxDH9MBawL4dLBfKqaoy76O4j3UyXwSYneI2yFvgNzpyI6l5Bir +ahGKxHKBHJD6PSzQE5AltR6MRXFGNBn3H9n+PeYGZuOgZgLjA+3wDNBBraWA +GDcN9KmujJQn5FA+1uT4vdT8g+5Rvh58P5UbQX/AT01mOHp0dCn5/mew4zL0 +POk2PB9HPZ+WlkbKn3ofBz5TMQasb2Npgc+wlo/Vf/Dz1PxT7yRRY0MDmiBP +gL5hbcBrv/vY58FPgw5CP6BLsFcEPMG8gmzgWZAxzFN2dvavngW4Mf/P/o7R +T/zET/zET/zET/zET/zET/zET/zE/078H3R54A0AoAAA +==== --- python2.7-2.7.6.orig/debian/idle.desktop.in +++ python2.7-2.7.6/debian/idle.desktop.in @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=IDLE (using Python-@VER@) +Comment=Integrated Development Environment for Python (using Python-@VER@) +Exec=/usr/bin/idle-@PVER@ +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=false +Type=Application +Categories=Application;Development; +StartupNotify=true --- python2.7-2.7.6.orig/debian/imghdrdata.tgz.uue +++ python2.7-2.7.6/debian/imghdrdata.tgz.uue @@ -0,0 +1,121 @@ +begin-base64 664 imghdrdata.tgz +H4sIAEAwDVMAA+xbCVxTV7o/l7BTR0CtC9iGilZ9IkkgYZEAIQmELTJUq63O +K0EDhEVQggURZZVFqUUp1K1PZATB4laLVRRZXDpKlQoUl6mO2Kot8uoynYz2 +5Z33nXsDRkDt/MbSeR0+8r/JOef7vnvOufd+/7NcVHGRUYuXLVaoFY7olxIO +iIsLn3xzXfgc/e9eQVyeE8eJI3By5nIRh8sV8FwQm/+L1UhPkhLVimVsNloc +HxP/LL3nlf8/FdXj65+Qoo6KXzIzMVL1gs9BLrBA4Py06+8k4Lv0u/5OAgFc +f84Lrseg8m9+/anLFIVYyBL+DHVZ+Fet0LAMsZDLbjgOIAdkAQ4CHiBk5ARI +AtQhZGwAkAHeB1xCyGQsANImKaDLAkwGvAUoADQC4B4y8gZkA1rAZjRgIeCP +gNtgZw+YC1gDusYAHiACUAr4EmxGAeYAPgRcA5upgATAZwAN2HEB4YCNoG8G +8AIkAsC/4XWweR0QBfgYcB9sPABQF2Ooiwmcz8QTAI+zyXZoPNQfjQBYAEx0 +v1/SfY8EWAGsAaN1GKkr6wWrX9pST5dgVL/0i7YfqYOlDtb96m+pS/fmkfaY +6zDSki63JLdBvulEvo+f1PVVU3JFUe69R1qMHzUY0YnWtgutLadLmYSXm+MU +2/HWdCI/qEWD8cXUWda0VYbWCANotatXLra34rNMQi5x50zBNnQiQ2OEszXe +tmaUEUQfQ2SCGZ0b1650trW2MIn5xGKyLSSyDcxGWZvgLBF/BvUKZQGFLJxx +26g745QB0Sy4dePa6ZNN9XV1W5h0+Hy50Hm63bhx1pDONrXz4IN+tVFVRgol +otgo21vojswx1UQh9F5SYgLqvkWf+HxLC7WZ5JXv2IpiwYnYzdHe1payhrzs +eA0OBJsVlDPKEYuEtj+aYeoBUU5LUfNu9HmgGknenl1lgfGxinnBYreZ9rbU +BMjL6cR4wSdm5KwilOsr8Rag+1oTTGmJfkZaciS6/t1Nxgl1luQdqKkoQkui +wYmP60x7ygbycqGjq+UVGjDTUH5oTYCf2EtgY4gyu7QsDOVrcjNWLldxDVF2 +86XONuo8yTp8YPfOjVLIkopcHahJFHk282oXBsn8RDEasPJF64L9fX08Z7kI ++Dx0h/bz3tqc9NSkhGhVVBg6d/krqo3k1R/aV12+taR4Qy6S+rhQDpBnChex +dnYe2AhRbkiQTCoSurME2TyEmXblrs/PXp2ijmepssPQ1ctUB8lrPvrp3l1l +W1jF2bkoUEQJIM8cZ9eKwaaHskd5obMDZRJvoRtLkIWwlnoI5XlFhXlZacmJ +cSxVFur6mvaTd6qx7mBNxfZNrOIsNDeA8oS8jGPmOEuGNVQmZY7WInmQTCx0 +E7gKBHAPrUXrC3LS1LERsSoVnTxxvLamrOT90uJiSOahVdvLyiurq1k4UzaO +uf11vcLcjLoOYRKH9leXbyspphMmOFM0hjEIwlKRp7vOoACTlusMjuK9u3Zs +6TOYasEYyAOgpR4ujE7hmqxVyUujmETDkYM1lR+V0InMvT0s6OgNFizWPxfo +B5WB47+EhLgXfI7njP+4zlz+8PjvV5IQgTlXwOYKzHl8vrl+gbywIWDNEVnW +QcmqGu/kSo+lH7lElTzDUVDBUYyxdPVeUcouT/UO9/gtAlXxM/T9cw75pu/3 +Sa32TCqflbDNJbpkUH35+hNBBcdlObXitBqhuswttkQQ8b5rbCkoD9QPLTo1 +u7AxMK+OVDsNql0hTNzuFreJUWb0cddc7dcBDzs8SePXNwflH5Vlf8pUG/wz +1WY+vLBcon81EF8WaTsE8Dt4bT1d7X291d7KVJsftYFRvnNOii/74K9ccJsD +JANyD/tlHBCv3O21fKdAtdGGK9WvbVezVHtJhDtdQRmfnwQ5vhkHmGoLIosg +ef/6Eu130fimAt+Yh68F4ys+tPJMfN5ee9YGFMRpe5hq2/ICf7wRj7tj8a0+ +ZTHudGOUcYvtg8YJoO+dVC5M3OGesJW0iyiH4xvz8TV5r7Ijowyfps3W/fq2 +T/n2aWH3Sefupund9XbddePgc2pLf2Wir/MswZ3uuI2DWyeD22fcD9qrtPJF +d9wOylPgXmLa+DS51+r1qM1Ne8GRKLfYPjo9vqF0kGoMy7NlkPi/JPIFn+N5 +8d/FxXk4/v9Kkh8i9xthPoGE/hH+Mkko0s0jyBwATXUY+QZ8sRfJQoMRWjEF +oXSYRD2CrHSYxCXB9fk+DCF3mKSNTdh65PcwyaJOhgTNIVGOoY9BWWPQkM4U +QQDvC85MRGUCLwRYREdXOOoHUiaEIjpy6sdMCB0QG5moCKGPiXtQOjCs9Ytm +g4YyREcn/WRf8Hla2OnjzUFpcSD3AaMxzKVPW0BVfQwFHcUwEXAQEBBQTx/R +6LMMIYjzk56gDIYCGGpg4nyLLVDA4+APYV8/SvdG4A3+CKZP6E11qPwNtLeH +DECnisboxsmyccc0mea14h57zew8Icwn/GI0vhoyOdF0LvikKV4TuMKZTLyq +q0BS2GQCN+MVmPEZUTBdhMniRB+YZ/6dZ7kUzkCFB/pJ3mbV7SRX6Ed/iWjO +uLZFYcjAt2LfXdOIl98UGE/NW1fwXn7h2sjIHDN7+ymTK/94KjEhM2Xhnz2O +rvwfA9W9e5k+7PqEFb7zI95cLvcIYc+TzFln53ic7V7B+d3nY0unTi8pDp/q +PzU4YGZgYenLpUUOe3cVL9pVvafqg3kho+d0hbxZtfvjecqQsy2hna3t0VGx +0XtiVB1vhrfmT2vviImJj/3+dqyq58KtMA7njiC6+7ue7tt34nu+5wkUHL7T +IXTfoebjuNi4Htc7421tt21N/WlK0Fbnw2ubm06O6VpxyOyNCvnaC8s1CX/9 +q4FF8k9/l3fffzAyYU3KOefW12TTXO3bR39ujLzDfVZ/7rDlW+iAyWrpfDXE +Y6X7omVK+EI8GCA7cLgOPMEcHsed7+bu5PIfHJ47h/PTZpN3nzCIi1+sikgZ +aMDhMAaNP6ypIDenv1Qu2eMTlkl+DxL/w4d4/M/h8LkD4r+z83D8HwoJcdaN +/39afe/4o2sdq2v2L7i3U/FO43xqH/zdNbn7Kvx54eFF4d+mDHz+w+MSXvA5 +nvP883hc3sDnnz/8/A+F+AQX6PZ9CgAr0eNlZAqx6aXpvn2hJwT3fuiEj19o +YnrTj1PDPntlDDunm/J2chqVHhExxTsiwnj7pk1mHuadLPuF63n6HgZ1+6SY +AiYCyEawD8APQEZ+roBXdeVPFa/We0FubY9aHC9oNVNaMbZtwXj86UcXrUsb +UqF4FmJWyp8q8qtajeQKxu4XMea0Y0x8ELE5q9VAsTeAzGfNAEaIdBeix0sk +TVbsreffwFh+DWPaRyf4aMN4sq4eUC7StWsG4BXE7D6Q9tgBPEhZ+C2Me30I +T9+udj7ZXTW9qbvKrr67alwdA+stp1J0vtjlSd7xOxKFmq0J7sR/YGw3xvo+ +xFAPN6iHI9TD/jxTDwLrzU0rQN95T5q4c1eKCJephTiQZ7sg/saPnxAfCvAx +D3wE6/mYqedjQuODJlKHAxm+mpo0Ca5I9sZFkYJq0oVLrt+viP5Oq1HcfOzD +B3y46vnQ9aff4dwAfCDDD+9eKcY7l3vhjSpBrZRrsxDKggAy3fUXSZu7YkSX +tBriwwF8TDpP96dv/dpgfCjHH+9L98XVqT64PMkTb02YhUuiXXCxSoA3RPE1 +uWG8WtCdLT13J8/nMsYuXzE+IE/YvD4EH80Pwp9my/De1VLc2xdb4t1p+17o +fIgDr2IsAh+CDm0PpO1PFYUeayycjevyAvHBLBnu7YvtiUK8Kc7tCR+kPXO7 +MA74Wqvx7HhIRmL04tuJ9fJVxwuCttfmyMpq0sTlcP7Kkli36vcjBNWlsa5P +2APGPev+JX2xX68vtun1he6eGfMs+6MFQfT93tsXO9SefX0BxVN19+xTpaFQ +vvfImoAeui9WSXAl9MVHSz00JVEuG3S2v8SC9rD8QzKQ/5cpEl/wOZ7H/xzn +/u//OAn4TsP8PxTyVkX0B+gx6bN1vPzUJ3OvvLChJ2DNESzLOoglq2qwd3Kl +xmPpRxtcokp+ziONmQURekkEi1J2YU/1DuwevwULVMXPDSnE3j/nEPZN3499 +UquxZ1I5npWwDbtElxD7p4W0VfL1J7YHFRwvk+XUlovTaiqF6rJqt9iSakHE ++9g1tpTYEgwWUo+FFp3CswsbcWBeHdPmNNLmCixM3I7JGo3Ottce4665Gu3X +AZkPOzxJSMch65txUP5RLMv+tK/NZDFH1+Ze1PLCcsW0/dVAjC+LerQdAnuS +Dl5br2vzPr02b+1ts4YftYHYzgbdPLL9QJaFyLoQbnMQEvuA3MPYL+MAFq/c +jb2W76wVqDYutOFKn6BUQExXs1RDtiPIChLZkMDnJ/lCvsYXbHVtrhZEFpFl +sIr715doyM4EWWciC01kpYksNTG2M8HWXqM9a0N8d4rT9vS2eYEtL/ATsk9B +VqPIctRjWzEmC1M6W0w2IB40TiD1ivdOKtcIE+EeSdgaSPcPbRuOyeIVWb16 +bOvYa0uwommztTPqN6Si7R/bVt8+LazqPulc1d00vaq73q6qu24cQcqpLdb0 +kAr1G9LR9n3nlWCyaEZWzciyGZxzsCFdf9GQfQ7a9iLYthNbsteBSX95o4FD +yv4SdK/Vq+VRm5uG7HzQti22Fx+dHp/aUGr93CEt+ieH1MPym5OB/B+pinjB +53je/g/XeeD832l4/j8k4ufv6+qmIK9//m0xItu59XYQeSGgQDyC0AKRkewn +QFyFEAfRps2BxB0I022OEDghfpLw184BsgLOgbBEGACCcac70B9EOCAkwimX +RYSVgCAgVl+RADsSkrsWTEIhRNKuuYQHIKwCmwAp3AoHegGWIATTHQvUBiwN +xAM8B9QFjAcDDeA+oG9gbiBg4FGghlnksw3GIUDLwBZANjCuAKoExgPigjEK +UBCwJ5Ag8D9QEjAaDF6Aj4FWYTQBJAccCfQOLA2DBOBboE0Y5QDpA3fDkAVY +GAYQMPaBoQAwOhkU/AJLonYPDSHmK5EdtvCPU0QqgxWRqkUxJpGKuDiFkEPz +Cv2mLjLZla7MVCreDg3y9XbJWpf5h8WhARKha+G6eUUST1d+ifKdeUESN56b +6wfrFikWzg3x8/bgVypfnzReGf7OnJCAffzjXOWkiaP+a96cDd6VTo02JyyU +pwP9thVOHGthosz1c1I6OM54fcrECRamhsqgDcqZnBnTptiNtTI1Msj08VT+ +cO/bW0bm8zMjDZpYLKjw3dHx/5ltaCD8oOhdkY8B7zv7kqq7+xpQIdvEyIBe +ZxmWf1kZGP+jE4Z6/5/jNPD9/+H539AIvoj/giwDfP19EUVRiPwhfAWJEcuA +CDmyQAyNDYmYGhsbGZuZmpubmZqZmb808iVzi99ZmJmNsBrxu5GWllaW5i9Z +j7K2HAW/LYkTiliyDE3B0NLCzMLyHxbcgKxMSchjUa8hAyuKZUXhE+hluqr6 +YmJoBPn2logypAyhxr35lAHU3MjE1HqU1WtotBmXB1pj+hsjZAzZk6xA24hl +9DiXMrBiGRoZ2yFr7piXFRnX8WX0EoQ7yLVCXmh0xYVom8TGm6Os2z+wfWC1 +6JvJyvojb99RSb33f8s+MGfnqxfOfPboPnt3ibA0diP/5pZ3O2/GVY7N2DnP +drXt90u7At06b7z2xv0JqqvtSwNcD2beDsyfvlT1yhcOdrPu/XB4gvrj/y57 +O+m9DtnHygU5azNyUu2mfRhZFVN82F85+/DnOdOsAjOm311x6b5H+qq59SP+ +Fl7m3XL75mbhwkPiTzpXKOfvv/R7u7zjiz9ru9ccZTitofV/6zwM/uIxx+Tg +sUupc26+/tOSa8VhozPDRxV+FvrhVBej/GUpYd/w8uObM9+rDF33PbuwPnn8 +qyY1q/GlX/LWG5Z/ARkY/5OHfP/f2Wng+J8//P7XkMikxcoI1RIlm7n477yr +WqyOIq8D9MuPUqoio9SkALpLrVrEXhQFvaYrDFepExf8gS1kp5qz2Zxkie8M +OPpKydGV+S0hRz7z24ccRT6PdXz4tCatIxH1WtGuREyRgFZmipzIkcv85pAj +R/KU3/TppBydKybp6zpj8N9i+ujbe0ybZf78vvstyCDv/0QO+fM/yPv//OH5 +/5BICL/f+/9ZaSuS4lWKPoV0vDwhNvJxeuW7y+KiwnXpnIyV6tjF7yxWMOnc +7NUr1PExSgWkr166gHLSU2ljheItdLnzAsrQGYe9hc50trWiVcmJSxQziWXD +V+2tX6BkdXwY+vM3XdfIP4598SekToh1vHpTlzzTgOJiohD5J6mL7V9+cebM +JvqckDzR3HD08OHNTJXo0nNn+up7+WLHl+fwn/rSX7SeP3fm5LP+k+HfSgY+ +/2pVxAteAHze/p8zX9Dv+XfmOHGHn/+hEH//6ch0kFdx5IUNewPWHOnR2+bD +Hks/0rhElfys3ftnbPP9rLcHnrHN99S3F+TrT6wKKji+XZZTWyZOqykXqssq +ddt81XrbfIO+PRFadOrYz9zmo+3JqqX26wDNww5P+u2Nn7nNh3lhufTbI7pt +PqztENBvjzxnmw/zozZodLaz75yT5ult89Fvr/Tb5gObjbU2XOmAt2e6mqUx +2ksijd42H/32jG/GAU1vmwWRRfTbO/evL6n4v/19mfUdzzQfaJMOePWOc+26 +6zA/yxh5R399nL+ZiGm+/58PSoFXDzmULs63LV70HbQyHcj3JnKa7/+hWULg +1UsMaFN9yHpfHLddhWWab+Wx2ULw1VMMaFN9eKb5cK3eQgF/7/l9xzLNBwsv +BwYCU30fL9j7/LpseebvJf3v0Gm+/7+OS944MF2IqNVrDCRO9QkC3cAMdgZ4 +7R8SmwnIBhUQt4AEM1QchNmgbFCwcSGJ8zIygbeaKwH9JcjIAhYDWSWEpEYU +ygaZKwZlNwCxOFQ9SEIGSb0mkM0Edicjgx0jK5gN2n5uD2SzAdmPgOqDkNwD +8T4EMnBdXwwK+YaHVSEgmuHsGfDCJoZZM2eCxdPSwFHzQSOGH8yX5g0Ay0dY +gtXTrFocBaNgFIyCUTAKRsEoGBAAAAClciYAUAAA +==== --- python2.7-2.7.6.orig/debian/libPVER-dbg.overrides.in +++ python2.7-2.7.6/debian/libPVER-dbg.overrides.in @@ -0,0 +1,7 @@ +lib@PVER@-dbg binary: package-name-doesnt-match-sonames +lib@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink + +lib@PVER@-dbg binary: arch-dependent-file-not-in-arch-specific-directory + +# pointless lintian ... +lib@PVER@-dbg binary: hardening-no-fortify-functions --- python2.7-2.7.6.orig/debian/libPVER-dbg.prerm.in +++ python2.7-2.7.6/debian/libPVER-dbg.prerm.in @@ -0,0 +1,23 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + dpkg -L lib@PVER@-dbg \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/libPVER-dbg.symbols.in +++ python2.7-2.7.6/debian/libPVER-dbg.symbols.in @@ -0,0 +1,33 @@ +libpython@VER@_d.so.1.0 libpython@VER@-dbg #MINVER# + Py_InitModule4TraceRefs@Base @VER@ +#include "libpython.symbols" + _PyDict_Dummy@Base @VER@ + _PyMem_DebugFree@Base @VER@ + _PyMem_DebugMalloc@Base @VER@ + _PyMem_DebugRealloc@Base @VER@ + _PyObject_DebugCheckAddress@Base @VER@ + _PyObject_DebugCheckAddressApi@Base @VER@ + _PyObject_DebugDumpAddress@Base @VER@ + _PyObject_DebugFree@Base @VER@ + _PyObject_DebugFreeApi@Base @VER@ + _PyObject_DebugMalloc@Base @VER@ + _PyObject_DebugMallocApi@Base @VER@ + _PyObject_DebugMallocStats@Base @VER@ + _PyObject_DebugRealloc@Base @VER@ + _PyObject_DebugReallocApi@Base @VER@ + _PySet_Dummy@Base @VER@ + _Py_AddToAllObjects@Base @VER@ + _Py_Dealloc@Base @VER@ + _Py_ForgetReference@Base @VER@ + _Py_GetObjects@Base @VER@ + _Py_GetRefTotal@Base @VER@ + _Py_HashSecret_Initialized@Base @VER@ + _Py_NegativeRefcount@Base @VER@ + _Py_NewReference@Base @VER@ + _Py_PrintReferenceAddresses@Base @VER@ + _Py_PrintReferences@Base @VER@ + _Py_RefTotal@Base @VER@ + _Py_dumptree@Base @VER@ + _Py_printtree@Base @VER@ + _Py_showtree@Base @VER@ + _Py_tok_dump@Base @VER@ --- python2.7-2.7.6.orig/debian/libPVER-dev.overrides.in +++ python2.7-2.7.6/debian/libPVER-dev.overrides.in @@ -0,0 +1,3 @@ +lib@PVER@-dev binary: python-script-but-no-python-dep + +lib@PVER@-dev binary: arch-dependent-file-not-in-arch-specific-directory --- python2.7-2.7.6.orig/debian/libPVER-minimal.overrides.in +++ python2.7-2.7.6/debian/libPVER-minimal.overrides.in @@ -0,0 +1 @@ +lib@PVER@-minimal binary: python-script-but-no-python-dep --- python2.7-2.7.6.orig/debian/libPVER-minimal.postinst.in +++ python2.7-2.7.6/debian/libPVER-minimal.postinst.in @@ -0,0 +1,13 @@ +#! /bin/sh + +set -e + +if [ ! -f /etc/@PVER@/sitecustomize.py ]; then + cat <<-EOF + # Empty sitecustomize.py to avoid a dangling symlink +EOF +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/libPVER-minimal.postrm.in +++ python2.7-2.7.6/debian/libPVER-minimal.postrm.in @@ -0,0 +1,26 @@ +#! /bin/sh + +set -e + +if [ "$1" = "remove" ]; then + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W pkgname \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + find /usr/lib/@PVER@ -name '*.py[co]' -print0 | xargs -r0 rm -f + fi +fi + +if [ "$1" = "purge" ]; then + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W pkgname \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + rm -f /etc/@PVER@/site.py /etc/@PVER@/sitecustomize.py + if [ -d /etc/@PVER@ ]; then + rmdir --ignore-fail-on-non-empty /etc/@PVER@ 2>/dev/null + fi + fi +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.6.orig/debian/libPVER-minimal.prerm.in +++ python2.7-2.7.6/debian/libPVER-minimal.prerm.in @@ -0,0 +1,35 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + dpkg -L $1 \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 +} + +case "$1" in + remove) + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W pkgname \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + remove_bytecode lib@PVER@-minimal + fi + ;; + upgrade) + remove_bytecode lib@PVER@-minimal + # byte compilation in @PVER@-minimal postinst, strict dependency + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/libPVER-stdlib.overrides.in +++ python2.7-2.7.6/debian/libPVER-stdlib.overrides.in @@ -0,0 +1,14 @@ +# idlelib images +lib@PVER@-stdlib binary: image-file-in-usr-lib + +# license file referred by the standard library +lib@PVER@-stdlib binary: extra-license-file + +# template files +lib@PVER@-stdlib binary: interpreter-not-absolute usr/lib/python3.3/venv/scripts/posix/pydoc #!__VENV_PYTHON__ +lib@PVER@-stdlib binary: unusual-interpreter usr/lib/python3.3/venv/scripts/posix/pydoc #!__VENV_PYTHON__ + +# the split is the reason for that +lib@PVER@-stdlib binary: python-script-but-no-python-dep + +lib@PVER@-stdlib binary: arch-dependent-file-not-in-arch-specific-directory --- python2.7-2.7.6.orig/debian/libPVER-stdlib.prerm.in +++ python2.7-2.7.6/debian/libPVER-stdlib.prerm.in @@ -0,0 +1,35 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + dpkg -L $1 \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 +} + +case "$1" in + remove) + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W pkgname \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + remove_bytecode lib@PVER@-stdlib + fi + ;; + upgrade) + remove_bytecode lib@PVER@-stdlib + # byte compilation in @PVER@ postinst, strict dependency + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/libPVER-testsuite.overrides.in +++ python2.7-2.7.6/debian/libPVER-testsuite.overrides.in @@ -0,0 +1,2 @@ +lib@PVER@-testsuite binary: python-script-but-no-python-dep +lib@PVER@-testsuite binary: image-file-in-usr-lib --- python2.7-2.7.6.orig/debian/libPVER-testsuite.prerm.in +++ python2.7-2.7.6/debian/libPVER-testsuite.prerm.in @@ -0,0 +1,29 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + dpkg -L $1 \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 +} + +case "$1" in + remove) + remove_bytecode lib@PVER@-testsuite + ;; + upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.6.orig/debian/libPVER.overrides.in +++ python2.7-2.7.6/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python2.7-2.7.6.orig/debian/libPVER.symbols.in +++ python2.7-2.7.6/debian/libPVER.symbols.in @@ -0,0 +1,3 @@ +libpython@VER@.so.1.0 libpython@VER@ #MINVER# + Py_InitModule4@Base @VER@ +#include "libpython.symbols" --- python2.7-2.7.6.orig/debian/libpython.symbols.in +++ python2.7-2.7.6/debian/libpython.symbols.in @@ -0,0 +1,1337 @@ + PyAST_Check@Base @VER@ + PyAST_Compile@Base @VER@ + PyAST_FromNode@Base @VER@ + PyAST_mod2obj@Base @VER@ + PyAST_obj2mod@Base @VER@ + PyArena_AddPyObject@Base @VER@ + PyArena_Free@Base @VER@ + PyArena_Malloc@Base @VER@ + PyArena_New@Base @VER@ + PyArg_Parse@Base @VER@ + PyArg_ParseTuple@Base @VER@ + PyArg_ParseTupleAndKeywords@Base @VER@ + PyArg_UnpackTuple@Base @VER@ + PyArg_VaParse@Base @VER@ + PyArg_VaParseTupleAndKeywords@Base @VER@ + PyBaseObject_Type@Base @VER@ + PyBaseString_Type@Base @VER@ + PyBool_FromLong@Base @VER@ + PyBool_Type@Base @VER@ + PyBuffer_FillContiguousStrides@Base @VER@ + PyBuffer_FillInfo@Base @VER@ + PyBuffer_FromContiguous@Base @VER@ + PyBuffer_FromMemory@Base @VER@ + PyBuffer_FromObject@Base @VER@ + PyBuffer_FromReadWriteMemory@Base @VER@ + PyBuffer_FromReadWriteObject@Base @VER@ + PyBuffer_GetPointer@Base @VER@ + PyBuffer_IsContiguous@Base @VER@ + PyBuffer_New@Base @VER@ + PyBuffer_Release@Base @VER@ + PyBuffer_ToContiguous@Base @VER@ + PyBuffer_Type@Base @VER@ + (optional)PyBufferedIOBase_Type@Base @VER@ + (optional)PyBufferedRWPair_Type@Base @VER@ + (optional)PyBufferedRandom_Type@Base @VER@ + (optional)PyBufferedReader_Type@Base @VER@ + (optional)PyBufferedWriter_Type@Base @VER@ + PyByteArrayIter_Type@Base @VER@ + PyByteArray_AsString@Base @VER@ + PyByteArray_Concat@Base @VER@ + PyByteArray_Fini@Base @VER@ + PyByteArray_FromObject@Base @VER@ + PyByteArray_FromStringAndSize@Base @VER@ + PyByteArray_Init@Base @VER@ + PyByteArray_Resize@Base @VER@ + PyByteArray_Size@Base @VER@ + PyByteArray_Type@Base @VER@ + (optional)PyBytesIO_Type@Base @VER@ + PyCFunction_Call@Base @VER@ + PyCFunction_ClearFreeList@Base @VER@ + PyCFunction_Fini@Base @VER@ + PyCFunction_GetFlags@Base @VER@ + PyCFunction_GetFunction@Base @VER@ + PyCFunction_GetSelf@Base @VER@ + PyCFunction_New@Base @VER@ + PyCFunction_NewEx@Base @VER@ + PyCFunction_Type@Base @VER@ + PyCObject_AsVoidPtr@Base @VER@ + PyCObject_FromVoidPtr@Base @VER@ + PyCObject_FromVoidPtrAndDesc@Base @VER@ + PyCObject_GetDesc@Base @VER@ + PyCObject_Import@Base @VER@ + PyCObject_SetVoidPtr@Base @VER@ + PyCObject_Type@Base @VER@ + PyCallIter_New@Base @VER@ + PyCallIter_Type@Base @VER@ + PyCallable_Check@Base @VER@ + PyCapsule_GetContext@Base @VER@ + PyCapsule_GetDestructor@Base @VER@ + PyCapsule_GetName@Base @VER@ + PyCapsule_GetPointer@Base @VER@ + PyCapsule_Import@Base @VER@ + PyCapsule_IsValid@Base @VER@ + PyCapsule_New@Base @VER@ + PyCapsule_SetContext@Base @VER@ + PyCapsule_SetDestructor@Base @VER@ + PyCapsule_SetName@Base @VER@ + PyCapsule_SetPointer@Base @VER@ + PyCapsule_Type@Base @VER@ + PyCell_Get@Base @VER@ + PyCell_New@Base @VER@ + PyCell_Set@Base @VER@ + PyCell_Type@Base @VER@ + PyClassMethod_New@Base @VER@ + PyClassMethod_Type@Base @VER@ + PyClass_IsSubclass@Base @VER@ + PyClass_New@Base @VER@ + PyClass_Type@Base @VER@ + PyCode_Addr2Line@Base @VER@ + PyCode_New@Base @VER@ + PyCode_NewEmpty@Base @VER@ + PyCode_Optimize@Base @VER@ + PyCode_Type@Base @VER@ + PyCodec_BackslashReplaceErrors@Base @VER@ + PyCodec_Decode@Base @VER@ + PyCodec_Decoder@Base @VER@ + PyCodec_Encode@Base @VER@ + PyCodec_Encoder@Base @VER@ + PyCodec_IgnoreErrors@Base @VER@ + PyCodec_IncrementalDecoder@Base @VER@ + PyCodec_IncrementalEncoder@Base @VER@ + PyCodec_LookupError@Base @VER@ + PyCodec_Register@Base @VER@ + PyCodec_RegisterError@Base @VER@ + PyCodec_ReplaceErrors@Base @VER@ + PyCodec_StreamReader@Base @VER@ + PyCodec_StreamWriter@Base @VER@ + PyCodec_StrictErrors@Base @VER@ + PyCodec_XMLCharRefReplaceErrors@Base @VER@ + PyComplex_AsCComplex@Base @VER@ + PyComplex_FromCComplex@Base @VER@ + PyComplex_FromDoubles@Base @VER@ + PyComplex_ImagAsDouble@Base @VER@ + PyComplex_RealAsDouble@Base @VER@ + PyComplex_Type@Base @VER@ + PyDescr_NewClassMethod@Base @VER@ + PyDescr_NewGetSet@Base @VER@ + PyDescr_NewMember@Base @VER@ + PyDescr_NewMethod@Base @VER@ + PyDescr_NewWrapper@Base @VER@ + PyDictItems_Type@Base @VER@ + PyDictIterItem_Type@Base @VER@ + PyDictIterKey_Type@Base @VER@ + PyDictIterValue_Type@Base @VER@ + PyDictKeys_Type@Base @VER@ + PyDictProxy_New@Base @VER@ + PyDictProxy_Type@Base @VER@ + PyDictValues_Type@Base @VER@ + PyDict_Clear@Base @VER@ + PyDict_Contains@Base @VER@ + PyDict_Copy@Base @VER@ + PyDict_DelItem@Base @VER@ + PyDict_DelItemString@Base @VER@ + PyDict_Fini@Base @VER@ + PyDict_GetItem@Base @VER@ + PyDict_GetItemString@Base @VER@ + PyDict_Items@Base @VER@ + PyDict_Keys@Base @VER@ + PyDict_Merge@Base @VER@ + PyDict_MergeFromSeq2@Base @VER@ + PyDict_New@Base @VER@ + PyDict_Next@Base @VER@ + PyDict_SetItem@Base @VER@ + PyDict_SetItemString@Base @VER@ + PyDict_Size@Base @VER@ + PyDict_Type@Base @VER@ + PyDict_Update@Base @VER@ + PyDict_Values@Base @VER@ + PyEllipsis_Type@Base @VER@ + PyEnum_Type@Base @VER@ + PyErr_BadArgument@Base @VER@ + PyErr_BadInternalCall@Base @VER@ + PyErr_CheckSignals@Base @VER@ + PyErr_Clear@Base @VER@ + PyErr_Display@Base @VER@ + PyErr_ExceptionMatches@Base @VER@ + PyErr_Fetch@Base @VER@ + PyErr_Format@Base @VER@ + PyErr_GivenExceptionMatches@Base @VER@ + PyErr_NewException@Base @VER@ + PyErr_NewExceptionWithDoc@Base @VER@ + PyErr_NoMemory@Base @VER@ + PyErr_NormalizeException@Base @VER@ + PyErr_Occurred@Base @VER@ + PyErr_Print@Base @VER@ + PyErr_PrintEx@Base @VER@ + PyErr_ProgramText@Base @VER@ + PyErr_Restore@Base @VER@ + PyErr_SetFromErrno@Base @VER@ + PyErr_SetFromErrnoWithFilename@Base @VER@ + PyErr_SetFromErrnoWithFilenameObject@Base @VER@ + PyErr_SetInterrupt@Base @VER@ + PyErr_SetNone@Base @VER@ + PyErr_SetObject@Base @VER@ + PyErr_SetString@Base @VER@ + PyErr_SyntaxLocation@Base @VER@ + PyErr_Warn@Base @VER@ + PyErr_WarnEx@Base @VER@ + PyErr_WarnExplicit@Base @VER@ + PyErr_WriteUnraisable@Base @VER@ + PyEval_AcquireLock@Base @VER@ + PyEval_AcquireThread@Base @VER@ + PyEval_CallFunction@Base @VER@ + PyEval_CallMethod@Base @VER@ + PyEval_CallObjectWithKeywords@Base @VER@ + PyEval_EvalCode@Base @VER@ + PyEval_EvalCodeEx@Base @VER@ + PyEval_EvalFrame@Base @VER@ + PyEval_EvalFrameEx@Base @VER@ + PyEval_GetBuiltins@Base @VER@ + PyEval_GetCallStats@Base @VER@ + PyEval_GetFrame@Base @VER@ + PyEval_GetFuncDesc@Base @VER@ + PyEval_GetFuncName@Base @VER@ + PyEval_GetGlobals@Base @VER@ + PyEval_GetLocals@Base @VER@ + PyEval_GetRestricted@Base @VER@ + PyEval_InitThreads@Base @VER@ + PyEval_MergeCompilerFlags@Base @VER@ + PyEval_ReInitThreads@Base @VER@ + PyEval_ReleaseLock@Base @VER@ + PyEval_ReleaseThread@Base @VER@ + PyEval_RestoreThread@Base @VER@ + PyEval_SaveThread@Base @VER@ + PyEval_SetProfile@Base @VER@ + PyEval_SetTrace@Base @VER@ + PyEval_ThreadsInitialized@Base @VER@ + PyExc_ArithmeticError@Base @VER@ + PyExc_AssertionError@Base @VER@ + PyExc_AttributeError@Base @VER@ + PyExc_BaseException@Base @VER@ + (optional)PyExc_BlockingIOError@Base @VER@ + PyExc_BufferError@Base @VER@ + PyExc_BytesWarning@Base @VER@ + PyExc_DeprecationWarning@Base @VER@ + PyExc_EOFError@Base @VER@ + PyExc_EnvironmentError@Base @VER@ + PyExc_Exception@Base @VER@ + PyExc_FloatingPointError@Base @VER@ + PyExc_FutureWarning@Base @VER@ + PyExc_GeneratorExit@Base @VER@ + PyExc_IOError@Base @VER@ + PyExc_ImportError@Base @VER@ + PyExc_ImportWarning@Base @VER@ + PyExc_IndentationError@Base @VER@ + PyExc_IndexError@Base @VER@ + PyExc_KeyError@Base @VER@ + PyExc_KeyboardInterrupt@Base @VER@ + PyExc_LookupError@Base @VER@ + PyExc_MemoryError@Base @VER@ + PyExc_MemoryErrorInst@Base @VER@ + PyExc_NameError@Base @VER@ + PyExc_NotImplementedError@Base @VER@ + PyExc_OSError@Base @VER@ + PyExc_OverflowError@Base @VER@ + PyExc_PendingDeprecationWarning@Base @VER@ + PyExc_RecursionErrorInst@Base @VER@ + PyExc_ReferenceError@Base @VER@ + PyExc_RuntimeError@Base @VER@ + PyExc_RuntimeWarning@Base @VER@ + PyExc_StandardError@Base @VER@ + PyExc_StopIteration@Base @VER@ + PyExc_SyntaxError@Base @VER@ + PyExc_SyntaxWarning@Base @VER@ + PyExc_SystemError@Base @VER@ + PyExc_SystemExit@Base @VER@ + PyExc_TabError@Base @VER@ + PyExc_TypeError@Base @VER@ + PyExc_UnboundLocalError@Base @VER@ + PyExc_UnicodeDecodeError@Base @VER@ + PyExc_UnicodeEncodeError@Base @VER@ + PyExc_UnicodeError@Base @VER@ + PyExc_UnicodeTranslateError@Base @VER@ + PyExc_UnicodeWarning@Base @VER@ + PyExc_UserWarning@Base @VER@ + PyExc_ValueError@Base @VER@ + PyExc_Warning@Base @VER@ + PyExc_ZeroDivisionError@Base @VER@ + (optional)PyFileIO_Type@Base @VER@ + PyFile_AsFile@Base @VER@ + PyFile_DecUseCount@Base @VER@ + PyFile_FromFile@Base @VER@ + PyFile_FromString@Base @VER@ + PyFile_GetLine@Base @VER@ + PyFile_IncUseCount@Base @VER@ + PyFile_Name@Base @VER@ + PyFile_SetBufSize@Base @VER@ + PyFile_SetEncoding@Base @VER@ + PyFile_SetEncodingAndErrors@Base @VER@ + PyFile_SoftSpace@Base @VER@ + PyFile_Type@Base @VER@ + PyFile_WriteObject@Base @VER@ + PyFile_WriteString@Base @VER@ + PyFloat_AsDouble@Base @VER@ + PyFloat_AsReprString@Base @VER@ + PyFloat_AsString@Base @VER@ + PyFloat_ClearFreeList@Base @VER@ + PyFloat_Fini@Base @VER@ + PyFloat_FromDouble@Base @VER@ + PyFloat_FromString@Base @VER@ + PyFloat_GetInfo@Base @VER@ + PyFloat_GetMax@Base @VER@ + PyFloat_GetMin@Base @VER@ + PyFloat_Type@Base @VER@ + PyFrame_BlockPop@Base @VER@ + PyFrame_BlockSetup@Base @VER@ + PyFrame_ClearFreeList@Base @VER@ + PyFrame_FastToLocals@Base @VER@ + PyFrame_Fini@Base @VER@ + PyFrame_GetLineNumber@Base @VER@ + PyFrame_LocalsToFast@Base @VER@ + PyFrame_New@Base @VER@ + PyFrame_Type@Base @VER@ + PyFrozenSet_New@Base @VER@ + PyFrozenSet_Type@Base @VER@ + PyFunction_GetClosure@Base @VER@ + PyFunction_GetCode@Base @VER@ + PyFunction_GetDefaults@Base @VER@ + PyFunction_GetGlobals@Base @VER@ + PyFunction_GetModule@Base @VER@ + PyFunction_New@Base @VER@ + PyFunction_SetClosure@Base @VER@ + PyFunction_SetDefaults@Base @VER@ + PyFunction_Type@Base @VER@ + PyFuture_FromAST@Base @VER@ + PyGC_Collect@Base @VER@ + PyGILState_Ensure@Base @VER@ + PyGILState_GetThisThreadState@Base @VER@ + PyGILState_Release@Base @VER@ + PyGen_NeedsFinalizing@Base @VER@ + PyGen_New@Base @VER@ + PyGen_Type@Base @VER@ + PyGetSetDescr_Type@Base @VER@ + PyGrammar_AddAccelerators@Base @VER@ + PyGrammar_FindDFA@Base @VER@ + PyGrammar_LabelRepr@Base @VER@ + PyGrammar_RemoveAccelerators@Base @VER@ + (optional)PyIOBase_Type@Base @VER@ + PyImport_AddModule@Base @VER@ + PyImport_AppendInittab@Base @VER@ + PyImport_Cleanup@Base @VER@ + PyImport_ExecCodeModule@Base @VER@ + PyImport_ExecCodeModuleEx@Base @VER@ + PyImport_ExtendInittab@Base @VER@ + PyImport_FrozenModules@Base @VER@ + PyImport_GetImporter@Base @VER@ + PyImport_GetMagicNumber@Base @VER@ + PyImport_GetModuleDict@Base @VER@ + PyImport_Import@Base @VER@ + PyImport_ImportFrozenModule@Base @VER@ + PyImport_ImportModule@Base @VER@ + PyImport_ImportModuleLevel@Base @VER@ + PyImport_ImportModuleNoBlock@Base @VER@ + PyImport_Inittab@Base @VER@ + PyImport_ReloadModule@Base @VER@ + (optional)PyIncrementalNewlineDecoder_Type@Base @VER@ + PyInstance_New@Base @VER@ + PyInstance_NewRaw@Base @VER@ + PyInstance_Type@Base @VER@ + PyInt_AsLong@Base @VER@ + PyInt_AsSsize_t@Base @VER@ + PyInt_AsUnsignedLongLongMask@Base @VER@ + PyInt_AsUnsignedLongMask@Base @VER@ + PyInt_ClearFreeList@Base @VER@ + PyInt_Fini@Base @VER@ + PyInt_FromLong@Base @VER@ + PyInt_FromSize_t@Base @VER@ + PyInt_FromSsize_t@Base @VER@ + PyInt_FromString@Base @VER@ + PyInt_FromUnicode@Base @VER@ + PyInt_GetMax@Base @VER@ + PyInt_Type@Base @VER@ + PyInterpreterState_Clear@Base @VER@ + PyInterpreterState_Delete@Base @VER@ + PyInterpreterState_Head@Base @VER@ + PyInterpreterState_New@Base @VER@ + PyInterpreterState_Next@Base @VER@ + PyInterpreterState_ThreadHead@Base @VER@ + PyIter_Next@Base @VER@ + PyListIter_Type@Base @VER@ + PyListRevIter_Type@Base @VER@ + PyList_Append@Base @VER@ + PyList_AsTuple@Base @VER@ + PyList_Fini@Base @VER@ + PyList_GetItem@Base @VER@ + PyList_GetSlice@Base @VER@ + PyList_Insert@Base @VER@ + PyList_New@Base @VER@ + PyList_Reverse@Base @VER@ + PyList_SetItem@Base @VER@ + PyList_SetSlice@Base @VER@ + PyList_Size@Base @VER@ + PyList_Sort@Base @VER@ + PyList_Type@Base @VER@ + PyLong_AsDouble@Base @VER@ + PyLong_AsLong@Base @VER@ + PyLong_AsLongAndOverflow@Base @VER@ + PyLong_AsLongLong@Base @VER@ + PyLong_AsLongLongAndOverflow@Base @VER@ + PyLong_AsSsize_t@Base @VER@ + PyLong_AsUnsignedLong@Base @VER@ + PyLong_AsUnsignedLongLong@Base @VER@ + PyLong_AsUnsignedLongLongMask@Base @VER@ + PyLong_AsUnsignedLongMask@Base @VER@ + PyLong_AsVoidPtr@Base @VER@ + PyLong_FromDouble@Base @VER@ + PyLong_FromLong@Base @VER@ + PyLong_FromLongLong@Base @VER@ + PyLong_FromSize_t@Base @VER@ + PyLong_FromSsize_t@Base @VER@ + PyLong_FromString@Base @VER@ + PyLong_FromUnicode@Base @VER@ + PyLong_FromUnsignedLong@Base @VER@ + PyLong_FromUnsignedLongLong@Base @VER@ + PyLong_FromVoidPtr@Base @VER@ + PyLong_GetInfo@Base @VER@ + PyLong_Type@Base @VER@ + PyMapping_Check@Base @VER@ + PyMapping_GetItemString@Base @VER@ + PyMapping_HasKey@Base @VER@ + PyMapping_HasKeyString@Base @VER@ + PyMapping_Length@Base @VER@ + PyMapping_SetItemString@Base @VER@ + PyMapping_Size@Base @VER@ + PyMarshal_Init@Base @VER@ + PyMarshal_ReadLastObjectFromFile@Base @VER@ + PyMarshal_ReadLongFromFile@Base @VER@ + PyMarshal_ReadObjectFromFile@Base @VER@ + PyMarshal_ReadObjectFromString@Base @VER@ + PyMarshal_ReadShortFromFile@Base @VER@ + PyMarshal_WriteLongToFile@Base @VER@ + PyMarshal_WriteObjectToFile@Base @VER@ + PyMarshal_WriteObjectToString@Base @VER@ + PyMem_Free@Base @VER@ + PyMem_Malloc@Base @VER@ + PyMem_Realloc@Base @VER@ + PyMemberDescr_Type@Base @VER@ + PyMember_Get@Base @VER@ + PyMember_GetOne@Base @VER@ + PyMember_Set@Base @VER@ + PyMember_SetOne@Base @VER@ + PyMemoryView_FromBuffer@Base @VER@ + PyMemoryView_FromObject@Base @VER@ + PyMemoryView_GetContiguous@Base @VER@ + PyMemoryView_Type@Base @VER@ + PyMethod_Class@Base @VER@ + PyMethod_ClearFreeList@Base @VER@ + PyMethod_Fini@Base @VER@ + PyMethod_Function@Base @VER@ + PyMethod_New@Base @VER@ + PyMethod_Self@Base @VER@ + PyMethod_Type@Base @VER@ + PyModule_AddIntConstant@Base @VER@ + PyModule_AddObject@Base @VER@ + PyModule_AddStringConstant@Base @VER@ + PyModule_GetDict@Base @VER@ + PyModule_GetFilename@Base @VER@ + PyModule_GetName@Base @VER@ + PyModule_GetWarningsModule@Base @VER@ + PyModule_New@Base @VER@ + PyModule_Type@Base @VER@ + PyNode_AddChild@Base @VER@ + PyNode_Compile@Base @VER@ + PyNode_Free@Base @VER@ + PyNode_ListTree@Base @VER@ + PyNode_New@Base @VER@ + PyNullImporter_Type@Base @VER@ + PyNumber_Absolute@Base @VER@ + PyNumber_Add@Base @VER@ + PyNumber_And@Base @VER@ + (optional)PyNumber_AsOff_t@Base @VER@ + PyNumber_AsSsize_t@Base @VER@ + PyNumber_Check@Base @VER@ + PyNumber_Coerce@Base @VER@ + PyNumber_CoerceEx@Base @VER@ + PyNumber_Divide@Base @VER@ + PyNumber_Divmod@Base @VER@ + PyNumber_Float@Base @VER@ + PyNumber_FloorDivide@Base @VER@ + PyNumber_InPlaceAdd@Base @VER@ + PyNumber_InPlaceAnd@Base @VER@ + PyNumber_InPlaceDivide@Base @VER@ + PyNumber_InPlaceFloorDivide@Base @VER@ + PyNumber_InPlaceLshift@Base @VER@ + PyNumber_InPlaceMultiply@Base @VER@ + PyNumber_InPlaceOr@Base @VER@ + PyNumber_InPlacePower@Base @VER@ + PyNumber_InPlaceRemainder@Base @VER@ + PyNumber_InPlaceRshift@Base @VER@ + PyNumber_InPlaceSubtract@Base @VER@ + PyNumber_InPlaceTrueDivide@Base @VER@ + PyNumber_InPlaceXor@Base @VER@ + PyNumber_Index@Base @VER@ + PyNumber_Int@Base @VER@ + PyNumber_Invert@Base @VER@ + PyNumber_Long@Base @VER@ + PyNumber_Lshift@Base @VER@ + PyNumber_Multiply@Base @VER@ + PyNumber_Negative@Base @VER@ + PyNumber_Or@Base @VER@ + PyNumber_Positive@Base @VER@ + PyNumber_Power@Base @VER@ + PyNumber_Remainder@Base @VER@ + PyNumber_Rshift@Base @VER@ + PyNumber_Subtract@Base @VER@ + PyNumber_ToBase@Base @VER@ + PyNumber_TrueDivide@Base @VER@ + PyNumber_Xor@Base @VER@ + PyOS_AfterFork@Base @VER@ + PyOS_FiniInterrupts@Base @VER@ + PyOS_InitInterrupts@Base @VER@ + PyOS_InputHook@Base @VER@ + PyOS_InterruptOccurred@Base @VER@ + PyOS_Readline@Base @VER@ + PyOS_ReadlineFunctionPointer@Base @VER@ + PyOS_StdioReadline@Base @VER@ + PyOS_ascii_atof@Base @VER@ + PyOS_ascii_formatd@Base @VER@ + PyOS_ascii_strtod@Base @VER@ + PyOS_double_to_string@Base @VER@ + PyOS_getsig@Base @VER@ + PyOS_mystricmp@Base @VER@ + PyOS_mystrnicmp@Base @VER@ + PyOS_setsig@Base @VER@ + PyOS_snprintf@Base @VER@ + PyOS_string_to_double@Base @VER@ + PyOS_strtol@Base @VER@ + PyOS_strtoul@Base @VER@ + PyOS_vsnprintf@Base @VER@ + PyObject_AsCharBuffer@Base @VER@ + PyObject_AsFileDescriptor@Base @VER@ + PyObject_AsReadBuffer@Base @VER@ + PyObject_AsWriteBuffer@Base @VER@ + PyObject_Call@Base @VER@ + PyObject_CallFunction@Base @VER@ + PyObject_CallFunctionObjArgs@Base @VER@ + PyObject_CallMethod@Base @VER@ + PyObject_CallMethodObjArgs@Base @VER@ + PyObject_CallObject@Base @VER@ + PyObject_CheckReadBuffer@Base @VER@ + PyObject_ClearWeakRefs@Base @VER@ + PyObject_Cmp@Base @VER@ + PyObject_Compare@Base @VER@ + PyObject_CopyData@Base @VER@ + PyObject_DelItem@Base @VER@ + PyObject_DelItemString@Base @VER@ + PyObject_Dir@Base @VER@ + PyObject_Format@Base @VER@ + PyObject_Free@Base @VER@ + PyObject_GC_Del@Base @VER@ + PyObject_GC_Track@Base @VER@ + PyObject_GC_UnTrack@Base @VER@ + PyObject_GenericGetAttr@Base @VER@ + PyObject_GenericSetAttr@Base @VER@ + PyObject_GetAttr@Base @VER@ + PyObject_GetAttrString@Base @VER@ + PyObject_GetBuffer@Base @VER@ + PyObject_GetItem@Base @VER@ + PyObject_GetIter@Base @VER@ + PyObject_HasAttr@Base @VER@ + PyObject_HasAttrString@Base @VER@ + PyObject_Hash@Base @VER@ + PyObject_HashNotImplemented@Base @VER@ + PyObject_Init@Base @VER@ + PyObject_InitVar@Base @VER@ + PyObject_IsInstance@Base @VER@ + PyObject_IsSubclass@Base @VER@ + PyObject_IsTrue@Base @VER@ + PyObject_Length@Base @VER@ + PyObject_Malloc@Base @VER@ + PyObject_Not@Base @VER@ + PyObject_Print@Base @VER@ + PyObject_Realloc@Base @VER@ + PyObject_Repr@Base @VER@ + PyObject_RichCompare@Base @VER@ + PyObject_RichCompareBool@Base @VER@ + PyObject_SelfIter@Base @VER@ + PyObject_SetAttr@Base @VER@ + PyObject_SetAttrString@Base @VER@ + PyObject_SetItem@Base @VER@ + PyObject_Size@Base @VER@ + PyObject_Str@Base @VER@ + PyObject_Type@Base @VER@ + PyObject_Unicode@Base @VER@ + PyParser_ASTFromFile@Base @VER@ + PyParser_ASTFromString@Base @VER@ + PyParser_AddToken@Base @VER@ + PyParser_Delete@Base @VER@ + PyParser_New@Base @VER@ + PyParser_ParseFile@Base @VER@ + PyParser_ParseFileFlags@Base @VER@ + PyParser_ParseFileFlagsEx@Base @VER@ + PyParser_ParseString@Base @VER@ + PyParser_ParseStringFlags@Base @VER@ + PyParser_ParseStringFlagsFilename@Base @VER@ + PyParser_ParseStringFlagsFilenameEx@Base @VER@ + PyParser_SetError@Base @VER@ + PyParser_SimpleParseFile@Base @VER@ + PyParser_SimpleParseFileFlags@Base @VER@ + PyParser_SimpleParseString@Base @VER@ + PyParser_SimpleParseStringFilename@Base @VER@ + PyParser_SimpleParseStringFlags@Base @VER@ + PyParser_SimpleParseStringFlagsFilename@Base @VER@ + PyProperty_Type@Base @VER@ + PyRange_Type@Base @VER@ + (optional)PyRawIOBase_Type@Base @VER@ + PyReversed_Type@Base @VER@ + PyRun_AnyFile@Base @VER@ + PyRun_AnyFileEx@Base @VER@ + PyRun_AnyFileExFlags@Base @VER@ + PyRun_AnyFileFlags@Base @VER@ + PyRun_File@Base @VER@ + PyRun_FileEx@Base @VER@ + PyRun_FileExFlags@Base @VER@ + PyRun_FileFlags@Base @VER@ + PyRun_InteractiveLoop@Base @VER@ + PyRun_InteractiveLoopFlags@Base @VER@ + PyRun_InteractiveOne@Base @VER@ + PyRun_InteractiveOneFlags@Base @VER@ + PyRun_SimpleFile@Base @VER@ + PyRun_SimpleFileEx@Base @VER@ + PyRun_SimpleFileExFlags@Base @VER@ + PyRun_SimpleString@Base @VER@ + PyRun_SimpleStringFlags@Base @VER@ + PyRun_String@Base @VER@ + PyRun_StringFlags@Base @VER@ + PySTEntry_Type@Base @VER@ + PyST_GetScope@Base @VER@ + PySeqIter_New@Base @VER@ + PySeqIter_Type@Base @VER@ + PySequence_Check@Base @VER@ + PySequence_Concat@Base @VER@ + PySequence_Contains@Base @VER@ + PySequence_Count@Base @VER@ + PySequence_DelItem@Base @VER@ + PySequence_DelSlice@Base @VER@ + PySequence_Fast@Base @VER@ + PySequence_GetItem@Base @VER@ + PySequence_GetSlice@Base @VER@ + PySequence_In@Base @VER@ + PySequence_InPlaceConcat@Base @VER@ + PySequence_InPlaceRepeat@Base @VER@ + PySequence_Index@Base @VER@ + PySequence_Length@Base @VER@ + PySequence_List@Base @VER@ + PySequence_Repeat@Base @VER@ + PySequence_SetItem@Base @VER@ + PySequence_SetSlice@Base @VER@ + PySequence_Size@Base @VER@ + PySequence_Tuple@Base @VER@ + PySet_Add@Base @VER@ + PySet_Clear@Base @VER@ + PySet_Contains@Base @VER@ + PySet_Discard@Base @VER@ + PySet_Fini@Base @VER@ + PySet_New@Base @VER@ + PySet_Pop@Base @VER@ + PySet_Size@Base @VER@ + PySet_Type@Base @VER@ + PySignal_SetWakeupFd@Base @VER@ + PySlice_GetIndices@Base @VER@ + PySlice_GetIndicesEx@Base @VER@ + PySlice_New@Base @VER@ + PySlice_Type@Base @VER@ + PyStaticMethod_New@Base @VER@ + PyStaticMethod_Type@Base @VER@ + (optional)PyStringIO_Type@Base @VER@ + PyString_AsDecodedObject@Base @VER@ + PyString_AsDecodedString@Base @VER@ + PyString_AsEncodedObject@Base @VER@ + PyString_AsEncodedString@Base @VER@ + PyString_AsString@Base @VER@ + PyString_AsStringAndSize@Base @VER@ + PyString_Concat@Base @VER@ + PyString_ConcatAndDel@Base @VER@ + PyString_Decode@Base @VER@ + PyString_DecodeEscape@Base @VER@ + PyString_Encode@Base @VER@ + PyString_Fini@Base @VER@ + PyString_Format@Base @VER@ + PyString_FromFormat@Base @VER@ + PyString_FromFormatV@Base @VER@ + PyString_FromString@Base @VER@ + PyString_FromStringAndSize@Base @VER@ + PyString_InternFromString@Base @VER@ + PyString_InternImmortal@Base @VER@ + PyString_InternInPlace@Base @VER@ + PyString_Repr@Base @VER@ + PyString_Size@Base @VER@ + PyString_Type@Base @VER@ + PyStructSequence_InitType@Base @VER@ + PyStructSequence_New@Base @VER@ + PyStructSequence_UnnamedField@Base @VER@ + PySuper_Type@Base @VER@ + PySymtable_Build@Base @VER@ + PySymtable_Free@Base @VER@ + PySymtable_Lookup@Base @VER@ + PySys_AddWarnOption@Base @VER@ + PySys_GetFile@Base @VER@ + PySys_GetObject@Base @VER@ + PySys_HasWarnOptions@Base @VER@ + PySys_ResetWarnOptions@Base @VER@ + PySys_SetArgv@Base @VER@ + PySys_SetArgvEx@Base @VER@ + PySys_SetObject@Base @VER@ + PySys_SetPath@Base @VER@ + PySys_WriteStderr@Base @VER@ + PySys_WriteStdout@Base @VER@ + (optional)PyTextIOBase_Type@Base @VER@ + (optional)PyTextIOWrapper_Type@Base @VER@ + PyThreadState_Clear@Base @VER@ + PyThreadState_Delete@Base @VER@ + PyThreadState_DeleteCurrent@Base @VER@ + PyThreadState_Get@Base @VER@ + PyThreadState_GetDict@Base @VER@ + PyThreadState_New@Base @VER@ + PyThreadState_Next@Base @VER@ + PyThreadState_SetAsyncExc@Base @VER@ + PyThreadState_Swap@Base @VER@ + PyThread_ReInitTLS@Base @VER@ + PyThread_acquire_lock@Base @VER@ + PyThread_allocate_lock@Base @VER@ + PyThread_create_key@Base @VER@ + PyThread_delete_key@Base @VER@ + PyThread_delete_key_value@Base @VER@ + PyThread_exit_thread@Base @VER@ + PyThread_free_lock@Base @VER@ + PyThread_get_key_value@Base @VER@ + PyThread_get_stacksize@Base @VER@ + PyThread_get_thread_ident@Base @VER@ + PyThread_init_thread@Base @VER@ + PyThread_release_lock@Base @VER@ + PyThread_set_key_value@Base @VER@ + PyThread_set_stacksize@Base @VER@ + PyThread_start_new_thread@Base @VER@ + PyToken_OneChar@Base @VER@ + PyToken_ThreeChars@Base @VER@ + PyToken_TwoChars@Base @VER@ + PyTokenizer_Free@Base @VER@ + PyTokenizer_FromFile@Base @VER@ + PyTokenizer_FromString@Base @VER@ + PyTokenizer_Get@Base @VER@ + PyTokenizer_RestoreEncoding@Base @VER@ + PyTraceBack_Here@Base @VER@ + PyTraceBack_Print@Base @VER@ + PyTraceBack_Type@Base @VER@ + PyTupleIter_Type@Base @VER@ + PyTuple_ClearFreeList@Base @VER@ + PyTuple_Fini@Base @VER@ + PyTuple_GetItem@Base @VER@ + PyTuple_GetSlice@Base @VER@ + PyTuple_New@Base @VER@ + PyTuple_Pack@Base @VER@ + PyTuple_SetItem@Base @VER@ + PyTuple_Size@Base @VER@ + PyTuple_Type@Base @VER@ + PyType_ClearCache@Base @VER@ + PyType_GenericAlloc@Base @VER@ + PyType_GenericNew@Base @VER@ + PyType_IsSubtype@Base @VER@ + PyType_Modified@Base @VER@ + PyType_Ready@Base @VER@ + PyType_Type@Base @VER@ + PyUnicodeDecodeError_Create@Base @VER@ + PyUnicodeDecodeError_GetEncoding@Base @VER@ + PyUnicodeDecodeError_GetEnd@Base @VER@ + PyUnicodeDecodeError_GetObject@Base @VER@ + PyUnicodeDecodeError_GetReason@Base @VER@ + PyUnicodeDecodeError_GetStart@Base @VER@ + PyUnicodeDecodeError_SetEnd@Base @VER@ + PyUnicodeDecodeError_SetReason@Base @VER@ + PyUnicodeDecodeError_SetStart@Base @VER@ + PyUnicodeEncodeError_Create@Base @VER@ + PyUnicodeEncodeError_GetEncoding@Base @VER@ + PyUnicodeEncodeError_GetEnd@Base @VER@ + PyUnicodeEncodeError_GetObject@Base @VER@ + PyUnicodeEncodeError_GetReason@Base @VER@ + PyUnicodeEncodeError_GetStart@Base @VER@ + PyUnicodeEncodeError_SetEnd@Base @VER@ + PyUnicodeEncodeError_SetReason@Base @VER@ + PyUnicodeEncodeError_SetStart@Base @VER@ + PyUnicodeTranslateError_Create@Base @VER@ + PyUnicodeTranslateError_GetEnd@Base @VER@ + PyUnicodeTranslateError_GetObject@Base @VER@ + PyUnicodeTranslateError_GetReason@Base @VER@ + PyUnicodeTranslateError_GetStart@Base @VER@ + PyUnicodeTranslateError_SetEnd@Base @VER@ + PyUnicodeTranslateError_SetReason@Base @VER@ + PyUnicodeTranslateError_SetStart@Base @VER@ + PyUnicodeUCS4_AsASCIIString@Base @VER@ + PyUnicodeUCS4_AsCharmapString@Base @VER@ + PyUnicodeUCS4_AsEncodedObject@Base @VER@ + PyUnicodeUCS4_AsEncodedString@Base @VER@ + PyUnicodeUCS4_AsLatin1String@Base @VER@ + PyUnicodeUCS4_AsRawUnicodeEscapeString@Base @VER@ + PyUnicodeUCS4_AsUTF16String@Base @VER@ + PyUnicodeUCS4_AsUTF32String@Base @VER@ + PyUnicodeUCS4_AsUTF8String@Base @VER@ + PyUnicodeUCS4_AsUnicode@Base @VER@ + PyUnicodeUCS4_AsUnicodeEscapeString@Base @VER@ + PyUnicodeUCS4_AsWideChar@Base @VER@ + PyUnicodeUCS4_ClearFreelist@Base @VER@ + PyUnicodeUCS4_Compare@Base @VER@ + PyUnicodeUCS4_Concat@Base @VER@ + PyUnicodeUCS4_Contains@Base @VER@ + PyUnicodeUCS4_Count@Base @VER@ + PyUnicodeUCS4_Decode@Base @VER@ + PyUnicodeUCS4_DecodeASCII@Base @VER@ + PyUnicodeUCS4_DecodeCharmap@Base @VER@ + PyUnicodeUCS4_DecodeLatin1@Base @VER@ + PyUnicodeUCS4_DecodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS4_DecodeUTF16@Base @VER@ + PyUnicodeUCS4_DecodeUTF16Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUTF32@Base @VER@ + PyUnicodeUCS4_DecodeUTF32Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUTF8@Base @VER@ + PyUnicodeUCS4_DecodeUTF8Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUnicodeEscape@Base @VER@ + PyUnicodeUCS4_Encode@Base @VER@ + PyUnicodeUCS4_EncodeASCII@Base @VER@ + PyUnicodeUCS4_EncodeCharmap@Base @VER@ + PyUnicodeUCS4_EncodeDecimal@Base @VER@ + PyUnicodeUCS4_EncodeLatin1@Base @VER@ + PyUnicodeUCS4_EncodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS4_EncodeUTF16@Base @VER@ + PyUnicodeUCS4_EncodeUTF32@Base @VER@ + PyUnicodeUCS4_EncodeUTF8@Base @VER@ + PyUnicodeUCS4_EncodeUnicodeEscape@Base @VER@ + PyUnicodeUCS4_Find@Base @VER@ + PyUnicodeUCS4_Format@Base @VER@ + PyUnicodeUCS4_FromEncodedObject@Base @VER@ + PyUnicodeUCS4_FromFormat@Base @VER@ + PyUnicodeUCS4_FromFormatV@Base @VER@ + PyUnicodeUCS4_FromObject@Base @VER@ + PyUnicodeUCS4_FromOrdinal@Base @VER@ + PyUnicodeUCS4_FromString@Base @VER@ + PyUnicodeUCS4_FromStringAndSize@Base @VER@ + PyUnicodeUCS4_FromUnicode@Base @VER@ + PyUnicodeUCS4_FromWideChar@Base @VER@ + PyUnicodeUCS4_GetDefaultEncoding@Base @VER@ + PyUnicodeUCS4_GetMax@Base @VER@ + PyUnicodeUCS4_GetSize@Base @VER@ + PyUnicodeUCS4_Join@Base @VER@ + PyUnicodeUCS4_Partition@Base @VER@ + PyUnicodeUCS4_RPartition@Base @VER@ + PyUnicodeUCS4_RSplit@Base @VER@ + PyUnicodeUCS4_Replace@Base @VER@ + PyUnicodeUCS4_Resize@Base @VER@ + PyUnicodeUCS4_RichCompare@Base @VER@ + PyUnicodeUCS4_SetDefaultEncoding@Base @VER@ + PyUnicodeUCS4_Split@Base @VER@ + PyUnicodeUCS4_Splitlines@Base @VER@ + PyUnicodeUCS4_Tailmatch@Base @VER@ + PyUnicodeUCS4_Translate@Base @VER@ + PyUnicodeUCS4_TranslateCharmap@Base @VER@ + PyUnicode_AsDecodedObject@Base @VER@ + PyUnicode_BuildEncodingMap@Base @VER@ + PyUnicode_DecodeUTF7@Base @VER@ + PyUnicode_DecodeUTF7Stateful@Base @VER@ + PyUnicode_EncodeUTF7@Base @VER@ + PyUnicode_Type@Base @VER@ + PyWeakref_GetObject@Base @VER@ + PyWeakref_NewProxy@Base @VER@ + PyWeakref_NewRef@Base @VER@ + PyWrapperDescr_Type@Base @VER@ + PyWrapper_New@Base @VER@ + Py_AddPendingCall@Base @VER@ + Py_AtExit@Base @VER@ + Py_BuildValue@Base @VER@ + Py_BytesWarningFlag@Base @VER@ + Py_CompileString@Base @VER@ + Py_CompileStringFlags@Base @VER@ + Py_DebugFlag@Base @VER@ + Py_DecRef@Base @VER@ + Py_DivisionWarningFlag@Base @VER@ + Py_DontWriteBytecodeFlag@Base @VER@ + Py_EndInterpreter@Base @VER@ + Py_Exit@Base @VER@ + Py_FatalError@Base @VER@ + Py_FdIsInteractive@Base @VER@ + Py_FileSystemDefaultEncoding@Base @VER@ + Py_Finalize@Base @VER@ + Py_FindMethod@Base @VER@ + Py_FindMethodInChain@Base @VER@ + Py_FlushLine@Base @VER@ + Py_FrozenFlag@Base @VER@ + Py_FrozenMain@Base @VER@ + Py_GetArgcArgv@Base @VER@ + Py_GetBuildInfo@Base @VER@ + Py_GetCompiler@Base @VER@ + Py_GetCopyright@Base @VER@ + Py_GetExecPrefix@Base @VER@ + Py_GetPath@Base @VER@ + Py_GetPlatform@Base @VER@ + Py_GetPrefix@Base @VER@ + Py_GetProgramFullPath@Base @VER@ + Py_GetProgramName@Base @VER@ + Py_GetPythonHome@Base @VER@ + Py_GetRecursionLimit@Base @VER@ + Py_GetVersion@Base @VER@ + Py_HashRandomizationFlag@Base @VER@ + Py_IgnoreEnvironmentFlag@Base @VER@ + Py_IncRef@Base @VER@ + Py_Initialize@Base @VER@ + Py_InitializeEx@Base @VER@ + Py_InspectFlag@Base @VER@ + Py_InteractiveFlag@Base @VER@ + Py_IsInitialized@Base @VER@ + Py_Main@Base @VER@ + Py_MakePendingCalls@Base @VER@ + Py_NewInterpreter@Base @VER@ + Py_NoSiteFlag@Base @VER@ + Py_NoUserSiteDirectory@Base @VER@ + Py_OptimizeFlag@Base @VER@ + Py_Py3kWarningFlag@Base @VER@ + Py_ReprEnter@Base @VER@ + Py_ReprLeave@Base @VER@ + Py_SetProgramName@Base @VER@ + Py_SetPythonHome@Base @VER@ + Py_SetRecursionLimit@Base @VER@ + Py_SubversionRevision@Base @VER@ + Py_SubversionShortBranch@Base @VER@ + Py_SymtableString@Base @VER@ + Py_TabcheckFlag@Base @VER@ + Py_UnicodeFlag@Base @VER@ + Py_UniversalNewlineFgets@Base @VER@ + Py_UniversalNewlineFread@Base @VER@ + Py_UseClassExceptionsFlag@Base @VER@ + Py_VaBuildValue@Base @VER@ + Py_VerboseFlag@Base @VER@ + Py_meta_grammar@Base @VER@ + Py_pgen@Base @VER@ + _PyArg_NoKeywords@Base @VER@ + _PyArg_ParseTupleAndKeywords_SizeT@Base @VER@ + _PyArg_ParseTuple_SizeT@Base @VER@ + _PyArg_Parse_SizeT@Base @VER@ + _PyArg_VaParseTupleAndKeywords_SizeT@Base @VER@ + _PyArg_VaParse_SizeT@Base @VER@ + _PyBuiltin_Init@Base @VER@ + _PyByteArray_empty_string@Base @VER@ + _PyBytes_FormatAdvanced@Base @VER@ + _PyCode_CheckLineNumber@Base @VER@ + _PyCodec_Lookup@Base @VER@ + _PyComplex_FormatAdvanced@Base @VER@ + _PyDict_Contains@Base @VER@ + _PyDict_MaybeUntrack@Base @VER@ + _PyDict_NewPresized@Base @VER@ + _PyDict_Next@Base @VER@ + _PyErr_BadInternalCall@Base @VER@ + _PyEval_CallTracing@Base @VER@ + _PyEval_SliceIndex@Base @VER@ + _PyExc_Fini@Base @VER@ + _PyExc_Init@Base @VER@ + (optional)_PyFileIO_closed@Base @VER@ + _PyFile_SanitizeMode@Base @VER@ + _PyFloat_FormatAdvanced@Base @VER@ + _PyFloat_Init@Base @VER@ + _PyFloat_Pack4@Base @VER@ + _PyFloat_Pack8@Base @VER@ + _PyFloat_Unpack4@Base @VER@ + _PyFloat_Unpack8@Base @VER@ + _PyFrame_Init@Base @VER@ + _PyGC_Dump@Base @VER@ + _PyGC_generation0@Base @VER@ + _PyGILState_Fini@Base @VER@ + _PyGILState_Init@Base @VER@ + (optional)_PyIOBase_check_closed@Base @VER@ + (optional)_PyIOBase_check_readable@Base @VER@ + (optional)_PyIOBase_check_seekable@Base @VER@ + (optional)_PyIOBase_check_writable@Base @VER@ + (optional)_PyIOBase_finalize@Base @VER@ + (optional)_PyIO_ConvertSsize_t@Base @VER@ + (optional)_PyIO_empty_bytes@Base @VER@ + (optional)_PyIO_empty_str@Base @VER@ + (optional)_PyIO_find_line_ending@Base @VER@ + (optional)_PyIO_locale_module@Base @VER@ + (optional)_PyIO_os_module@Base @VER@ + (optional)_PyIO_str_close@Base @VER@ + (optional)_PyIO_str_closed@Base @VER@ + (optional)_PyIO_str_decode@Base @VER@ + (optional)_PyIO_str_encode@Base @VER@ + (optional)_PyIO_str_fileno@Base @VER@ + (optional)_PyIO_str_flush@Base @VER@ + (optional)_PyIO_str_getstate@Base @VER@ + (optional)_PyIO_str_isatty@Base @VER@ + (optional)_PyIO_str_newlines@Base @VER@ + (optional)_PyIO_str_nl@Base @VER@ + (optional)_PyIO_str_read1@Base @VER@ + (optional)_PyIO_str_read@Base @VER@ + (optional)_PyIO_str_readable@Base @VER@ + (optional)_PyIO_str_readinto@Base @VER@ + (optional)_PyIO_str_readline@Base @VER@ + (optional)_PyIO_str_reset@Base @VER@ + (optional)_PyIO_str_seek@Base @VER@ + (optional)_PyIO_str_seekable@Base @VER@ + (optional)_PyIO_str_setstate@Base @VER@ + (optional)_PyIO_str_tell@Base @VER@ + (optional)_PyIO_str_truncate@Base @VER@ + (optional)_PyIO_str_writable@Base @VER@ + (optional)_PyIO_str_write@Base @VER@ + (optional)_PyIO_trap_eintr@Base @VER@ + (optional)_PyIO_unsupported_operation@Base @VER@ + (optional)_PyIO_zero@Base @VER@ + _PyImportHooks_Init@Base @VER@ + _PyImport_AcquireLock@Base @VER@ + _PyImport_DynLoadFiletab@Base @VER@ + _PyImport_Filetab@Base @VER@ + _PyImport_FindExtension@Base @VER@ + _PyImport_FindModule@Base @VER@ + _PyImport_Fini@Base @VER@ + _PyImport_FixupExtension@Base @VER@ + _PyImport_GetDynLoadFunc@Base @VER@ + _PyImport_Init@Base @VER@ + _PyImport_Inittab@Base @VER@ + _PyImport_IsScript@Base @VER@ + _PyImport_LoadDynamicModule@Base @VER@ + _PyImport_ReleaseLock@Base @VER@ + _PyImport_ReInitLock@Base @VER@ + (optional)_PyIncrementalNewlineDecoder_decode@Base @VER@ + _PyInstance_Lookup@Base @VER@ + _PyInt_AsInt@Base @VER@ + _PyInt_Format@Base @VER@ + _PyInt_FormatAdvanced@Base @VER@ + _PyInt_FromGid@Base @VER@ + _PyInt_FromUid@Base @VER@ + _PyInt_Init@Base @VER@ + _PyList_Extend@Base @VER@ + _PyLong_AsByteArray@Base @VER@ + _PyLong_AsInt@Base @VER@ + _PyLong_Copy@Base @VER@ + _PyLong_DigitValue@Base @VER@ + _PyLong_Format@Base @VER@ + _PyLong_FormatAdvanced@Base @VER@ + _PyLong_Frexp@Base @VER@ + _PyLong_FromByteArray@Base @VER@ + _PyLong_Init@Base @VER@ + _PyLong_New@Base @VER@ + _PyLong_NumBits@Base @VER@ + _PyLong_Sign@Base @VER@ + _PyModule_Clear@Base @VER@ + _PyNode_SizeOf@Base @VER@ + _PyNumber_ConvertIntegralToInt@Base @VER@ + _PyOS_GetOpt@Base @VER@ + _PyOS_ReadlineTState@Base @VER@ + _PyOS_ResetGetOpt@Base @VER@ + _PyOS_URandom@Base @VER@ + _PyOS_ascii_formatd@Base @VER@ + _PyOS_ascii_strtod@Base @VER@ + _PyOS_mystrnicmp_hack@Base @VER@ + _PyOS_optarg@Base @VER@ + _PyOS_opterr@Base @VER@ + _PyOS_optind@Base @VER@ + _PyObject_CallFunction_SizeT@Base @VER@ + _PyObject_CallMethod_SizeT@Base @VER@ + _PyObject_Del@Base @VER@ + _PyObject_Dump@Base @VER@ + _PyObject_GC_Del@Base @VER@ + _PyObject_GC_Malloc@Base @VER@ + _PyObject_GC_New@Base @VER@ + _PyObject_GC_NewVar@Base @VER@ + _PyObject_GC_Resize@Base @VER@ + _PyObject_GC_Track@Base @VER@ + _PyObject_GC_UnTrack@Base @VER@ + _PyObject_GenericGetAttrWithDict@Base @VER@ + _PyObject_GenericSetAttrWithDict@Base @VER@ + _PyObject_GetDictPtr@Base @VER@ + _PyObject_LengthHint@Base @VER@ + _PyObject_LookupSpecial@Base @VER@ + _PyObject_New@Base @VER@ + _PyObject_NewVar@Base @VER@ + _PyObject_NextNotImplemented@Base @VER@ + _PyObject_RealIsInstance@Base @VER@ + _PyObject_RealIsSubclass@Base @VER@ + _PyObject_SlotCompare@Base @VER@ + _PyObject_Str@Base @VER@ + _PyParser_Grammar@Base @VER@ + _PyParser_TokenNames@Base @VER@ + _PyRandom_Init@Base @VER@ + _PySequence_IterSearch@Base @VER@ + _PySet_Next@Base @VER@ + _PySet_NextEntry@Base @VER@ + _PySet_Update@Base @VER@ + _PySlice_FromIndices@Base @VER@ + _PyString_Eq@Base @VER@ + _PyString_FormatLong@Base @VER@ + _PyString_InsertThousandsGrouping@Base @VER@ + _PyString_Join@Base @VER@ + _PyString_Resize@Base @VER@ + _PySys_Init@Base @VER@ + _PyThreadState_Current@Base @VER@ + _PyThreadState_GetFrame@Base @VER@ + _PyThreadState_Init@Base @VER@ + _PyThreadState_Prealloc@Base @VER@ + _PyThread_CurrentFrames@Base @VER@ + _PyTime_DoubleToTimet@Base @VER@ + _PyTime_FloatTime@Base @VER@ + _PyTrash_delete_later@Base @VER@ + _PyTrash_delete_nesting@Base @VER@ + _PyTrash_deposit_object@Base @VER@ + _PyTrash_destroy_chain@Base @VER@ + _PyTrash_thread_deposit_object@Base @VER@ + _PyTrash_thread_destroy_chain@Base @VER@ + _PyTuple_MaybeUntrack@Base @VER@ + _PyTuple_Resize@Base @VER@ + _PyType_Lookup@Base @VER@ + _PyUnicodeUCS4_AsDefaultEncodedString@Base @VER@ + _PyUnicodeUCS4_Fini@Base @VER@ + _PyUnicodeUCS4_Init@Base @VER@ + _PyUnicodeUCS4_IsAlpha@Base @VER@ + _PyUnicodeUCS4_IsDecimalDigit@Base @VER@ + _PyUnicodeUCS4_IsDigit@Base @VER@ + _PyUnicodeUCS4_IsLinebreak@Base @VER@ + _PyUnicodeUCS4_IsLowercase@Base @VER@ + _PyUnicodeUCS4_IsNumeric@Base @VER@ + _PyUnicodeUCS4_IsTitlecase@Base @VER@ + _PyUnicodeUCS4_IsUppercase@Base @VER@ + _PyUnicodeUCS4_IsWhitespace@Base @VER@ + _PyUnicodeUCS4_ToDecimalDigit@Base @VER@ + _PyUnicodeUCS4_ToDigit@Base @VER@ + _PyUnicodeUCS4_ToLowercase@Base @VER@ + _PyUnicodeUCS4_ToNumeric@Base @VER@ + _PyUnicodeUCS4_ToTitlecase@Base @VER@ + _PyUnicodeUCS4_ToUppercase@Base @VER@ + _PyUnicode_BidirectionalNames@Base @VER@ + _PyUnicode_CategoryNames@Base @VER@ + _PyUnicode_Database_Records@Base @VER@ + _PyUnicode_DecodeUnicodeInternal@Base @VER@ + _PyUnicode_EastAsianWidthNames@Base @VER@ + _PyUnicode_FormatAdvanced@Base @VER@ + _PyUnicode_TypeRecords@Base @VER@ + _PyUnicode_XStrip@Base @VER@ + _PyWarnings_Init@Base @VER@ + _PyWeakref_CallableProxyType@Base @VER@ + _PyWeakref_ClearRef@Base @VER@ + _PyWeakref_GetWeakrefCount@Base @VER@ + _PyWeakref_ProxyType@Base @VER@ + _PyWeakref_RefType@Base @VER@ + _Py_Assert@Base @VER@ + _Py_Assign@Base @VER@ + _Py_Attribute@Base @VER@ + _Py_AugAssign@Base @VER@ + _Py_BinOp@Base @VER@ + _Py_BoolOp@Base @VER@ + _Py_Break@Base @VER@ + _Py_BuildValue_SizeT@Base @VER@ + _Py_Call@Base @VER@ + _Py_CheckInterval@Base @VER@ + _Py_CheckRecursionLimit@Base @VER@ + _Py_CheckRecursiveCall@Base @VER@ + _Py_ClassDef@Base @VER@ + _Py_Compare@Base @VER@ + _Py_Continue@Base @VER@ + _Py_Delete@Base @VER@ + _Py_Dict@Base @VER@ + _Py_DictComp@Base @VER@ + _Py_DisplaySourceLine@Base @VER@ + _Py_Ellipsis@Base @VER@ + _Py_EllipsisObject@Base @VER@ + _Py_ExceptHandler@Base @VER@ + _Py_Exec@Base @VER@ + _Py_Expr@Base @VER@ + _Py_Expression@Base @VER@ + _Py_ExtSlice@Base @VER@ + _Py_For@Base @VER@ + _Py_FunctionDef@Base @VER@ + _Py_GeneratorExp@Base @VER@ + _Py_Gid_Converter@Base @VER@ + _Py_Global@Base @VER@ + _Py_HashDouble@Base @VER@ + _Py_HashPointer@Base @VER@ + _Py_HashSecret@Base @VER@ + _Py_If@Base @VER@ + _Py_IfExp@Base @VER@ + _Py_Import@Base @VER@ + _Py_ImportFrom@Base @VER@ + _Py_Index@Base @VER@ + _Py_InsertThousandsGroupingLocale@Base @VER@ + _Py_Interactive@Base @VER@ + _Py_Lambda@Base @VER@ + _Py_List@Base @VER@ + _Py_ListComp@Base @VER@ + _Py_Mangle@Base @VER@ + _Py_Module@Base @VER@ + _Py_Name@Base @VER@ + _Py_NoneStruct@Base @VER@ + _Py_NotImplementedStruct@Base @VER@ + _Py_Num@Base @VER@ + _Py_PackageContext@Base @VER@ + _Py_Pass@Base @VER@ + _Py_Print@Base @VER@ + _Py_QnewFlag@Base @VER@ + _Py_Raise@Base @VER@ + _Py_ReadyTypes@Base @VER@ + _Py_ReleaseInternedStrings@Base @VER@ + _Py_Repr@Base @VER@ + _Py_Return@Base @VER@ + _Py_Set@Base @VER@ + _Py_SetComp@Base @VER@ + _Py_Slice@Base @VER@ + _Py_Str@Base @VER@ + _Py_Subscript@Base @VER@ + _Py_Suite@Base @VER@ + _Py_SwappedOp@Base @VER@ + _Py_Ticker@Base @VER@ + _Py_TrueStruct@Base @VER@ + _Py_TryExcept@Base @VER@ + _Py_TryFinally@Base @VER@ + _Py_Tuple@Base @VER@ + _Py_Uid_Converter@Base @VER@ + _Py_UnaryOp@Base @VER@ + _Py_VaBuildValue_SizeT@Base @VER@ + _Py_While@Base @VER@ + _Py_With@Base @VER@ + _Py_Yield@Base @VER@ + _Py_ZeroStruct@Base @VER@ + _Py_abstract_hack@Base @VER@ + _Py_add_one_to_index_C@Base @VER@ + _Py_add_one_to_index_F@Base @VER@ + (optional)_Py_acosh@Base @VER@ + _Py_addarc@Base @VER@ + _Py_addbit@Base @VER@ + _Py_adddfa@Base @VER@ + _Py_addfirstsets@Base @VER@ + _Py_addlabel@Base @VER@ + _Py_addstate@Base @VER@ + _Py_alias@Base @VER@ + _Py_arguments@Base @VER@ + _Py_ascii_whitespace@Base @VER@ + (optional)_Py_asinh@Base @VER@ + (optional)_Py_atanh@Base @VER@ + _Py_bytes_capitalize@Base @VER@ + _Py_bytes_isalnum@Base @VER@ + _Py_bytes_isalpha@Base @VER@ + _Py_bytes_isdigit@Base @VER@ + _Py_bytes_islower@Base @VER@ + _Py_bytes_isspace@Base @VER@ + _Py_bytes_istitle@Base @VER@ + _Py_bytes_isupper@Base @VER@ + _Py_bytes_lower@Base @VER@ + _Py_bytes_swapcase@Base @VER@ + _Py_bytes_title@Base @VER@ + _Py_bytes_upper@Base @VER@ + _Py_c_abs@Base @VER@ + _Py_c_diff@Base @VER@ + _Py_c_neg@Base @VER@ + _Py_c_pow@Base @VER@ + _Py_c_prod@Base @VER@ + _Py_c_quot@Base @VER@ + _Py_c_sum@Base @VER@ + _Py_capitalize__doc__@Base @VER@ + _Py_capsule_hack@Base @VER@ + _Py_cobject_hack@Base @VER@ + _Py_comprehension@Base @VER@ + _Py_ctype_table@Base @VER@ + _Py_ctype_tolower@Base @VER@ + _Py_ctype_toupper@Base @VER@ + _Py_delbitset@Base @VER@ + (arch=!m68k)_Py_dg_dtoa@Base @VER@ + (arch=!m68k)_Py_dg_freedtoa@Base @VER@ + (arch=!m68k)_Py_dg_strtod@Base @VER@ + _Py_double_round@Base @VER@ + (optional)_Py_expm1@Base @VER@ + _Py_findlabel@Base @VER@ + (arch=i386 lpia m68k)_Py_force_double@Base @VER@ + (arch=amd64 i386 lpia)_Py_get_387controlword@Base @VER@ + _Py_hgidentifier@Base 2.7.1 + _Py_hgversion@Base 2.7.1 + _Py_isalnum__doc__@Base @VER@ + _Py_isalpha__doc__@Base @VER@ + _Py_isdigit__doc__@Base @VER@ + _Py_islower__doc__@Base @VER@ + _Py_isspace__doc__@Base @VER@ + _Py_istitle__doc__@Base @VER@ + _Py_isupper__doc__@Base @VER@ + _Py_keyword@Base @VER@ + (optional)_Py_log1p@Base @VER@ + _Py_lower__doc__@Base @VER@ + _Py_mergebitset@Base @VER@ + _Py_meta_grammar@Base @VER@ + _Py_newbitset@Base @VER@ + _Py_newgrammar@Base @VER@ + (optional)_Py_parse_inf_or_nan@Base @VER@ + _Py_pgen@Base @VER@ + _Py_samebitset@Base @VER@ + (arch=amd64 i386 lpia)_Py_set_387controlword@Base @VER@ + _Py_svnversion@Base @VER@ + _Py_swapcase__doc__@Base @VER@ + _Py_title__doc__@Base @VER@ + _Py_translatelabels@Base @VER@ + _Py_upper__doc__@Base @VER@ + + PyFPE_counter@Base @VER@ + PyFPE_dummy@Base @VER@ + PyFPE_jbuf@Base @VER@ + + asdl_int_seq_new@Base @VER@ + asdl_seq_new@Base @VER@ + +# don't check for the following symbols, found in extensions +# which either can be built as builtin or extension. + + (optional)fast_save_leave@Base @VER@ + (optional)partial_reduce@Base @VER@ + (optional)partial_setstate@Base @VER@ + + (optional)md5_append@Base @VER@ + (optional)md5_finish@Base @VER@ + (optional)md5_init@Base @VER@ + +# _check_for_multiple_distdirs@Base @VER@ + (optional)init_ast@Base @VER@ + (optional)init_bisect@Base @VER@ + (optional)init_codecs@Base @VER@ + (optional)init_collections@Base @VER@ + (optional)init_functools@Base @VER@ + (optional)init_hashlib@Base @VER@ + (optional)init_heapq@Base @VER@ + (optional)init_io@Base @VER@ + (optional)init_locale@Base @VER@ + (optional)init_md5@Base @VER@ + (optional)init_random@Base @VER@ + (optional)init_sha@Base @VER@ + (optional)init_sha256@Base @VER@ + (optional)init_sha512@Base @VER@ + (optional)init_socket@Base @VER@ + (optional)init_sockobject@Base @VER@ + (optional)init_sre@Base @VER@ + (optional)init_ssl@Base @VER@ + (optional)init_struct@Base @VER@ + (optional)init_symtable@Base @VER@ + (optional)init_weakref@Base @VER@ + (optional)initarray@Base @VER@ + (optional)initbinascii@Base @VER@ + (optional)initcPickle@Base @VER@ + (optional)initcStringIO@Base @VER@ + (optional)initcmath@Base @VER@ + (optional)initerrno@Base @VER@ + (optional)initfcntl@Base @VER@ + (optional)initgc@Base @VER@ + (optional)initgrp@Base @VER@ + (optional)initimp@Base @VER@ + (optional)inititertools@Base @VER@ + (optional)initmath@Base @VER@ + (optional)initoperator@Base @VER@ + (optional)initposix@Base @VER@ + (optional)initpwd@Base @VER@ + (optional)initselect@Base @VER@ + (optional)initsignal@Base @VER@ + (optional)initspwd@Base @VER@ + (optional)initstrop@Base @VER@ + (optional)initsyslog@Base @VER@ + (optional)initthread@Base @VER@ + (optional)inittime@Base @VER@ + (optional)initunicodedata@Base @VER@ + (optional)initxxsubtype@Base @VER@ + (optional)initzipimport@Base @VER@ + (optional)initzlib@Base @VER@ --- python2.7-2.7.6.orig/debian/locale-gen +++ python2.7-2.7.6/debian/locale-gen @@ -0,0 +1,31 @@ +#!/bin/sh + +LOCPATH=`pwd`/locales +export LOCPATH + +[ -d $LOCPATH ] || mkdir -p $LOCPATH + +umask 022 + +echo "Generating locales..." +while read locale charset; do + case $locale in \#*) continue;; esac + [ -n "$locale" -a -n "$charset" ] || continue + echo -n " `echo $locale | sed 's/\([^.\@]*\).*/\1/'`" + echo -n ".$charset" + echo -n `echo $locale | sed 's/\([^\@]*\)\(\@.*\)*/\2/'` + echo -n '...' + if [ -f $LOCPATH/$locale ]; then + input=$locale + else + input=`echo $locale | sed 's/\([^.]*\)[^@]*\(.*\)/\1\2/'` + fi + localedef -i $input -c -f $charset $LOCPATH/$locale #-A /etc/locale.alias + echo ' done'; \ +done < +# elif defined(__x86_64__) && defined(__ILP32__) +# include +# elif defined(__i386__) +# include +# elif defined(__aarch64__) && defined(__AARCH64EL__) +# include +# elif defined(__alpha__) +# include +# elif defined(__ARM_EABI__) && defined(__ARM_PCS_VFP) +# include +# elif defined(__ARM_EABI__) && !defined(__ARM_PCS_VFP) +# include +# elif defined(__hppa__) +# include +# elif defined(__ia64__) +# include +# elif defined(__m68k__) && !defined(__mcoldfire__) +# include +# elif defined(__mips_hard_float) && defined(_MIPSEL) +# if _MIPS_SIM == _ABIO32 +# include +# elif _MIPS_SIM == _ABIN32 +# include +# elif _MIPS_SIM == _ABI64 +# include +# else +# error unknown multiarch location for @header@ +# endif +# elif defined(__mips_hard_float) +# if _MIPS_SIM == _ABIO32 +# include +# elif _MIPS_SIM == _ABIN32 +# include +# elif _MIPS_SIM == _ABI64 +# include +# else +# error unknown multiarch location for @header@ +# endif +# elif defined(__or1k__) +# include +# elif defined(__powerpc__) && defined(__SPE__) +# include +# elif defined(__powerpc64__) +# if defined(__LITTLE_ENDIAN__) +# include +# else +# include +# endif +# elif defined(__powerpc__) +# include +# elif defined(__s390x__) +# include +# elif defined(__s390__) +# include +# elif defined(__sh__) && defined(__LITTLE_ENDIAN__) +# include +# elif defined(__sparc__) && defined(__arch64__) +# include +# elif defined(__sparc__) +# include +# else +# error unknown multiarch location for @header@ +# endif +#elif defined(__FreeBSD_kernel__) +# if defined(__LP64__) +# include +# elif defined(__i386__) +# include +# else +# error unknown multiarch location for @header@ +# endif +#elif defined(__gnu_hurd__) +# include +#else +# error unknown multiarch location for @header@ +#endif --- python2.7-2.7.6.orig/debian/patches/CVE-2013-1752-httplib-2.patch +++ python2.7-2.7.6/debian/patches/CVE-2013-1752-httplib-2.patch @@ -0,0 +1,53 @@ + +# HG changeset patch +# User Berker Peksag +# Date 1407212157 -10800 +# Node ID 5e310c6a8520603bca8bc4b40eaf4f074db47c0d +# Parent 46c7a724b487295257423a69478392cb01ce74e6 +Issue #16037: HTTPMessage.readheaders() raises an HTTPException when more +than 100 headers are read. + +Patch by Jyrki Pulliainen and Daniel Eriksson. + +Index: python2.7-2.7.6/Lib/httplib.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/httplib.py 2015-06-18 13:18:10.073292537 -0400 ++++ python2.7-2.7.6/Lib/httplib.py 2015-06-18 13:18:10.073292537 -0400 +@@ -215,6 +215,10 @@ + # maximal line length when calling readline(). + _MAXLINE = 65536 + ++# maximum amount of headers accepted ++_MAXHEADERS = 100 ++ ++ + class HTTPMessage(mimetools.Message): + + def addheader(self, key, value): +@@ -271,6 +275,8 @@ + elif self.seekable: + tell = self.fp.tell + while True: ++ if len(hlist) > _MAXHEADERS: ++ raise HTTPException("got more than %d headers" % _MAXHEADERS) + if tell: + try: + startofline = tell() +Index: python2.7-2.7.6/Lib/test/test_httplib.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/test/test_httplib.py 2015-06-18 13:18:10.073292537 -0400 ++++ python2.7-2.7.6/Lib/test/test_httplib.py 2015-06-18 13:18:10.073292537 -0400 +@@ -257,6 +257,13 @@ + if resp.read() != "": + self.fail("Did not expect response from HEAD request") + ++ def test_too_many_headers(self): ++ headers = '\r\n'.join('Header%d: foo' % i for i in xrange(200)) + '\r\n' ++ text = ('HTTP/1.1 200 OK\r\n' + headers) ++ s = FakeSocket(text) ++ r = httplib.HTTPResponse(s) ++ self.assertRaises(httplib.HTTPException, r.begin) ++ + def test_send_file(self): + expected = 'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \ + 'Accept-Encoding: identity\r\nContent-Length:' --- python2.7-2.7.6.orig/debian/patches/CVE-2013-1752-poplib.patch +++ python2.7-2.7.6/debian/patches/CVE-2013-1752-poplib.patch @@ -0,0 +1,60 @@ + +# HG changeset patch +# User Benjamin Peterson +# Date 1417827758 18000 +# Node ID 339f877cca115c1901f5dd93d7bc066031d2a669 +# Parent 54af094087953f4997a4ead63e949d845c4b4412 +in poplib, limit maximum line length that we read from the network (closes #16041) + +Patch from Berker Peksag. + +diff --git a/Lib/poplib.py b/Lib/poplib.py +--- a/Lib/poplib.py ++++ b/Lib/poplib.py +@@ -32,6 +32,12 @@ CR = '\r' + LF = '\n' + CRLF = CR+LF + ++# maximal line length when calling readline(). This is to prevent ++# reading arbitrary length lines. RFC 1939 limits POP3 line length to ++# 512 characters, including CRLF. We have selected 2048 just to be on ++# the safe side. ++_MAXLINE = 2048 ++ + + class POP3: + +@@ -103,7 +109,9 @@ class POP3: + # Raise error_proto('-ERR EOF') if the connection is closed. + + def _getline(self): +- line = self.file.readline() ++ line = self.file.readline(_MAXLINE + 1) ++ if len(line) > _MAXLINE: ++ raise error_proto('line too long') + if self._debugging > 1: print '*get*', repr(line) + if not line: raise error_proto('-ERR EOF') + octets = len(line) +@@ -365,6 +373,8 @@ else: + match = renewline.match(self.buffer) + while not match: + self._fillBuffer() ++ if len(self.buffer) > _MAXLINE: ++ raise error_proto('line too long') + match = renewline.match(self.buffer) + line = match.group(0) + self.buffer = renewline.sub('' ,self.buffer, 1) +diff --git a/Lib/test/test_poplib.py b/Lib/test/test_poplib.py +--- a/Lib/test/test_poplib.py ++++ b/Lib/test/test_poplib.py +@@ -198,6 +198,10 @@ class TestPOP3Class(TestCase): + 113) + self.assertEqual(self.client.retr('foo'), expected) + ++ def test_too_long_lines(self): ++ self.assertRaises(poplib.error_proto, self.client._shortcmd, ++ 'echo +%s' % ((poplib._MAXLINE + 10) * 'a')) ++ + def test_dele(self): + self.assertOK(self.client.dele('foo')) + --- python2.7-2.7.6.orig/debian/patches/CVE-2013-1752-smtplib.patch +++ python2.7-2.7.6/debian/patches/CVE-2013-1752-smtplib.patch @@ -0,0 +1,102 @@ + +# HG changeset patch +# User Benjamin Peterson +# Date 1417827918 18000 +# Node ID 923aac88a3cc76a95d5a04d9d3ece245147a8064 +# Parent 339f877cca115c1901f5dd93d7bc066031d2a669 +smtplib: limit amount read from the network (closes #16042) + +Index: python2.7-2.7.6/Lib/smtplib.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/smtplib.py 2015-06-18 13:21:01.279158672 -0400 ++++ python2.7-2.7.6/Lib/smtplib.py 2015-06-18 13:21:01.275158628 -0400 +@@ -57,6 +57,7 @@ + SMTP_PORT = 25 + SMTP_SSL_PORT = 465 + CRLF = "\r\n" ++_MAXLINE = 8192 # more than 8 times larger than RFC 821, 4.5.3 + + OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I) + +@@ -179,10 +180,14 @@ + def __init__(self, sslobj): + self.sslobj = sslobj + +- def readline(self): ++ def readline(self, size=-1): ++ if size < 0: ++ size = None + str = "" + chr = None + while chr != "\n": ++ if size is not None and len(str) >= size: ++ break + chr = self.sslobj.read(1) + if not chr: + break +@@ -353,7 +358,7 @@ + self.file = self.sock.makefile('rb') + while 1: + try: +- line = self.file.readline() ++ line = self.file.readline(_MAXLINE + 1) + except socket.error as e: + self.close() + raise SMTPServerDisconnected("Connection unexpectedly closed: " +@@ -363,6 +368,8 @@ + raise SMTPServerDisconnected("Connection unexpectedly closed") + if self.debuglevel > 0: + print>>stderr, 'reply:', repr(line) ++ if len(line) > _MAXLINE: ++ raise SMTPResponseException(500, "Line too long.") + resp.append(line[4:].strip()) + code = line[:3] + # Check that the error code is syntactically correct. +Index: python2.7-2.7.6/Lib/test/test_smtplib.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/test/test_smtplib.py 2015-06-18 13:21:01.279158672 -0400 ++++ python2.7-2.7.6/Lib/test/test_smtplib.py 2015-06-18 13:21:01.275158628 -0400 +@@ -292,6 +292,33 @@ + HOST, self.port, 'localhost', 3) + + ++@unittest.skipUnless(threading, 'Threading required for this test.') ++class TooLongLineTests(unittest.TestCase): ++ respdata = '250 OK' + ('.' * smtplib._MAXLINE * 2) + '\n' ++ ++ def setUp(self): ++ self.old_stdout = sys.stdout ++ self.output = StringIO.StringIO() ++ sys.stdout = self.output ++ ++ self.evt = threading.Event() ++ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ++ self.sock.settimeout(15) ++ self.port = test_support.bind_port(self.sock) ++ servargs = (self.evt, self.respdata, self.sock) ++ threading.Thread(target=server, args=servargs).start() ++ self.evt.wait() ++ self.evt.clear() ++ ++ def tearDown(self): ++ self.evt.wait() ++ sys.stdout = self.old_stdout ++ ++ def testLineTooLong(self): ++ self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP, ++ HOST, self.port, 'localhost', 3) ++ ++ + sim_users = {'Mr.A@somewhere.com':'John A', + 'Ms.B@somewhere.com':'Sally B', + 'Mrs.C@somewhereesle.com':'Ruth C', +@@ -511,7 +538,8 @@ + def test_main(verbose=None): + test_support.run_unittest(GeneralTests, DebuggingServerTests, + NonConnectingTests, +- BadHELOServerTests, SMTPSimTests) ++ BadHELOServerTests, SMTPSimTests, ++ TooLongLineTests) + + if __name__ == '__main__': + test_main() --- python2.7-2.7.6.orig/debian/patches/CVE-2013-1753.patch +++ python2.7-2.7.6/debian/patches/CVE-2013-1753.patch @@ -0,0 +1,88 @@ + +# HG changeset patch +# User Benjamin Peterson +# Date 1417828515 18000 +# Node ID d50096708b2d701937e78f525446d729fc28db88 +# Parent 923aac88a3cc76a95d5a04d9d3ece245147a8064 +add a default limit for the amount of data xmlrpclib.gzip_decode will return (closes #16043) + +diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py +--- a/Lib/test/test_xmlrpc.py ++++ b/Lib/test/test_xmlrpc.py +@@ -737,7 +737,7 @@ class GzipServerTestCase(BaseServerTestC + with cm: + p.pow(6, 8) + +- def test_gsip_response(self): ++ def test_gzip_response(self): + t = self.Transport() + p = xmlrpclib.ServerProxy(URL, transport=t) + old = self.requestHandler.encode_threshold +@@ -750,6 +750,23 @@ class GzipServerTestCase(BaseServerTestC + self.requestHandler.encode_threshold = old + self.assertTrue(a>b) + ++ def test_gzip_decode_limit(self): ++ max_gzip_decode = 20 * 1024 * 1024 ++ data = '\0' * max_gzip_decode ++ encoded = xmlrpclib.gzip_encode(data) ++ decoded = xmlrpclib.gzip_decode(encoded) ++ self.assertEqual(len(decoded), max_gzip_decode) ++ ++ data = '\0' * (max_gzip_decode + 1) ++ encoded = xmlrpclib.gzip_encode(data) ++ ++ with self.assertRaisesRegexp(ValueError, ++ "max gzipped payload length exceeded"): ++ xmlrpclib.gzip_decode(encoded) ++ ++ xmlrpclib.gzip_decode(encoded, max_decode=-1) ++ ++ + #Test special attributes of the ServerProxy object + class ServerProxyTestCase(unittest.TestCase): + def setUp(self): +diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py +--- a/Lib/xmlrpclib.py ++++ b/Lib/xmlrpclib.py +@@ -49,6 +49,7 @@ + # 2003-07-12 gp Correct marshalling of Faults + # 2003-10-31 mvl Add multicall support + # 2004-08-20 mvl Bump minimum supported Python version to 2.1 ++# 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability + # + # Copyright (c) 1999-2002 by Secret Labs AB. + # Copyright (c) 1999-2002 by Fredrik Lundh. +@@ -1165,10 +1166,13 @@ def gzip_encode(data): + # in the HTTP header, as described in RFC 1952 + # + # @param data The encoded data ++# @keyparam max_decode Maximum bytes to decode (20MB default), use negative ++# values for unlimited decoding + # @return the unencoded data + # @raises ValueError if data is not correctly coded. ++# @raises ValueError if max gzipped payload length exceeded + +-def gzip_decode(data): ++def gzip_decode(data, max_decode=20971520): + """gzip encoded data -> unencoded data + + Decode data using the gzip content encoding as described in RFC 1952 +@@ -1178,11 +1182,16 @@ def gzip_decode(data): + f = StringIO.StringIO(data) + gzf = gzip.GzipFile(mode="rb", fileobj=f) + try: +- decoded = gzf.read() ++ if max_decode < 0: # no limit ++ decoded = gzf.read() ++ else: ++ decoded = gzf.read(max_decode + 1) + except IOError: + raise ValueError("invalid data") + f.close() + gzf.close() ++ if max_decode >= 0 and len(decoded) > max_decode: ++ raise ValueError("max gzipped payload length exceeded") + return decoded + + ## --- python2.7-2.7.6.orig/debian/patches/CVE-2014-4616.patch +++ python2.7-2.7.6/debian/patches/CVE-2014-4616.patch @@ -0,0 +1,48 @@ +Description: fix arbitrary memory read via idx argument +Origin: upstream, https://hg.python.org/cpython/rev/50c07ed1743d +Origin: upstream, https://hg.python.org/cpython/rev/4bd1fb0f4f44 +Origin: upstream, https://hg.python.org/cpython/rev/c7b93519807a +Bug: http://bugs.python.org/issue21529 + +Index: python2.7-2.7.6/Lib/json/tests/test_decode.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/json/tests/test_decode.py 2013-11-10 02:36:40.000000000 -0500 ++++ python2.7-2.7.6/Lib/json/tests/test_decode.py 2015-06-18 13:21:50.411694909 -0400 +@@ -60,5 +60,10 @@ + msg = 'escape' + self.assertRaisesRegexp(ValueError, msg, self.loads, s) + ++ def test_negative_index(self): ++ d = self.json.JSONDecoder() ++ self.assertRaises(ValueError, d.raw_decode, 'a'*42, -50000) ++ self.assertRaises(ValueError, d.raw_decode, u'a'*42, -50000) ++ + class TestPyDecode(TestDecode, PyTest): pass + class TestCDecode(TestDecode, CTest): pass +Index: python2.7-2.7.6/Modules/_json.c +=================================================================== +--- python2.7-2.7.6.orig/Modules/_json.c 2015-06-18 13:20:43.406963689 -0400 ++++ python2.7-2.7.6/Modules/_json.c 2015-06-18 13:21:57.575773124 -0400 +@@ -1468,7 +1468,10 @@ + PyObject *res; + char *str = PyString_AS_STRING(pystr); + Py_ssize_t length = PyString_GET_SIZE(pystr); +- if (idx >= length) { ++ if (idx < 0) ++ /* Compatibility with the Python version. */ ++ idx += length; ++ if (idx < 0 || idx >= length) { + PyErr_SetNone(PyExc_StopIteration); + return NULL; + } +@@ -1555,6 +1558,10 @@ + PyObject *res; + Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr); + Py_ssize_t length = PyUnicode_GET_SIZE(pystr); ++ if (idx < 0) { ++ PyErr_SetString(PyExc_ValueError, "idx cannot be negative"); ++ return NULL; ++ } + if (idx >= length) { + PyErr_SetNone(PyExc_StopIteration); + return NULL; --- python2.7-2.7.6.orig/debian/patches/CVE-2014-4650.patch +++ python2.7-2.7.6/debian/patches/CVE-2014-4650.patch @@ -0,0 +1,37 @@ + +# HG changeset patch +# User Benjamin Peterson +# Date 1402796189 25200 +# Node ID b4bab078876811c7d95231d08aa6fa7142fdda66 +# Parent bb8b0c7fefd0c5ed99b3f336178a4f9554a1d0ef +url unquote the path before checking if it refers to a CGI script (closes #21766) + +Index: python2.7-2.7.6/Lib/CGIHTTPServer.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/CGIHTTPServer.py 2015-06-18 13:27:07.803166094 -0400 ++++ python2.7-2.7.6/Lib/CGIHTTPServer.py 2015-06-18 13:27:07.799166050 -0400 +@@ -84,7 +84,7 @@ + path begins with one of the strings in self.cgi_directories + (and the next character is a '/' or the end of the string). + """ +- collapsed_path = _url_collapse_path(self.path) ++ collapsed_path = _url_collapse_path(urllib.unquote(self.path)) + dir_sep = collapsed_path.find('/', 1) + head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:] + if head in self.cgi_directories: +Index: python2.7-2.7.6/Lib/test/test_httpservers.py +=================================================================== +--- python2.7-2.7.6.orig/Lib/test/test_httpservers.py 2015-06-18 13:27:07.803166094 -0400 ++++ python2.7-2.7.6/Lib/test/test_httpservers.py 2015-06-18 13:27:07.799166050 -0400 +@@ -511,6 +511,11 @@ + (res.read(), res.getheader('Content-type'), res.status)) + self.assertEqual(os.environ['SERVER_SOFTWARE'], signature) + ++ def test_urlquote_decoding_in_cgi_check(self): ++ res = self.request('/cgi-bin%2ffile1.py') ++ self.assertEqual((b'Hello World\n', 'text/html', 200), ++ (res.read(), res.getheader('Content-type'), res.status)) ++ + + class SimpleHTTPRequestHandlerTestCase(unittest.TestCase): + """ Test url parsing """ --- python2.7-2.7.6.orig/debian/patches/CVE-2014-7185.patch +++ python2.7-2.7.6/debian/patches/CVE-2014-7185.patch @@ -0,0 +1,51 @@ + +# HG changeset patch +# User Benjamin Peterson +# Date 1403579547 25200 +# Node ID 8d963c7db507be561e26bbbb852e3a2be3327c3f +# Parent 8e0b7393e921fb5e05c40265f9272dec90512ef6 +avoid overflow with large buffer sizes and/or offsets (closes #21831) + +diff --git a/Lib/test/test_buffer.py b/Lib/test/test_buffer.py +--- a/Lib/test/test_buffer.py ++++ b/Lib/test/test_buffer.py +@@ -4,6 +4,7 @@ For now, tests just new or changed funct + + """ + ++import sys + import unittest + from test import test_support + +@@ -29,6 +30,11 @@ class BufferTests(unittest.TestCase): + m = memoryview(b) # Should not raise an exception + self.assertEqual(m.tobytes(), s) + ++ def test_large_buffer_size_and_offset(self): ++ data = bytearray('hola mundo') ++ buf = buffer(data, sys.maxsize, sys.maxsize) ++ self.assertEqual(buf[:4096], "") ++ + + def test_main(): + with test_support.check_py3k_warnings(("buffer.. not supported", +diff --git a/Objects/bufferobject.c b/Objects/bufferobject.c +--- a/Objects/bufferobject.c ++++ b/Objects/bufferobject.c +@@ -88,7 +88,7 @@ get_buf(PyBufferObject *self, void **ptr + *size = count; + else + *size = self->b_size; +- if (offset + *size > count) ++ if (*size > count - offset) + *size = count - offset; + } + return 1; +@@ -875,4 +875,4 @@ PyTypeObject PyBuffer_Type = { + 0, /* tp_init */ + 0, /* tp_alloc */ + buffer_new, /* tp_new */ +-}; +\ No newline at end of file ++}; + --- python2.7-2.7.6.orig/debian/patches/CVE-2016-0772.patch +++ python2.7-2.7.6/debian/patches/CVE-2016-0772.patch @@ -0,0 +1,28 @@ +Origin: https://hg.python.org/cpython/rev/b3ce713fb9be +# HG changeset patch +# User Benjamin Peterson +# Date 1465676202 25200 +# Node ID b3ce713fb9beebfff9848cefa0acbd59acc68fe9 +# Parent 3017e41b0c99d24e88faf1de447f230e2f64d122 +raise an error when STARTTLS fails + +[Modified from upstream commit to drop changes to Misc/NEWS to avoid + patch application conflicts. --sbeattie] + +CVE-2016-0772 + +diff --git a/Lib/smtplib.py b/Lib/smtplib.py +--- a/Lib/smtplib.py ++++ b/Lib/smtplib.py +@@ -656,6 +656,11 @@ class SMTP: + self.ehlo_resp = None + self.esmtp_features = {} + self.does_esmtp = 0 ++ else: ++ # RFC 3207: ++ # 501 Syntax error (no parameters allowed) ++ # 454 TLS not available due to temporary reason ++ raise SMTPResponseException(resp, reply) + return (resp, reply) + + def sendmail(self, from_addr, to_addrs, msg, mail_options=[], --- python2.7-2.7.6.orig/debian/patches/CVE-2016-1000110-pre.patch +++ python2.7-2.7.6/debian/patches/CVE-2016-1000110-pre.patch @@ -0,0 +1,184 @@ +Origin: https://hg.python.org/cpython/rev/ba915d561667/ +# HG changeset patch +# User Senthil Kumaran +# Date 1461601074 25200 +# Node ID c502deb19cb09862f0748589b268356933abebdd +# Parent d0d541c2afb78cc1a0ff68073cda3a1c4272f151 +backport fix for Issue #26804. + +urllib.request will prefer lower_case proxy environment variables over +UPPER_CASE or Mixed_Case ones. + +[This patch is a prerequisite for the patch for CVE-2016-1000110. This +patch differs from the upstream commit in that the change to Misc/NEWS +have been dropped to avoid patch conflicts. -- sbeattie] + +diff --git a/Doc/library/urllib.rst b/Doc/library/urllib.rst +--- a/Doc/library/urllib.rst ++++ b/Doc/library/urllib.rst +@@ -292,6 +292,8 @@ Utility functions + in case insensitive way, for all operating systems first, and when it cannot + find it, looks for proxy information from Mac OSX System Configuration for + Mac OS X and Windows Systems Registry for Windows. ++ If both lowercase and uppercase environment variables exist (and disagree), ++ lowercase is preferred. + + .. note:: + urllib also exposes certain utility functions like splittype, splithost and +diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py +--- a/Lib/test/test_urllib.py ++++ b/Lib/test/test_urllib.py +@@ -1,5 +1,6 @@ + """Regresssion tests for urllib""" + ++import collections + import urllib + import httplib + import unittest +@@ -158,8 +159,46 @@ class ProxyTests(unittest.TestCase): + # getproxies_environment use lowered case truncated (no '_proxy') keys + self.assertEqual('localhost', proxies['no']) + # List of no_proxies with space. +- self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com') ++ self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234') + self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com')) ++ self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888')) ++ self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234')) ++ ++ ++class ProxyTests_withOrderedEnv(unittest.TestCase): ++ ++ def setUp(self): ++ # We need to test conditions, where variable order _is_ significant ++ self._saved_env = os.environ ++ # Monkey patch os.environ, start with empty fake environment ++ os.environ = collections.OrderedDict() ++ ++ def tearDown(self): ++ os.environ = self._saved_env ++ ++ def test_getproxies_environment_prefer_lowercase(self): ++ # Test lowercase preference with removal ++ os.environ['no_proxy'] = '' ++ os.environ['No_Proxy'] = 'localhost' ++ self.assertFalse(urllib.proxy_bypass_environment('localhost')) ++ self.assertFalse(urllib.proxy_bypass_environment('arbitrary')) ++ os.environ['http_proxy'] = '' ++ os.environ['HTTP_PROXY'] = 'http://somewhere:3128' ++ proxies = urllib.getproxies_environment() ++ self.assertEqual({}, proxies) ++ # Test lowercase preference of proxy bypass and correct matching including ports ++ os.environ['no_proxy'] = 'localhost, noproxy.com, my.proxy:1234' ++ os.environ['No_Proxy'] = 'xyz.com' ++ self.assertTrue(urllib.proxy_bypass_environment('localhost')) ++ self.assertTrue(urllib.proxy_bypass_environment('noproxy.com:5678')) ++ self.assertTrue(urllib.proxy_bypass_environment('my.proxy:1234')) ++ self.assertFalse(urllib.proxy_bypass_environment('my.proxy')) ++ self.assertFalse(urllib.proxy_bypass_environment('arbitrary')) ++ # Test lowercase preference with replacement ++ os.environ['http_proxy'] = 'http://somewhere:3128' ++ os.environ['Http_Proxy'] = 'http://somewhereelse:3128' ++ proxies = urllib.getproxies_environment() ++ self.assertEqual('http://somewhere:3128', proxies['http']) + + + class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin): +@@ -1030,6 +1069,8 @@ def test_main(): + Pathname_Tests, + Utility_Tests, + URLopener_Tests, ++ ProxyTests, ++ ProxyTests_withOrderedEnv, + #FTPWrapperTests, + ) + +diff --git a/Lib/urllib.py b/Lib/urllib.py +--- a/Lib/urllib.py ++++ b/Lib/urllib.py +@@ -1379,25 +1379,42 @@ def getproxies_environment(): + """Return a dictionary of scheme -> proxy server URL mappings. + + Scan the environment for variables named _proxy; +- this seems to be the standard convention. If you need a +- different way, you can pass a proxies dictionary to the ++ this seems to be the standard convention. In order to prefer lowercase ++ variables, we process the environment in two passes, first matches any ++ and second matches only lower case proxies. ++ ++ If you need a different way, you can pass a proxies dictionary to the + [Fancy]URLopener constructor. +- + """ + proxies = {} + for name, value in os.environ.items(): + name = name.lower() + if value and name[-6:] == '_proxy': + proxies[name[:-6]] = value ++ ++ for name, value in os.environ.items(): ++ if name[-6:] == '_proxy': ++ name = name.lower() ++ if value: ++ proxies[name[:-6]] = value ++ else: ++ proxies.pop(name[:-6], None) ++ + return proxies + +-def proxy_bypass_environment(host): ++def proxy_bypass_environment(host, proxies=None): + """Test if proxies should not be used for a particular host. + +- Checks the environment for a variable named no_proxy, which should +- be a list of DNS suffixes separated by commas, or '*' for all hosts. ++ Checks the proxies dict for the value of no_proxy, which should be a ++ list of comma separated DNS suffixes, or '*' for all hosts. + """ +- no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '') ++ if proxies is None: ++ proxies = getproxies_environment() ++ # don't bypass, if no_proxy isn't specified ++ try: ++ no_proxy = proxies['no'] ++ except KeyError: ++ return 0 + # '*' is special case for always bypass + if no_proxy == '*': + return 1 +@@ -1483,8 +1500,14 @@ if sys.platform == 'darwin': + return _get_proxies() + + def proxy_bypass(host): +- if getproxies_environment(): +- return proxy_bypass_environment(host) ++ """Return True, if a host should be bypassed. ++ ++ Checks proxy settings gathered from the environment, if specified, or ++ from the MacOSX framework SystemConfiguration. ++ """ ++ proxies = getproxies_environment() ++ if proxies: ++ return proxy_bypass_environment(host, proxies) + else: + return proxy_bypass_macosx_sysconf(host) + +@@ -1600,14 +1623,14 @@ elif os.name == 'nt': + return 0 + + def proxy_bypass(host): +- """Return a dictionary of scheme -> proxy server URL mappings. ++ """Return True, if the host should be bypassed. + +- Returns settings gathered from the environment, if specified, ++ Checks proxy settings gathered from the environment, if specified, + or the registry. +- + """ +- if getproxies_environment(): +- return proxy_bypass_environment(host) ++ proxies = getproxies_environment() ++ if proxies: ++ return proxy_bypass_environment(host, proxies) + else: + return proxy_bypass_registry(host) + --- python2.7-2.7.6.orig/debian/patches/CVE-2016-1000110.patch +++ python2.7-2.7.6/debian/patches/CVE-2016-1000110.patch @@ -0,0 +1,115 @@ +Origin: https://hg.python.org/cpython/rev/ba915d561667/ +# HG changeset patch +# User Senthil Kumaran +# Date 1469882993 25200 +# Node ID ba915d561667fa0584ad89f8d5a844fd43803c0d +# Parent c8c1ea94379a7706638f1571988576d504d7fc98 +Prevent HTTPoxy attack (CVE-2016-1000110) + +Ignore the HTTP_PROXY variable when REQUEST_METHOD environment is set, which +indicates that the script is in CGI mode. + +Issue reported and patch contributed by Rémi Rampin. + +[Patch differs from upstream commit in that it drops the changes to + Misc/NEWS and Misc/ACKS to avoid patch conflicts -- sbeattie.] + +CVE-2016-1000110 + +diff --git a/Doc/howto/urllib2.rst b/Doc/howto/urllib2.rst +--- a/Doc/howto/urllib2.rst ++++ b/Doc/howto/urllib2.rst +@@ -525,6 +525,11 @@ setting up a `Basic Authentication`_ han + through a proxy. However, this can be enabled by extending urllib2 as + shown in the recipe [#]_. + ++.. note:: ++ ++ ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see ++ the documentation on :func:`~urllib.getproxies`. ++ + + Sockets and Layers + ================== +diff --git a/Doc/library/urllib.rst b/Doc/library/urllib.rst +--- a/Doc/library/urllib.rst ++++ b/Doc/library/urllib.rst +@@ -295,6 +295,16 @@ Utility functions + If both lowercase and uppercase environment variables exist (and disagree), + lowercase is preferred. + ++ .. note:: ++ ++ If the environment variable ``REQUEST_METHOD`` is set, which usually ++ indicates your script is running in a CGI environment, the environment ++ variable ``HTTP_PROXY`` (uppercase ``_PROXY``) will be ignored. This is ++ because that variable can be injected by a client using the "Proxy:" ++ HTTP header. If you need to use an HTTP proxy in a CGI environment, ++ either use ``ProxyHandler`` explicitly, or make sure the variable name ++ is in lowercase (or at least the ``_proxy`` suffix). ++ + .. note:: + urllib also exposes certain utility functions like splittype, splithost and + others parsing URL into various components. But it is recommended to use +diff --git a/Doc/library/urllib2.rst b/Doc/library/urllib2.rst +--- a/Doc/library/urllib2.rst ++++ b/Doc/library/urllib2.rst +@@ -229,6 +229,11 @@ The following classes are provided: + + To disable autodetected proxy pass an empty dictionary. + ++ .. note:: ++ ++ ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; ++ see the documentation on :func:`~urllib.getproxies`. ++ + + .. class:: HTTPPasswordMgr() + +diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py +--- a/Lib/test/test_urllib.py ++++ b/Lib/test/test_urllib.py +@@ -170,6 +170,18 @@ class ProxyTests(unittest.TestCase): + self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com:8888')) + self.assertTrue(urllib.proxy_bypass_environment('newdomain.com:1234')) + ++ def test_proxy_cgi_ignore(self): ++ try: ++ self.env.set('HTTP_PROXY', 'http://somewhere:3128') ++ proxies = urllib.getproxies_environment() ++ self.assertEqual('http://somewhere:3128', proxies['http']) ++ self.env.set('REQUEST_METHOD', 'GET') ++ proxies = urllib.getproxies_environment() ++ self.assertNotIn('http', proxies) ++ finally: ++ self.env.unset('REQUEST_METHOD') ++ self.env.unset('HTTP_PROXY') ++ + + class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin): + """Test urlopen() opening a fake http connection.""" +diff --git a/Lib/urllib.py b/Lib/urllib.py +--- a/Lib/urllib.py ++++ b/Lib/urllib.py +@@ -1380,12 +1380,21 @@ def getproxies_environment(): + If you need a different way, you can pass a proxies dictionary to the + [Fancy]URLopener constructor. + """ ++ # Get all variables + proxies = {} + for name, value in os.environ.items(): + name = name.lower() + if value and name[-6:] == '_proxy': + proxies[name[:-6]] = value + ++ # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY ++ # (non-all-lowercase) as it may be set from the web server by a "Proxy:" ++ # header from the client ++ # If "proxy" is lowercase, it will still be used thanks to the next block ++ if 'REQUEST_METHOD' in os.environ: ++ proxies.pop('http', None) ++ ++ # Get lowercase variables + for name, value in os.environ.items(): + if name[-6:] == '_proxy': + name = name.lower() --- python2.7-2.7.6.orig/debian/patches/CVE-2016-5636-pre.patch +++ python2.7-2.7.6/debian/patches/CVE-2016-5636-pre.patch @@ -0,0 +1,25 @@ +Origin: https://hg.python.org/cpython/rev/2edbdb79cd6d +# HG changeset patch +# User Benjamin Peterson +# Date 1453442566 28800 +# Node ID 2edbdb79cd6d2581d29e4686f13b01af58c7b04f +# Parent 89a84ada27c5c5c75649a4176f8f86bbefe0a76f +reject negative data_size + +[Prequesite for CVE-2016-5636 fix -- sbeattie] + +diff --git a/Modules/zipimport.c b/Modules/zipimport.c +--- a/Modules/zipimport.c ++++ b/Modules/zipimport.c +@@ -861,6 +861,10 @@ get_data(char *archive, PyObject *toc_en + &date, &crc)) { + return NULL; + } ++ if (data_size < 0) { ++ PyErr_Format(ZipImportError, "negative data size"); ++ return NULL; ++ } + + fp = fopen(archive, "rb"); + if (!fp) { + --- python2.7-2.7.6.orig/debian/patches/CVE-2016-5636.patch +++ python2.7-2.7.6/debian/patches/CVE-2016-5636.patch @@ -0,0 +1,29 @@ +Origin: https://hg.python.org/cpython/rev/985fc64c60d6 +# HG changeset patch +# User Benjamin Peterson +# Date 1453357424 28800 +# Node ID 985fc64c60d6adffd1138b6cc46df388ca91ca5d +# Parent 7ec954b9fc54448a35b56d271340ba109eb381b9 +prevent buffer overflow in get_data (closes #26171) + +[Patch differs from upstream in that the changes to the Misc/NEWS file +have been dropped to avoid patch conflicts. --sbeattie] + +CVE-2016-5636 + +diff --git a/Modules/zipimport.c b/Modules/zipimport.c +--- a/Modules/zipimport.c ++++ b/Modules/zipimport.c +@@ -895,6 +895,11 @@ get_data(char *archive, PyObject *toc_en + PyMarshal_ReadShortFromFile(fp); /* local header size */ + file_offset += l; /* Start of file data */ + ++ if (data_size > LONG_MAX - 1) { ++ fclose(fp); ++ PyErr_NoMemory(); ++ return NULL; ++ } + raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ? + data_size : data_size + 1); + if (raw_data == NULL) { + --- python2.7-2.7.6.orig/debian/patches/CVE-2016-5699.patch +++ python2.7-2.7.6/debian/patches/CVE-2016-5699.patch @@ -0,0 +1,151 @@ +Origin: https://hg.python.org/cpython/rev/1c45047c5102 +# HG changeset patch +# User Serhiy Storchaka +# Date 1426151571 -7200 +# Node ID 1c45047c51020d46246385949d5c02e026d47320 +# Parent 36bd5add973285cce9d3ec7e068bbb20c9080565 +Issue #22928: Disabled HTTP header injections in httplib. +Original patch by Demian Brecht. + +[Patch differs from commit in that changes to the Misc/NEWS file have + been dropped to avoid patch conflicts -- sbeattie] + +CVE-2016-5699 + +diff --git a/Lib/httplib.py b/Lib/httplib.py +--- a/Lib/httplib.py ++++ b/Lib/httplib.py +@@ -68,6 +68,7 @@ Req-sent-unread-response _CS_REQ_S + + from array import array + import os ++import re + import socket + from sys import py3kwarning + from urlparse import urlsplit +@@ -218,6 +219,34 @@ MAXAMOUNT = 1048576 + # maximum amount of headers accepted + _MAXHEADERS = 100 + ++# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2) ++# ++# VCHAR = %x21-7E ++# obs-text = %x80-FF ++# header-field = field-name ":" OWS field-value OWS ++# field-name = token ++# field-value = *( field-content / obs-fold ) ++# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] ++# field-vchar = VCHAR / obs-text ++# ++# obs-fold = CRLF 1*( SP / HTAB ) ++# ; obsolete line folding ++# ; see Section 3.2.4 ++ ++# token = 1*tchar ++# ++# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" ++# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" ++# / DIGIT / ALPHA ++# ; any VCHAR, except delimiters ++# ++# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1 ++ ++# the patterns for both name and value are more leniant than RFC ++# definitions to allow for backwards compatibility ++_is_legal_header_name = re.compile(r'\A[^:\s][^:\r\n]*\Z').match ++_is_illegal_header_value = re.compile(r'\n(?![ \t])|\r(?![ \t\n])').search ++ + + class HTTPMessage(mimetools.Message): + +@@ -983,7 +1012,16 @@ class HTTPConnection: + if self.__state != _CS_REQ_STARTED: + raise CannotSendHeader() + +- hdr = '%s: %s' % (header, '\r\n\t'.join([str(v) for v in values])) ++ header = '%s' % header ++ if not _is_legal_header_name(header): ++ raise ValueError('Invalid header name %r' % (header,)) ++ ++ values = [str(v) for v in values] ++ for one_value in values: ++ if _is_illegal_header_value(one_value): ++ raise ValueError('Invalid header value %r' % (one_value,)) ++ ++ hdr = '%s: %s' % (header, '\r\n\t'.join(values)) + self._output(hdr) + + def endheaders(self, message_body=None): +diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py +--- a/Lib/test/test_httplib.py ++++ b/Lib/test/test_httplib.py +@@ -145,6 +145,33 @@ class HeaderTests(TestCase): + conn.putheader('Content-length',42) + self.assertIn('Content-length: 42', conn._buffer) + ++ conn.putheader('Foo', ' bar ') ++ self.assertIn(b'Foo: bar ', conn._buffer) ++ conn.putheader('Bar', '\tbaz\t') ++ self.assertIn(b'Bar: \tbaz\t', conn._buffer) ++ conn.putheader('Authorization', 'Bearer mytoken') ++ self.assertIn(b'Authorization: Bearer mytoken', conn._buffer) ++ conn.putheader('IterHeader', 'IterA', 'IterB') ++ self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer) ++ conn.putheader('LatinHeader', b'\xFF') ++ self.assertIn(b'LatinHeader: \xFF', conn._buffer) ++ conn.putheader('Utf8Header', b'\xc3\x80') ++ self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer) ++ conn.putheader('C1-Control', b'next\x85line') ++ self.assertIn(b'C1-Control: next\x85line', conn._buffer) ++ conn.putheader('Embedded-Fold-Space', 'is\r\n allowed') ++ self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer) ++ conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed') ++ self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer) ++ conn.putheader('Key Space', 'value') ++ self.assertIn(b'Key Space: value', conn._buffer) ++ conn.putheader('KeySpace ', 'value') ++ self.assertIn(b'KeySpace : value', conn._buffer) ++ conn.putheader(b'Nonbreak\xa0Space', 'value') ++ self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer) ++ conn.putheader(b'\xa0NonbreakSpace', 'value') ++ self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer) ++ + def test_ipv6host_header(self): + # Default host header on IPv6 transaction should wrapped by [] if + # its actual IPv6 address +@@ -174,6 +201,35 @@ class HeaderTests(TestCase): + self.assertEqual(resp.getheader('First'), 'val') + self.assertEqual(resp.getheader('Second'), 'val') + ++ def test_invalid_headers(self): ++ conn = httplib.HTTPConnection('example.com') ++ conn.sock = FakeSocket('') ++ conn.putrequest('GET', '/') ++ ++ # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no ++ # longer allowed in header names ++ cases = ( ++ (b'Invalid\r\nName', b'ValidValue'), ++ (b'Invalid\rName', b'ValidValue'), ++ (b'Invalid\nName', b'ValidValue'), ++ (b'\r\nInvalidName', b'ValidValue'), ++ (b'\rInvalidName', b'ValidValue'), ++ (b'\nInvalidName', b'ValidValue'), ++ (b' InvalidName', b'ValidValue'), ++ (b'\tInvalidName', b'ValidValue'), ++ (b'Invalid:Name', b'ValidValue'), ++ (b':InvalidName', b'ValidValue'), ++ (b'ValidName', b'Invalid\r\nValue'), ++ (b'ValidName', b'Invalid\rValue'), ++ (b'ValidName', b'Invalid\nValue'), ++ (b'ValidName', b'InvalidValue\r\n'), ++ (b'ValidName', b'InvalidValue\r'), ++ (b'ValidName', b'InvalidValue\n'), ++ ) ++ for name, value in cases: ++ with self.assertRaisesRegexp(ValueError, 'Invalid header'): ++ conn.putheader(name, value) ++ + + class BasicTest(TestCase): + def test_status_lines(self): --- python2.7-2.7.6.orig/debian/patches/CVE-2017-1000158.patch +++ python2.7-2.7.6/debian/patches/CVE-2017-1000158.patch @@ -0,0 +1,57 @@ +From c3c9db89273fabc62ea1b48389d9a3000c1c03ae Mon Sep 17 00:00:00 2001 +From: Jay Bosamiya +Date: Sun, 18 Jun 2017 22:11:03 +0530 +Subject: [PATCH] [2.7] bpo-30657: Check & prevent integer overflow in + PyString_DecodeEscape (#2174) + +#--- +# Misc/ACKS | 1 + +# Misc/NEWS | 3 +++ +# Objects/stringobject.c | 8 +++++++- +# 3 files changed, 11 insertions(+), 1 deletion(-) +# +#diff --git a/Misc/ACKS b/Misc/ACKS +#index 95be42717a0..a411bc5ffc8 100644 +#--- a/Misc/ACKS +#+++ b/Misc/ACKS +#@@ -152,6 +152,7 @@ Gregory Bond +# Matias Bordese +# Jonas Borgström +# Jurjen Bos +#+Jay Bosamiya +# Peter Bosch +# Dan Boswell +# Eric Bouck +#diff --git a/Misc/NEWS b/Misc/NEWS +#index b89f6ea62d8..62559edf837 100644 +#--- a/Misc/NEWS +#+++ b/Misc/NEWS +#@@ -10,6 +10,9 @@ What's New in Python 2.7.14? +# Core and Builtins +# ----------------- +# +#+- bpo-30657: Fixed possible integer overflow in PyString_DecodeEscape. +#+ Patch by Jay Bosamiya. +#+ +# - bpo-27945: Fixed various segfaults with dict when input collections are +# mutated during searching, inserting or comparing. Based on patches by +# Duane Griffin and Tim Mitchell. +diff --git a/Objects/stringobject.c b/Objects/stringobject.c +index c78e19316a0..59d22e76946 100644 +--- a/Objects/stringobject.c ++++ b/Objects/stringobject.c +@@ -612,7 +612,13 @@ PyObject *PyString_DecodeEscape(const char *s, + char *p, *buf; + const char *end; + PyObject *v; +- Py_ssize_t newlen = recode_encoding ? 4*len:len; ++ Py_ssize_t newlen; ++ /* Check for integer overflow */ ++ if (recode_encoding && (len > PY_SSIZE_T_MAX / 4)) { ++ PyErr_SetString(PyExc_OverflowError, "string is too large"); ++ return NULL; ++ } ++ newlen = recode_encoding ? 4*len:len; + v = PyString_FromStringAndSize((char *)NULL, newlen); + if (v == NULL) + return NULL; --- python2.7-2.7.6.orig/debian/patches/add-python-config-sh.diff +++ python2.7-2.7.6/debian/patches/add-python-config-sh.diff @@ -0,0 +1,174 @@ +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -1065,6 +1065,8 @@ + # Substitution happens here, as the completely-expanded BINDIR + # is not available in configure + sed -e "s,@EXENAME@,$(BINDIR)/python$(VERSION)$(EXE)," < $(srcdir)/Misc/python-config.in >python-config ++ # Replace makefile compat. variable references with shell script compat. ones; $(VAR) -> ${VAR} ++ sed -e "s,\$$(\([A-Za-z0-9_]*\)),\$$\{\1\},g" < Misc/python-config.sh >python-config.sh + + # Install the include files + INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY) +@@ -1124,6 +1126,7 @@ + $(INSTALL_SCRIPT) $(srcdir)/install-sh $(DESTDIR)$(LIBPL)/install-sh + $(INSTALL_SCRIPT) python-config $(DESTDIR)$(BINDIR)/python$(VERSION)-config + rm python-config ++ $(INSTALL_SCRIPT) python-config.sh $(DESTDIR)$(BINDIR)/python-config.sh + @if [ -s Modules/python.exp -a \ + "`echo $(MACHDEP) | sed 's/^\(...\).*/\1/'`" = "aix" ]; then \ + echo; echo "Installing support files for building shared extension modules on AIX:"; \ +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -55,3 +55,11 @@ + libs.extend(getvar('LINKFORSHARED').split()) + print ' '.join(libs) + ++ elif opt == '--extension-suffix': ++ print sysconfig.get_config_var('SO') ++ ++ elif opt == '--abiflags': ++ print '' ++ ++ elif opt == '--configdir': ++ print sysconfig.get_config_var('LIBPL') +--- /dev/null ++++ b/Misc/python-config.sh.in +@@ -0,0 +1,103 @@ ++#!/bin/sh ++ ++exit_with_usage () ++{ ++ echo "Usage: $0 --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--help|--configdir" ++ exit $1 ++} ++ ++if [ "$1" = "" ] ; then ++ exit_with_usage 1 ++fi ++ ++# Returns the actual prefix where this script was installed to. ++installed_prefix () ++{ ++ local RESULT=$(dirname $(cd $(dirname "$1") && pwd -P)) ++ if [ $(which readlink) ] ; then ++ RESULT=$(readlink -f "$RESULT") ++ fi ++ echo $RESULT ++} ++ ++prefix_build="@prefix@" ++prefix_real=$(installed_prefix "$0") ++ ++# Use sed to fix paths from their built to locations to their installed to locations. ++prefix=$(echo "$prefix_build" | sed "s#$prefix_build#$prefix_real#") ++exec_prefix_build="@exec_prefix@" ++exec_prefix=$(echo "$exec_prefix_build" | sed "s#$exec_prefix_build#$prefix_real#") ++includedir=$(echo "@includedir@" | sed "s#$prefix_build#$prefix_real#") ++libdir=$(echo "@libdir@" | sed "s#$prefix_build#$prefix_real#") ++CFLAGS=$(echo "@CFLAGS@" | sed "s#$prefix_build#$prefix_real#") ++VERSION="@VERSION@" ++LIBM="@LIBM@" ++LIBC="@LIBC@" ++SYSLIBS="$LIBM $LIBC" ++ABIFLAGS="@DEBUG_EXT@" ++MULTIARCH="@MULTIARCH@" ++LIBS="@LIBS@ $SYSLIBS -lpython${VERSION}${ABIFLAGS}" ++BASECFLAGS="@BASECFLAGS@" ++LDLIBRARY="@LDLIBRARY@" ++LINKFORSHARED="@LINKFORSHARED@" ++OPT="@OPT@" ++PY_ENABLE_SHARED="@PY_ENABLE_SHARED@" ++LIBDEST=${prefix}/lib/python${VERSION} ++LIBPL=${LIBDEST}/config-${MULTIARCH}${ABIFLAGS} ++SO="${ABIFLAGS}.so" ++PYTHONFRAMEWORK="@PYTHONFRAMEWORK@" ++INCDIR="-I$includedir/python${VERSION}${ABIFLAGS}" ++PLATINCDIR="-I$includedir/$MULTIARCH/python${VERSION}${ABIFLAGS}" ++ ++# Scan for --help or unknown argument. ++for ARG in $* ++do ++ case $ARG in ++ --help) ++ exit_with_usage 0 ++ ;; ++ --prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--extension-suffix|--configdir) ++ ;; ++ *) ++ exit_with_usage 1 ++ ;; ++ esac ++done ++ ++for ARG in $* ++do ++ case $ARG in ++ --prefix) ++ echo "$prefix" ++ ;; ++ --exec-prefix) ++ echo "$exec_prefix" ++ ;; ++ --includes) ++ echo "$INCDIR" "$PLATINCDIR" ++ ;; ++ --cflags) ++ echo "$INCDIR $PLATINCDIR $BASECFLAGS $CFLAGS $OPT" ++ ;; ++ --libs) ++ echo "$LIBS" ++ ;; ++ --ldflags) ++ LINKFORSHAREDUSED= ++ if [ -z "$PYTHONFRAMEWORK" ] ; then ++ LINKFORSHAREDUSED=$LINKFORSHARED ++ fi ++ LIBPLUSED= ++ if [ "$PY_ENABLE_SHARED" = "0" ] ; then ++ LIBPLUSED="-L$LIBPL" ++ fi ++ echo "$LIBPLUSED -L$libdir $LIBS $LINKFORSHAREDUSED" ++ ;; ++ --extension-suffix) ++ echo "$SO" ++ ;; ++ --configdir) ++ echo "$LIBPL" ++ ;; ++esac ++done +--- a/configure.ac ++++ b/configure.ac +@@ -870,6 +870,7 @@ + + # Other platforms follow + if test $enable_shared = "yes"; then ++ PY_ENABLE_SHARED=1 + AC_DEFINE(Py_ENABLE_SHARED, 1, [Defined if Python is built as a shared library.]) + case $ac_sys_system in + BeOS*) +@@ -930,6 +931,7 @@ + + esac + else # shared is disabled ++ PY_ENABLE_SHARED=0 + case $ac_sys_system in + CYGWIN*) + BLDLIBRARY='$(LIBRARY)' +@@ -937,6 +939,7 @@ + ;; + esac + fi ++AC_SUBST(PY_ENABLE_SHARED) + + if test "$cross_compiling" = yes; then + RUNSHARED= +@@ -4553,7 +4556,7 @@ + AC_MSG_RESULT(done) + + # generate output files +-AC_CONFIG_FILES(Makefile.pre Modules/Setup.config Misc/python.pc) ++AC_CONFIG_FILES(Makefile.pre Modules/Setup.config Misc/python.pc Misc/python-config.sh) + AC_CONFIG_FILES([Modules/ld_so_aix], [chmod +x Modules/ld_so_aix]) + AC_OUTPUT + --- python2.7-2.7.6.orig/debian/patches/atomic-pyc-rename.diff +++ python2.7-2.7.6/debian/patches/atomic-pyc-rename.diff @@ -0,0 +1,34 @@ +--- a/Lib/py_compile.py ++++ b/Lib/py_compile.py +@@ -120,13 +120,24 @@ + return + if cfile is None: + cfile = file + (__debug__ and 'c' or 'o') +- with open(cfile, 'wb') as fc: +- fc.write('\0\0\0\0') +- wr_long(fc, timestamp) +- marshal.dump(codeobject, fc) +- fc.flush() +- fc.seek(0, 0) +- fc.write(MAGIC) ++ # Atomically write the pyc/pyo file. Issue #13146. ++ # id() is used to generate a pseudo-random filename. ++ path_tmp = '{}.{}'.format(cfile, id(cfile)) ++ try: ++ with open(path_tmp, 'wb') as fc: ++ fc.write('\0\0\0\0') ++ wr_long(fc, timestamp) ++ marshal.dump(codeobject, fc) ++ fc.flush() ++ fc.seek(0, 0) ++ fc.write(MAGIC) ++ os.rename(path_tmp, cfile) ++ except OSError: ++ try: ++ os.unlink(path_tmp) ++ except OSError: ++ pass ++ raise + + def main(args=None): + """Compile several source files. --- python2.7-2.7.6.orig/debian/patches/bdist-wininst-notfound.diff +++ python2.7-2.7.6/debian/patches/bdist-wininst-notfound.diff @@ -0,0 +1,25 @@ +# DP: the wininst-* files cannot be built within Debian, needing a +# DP: zlib mingw build, which the zlib maintainer isn't going to provide. + +--- a/Lib/distutils/command/bdist_wininst.py ++++ b/Lib/distutils/command/bdist_wininst.py +@@ -14,6 +14,7 @@ + from distutils.core import Command + from distutils.dir_util import remove_tree + from distutils.errors import DistutilsOptionError, DistutilsPlatformError ++from distutils.errors import DistutilsFileError + from distutils import log + from distutils.util import get_platform + +@@ -360,7 +361,10 @@ + sfix = '' + + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) +- f = open(filename, "rb") ++ try: ++ f = open(filename, "rb") ++ except IOError, msg: ++ raise DistutilsFileError, str(msg) + ', %s not included in the Debian packages.' % filename + try: + return f.read() + finally: --- python2.7-2.7.6.orig/debian/patches/bsddb-libpath.diff +++ python2.7-2.7.6/debian/patches/bsddb-libpath.diff @@ -0,0 +1,19 @@ +# DP: Don't add the bsddb multilib path, if already in the standard lib path + +--- a/setup.py ++++ b/setup.py +@@ -1066,7 +1066,13 @@ + if db_setup_debug: + print "bsddb using BerkeleyDB lib:", db_ver, dblib + print "bsddb lib dir:", dblib_dir, " inc dir:", db_incdir +- db_incs = [db_incdir] ++ # only add db_incdir/dblib_dir if not in the standard paths ++ if db_incdir in inc_dirs: ++ db_incs = [] ++ else: ++ db_incs = [db_incdir] ++ if dblib_dir[0] in lib_dirs: ++ dblib_dir = [] + dblibs = [dblib] + # We add the runtime_library_dirs argument because the + # BerkeleyDB lib we're linking against often isn't in the --- python2.7-2.7.6.orig/debian/patches/build-hash.diff +++ python2.7-2.7.6/debian/patches/build-hash.diff @@ -0,0 +1,22 @@ +# DP: Always build the _md5, _sha1, _sha256 and _sha512 extension modules. + +--- a/setup.py ++++ b/setup.py +@@ -850,7 +850,7 @@ + print ("warning: openssl 0x%08x is too old for _hashlib" % + openssl_ver) + missing.append('_hashlib') +- if COMPILED_WITH_PYDEBUG or not have_usable_openssl: ++ if True or COMPILED_WITH_PYDEBUG or not have_usable_openssl: + # The _sha module implements the SHA1 hash algorithm. + exts.append( Extension('_sha', ['shamodule.c']) ) + # The _md5 module implements the RSA Data Security, Inc. MD5 +@@ -861,7 +861,7 @@ + depends = ['md5.h']) ) + + min_sha2_openssl_ver = 0x00908000 +- if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver: ++ if True or COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver: + # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash + exts.append( Extension('_sha256', ['sha256module.c']) ) + exts.append( Extension('_sha512', ['sha512module.c']) ) --- python2.7-2.7.6.orig/debian/patches/build-libpython.diff +++ python2.7-2.7.6/debian/patches/build-libpython.diff @@ -0,0 +1,22 @@ +# DP: Don't include object files twice in libpython. + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -404,7 +404,7 @@ + $(PYTHON_OBJS) \ + $(MODULE_OBJS) \ + $(SIGNAL_OBJS) \ +- $(MODOBJS) ++ $(sort $(MODOBJS)) + + ######################################################################### + # Rules +@@ -478,7 +478,7 @@ + $(AR) $(ARFLAGS) $@ $(OBJECT_OBJS) + $(AR) $(ARFLAGS) $@ $(PYTHON_OBJS) + $(AR) $(ARFLAGS) $@ $(MODULE_OBJS) $(SIGNAL_OBJS) +- $(AR) $(ARFLAGS) $@ $(MODOBJS) ++ $(AR) $(ARFLAGS) $@ $(sort $(MODOBJS)) + $(RANLIB) $@ + + libpython$(VERSION).so: $(LIBRARY_OBJS) --- python2.7-2.7.6.orig/debian/patches/cthreads.diff +++ python2.7-2.7.6/debian/patches/cthreads.diff @@ -0,0 +1,39 @@ +# DP: Remove cthreads detection + +--- a/configure.ac ++++ b/configure.ac +@@ -2154,7 +2154,6 @@ + + # Templates for things AC_DEFINEd more than once. + # For a single AC_DEFINE, no template is needed. +-AH_TEMPLATE(C_THREADS,[Define if you have the Mach cthreads package]) + AH_TEMPLATE(_REENTRANT, + [Define to force use of thread-safe errno, h_errno, and other functions]) + AH_TEMPLATE(WITH_THREAD, +@@ -2236,17 +2235,6 @@ + AC_MSG_RESULT($unistd_defines_pthreads) + + AC_DEFINE(_REENTRANT) +- AC_CHECK_HEADER(cthreads.h, [AC_DEFINE(WITH_THREAD) +- AC_DEFINE(C_THREADS) +- AC_DEFINE(HURD_C_THREADS, 1, +- [Define if you are using Mach cthreads directly under /include]) +- LIBS="$LIBS -lthreads" +- THREADOBJ="Python/thread.o"],[ +- AC_CHECK_HEADER(mach/cthreads.h, [AC_DEFINE(WITH_THREAD) +- AC_DEFINE(C_THREADS) +- AC_DEFINE(MACH_C_THREADS, 1, +- [Define if you are using Mach cthreads under mach /]) +- THREADOBJ="Python/thread.o"],[ + AC_MSG_CHECKING(for --with-pth) + AC_ARG_WITH([pth], + AS_HELP_STRING([--with-pth], [use GNU pth threading libraries]), +@@ -2301,7 +2289,7 @@ + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o"],[ + USE_THREAD_MODULE="#"]) +- ])])])])])])])])])]) ++ ])])])])])])])]) + + AC_CHECK_LIB(mpc, usconfig, [AC_DEFINE(WITH_THREAD) + LIBS="$LIBS -lmpc" --- python2.7-2.7.6.orig/debian/patches/ctypes-arm.diff +++ python2.7-2.7.6/debian/patches/ctypes-arm.diff @@ -0,0 +1,32 @@ +--- a/Lib/ctypes/util.py ++++ b/Lib/ctypes/util.py +@@ -213,16 +213,27 @@ + + def _findSoname_ldconfig(name): + import struct ++ # XXX this code assumes that we know all unames and that a single ++ # ABI is supported per uname; instead we should find what the ++ # ABI is (e.g. check ABI of current process) or simply ask libc ++ # to load the library for us ++ uname = os.uname()[4] ++ # ARM has a variety of unames, e.g. armv7l ++ if uname.startswith("arm"): ++ uname = "arm" + if struct.calcsize('l') == 4: +- machine = os.uname()[4] + '-32' ++ machine = uname + '-32' + else: +- machine = os.uname()[4] + '-64' ++ machine = uname + '-64' + mach_map = { + 'x86_64-64': 'libc6,x86-64', + 'ppc64-64': 'libc6,64bit', + 'sparc64-64': 'libc6,64bit', + 's390x-64': 'libc6,64bit', + 'ia64-64': 'libc6,IA-64', ++ # this actually breaks on biarch or multiarch as the first ++ # library wins; uname doesn't tell us which ABI we're using ++ 'arm-32': 'libc6(,hard-float)?', + } + abi_type = mach_map.get(machine, 'libc6') + --- python2.7-2.7.6.orig/debian/patches/deb-locations.diff +++ python2.7-2.7.6/debian/patches/deb-locations.diff @@ -0,0 +1,63 @@ +# DP: adjust locations of directories to debian policy + +--- a/Demo/tkinter/guido/ManPage.py ++++ b/Demo/tkinter/guido/ManPage.py +@@ -189,8 +189,9 @@ + def test(): + import os + import sys +- # XXX This directory may be different on your system +- MANDIR = '/usr/local/man/mann' ++ # XXX This directory may be different on your system, ++ # it is here set for Debian GNU/Linux. ++ MANDIR = '/usr/share/man' + DEFAULTPAGE = 'Tcl' + formatted = 0 + if sys.argv[1:] and sys.argv[1] == '-f': +--- a/Demo/tkinter/guido/tkman.py ++++ b/Demo/tkinter/guido/tkman.py +@@ -9,8 +9,8 @@ + from Tkinter import * + from ManPage import ManPage + +-MANNDIRLIST = ['/depot/sundry/man/mann','/usr/local/man/mann'] +-MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3'] ++MANNDIRLIST = ['/depot/sundry/man/mann','/usr/share/man/mann'] ++MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/share/man/man3'] + + foundmanndir = 0 + for dir in MANNDIRLIST: +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -338,7 +338,7 @@ + These are subject to difference depending on local installation + conventions; ${prefix} and ${exec_prefix} are installation-dependent + and should be interpreted as for GNU software; they may be the same. +-The default for both is \fI/usr/local\fP. ++On Debian GNU/{Hurd,Linux} the default for both is \fI/usr\fP. + .IP \fI${exec_prefix}/bin/python\fP + Recommended location of the interpreter. + .PP +--- a/Tools/faqwiz/faqconf.py ++++ b/Tools/faqwiz/faqconf.py +@@ -21,7 +21,7 @@ + OWNEREMAIL = "nobody@anywhere.org" # Email for feedback + HOMEURL = "http://www.python.org" # Related home page + HOMENAME = "Python home" # Name of related home page +-RCSBINDIR = "/usr/local/bin/" # Directory containing RCS commands ++RCSBINDIR = "/usr/bin/" # Directory containing RCS commands + # (must end in a slash) + + # Parameters you can normally leave alone +--- a/Tools/webchecker/webchecker.py ++++ b/Tools/webchecker/webchecker.py +@@ -19,7 +19,8 @@ + a directory listing is returned. Now, you can point webchecker to the + document tree in the local file system of your HTTP daemon, and have + most of it checked. In fact the default works this way if your local +-web tree is located at /usr/local/etc/httpd/htdpcs (the default for ++web tree is located at /var/www, which is the default for Debian ++GNU/Linux. Other systems use /usr/local/etc/httpd/htdocs (the default for + the NCSA HTTP daemon and probably others). + + Report printed: --- python2.7-2.7.6.orig/debian/patches/deb-setup.diff +++ python2.7-2.7.6/debian/patches/deb-setup.diff @@ -0,0 +1,19 @@ +# DP: Don't include /usr/local/include and /usr/local/lib as gcc search paths + +--- a/setup.py ++++ b/setup.py +@@ -436,10 +436,10 @@ + os.unlink(tmpfile) + + def detect_modules(self): +- # Ensure that /usr/local is always used +- if not cross_compiling: +- add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') +- add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') ++ # On Debian /usr/local is always used, so we don't include it twice ++ #if not cross_compiling: ++ # add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') ++ # add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') + if cross_compiling: + self.add_gcc_paths() + self.add_multiarch_paths() --- python2.7-2.7.6.orig/debian/patches/debug-build.diff +++ python2.7-2.7.6/debian/patches/debug-build.diff @@ -0,0 +1,228 @@ +# DP: Change the interpreter to build and install python extensions +# DP: built with the python-dbg interpreter with a different name into +# DP: the same path (by appending `_d' to the extension name). + +--- a/Lib/distutils/command/build.py ++++ b/Lib/distutils/command/build.py +@@ -91,7 +91,8 @@ + # 'lib.' under the base build directory. We only use one of + # them for a given distribution, though -- + if self.build_purelib is None: +- self.build_purelib = os.path.join(self.build_base, 'lib') ++ self.build_purelib = os.path.join(self.build_base, ++ 'lib' + plat_specifier) + if self.build_platlib is None: + self.build_platlib = os.path.join(self.build_base, + 'lib' + plat_specifier) +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -90,7 +90,7 @@ + # Include is located in the srcdir + inc_dir = os.path.join(srcdir, "Include") + return inc_dir +- return os.path.join(prefix, "include", "python" + get_python_version()) ++ return os.path.join(prefix, "include", "python" + get_python_version())+(sys.pydebug and "_d" or "") + elif os.name == "nt": + return os.path.join(prefix, "include") + elif os.name == "os2": +@@ -251,7 +251,7 @@ + if python_build: + return os.path.join(project_base, "Makefile") + lib_dir = get_python_lib(plat_specific=1, standard_lib=1) +- return os.path.join(lib_dir, "config", "Makefile") ++ return os.path.join(lib_dir, "config"+(sys.pydebug and "_d" or ""), "Makefile") + + + def parse_config_h(fp, g=None): +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -332,7 +332,7 @@ + def _get_makefile_filename(): + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile") ++ return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") + + def _generate_posix_vars(): + """Generate the Python module containing build-time variables.""" +@@ -461,7 +461,7 @@ + else: + inc_dir = _PROJECT_BASE + else: +- inc_dir = get_path('platinclude').replace("/usr/local","/usr",1) ++ inc_dir = get_path('platinclude').replace("/usr/local","/usr",1)+(sys.pydebug and "_d" or "") + return os.path.join(inc_dir, 'pyconfig.h') + + def get_scheme_names(): +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -117,8 +117,8 @@ + # Detailed destination directories + BINLIBDEST= $(LIBDIR)/python$(VERSION) + LIBDEST= $(SCRIPTDIR)/python$(VERSION) +-INCLUDEPY= $(INCLUDEDIR)/python$(VERSION) +-CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION) ++INCLUDEPY= $(INCLUDEDIR)/python$(VERSION)$(DEBUG_EXT) ++CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION)$(DEBUG_EXT) + LIBP= $(LIBDIR)/python$(VERSION) + + # Symbols used for using shared libraries +@@ -132,6 +132,8 @@ + EXE= @EXEEXT@ + BUILDEXE= @BUILDEXEEXT@ + ++DEBUG_EXT= @DEBUG_EXT@ ++ + # Short name and location for Mac OS X Python framework + UNIVERSALSDK=@UNIVERSALSDK@ + PYTHONFRAMEWORK= @PYTHONFRAMEWORK@ +@@ -481,7 +483,7 @@ + $(AR) $(ARFLAGS) $@ $(sort $(MODOBJS)) + $(RANLIB) $@ + +-libpython$(VERSION).so: $(LIBRARY_OBJS) ++libpython$(VERSION)$(DEBUG_EXT).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ + $(BLDSHARED) $(PY_LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ +@@ -1076,8 +1078,8 @@ + $(INSTALL_DATA) pyconfig.h $(DESTDIR)$(CONFINCLUDEPY)/pyconfig.h + + # Install the library and miscellaneous stuff needed for extending/embedding +-# This goes into $(exec_prefix) +-LIBPL= $(LIBP)/config ++# This goes into $(exec_prefix)$(DEBUG_EXT) ++LIBPL= $(LIBP)/config$(DEBUG_EXT) + + # pkgconfig directory + LIBPC= $(LIBDIR)/pkgconfig +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -45,7 +45,7 @@ + + elif opt in ('--libs', '--ldflags'): + libs = getvar('LIBS').split() + getvar('SYSLIBS').split() +- libs.append('-lpython'+pyver) ++ libs.append('-lpython' + pyver + (sys.pydebug and "_d" or "")) + # add the prefix/lib/pythonX.Y/config dir, but only if there is no + # shared library in prefix/lib/. + if opt == '--ldflags': +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -46,6 +46,10 @@ + {"module.exe", "rb", C_EXTENSION}, + {"MODULE.EXE", "rb", C_EXTENSION}, + #else ++#ifdef Py_DEBUG ++ {"_d.so", "rb", C_EXTENSION}, ++ {"module_d.so", "rb", C_EXTENSION}, ++#endif + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + #endif +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1506,6 +1506,12 @@ + PyString_FromString("legacy")); + #endif + ++#ifdef Py_DEBUG ++ PyDict_SetItemString(sysdict, "pydebug", Py_True); ++#else ++ PyDict_SetItemString(sysdict, "pydebug", Py_False); ++#endif ++ + #undef SET_SYS_FROM_STRING + if (PyErr_Occurred()) + return NULL; +--- a/configure.ac ++++ b/configure.ac +@@ -737,7 +737,7 @@ + AC_MSG_CHECKING(LIBRARY) + if test -z "$LIBRARY" + then +- LIBRARY='libpython$(VERSION).a' ++ LIBRARY='libpython$(VERSION)$(DEBUG_EXT).a' + fi + AC_MSG_RESULT($LIBRARY) + +@@ -883,8 +883,8 @@ + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; + Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*) +- LDLIBRARY='libpython$(VERSION).so' +- BLDLIBRARY='-L. -lpython$(VERSION)' ++ LDLIBRARY='libpython$(VERSION)$(DEBUG_EXT).so' ++ BLDLIBRARY='-L. -lpython$(VERSION)$(DEBUG_EXT)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + case $ac_sys_system in + FreeBSD*) +@@ -1027,6 +1027,12 @@ + fi], + [AC_MSG_RESULT(no)]) + ++if test "$Py_DEBUG" = 'true' ++then ++ DEBUG_EXT=_d ++fi ++AC_SUBST(DEBUG_EXT) ++ + # XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be + # merged with this chunk of code? + +@@ -1917,7 +1923,7 @@ + esac + ;; + CYGWIN*) SO=.dll;; +- *) SO=.so;; ++ *) SO=$DEBUG_EXT.so;; + esac + else + # this might also be a termcap variable, see #610332 +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -289,8 +289,8 @@ + finally: + os.chdir(old_wd) + self.assertTrue(os.path.exists(so_file)) +- self.assertEqual(os.path.splitext(so_file)[-1], +- sysconfig.get_config_var('SO')) ++ so_ext = sysconfig.get_config_var('SO') ++ self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext) + so_dir = os.path.dirname(so_file) + self.assertEqual(so_dir, other_tmp_dir) + cmd.compiler = None +@@ -298,8 +298,7 @@ + cmd.run() + so_file = cmd.get_outputs()[0] + self.assertTrue(os.path.exists(so_file)) +- self.assertEqual(os.path.splitext(so_file)[-1], +- sysconfig.get_config_var('SO')) ++ self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext) + so_dir = os.path.dirname(so_file) + self.assertEqual(so_dir, cmd.build_lib) + +--- a/Lib/distutils/tests/test_build.py ++++ b/Lib/distutils/tests/test_build.py +@@ -20,10 +20,6 @@ + # if not specified, plat_name gets the current platform + self.assertEqual(cmd.plat_name, get_platform()) + +- # build_purelib is build + lib +- wanted = os.path.join(cmd.build_base, 'lib') +- self.assertEqual(cmd.build_purelib, wanted) +- + # build_platlib is 'build/lib.platform-x.x[-pydebug]' + # examples: + # build/lib.macosx-10.3-i386-2.7 +@@ -34,6 +30,10 @@ + wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) + self.assertEqual(cmd.build_platlib, wanted) + ++ # build_purelib is build + lib ++ wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) ++ self.assertEqual(cmd.build_purelib, wanted) ++ + # by default, build_lib = build_purelib + self.assertEqual(cmd.build_lib, cmd.build_purelib) + --- python2.7-2.7.6.orig/debian/patches/disable-sem-check.diff +++ python2.7-2.7.6/debian/patches/disable-sem-check.diff @@ -0,0 +1,28 @@ +# DP: Assume working semaphores on Linux, don't rely on running kernel for the check. + +--- a/configure.ac ++++ b/configure.ac +@@ -3832,6 +3832,11 @@ + [ac_cv_posix_semaphores_enabled=no], + [ac_cv_posix_semaphores_enabled=yes]) + ) ++case $ac_sys_system in ++ Linux*) ++ # assume enabled, see https://launchpad.net/bugs/630511 ++ ac_cv_posix_semaphores_enabled=yes ++esac + AC_MSG_RESULT($ac_cv_posix_semaphores_enabled) + if test $ac_cv_posix_semaphores_enabled = no + then +@@ -3868,6 +3873,11 @@ + [ac_cv_broken_sem_getvalue=yes], + [ac_cv_broken_sem_getvalue=yes]) + ) ++case $ac_sys_system in ++ Linux*) ++ # assume enabled, see https://launchpad.net/bugs/630511 ++ ac_cv_broken_sem_getvalue=no ++esac + AC_MSG_RESULT($ac_cv_broken_sem_getvalue) + if test $ac_cv_broken_sem_getvalue = yes + then --- python2.7-2.7.6.orig/debian/patches/disable-utimes.diff +++ python2.7-2.7.6/debian/patches/disable-utimes.diff @@ -0,0 +1,13 @@ +# DP: disable check for utimes function, which is broken in glibc-2.3.2 + +--- a/configure.ac ++++ b/configure.ac +@@ -2698,7 +2698,7 @@ + setsid setpgid setpgrp setuid setvbuf snprintf \ + sigaction siginterrupt sigrelse strftime \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ +- truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) ++ truncate uname unsetenv waitpid wait3 wait4 wcscoll _getpty) + + # For some functions, having a definition is not sufficient, since + # we want to take their address. --- python2.7-2.7.6.orig/debian/patches/distutils-install-layout.diff +++ python2.7-2.7.6/debian/patches/distutils-install-layout.diff @@ -0,0 +1,382 @@ +# DP: distutils: Add an option --install-layout=deb, which +# DP: - installs into $prefix/dist-packages instead of $prefix/site-packages. +# DP: - doesn't encode the python version into the egg name. + +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -240,6 +240,8 @@ + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Platform | Standard installation location | Default value | Notes | + +=================+=====================================================+==================================================+=======+ ++| Debian/Ubuntu | :file:`{prefix}/lib/python{X.Y}/dist-packages` | :file:`/usr/local/lib/python{X.Y}/dist-packages` | \(0) | +++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Unix (pure) | :file:`{prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Unix (non-pure) | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | +@@ -249,6 +251,14 @@ + + Notes: + ++(0) ++ Starting with Python-2.6 Debian/Ubuntu uses for the Python which comes within ++ the Linux distribution a non-default name for the installation directory. This ++ is to avoid overwriting of the python modules which come with the distribution, ++ which unfortunately is the upstream behaviour of the installation tools. The ++ non-default name in :file:`/usr/local` is used not to overwrite a local python ++ installation (defaulting to :file:`/usr/local`). ++ + (1) + Most Linux distributions include Python as a standard part of the system, so + :file:`{prefix}` and :file:`{exec-prefix}` are usually both :file:`/usr` on +@@ -433,6 +443,15 @@ + + /usr/bin/python setup.py install --prefix=/usr/local + ++Starting with Python-2.6 Debian/Ubuntu does use ++:file:`/usr/lib/python{X.Y}/dist-packages` and ++:file:`/usr/local/lib/python{X.Y}/dist-packages` for the installation ++of python modules included in the Linux distribution. To overwrite ++the name of the site directory, explicitely use the :option:`--prefix` ++option, however make sure that the installation path is included in ++``sys.path``. For packaging of python modules for Debian/Ubuntu, use ++the new ``setup.py install`` option :option:`--install-layout=deb`. ++ + Another possibility is a network filesystem where the name used to write to a + remote directory is different from the name used to read it: for example, the + Python interpreter accessed as :file:`/usr/local/bin/python` might search for +@@ -684,6 +703,17 @@ + import them, this directory must be added to ``sys.path``. There are several + different ways to add the directory. + ++On Debian/Ubuntu, starting with Python-2.6 the convention for system ++installed packages is to put then in the ++:file:`/usr/lib/python{X.Y}/dist-packages/` directory, and for locally ++installed packages is to put them in the ++:file:`/usr/lib/python{X.Y}/dist-packages/` directory. To share the ++locally installed packages for the system provided Python with the ++locally installed packages of a local python installation, make ++:file:`/usr/lib/python{X.Y}/dist-packages/` a symbolic link to the ++:file:`{...}/site-packages/` directory of your local python ++installation. ++ + The most convenient way is to add a path configuration file to a directory + that's already on Python's path, usually to the :file:`.../site-packages/` + directory. Path configuration files have an extension of :file:`.pth`, and each +--- a/Lib/distutils/command/install.py ++++ b/Lib/distutils/command/install.py +@@ -47,6 +47,20 @@ + 'scripts': '$base/bin', + 'data' : '$base', + }, ++ 'unix_local': { ++ 'purelib': '$base/local/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/local/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/local/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/local/bin', ++ 'data' : '$base/local', ++ }, ++ 'deb_system': { ++ 'purelib': '$base/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/bin', ++ 'data' : '$base', ++ }, + 'unix_home': { + 'purelib': '$base/lib/python', + 'platlib': '$base/lib/python', +@@ -154,6 +168,9 @@ + + ('record=', None, + "filename in which to record list of installed files"), ++ ++ ('install-layout=', None, ++ "installation layout to choose (known values: deb, unix)"), + ] + + boolean_options = ['compile', 'force', 'skip-build', 'user'] +@@ -168,6 +185,7 @@ + self.exec_prefix = None + self.home = None + self.user = 0 ++ self.prefix_option = None + + # These select only the installation base; it's up to the user to + # specify the installation scheme (currently, that means supplying +@@ -189,6 +207,9 @@ + self.install_userbase = USER_BASE + self.install_usersite = USER_SITE + ++ # enable custom installation, known values: deb ++ self.install_layout = None ++ + self.compile = None + self.optimize = None + +@@ -421,6 +442,7 @@ + self.install_base = self.install_platbase = self.home + self.select_scheme("unix_home") + else: ++ self.prefix_option = self.prefix + if self.prefix is None: + if self.exec_prefix is not None: + raise DistutilsOptionError, \ +@@ -435,7 +457,23 @@ + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix +- self.select_scheme("unix_prefix") ++ if self.install_layout: ++ if self.install_layout.lower() in ['deb']: ++ self.select_scheme("deb_system") ++ elif self.install_layout.lower() in ['posix', 'unix']: ++ self.select_scheme("unix_prefix") ++ else: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif (self.prefix_option and os.path.normpath(self.prefix) != '/usr/local') \ ++ or 'PYTHONUSERBASE' in os.environ \ ++ or 'real_prefix' in sys.__dict__: ++ self.select_scheme("unix_prefix") ++ else: ++ if os.path.normpath(self.prefix) == '/usr/local': ++ self.select_scheme("deb_system") ++ else: ++ self.select_scheme("unix_local") + + # finalize_unix () + +--- a/Lib/distutils/command/install_egg_info.py ++++ b/Lib/distutils/command/install_egg_info.py +@@ -14,18 +14,37 @@ + description = "Install package's PKG-INFO metadata as an .egg-info file" + user_options = [ + ('install-dir=', 'd', "directory to install to"), ++ ('install-layout', None, "custom installation layout"), + ] + + def initialize_options(self): + self.install_dir = None ++ self.install_layout = None ++ self.prefix_option = None + + def finalize_options(self): + self.set_undefined_options('install_lib',('install_dir','install_dir')) +- basename = "%s-%s-py%s.egg-info" % ( +- to_filename(safe_name(self.distribution.get_name())), +- to_filename(safe_version(self.distribution.get_version())), +- sys.version[:3] +- ) ++ self.set_undefined_options('install',('install_layout','install_layout')) ++ self.set_undefined_options('install',('prefix_option','prefix_option')) ++ if self.install_layout: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) ++ if not self.install_layout.lower() in ['deb']: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif self.prefix_option or 'real_prefix' in sys.__dict__: ++ basename = "%s-%s-py%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())), ++ sys.version[:3] ++ ) ++ else: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -115,6 +115,7 @@ + If 'prefix' is supplied, use it instead of sys.prefix or + sys.exec_prefix -- i.e., ignore 'plat_specific'. + """ ++ is_default_prefix = not prefix or os.path.normpath(prefix) in ('/usr', '/usr/local') + if prefix is None: + prefix = plat_specific and EXEC_PREFIX or PREFIX + +@@ -123,6 +124,8 @@ + "lib", "python" + get_python_version()) + if standard_lib: + return libpython ++ elif is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__: ++ return os.path.join(libpython, "dist-packages") + else: + return os.path.join(libpython, "site-packages") + +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -273,6 +273,13 @@ + + if ENABLE_USER_SITE and os.path.isdir(user_site): + addsitedir(user_site, known_paths) ++ if ENABLE_USER_SITE: ++ for dist_libdir in ("local/lib", "lib"): ++ user_site = os.path.join(USER_BASE, dist_libdir, ++ "python" + sys.version[:3], ++ "dist-packages") ++ if os.path.isdir(user_site): ++ addsitedir(user_site, known_paths) + return known_paths + + def getsitepackages(): +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -16,6 +16,26 @@ + 'scripts': '{base}/bin', + 'data': '{base}', + }, ++ 'posix_local': { ++ 'stdlib': '{base}/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/lib/python{py_version_short}', ++ 'purelib': '{base}/local/lib/python{py_version_short}/dist-packages', ++ 'platlib': '{platbase}/local/lib/python{py_version_short}/dist-packages', ++ 'include': '{base}/local/include/python{py_version_short}', ++ 'platinclude': '{platbase}/local/include/python{py_version_short}', ++ 'scripts': '{base}/local/bin', ++ 'data': '{base}/local', ++ }, ++ 'deb_system': { ++ 'stdlib': '{base}/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/lib/python{py_version_short}', ++ 'purelib': '{base}/lib/python{py_version_short}/dist-packages', ++ 'platlib': '{platbase}/lib/python{py_version_short}/dist-packages', ++ 'include': '{base}/include/python{py_version_short}', ++ 'platinclude': '{platbase}/include/python{py_version_short}', ++ 'scripts': '{base}/bin', ++ 'data': '{base}', ++ }, + 'posix_home': { + 'stdlib': '{base}/lib/python', + 'platstdlib': '{base}/lib/python', +@@ -129,7 +149,7 @@ + _PYTHON_BUILD = is_python_build() + + if _PYTHON_BUILD: +- for scheme in ('posix_prefix', 'posix_home'): ++ for scheme in ('posix_prefix', 'posix_local', 'deb_system', 'posix_home'): + _INSTALL_SCHEMES[scheme]['include'] = '{projectbase}/Include' + _INSTALL_SCHEMES[scheme]['platinclude'] = '{srcdir}' + +@@ -163,8 +183,11 @@ + + def _get_default_scheme(): + if os.name == 'posix': +- # the default scheme for posix is posix_prefix +- return 'posix_prefix' ++ # the default scheme for posix on Debian/Ubuntu is posix_local ++ # FIXME: return dist-packages/posix_prefix only for ++ # is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__ ++ # is_default_prefix = not prefix or os.path.normpath(prefix) in ('/usr', '/usr/local') ++ return 'posix_local' + return os.name + + def _getuserbase(): +@@ -309,7 +332,7 @@ + def _get_makefile_filename(): + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib'), "config", "Makefile") ++ return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile") + + def _generate_posix_vars(): + """Generate the Python module containing build-time variables.""" +@@ -438,7 +461,7 @@ + else: + inc_dir = _PROJECT_BASE + else: +- inc_dir = get_path('platinclude') ++ inc_dir = get_path('platinclude').replace("/usr/local","/usr",1) + return os.path.join(inc_dir, 'pyconfig.h') + + def get_scheme_names(): +--- a/Lib/test/test_import.py ++++ b/Lib/test/test_import.py +@@ -301,7 +301,7 @@ + with check_warnings(('', ImportWarning)): + # Just a random non-package directory we always expect to be + # somewhere in sys.path... +- self.assertRaises(ImportError, __import__, "site-packages") ++ self.assertRaises(ImportError, __import__, "dist-packages") + + def test_import_by_filename(self): + path = os.path.abspath(TESTFN) +--- a/Lib/test/test_site.py ++++ b/Lib/test/test_site.py +@@ -242,10 +242,13 @@ + elif os.sep == '/': + # OS X non-framwework builds, Linux, FreeBSD, etc + self.assertEqual(len(dirs), 2) +- wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], +- 'site-packages') ++ wanted = os.path.join('xoxo', 'local', 'lib', ++ 'python' + sys.version[:3], ++ 'dist-packages') + self.assertEqual(dirs[0], wanted) +- wanted = os.path.join('xoxo', 'lib', 'site-python') ++ wanted = os.path.join('xoxo', 'lib', ++ 'python' + sys.version[:3], ++ 'dist-packages') + self.assertEqual(dirs[1], wanted) + else: + # other platforms +--- a/Lib/test/test_sysconfig.py ++++ b/Lib/test/test_sysconfig.py +@@ -239,8 +239,8 @@ + self.assertTrue(os.path.isfile(config_h), config_h) + + def test_get_scheme_names(self): +- wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', +- 'posix_home', 'posix_prefix', 'posix_user') ++ wanted = ('deb_system', 'nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', ++ 'posix_home', 'posix_local', 'posix_prefix', 'posix_user') + self.assertEqual(get_scheme_names(), wanted) + + def test_symlink(self): +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -195,7 +195,7 @@ + + found = [os.path.basename(line) for line in content.splitlines()] + expected = ['hello.py', 'hello.pyc', 'sayhi', +- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ 'UNKNOWN-0.0.0.egg-info'] + self.assertEqual(found, expected) + + def test_record_extensions(self): +@@ -225,7 +225,7 @@ + + found = [os.path.basename(line) for line in content.splitlines()] + expected = [_make_ext_name('xx'), +- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ 'UNKNOWN-0.0.0.egg-info'] + self.assertEqual(found, expected) + + def test_debug_mode(self): +--- a/Lib/distutils/tests/test_bdist_dumb.py ++++ b/Lib/distutils/tests/test_bdist_dumb.py +@@ -87,7 +87,7 @@ + fp.close() + + contents = sorted(os.path.basename(fn) for fn in contents) +- wanted = ['foo-0.1-py%s.%s.egg-info' % sys.version_info[:2], 'foo.py'] ++ wanted = ['foo-0.1.egg-info', 'foo.py'] + if not sys.dont_write_bytecode: + wanted.append('foo.pyc') + self.assertEqual(contents, sorted(wanted)) +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -359,6 +359,7 @@ + 'marshal', 'posix', 'signal', 'sys', + 'thread', 'zipimport') or + (file.startswith(basedir) and ++ not file.startswith(os.path.join(basedir, 'dist-packages')) and + not file.startswith(os.path.join(basedir, 'site-packages')))) and + object.__name__ not in ('xml.etree', 'test.pydoc_mod')): + if docloc.startswith("http://"): --- python2.7-2.7.6.orig/debian/patches/distutils-link.diff +++ python2.7-2.7.6/debian/patches/distutils-link.diff @@ -0,0 +1,18 @@ +# DP: Don't add standard library dirs to library_dirs and runtime_library_dirs. + +--- a/Lib/distutils/unixccompiler.py ++++ b/Lib/distutils/unixccompiler.py +@@ -155,7 +155,12 @@ + objects, output_dir = self._fix_object_args(objects, output_dir) + libraries, library_dirs, runtime_library_dirs = \ + self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) +- ++ # filter out standard library paths, which are not explicitely needed ++ # for linking ++ library_dirs = [dir for dir in library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] ++ runtime_library_dirs = [dir for dir in runtime_library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, + libraries) + if type(output_dir) not in (StringType, NoneType): --- python2.7-2.7.6.orig/debian/patches/distutils-sysconfig.diff +++ python2.7-2.7.6/debian/patches/distutils-sysconfig.diff @@ -0,0 +1,31 @@ +# DP: Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, +# DP: CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -173,8 +173,8 @@ + _osx_support.customize_compiler(_config_vars) + _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' + +- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ +- get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', ++ (cc, cxx, opt, cflags, extra_cflags, basecflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ ++ get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 'EXTRA_CFLAGS', 'BASECFLAGS', + 'CCSHARED', 'LDSHARED', 'SO', 'AR', + 'ARFLAGS') + +@@ -197,8 +197,13 @@ + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ if 'BASECFLAGS' in os.environ: ++ basecflags = os.environ['BASECFLAGS'] ++ if 'OPT' in os.environ: ++ opt = os.environ['OPT'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, extra_cflags) if x) + if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] --- python2.7-2.7.6.orig/debian/patches/do-not-italicize-punctuation.patch +++ python2.7-2.7.6/debian/patches/do-not-italicize-punctuation.patch @@ -0,0 +1,49 @@ +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -290,9 +290,9 @@ + from that file; + when called with + .B \-c +-.I command, ++.IR command , + it executes the Python statement(s) given as +-.I command. ++.IR command . + Here + .I command + may contain multiple statements separated by newlines. +@@ -302,7 +302,7 @@ + .PP + If available, the script name and additional arguments thereafter are + passed to the script in the Python variable +-.I sys.argv , ++.IR sys.argv , + which is a list of strings (you must first + .I import sys + to be able to access it). +@@ -316,14 +316,14 @@ + .I '-c'. + Note that options interpreted by the Python interpreter itself + are not placed in +-.I sys.argv. ++.IR sys.argv . + .PP + In interactive mode, the primary prompt is `>>>'; the second prompt + (which appears when a command is not complete) is `...'. + The prompts can be changed by assignment to + .I sys.ps1 + or +-.I sys.ps2. ++.IR sys.ps2 . + The interpreter quits when it reads an EOF at a prompt. + When an unhandled exception occurs, a stack trace is printed and + control returns to the primary prompt; in non-interactive mode, the +@@ -382,7 +382,7 @@ + inserted in the path in front of $PYTHONPATH. + The search path can be manipulated from within a Python program as the + variable +-.I sys.path . ++.IR sys.path . + .IP PYTHONSTARTUP + If this is the name of a readable file, the Python commands in that + file are executed before the first prompt is displayed in interactive --- python2.7-2.7.6.orig/debian/patches/doc-nodownload.diff +++ python2.7-2.7.6/debian/patches/doc-nodownload.diff @@ -0,0 +1,13 @@ +# DP: Don't try to download documentation tools + +--- a/Doc/Makefile ++++ b/Doc/Makefile +@@ -57,7 +57,7 @@ + + update: clean checkout + +-build: checkout ++build: + mkdir -p build/$(BUILDER) build/doctrees + $(PYTHON) tools/sphinx-build.py $(ALLSPHINXOPTS) + @echo --- python2.7-2.7.6.orig/debian/patches/enable-fpectl.diff +++ python2.7-2.7.6/debian/patches/enable-fpectl.diff @@ -0,0 +1,14 @@ +# DP: Enable the build of the fpectl module. + +--- a/setup.py ++++ b/setup.py +@@ -1371,6 +1371,9 @@ + else: + missing.append('_curses_panel') + ++ #fpectl fpectlmodule.c ... ++ exts.append( Extension('fpectl', ['fpectlmodule.c']) ) ++ + # Andrew Kuchling's zlib module. Note that some versions of zlib + # 1.1.3 have security problems. See CERT Advisory CA-2002-07: + # http://www.cert.org/advisories/CA-2002-07.html --- python2.7-2.7.6.orig/debian/patches/enable-sqlite-loadext.diff +++ python2.7-2.7.6/debian/patches/enable-sqlite-loadext.diff @@ -0,0 +1,15 @@ +# DP: Allow loading of extensions in the sqlite module + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -1176,7 +1176,7 @@ + sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"')) + + # Comment this out if you want the sqlite3 module to be able to load extensions. +- sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1")) ++ # sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1")) + + if host_platform == 'darwin': + # In every directory on the search path search for a dynamic --- python2.7-2.7.6.orig/debian/patches/ext-no-libpython-link.diff +++ python2.7-2.7.6/debian/patches/ext-no-libpython-link.diff @@ -0,0 +1,22 @@ +# DP: Don't link extensions with the shared libpython library. + +--- a/Lib/distutils/command/build_ext.py ++++ b/Lib/distutils/command/build_ext.py +@@ -234,7 +234,7 @@ + # For building extensions with a shared Python library, + # Python's library directory must be appended to library_dirs + # See Issues: #1600860, #4366 +- if (sysconfig.get_config_var('Py_ENABLE_SHARED')): ++ if False and (sysconfig.get_config_var('Py_ENABLE_SHARED')): + if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")): + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) +@@ -755,7 +755,7 @@ + return ext.libraries + else: + from distutils import sysconfig +- if sysconfig.get_config_var('Py_ENABLE_SHARED'): ++ if False and sysconfig.get_config_var('Py_ENABLE_SHARED'): + template = "python%d.%d" + pythonlib = (template % + (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff)) --- python2.7-2.7.6.orig/debian/patches/hg-updates.diff +++ python2.7-2.7.6/debian/patches/hg-updates.diff @@ -0,0 +1,29630 @@ +# DP: hg updates of the 2.7 release branch (until 2014-03-22). + +# hg diff -r v2.7.6 | filterdiff --exclude=.*ignore --exclude=.hg* --remove-timestamps + +diff -r 3a1db0d2747e Doc/Makefile +--- a/Doc/Makefile ++++ b/Doc/Makefile +@@ -170,6 +170,7 @@ + autobuild-dev: + make update + make dist SPHINXOPTS='-A daily=1 -A versionswitcher=1' ++ -make suspicious + + # for quick rebuilds (HTML only) + autobuild-html: +diff -r 3a1db0d2747e Doc/README.txt +--- a/Doc/README.txt ++++ b/Doc/README.txt +@@ -7,14 +7,13 @@ + + Documentation on the authoring Python documentation, including information about + both style and markup, is available in the "Documenting Python" chapter of the +-documentation. There's also a chapter intended to point out differences to +-those familiar with the previous docs written in LaTeX. ++documentation. + + + Building the docs + ================= + +-You need to have Python 2.4 or higher installed; the toolset used to build the ++You need to have Python 2 installed; the toolset used to build the + docs is written in Python. It is called *Sphinx*, it is not included in this + tree, but maintained separately. Also needed are the docutils, supplying the + base markup that Sphinx uses, Jinja, a templating engine, and optionally +@@ -33,6 +32,9 @@ + HTML output files. To view the generated HTML, point your favorite browser at + the top-level index `build/html/index.html` after running "make". + ++On Windows, we try to emulate the Makefile as closely as possible with a ++``make.bat`` file. ++ + Available make targets are: + + * "html", which builds standalone HTML files for offline viewing. +@@ -65,43 +67,23 @@ + `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and + keyword help. + ++ * "suspicious", which checks the parsed markup for text that looks like ++ malformed and thus unconverted reST. ++ + A "make update" updates the Subversion checkouts in `tools/`. + + + Without make + ------------ + +-You'll need to install the Sphinx package, either by checking it out via :: ++Install the Sphinx package and its dependencies from PyPI. + +- svn co http://svn.python.org/projects/external/Sphinx-0.6.7/sphinx tools/sphinx ++Then, from the ``Docs`` directory, run :: + +-or by installing it from PyPI. ++ sphinx-build -b . build/ + +-Then, you need to install Docutils, either by checking it out via :: +- +- svn co http://svn.python.org/projects/external/docutils-0.6/docutils tools/docutils +- +-or by installing it from http://docutils.sf.net/. +- +-You also need Jinja2, either by checking it out via :: +- +- svn co http://svn.python.org/projects/external/Jinja-2.3.1/jinja2 tools/jinja2 +- +-or by installing it from PyPI. +- +-You can optionally also install Pygments, either as a checkout via :: +- +- svn co http://svn.python.org/projects/external/Pygments-1.3.1/pygments tools/pygments +- +-or from PyPI at http://pypi.python.org/pypi/Pygments. +- +- +-Then, make an output directory, e.g. under `build/`, and run :: +- +- python tools/sphinx-build.py -b . build/ +- +-where `` is one of html, text, latex, or htmlhelp (for explanations see +-the make targets above). ++where ```` is one of html, text, latex, or htmlhelp (for explanations ++see the make targets above). + + + Contributing +@@ -127,7 +109,7 @@ + as long as you don't change or remove the copyright notice: + + ---------------------------------------------------------------------- +-Copyright (c) 2000-2013 Python Software Foundation. ++Copyright (c) 2000-2014 Python Software Foundation. + All rights reserved. + + Copyright (c) 2000 BeOpen.com. +diff -r 3a1db0d2747e Doc/about.rst +--- a/Doc/about.rst ++++ b/Doc/about.rst +@@ -7,14 +7,15 @@ + document processor specifically written for the Python documentation. + + .. _reStructuredText: http://docutils.sf.net/rst.html +-.. _Sphinx: http://sphinx.pocoo.org/ ++.. _Sphinx: http://sphinx-doc.org/ + + .. In the online version of these documents, you can submit comments and suggest + changes directly on the documentation pages. + +-Development of the documentation and its toolchain takes place on the +-docs@python.org mailing list. We're always looking for volunteers wanting +-to help with the docs, so feel free to send a mail there! ++Development of the documentation and its toolchain is an entirely volunteer ++effort, just like Python itself. If you want to contribute, please take a ++look at the :ref:`reporting-bugs` page for information on how to do so. New ++volunteers are always welcome! + + Many thanks go to: + +@@ -26,9 +27,6 @@ + `_ project from which Sphinx got many good + ideas. + +-See :ref:`reporting-bugs` for information how to report bugs in this +-documentation, or Python itself. +- + + Contributors to the Python Documentation + ---------------------------------------- +diff -r 3a1db0d2747e Doc/bugs.rst +--- a/Doc/bugs.rst ++++ b/Doc/bugs.rst +@@ -13,15 +13,17 @@ + ================== + + If you find a bug in this documentation or would like to propose an improvement, +-please send an e-mail to docs@python.org describing the bug and where you found +-it. If you have a suggestion how to fix it, include that as well. ++please submit a bug report on the :ref:`tracker `. If you ++have a suggestion how to fix it, include that as well. + +-docs@python.org is a mailing list run by volunteers; your request will be +-noticed, even if it takes a while to be processed. ++If you're short on time, you can also email your bug report to docs@python.org. ++'docs@' is a mailing list run by volunteers; your request will be noticed, ++though it may take a while to be processed. + +-Of course, if you want a more persistent record of your issue, you can use the +-issue tracker for documentation bugs as well. ++.. seealso:: ++ `Documentation bugs`_ on the Python issue tracker + ++.. _using-the-tracker: + + Using the Python issue tracker + ============================== +@@ -62,9 +64,6 @@ + + .. seealso:: + +- `Python Developer's Guide `_ +- Detailed description of the issue workflow and developers tools. +- + `How to Report Bugs Effectively `_ + Article which goes into some detail about how to create a useful bug report. + This describes what kind of information is useful and why it is useful. +@@ -73,3 +72,16 @@ + Information about writing a good bug report. Some of this is specific to the + Mozilla project, but describes general good practices. + ++ ++Getting started contributing to Python yourself ++=============================================== ++ ++Beyond just reporting bugs that you find, you are also welcome to submit ++patches to fix them. You can find more information on how to get started ++patching Python in the `Python Developer's Guide`_. If you have questions, ++the `core-mentorship mailing list`_ is a friendly place to get answers to ++any and all questions pertaining to the process of fixing issues in Python. ++ ++.. _Documentation bugs: http://bugs.python.org/issue?@filter=status&@filter=components&components=4&status=1&@columns=id,activity,title,status&@sort=-activity ++.. _Python Developer's Guide: http://docs.python.org/devguide/ ++.. _core-mentorship mailing list: https://mail.python.org/mailman/listinfo/core-mentorship/ +diff -r 3a1db0d2747e Doc/c-api/init.rst +--- a/Doc/c-api/init.rst ++++ b/Doc/c-api/init.rst +@@ -534,6 +534,7 @@ + .. index:: module: thread + + .. note:: ++ + When only the main thread exists, no GIL operations are needed. This is a + common situation (most Python programs do not use threads), and the lock + operations slow the interpreter down a bit. Therefore, the lock is not +diff -r 3a1db0d2747e Doc/copyright.rst +--- a/Doc/copyright.rst ++++ b/Doc/copyright.rst +@@ -4,7 +4,7 @@ + + Python and this documentation is: + +-Copyright © 2001-2013 Python Software Foundation. All rights reserved. ++Copyright © 2001-2014 Python Software Foundation. All rights reserved. + + Copyright © 2000 BeOpen.com. All rights reserved. + +diff -r 3a1db0d2747e Doc/distutils/apiref.rst +--- a/Doc/distutils/apiref.rst ++++ b/Doc/distutils/apiref.rst +@@ -1167,15 +1167,6 @@ + underscore. No { } or ( ) style quoting is available. + + +-.. function:: grok_environment_error(exc[, prefix='error: ']) +- +- Generate a useful error message from an :exc:`EnvironmentError` (:exc:`IOError` +- or :exc:`OSError`) exception object. Handles Python 1.5.1 and later styles, +- and does what it can to deal with exception objects that don't have a filename +- (which happens when the error is due to a two-file operation, such as +- :func:`~os.rename` or :func:`~os.link`). Returns the error message as a +- string prefixed with *prefix*. +- + + .. function:: split_quoted(s) + +@@ -1916,8 +1907,12 @@ + .. module:: distutils.command.clean + :synopsis: Clean a package build area + +- +-.. % todo ++This command removes the temporary files created by :command:`build` ++and its subcommands, like intermediary compiled object files. With ++the ``--all`` option, the complete build directory will be removed. ++ ++Extension modules built :ref:`in place ` ++will not be cleaned, as they are not in the build directory. + + + :mod:`distutils.command.config` --- Perform package configuration +diff -r 3a1db0d2747e Doc/distutils/configfile.rst +--- a/Doc/distutils/configfile.rst ++++ b/Doc/distutils/configfile.rst +@@ -69,6 +69,8 @@ + Note that an option spelled :option:`--foo-bar` on the command-line is spelled + :option:`foo_bar` in configuration files. + ++.. _distutils-build-ext-inplace: ++ + For example, say you want your extensions to be built "in-place"---that is, you + have an extension :mod:`pkg.ext`, and you want the compiled extension file + (:file:`ext.so` on Unix, say) to be put in the same source directory as your +diff -r 3a1db0d2747e Doc/distutils/index.rst +--- a/Doc/distutils/index.rst ++++ b/Doc/distutils/index.rst +@@ -12,6 +12,16 @@ + make Python modules and extensions easily available to a wider audience with + very little overhead for build/release/install mechanics. + ++.. note:: ++ ++ This guide only covers the basic tools for building and distributing ++ extensions that are provided as part of this version of Python. Third ++ party tools offer easier to use and more secure alternatives. Refer to the ++ `quick recommendations section ++ `__ ++ in the Python Packaging User Guide for more information. ++ ++ + .. toctree:: + :maxdepth: 2 + :numbered: +diff -r 3a1db0d2747e Doc/distutils/setupscript.rst +--- a/Doc/distutils/setupscript.rst ++++ b/Doc/distutils/setupscript.rst +@@ -684,6 +684,8 @@ + DistributionMetadata.download_url = None + + ++.. _debug-setup-script: ++ + Debugging the setup script + ========================== + +@@ -699,7 +701,8 @@ + and see that it's a permission problem. + + On the other hand, this doesn't help the developer to find the cause of the +-failure. For this purpose, the DISTUTILS_DEBUG environment variable can be set ++failure. For this purpose, the :envvar:`DISTUTILS_DEBUG` environment variable can be set + to anything except an empty string, and distutils will now print detailed +-information what it is doing, and prints the full traceback in case an exception +-occurs. ++information about what it is doing, dump the full traceback when an exception ++occurs, and print the whole command line when an external program (like a C ++compiler) fails. +diff -r 3a1db0d2747e Doc/extending/index.rst +--- a/Doc/extending/index.rst ++++ b/Doc/extending/index.rst +@@ -21,6 +21,15 @@ + For a detailed description of the whole Python/C API, see the separate + :ref:`c-api-index`. + ++.. note:: ++ ++ This guide only covers the basic tools for creating extensions provided ++ as part of this version of CPython. Third party tools may offer simpler ++ alternatives. Refer to the `binary extensions section ++ `__ ++ in the Python Packaging User Guide for more information. ++ ++ + .. toctree:: + :maxdepth: 2 + :numbered: +diff -r 3a1db0d2747e Doc/faq/general.rst +--- a/Doc/faq/general.rst ++++ b/Doc/faq/general.rst +@@ -181,8 +181,8 @@ + also available at http://docs.python.org/download.html. + + The documentation is written in reStructuredText and processed by `the Sphinx +-documentation tool `__. The reStructuredText source +-for the documentation is part of the Python source distribution. ++documentation tool `__. The reStructuredText source for ++the documentation is part of the Python source distribution. + + + I've never programmed before. Is there a Python tutorial? +@@ -268,9 +268,13 @@ + Where in the world is www.python.org located? + --------------------------------------------- + +-It's currently in Amsterdam, graciously hosted by `XS4ALL +-`_. Thanks to Thomas Wouters for his work in arranging +-python.org's hosting. ++The Python project's infrastructure is located all over the world. ++`www.python.org `_ is currently in Amsterdam, graciously ++hosted by `XS4ALL `_. `Upfront Systems ++`_ hosts `bugs.python.org ++`_. Most other Python services like `PyPI ++`_ and hg.python.org are hosted by `Oregon State ++University Open Source Lab `_. + + + Why is it called Python? +@@ -467,7 +471,8 @@ + Emacs users will be happy to know that there is a very good Python mode for + Emacs. All of these programming environments provide syntax highlighting, + auto-indenting, and access to the interactive interpreter while coding. Consult +-http://www.python.org/editors/ for a full list of Python editing environments. ++`the Python wiki `_ for a full list ++of Python editing environments. + + If you want to discuss Python's use in education, you may be interested in + joining `the edu-sig mailing list +diff -r 3a1db0d2747e Doc/faq/library.rst +--- a/Doc/faq/library.rst ++++ b/Doc/faq/library.rst +@@ -640,7 +640,7 @@ + .. XXX check if wiki page is still up to date + + A summary of available frameworks is maintained by Paul Boddie at +-http://wiki.python.org/moin/WebProgramming . ++http://wiki.python.org/moin/WebProgramming\ . + + Cameron Laird maintains a useful set of pages about Python web technologies at + http://phaseit.net/claird/comp.lang.python/web_python. +diff -r 3a1db0d2747e Doc/faq/programming.rst +--- a/Doc/faq/programming.rst ++++ b/Doc/faq/programming.rst +@@ -910,7 +910,7 @@ + >>> a = array.array('c', s) + >>> print a + array('c', 'Hello, world') +- >>> a[0] = 'y' ; print a ++ >>> a[0] = 'y'; print a + array('c', 'yello, world') + >>> a.tostring() + 'yello, world' +diff -r 3a1db0d2747e Doc/faq/windows.rst +--- a/Doc/faq/windows.rst ++++ b/Doc/faq/windows.rst +@@ -243,7 +243,7 @@ + ... + Py_Initialize(); // Initialize Python. + initmyAppc(); // Initialize (import) the helper class. +- PyRun_SimpleString("import myApp") ; // Import the shadow class. ++ PyRun_SimpleString("import myApp"); // Import the shadow class. + + 5. There are two problems with Python's C API which will become apparent if you + use a compiler other than MSVC, the compiler used to build pythonNN.dll. +diff -r 3a1db0d2747e Doc/howto/descriptor.rst +--- a/Doc/howto/descriptor.rst ++++ b/Doc/howto/descriptor.rst +@@ -167,7 +167,7 @@ + return self.val + + def __set__(self, obj, val): +- print 'Updating' , self.name ++ print 'Updating', self.name + self.val = val + + >>> class MyClass(object): +diff -r 3a1db0d2747e Doc/howto/functional.rst +--- a/Doc/howto/functional.rst ++++ b/Doc/howto/functional.rst +@@ -743,8 +743,8 @@ + Python wiki at http://wiki.python.org/moin/HowTo/Sorting.) + + The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an +-iterable's contents. :func:`any` returns True if any element in the iterable is +-a true value, and :func:`all` returns True if all of the elements are true ++iterable's contents. :func:`any` returns ``True`` if any element in the iterable is ++a true value, and :func:`all` returns ``True`` if all of the elements are true + values: + + >>> any([0,1,0]) +diff -r 3a1db0d2747e Doc/howto/logging-cookbook.rst +--- a/Doc/howto/logging-cookbook.rst ++++ b/Doc/howto/logging-cookbook.rst +@@ -835,3 +835,222 @@ + Note that the order of items might be different according to the version of + Python used. + ++ ++.. _custom-handlers: ++ ++.. currentmodule:: logging.config ++ ++Customizing handlers with :func:`dictConfig` ++-------------------------------------------- ++ ++There are times when you want to customize logging handlers in particular ways, ++and if you use :func:`dictConfig` you may be able to do this without ++subclassing. As an example, consider that you may want to set the ownership of a ++log file. On POSIX, this is easily done using :func:`shutil.chown`, but the file ++handlers in the stdlib don't offer built-in support. You can customize handler ++creation using a plain function such as:: ++ ++ def owned_file_handler(filename, mode='a', encoding=None, owner=None): ++ if owner: ++ if not os.path.exists(filename): ++ open(filename, 'a').close() ++ shutil.chown(filename, *owner) ++ return logging.FileHandler(filename, mode, encoding) ++ ++You can then specify, in a logging configuration passed to :func:`dictConfig`, ++that a logging handler be created by calling this function:: ++ ++ LOGGING = { ++ 'version': 1, ++ 'disable_existing_loggers': False, ++ 'formatters': { ++ 'default': { ++ 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' ++ }, ++ }, ++ 'handlers': { ++ 'file':{ ++ # The values below are popped from this dictionary and ++ # used to create the handler, set the handler's level and ++ # its formatter. ++ '()': owned_file_handler, ++ 'level':'DEBUG', ++ 'formatter': 'default', ++ # The values below are passed to the handler creator callable ++ # as keyword arguments. ++ 'owner': ['pulse', 'pulse'], ++ 'filename': 'chowntest.log', ++ 'mode': 'w', ++ 'encoding': 'utf-8', ++ }, ++ }, ++ 'root': { ++ 'handlers': ['file'], ++ 'level': 'DEBUG', ++ }, ++ } ++ ++In this example I am setting the ownership using the ``pulse`` user and group, ++just for the purposes of illustration. Putting it together into a working ++script, ``chowntest.py``:: ++ ++ import logging, logging.config, os, shutil ++ ++ def owned_file_handler(filename, mode='a', encoding=None, owner=None): ++ if owner: ++ if not os.path.exists(filename): ++ open(filename, 'a').close() ++ shutil.chown(filename, *owner) ++ return logging.FileHandler(filename, mode, encoding) ++ ++ LOGGING = { ++ 'version': 1, ++ 'disable_existing_loggers': False, ++ 'formatters': { ++ 'default': { ++ 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' ++ }, ++ }, ++ 'handlers': { ++ 'file':{ ++ # The values below are popped from this dictionary and ++ # used to create the handler, set the handler's level and ++ # its formatter. ++ '()': owned_file_handler, ++ 'level':'DEBUG', ++ 'formatter': 'default', ++ # The values below are passed to the handler creator callable ++ # as keyword arguments. ++ 'owner': ['pulse', 'pulse'], ++ 'filename': 'chowntest.log', ++ 'mode': 'w', ++ 'encoding': 'utf-8', ++ }, ++ }, ++ 'root': { ++ 'handlers': ['file'], ++ 'level': 'DEBUG', ++ }, ++ } ++ ++ logging.config.dictConfig(LOGGING) ++ logger = logging.getLogger('mylogger') ++ logger.debug('A debug message') ++ ++To run this, you will probably need to run as ``root``:: ++ ++ $ sudo python3.3 chowntest.py ++ $ cat chowntest.log ++ 2013-11-05 09:34:51,128 DEBUG mylogger A debug message ++ $ ls -l chowntest.log ++ -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log ++ ++Note that this example uses Python 3.3 because that's where :func:`shutil.chown` ++makes an appearance. This approach should work with any Python version that ++supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3 ++versions, you would need to implement the actual ownership change using e.g. ++:func:`os.chown`. ++ ++In practice, the handler-creating function may be in a utility module somewhere ++in your project. Instead of the line in the configuration:: ++ ++ '()': owned_file_handler, ++ ++you could use e.g.:: ++ ++ '()': 'ext://project.util.owned_file_handler', ++ ++where ``project.util`` can be replaced with the actual name of the package ++where the function resides. In the above working script, using ++``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable ++is resolved by :func:`dictConfig` from the ``ext://`` specification. ++ ++This example hopefully also points the way to how you could implement other ++types of file change - e.g. setting specific POSIX permission bits - in the ++same way, using :func:`os.chmod`. ++ ++Of course, the approach could also be extended to types of handler other than a ++:class:`~logging.FileHandler` - for example, one of the rotating file handlers, ++or a different type of handler altogether. ++ ++ ++.. _filters-dictconfig: ++ ++Configuring filters with :func:`dictConfig` ++------------------------------------------- ++ ++You *can* configure filters using :func:`~logging.config.dictConfig`, though it ++might not be obvious at first glance how to do it (hence this recipe). Since ++:class:`~logging.Filter` is the only filter class included in the standard ++library, and it is unlikely to cater to many requirements (it's only there as a ++base class), you will typically need to define your own :class:`~logging.Filter` ++subclass with an overridden :meth:`~logging.Filter.filter` method. To do this, ++specify the ``()`` key in the configuration dictionary for the filter, ++specifying a callable which will be used to create the filter (a class is the ++most obvious, but you can provide any callable which returns a ++:class:`~logging.Filter` instance). Here is a complete example:: ++ ++ import logging ++ import logging.config ++ import sys ++ ++ class MyFilter(logging.Filter): ++ def __init__(self, param=None): ++ self.param = param ++ ++ def filter(self, record): ++ if self.param is None: ++ allow = True ++ else: ++ allow = self.param not in record.msg ++ if allow: ++ record.msg = 'changed: ' + record.msg ++ return allow ++ ++ LOGGING = { ++ 'version': 1, ++ 'filters': { ++ 'myfilter': { ++ '()': MyFilter, ++ 'param': 'noshow', ++ } ++ }, ++ 'handlers': { ++ 'console': { ++ 'class': 'logging.StreamHandler', ++ 'filters': ['myfilter'] ++ } ++ }, ++ 'root': { ++ 'level': 'DEBUG', ++ 'handlers': ['console'] ++ }, ++ } ++ ++ if __name__ == '__main__': ++ logging.config.dictConfig(LOGGING) ++ logging.debug('hello') ++ logging.debug('hello - noshow') ++ ++This example shows how you can pass configuration data to the callable which ++constructs the instance, in the form of keyword parameters. When run, the above ++script will print:: ++ ++ changed: hello ++ ++which shows that the filter is working as configured. ++ ++A couple of extra points to note: ++ ++* If you can't refer to the callable directly in the configuration (e.g. if it ++ lives in a different module, and you can't import it directly where the ++ configuration dictionary is), you can use the form ``ext://...`` as described ++ in :ref:`logging-config-dict-externalobj`. For example, you could have used ++ the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above ++ example. ++ ++* As well as for filters, this technique can also be used to configure custom ++ handlers and formatters. See :ref:`logging-config-dict-userdef` for more ++ information on how logging supports using user-defined objects in its ++ configuration, and see the other cookbook recipe :ref:`custom-handlers` above. ++ +diff -r 3a1db0d2747e Doc/howto/logging.rst +--- a/Doc/howto/logging.rst ++++ b/Doc/howto/logging.rst +@@ -122,7 +122,8 @@ + ^^^^^^^^^^^^^^^^^ + + A very common situation is that of recording logging events in a file, so let's +-look at that next:: ++look at that next. Be sure to try the following in a newly-started Python ++interpreter, and don't just continue from the session described above:: + + import logging + logging.basicConfig(filename='example.log',level=logging.DEBUG) +diff -r 3a1db0d2747e Doc/howto/pyporting.rst +--- a/Doc/howto/pyporting.rst ++++ b/Doc/howto/pyporting.rst +@@ -10,238 +10,211 @@ + + With Python 3 being the future of Python while Python 2 is still in active + use, it is good to have your project available for both major releases of +- Python. This guide is meant to help you choose which strategy works best +- for your project to support both Python 2 & 3 along with how to execute +- that strategy. ++ Python. This guide is meant to help you figure out how best to support both ++ Python 2 & 3 simultaneously. + + If you are looking to port an extension module instead of pure Python code, + please see :ref:`cporting-howto`. + ++ If you would like to read one core Python developer's take on why Python 3 ++ came into existence, you can read Nick Coghlan's `Python 3 Q & A`_. + +-Choosing a Strategy +-=================== ++ If you prefer to read a (free) book on porting a project to Python 3, ++ consider reading `Porting to Python 3`_ by Lennart Regebro which should cover ++ much of what is discussed in this HOWTO. + +-When a project makes the decision that it's time to support both Python 2 & 3, +-a decision needs to be made as to how to go about accomplishing that goal. +-The chosen strategy will depend on how large the project's existing +-codebase is and how much divergence you want from your Python 2 codebase from +-your Python 3 one (e.g., starting a new version with Python 3). ++ For help with porting, you can email the python-porting_ mailing list with ++ questions. + +-If your project is brand-new or does not have a large codebase, then you may +-want to consider writing/porting :ref:`all of your code for Python 3 +-and use 3to2 ` to port your code for Python 2. ++The Short Version ++================= + +-If you would prefer to maintain a codebase which is semantically **and** +-syntactically compatible with Python 2 & 3 simultaneously, you can write +-:ref:`use_same_source`. While this tends to lead to somewhat non-idiomatic +-code, it does mean you keep a rapid development process for you, the developer. ++* Decide what's the oldest version of Python 2 you want to support (if at all) ++* Make sure you have a thorough test suite and use continuous integration ++ testing to make sure you stay compatible with the versions of Python you care ++ about ++* If you have dependencies, check their Python 3 status using caniusepython3 ++ (`command-line tool `__, ++ `web app `__) + +-Finally, you do have the option of :ref:`using 2to3 ` to translate +-Python 2 code into Python 3 code (with some manual help). This can take the +-form of branching your code and using 2to3 to start a Python 3 branch. You can +-also have users perform the translation at installation time automatically so +-that you only have to maintain a Python 2 codebase. ++With that done, your options are: + +-Regardless of which approach you choose, porting is not as hard or +-time-consuming as you might initially think. You can also tackle the problem +-piece-meal as a good portion of porting is simply updating your code to follow +-current best practices in a Python 2/3 compatible way. ++* If you are dropping Python 2 support, use 2to3_ to port to Python 3 ++* If you are keeping Python 2 support, then start writing Python 2/3-compatible ++ code starting **TODAY** + ++ + If you have dependencies that have not been ported, reach out to them to port ++ their project while working to make your code compatible with Python 3 so ++ you're ready when your dependencies are all ported ++ + If all your dependencies have been ported (or you have none), go ahead and ++ port to Python 3 + +-Universal Bits of Advice +------------------------- ++* If you are creating a new project that wants to have 2/3 compatibility, ++ code in Python 3 and then backport to Python 2 + +-Regardless of what strategy you pick, there are a few things you should +-consider. + +-One is make sure you have a robust test suite. You need to make sure everything +-continues to work, just like when you support a new minor version of Python. +-This means making sure your test suite is thorough and is ported properly +-between Python 2 & 3. You will also most likely want to use something like tox_ +-to automate testing between both a Python 2 and Python 3 VM. ++Before You Begin ++================ + +-Two, once your project has Python 3 support, make sure to add the proper +-classifier on the Cheeseshop_ (PyPI_). To have your project listed as Python 3 +-compatible it must have the +-`Python 3 classifier `_ +-(from +-http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/):: ++If your project is on the Cheeseshop_/PyPI_, make sure it has the proper ++`trove classifiers`_ to signify what versions of Python it **currently** ++supports. At minimum you should specify the major version(s), e.g. ++``Programming Language :: Python :: 2`` if your project currently only supports ++Python 2. It is preferrable that you be as specific as possible by listing every ++major/minor version of Python that you support, e.g. if your project supports ++Python 2.6 and 2.7, then you want the classifiers of:: + +- setup( +- name='Your Library', +- version='1.0', +- classifiers=[ +- # make sure to use :: Python *and* :: Python :: 3 so +- # that pypi can list the package on the python 3 page +- 'Programming Language :: Python', +- 'Programming Language :: Python :: 3' +- ], +- packages=['yourlibrary'], +- # make sure to add custom_fixers to the MANIFEST.in +- include_package_data=True, +- # ... +- ) ++ Programming Language :: Python :: 2 ++ Programming Language :: Python :: 2.6 ++ Programming Language :: Python :: 2.7 + ++Once your project supports Python 3 you will want to go back and add the ++appropriate classifiers for Python 3 as well. This is important as setting the ++``Programming Language :: Python :: 3`` classifier will lead to your project ++being listed under the `Python 3 Packages`_ section of PyPI. + +-Doing so will cause your project to show up in the +-`Python 3 packages list +-`_. You will know +-you set the classifier properly as visiting your project page on the Cheeseshop +-will show a Python 3 logo in the upper-left corner of the page. ++Make sure you have a robust test suite. You need to ++make sure everything continues to work, just like when you support a new ++minor/feature release of Python. This means making sure your test suite is ++thorough and is ported properly between Python 2 & 3 (consider using coverage_ ++to measure that you have effective test coverage). You will also most likely ++want to use something like tox_ to automate testing between all of your ++supported versions of Python. You will also want to **port your tests first** so ++that you can make sure that you detect breakage during the transition. Tests also ++tend to be simpler than the code they are testing so it gives you an idea of how ++easy it can be to port code. + +-Three, the six_ project provides a library which helps iron out differences +-between Python 2 & 3. If you find there is a sticky point that is a continual +-point of contention in your translation or maintenance of code, consider using +-a source-compatible solution relying on six. If you have to create your own +-Python 2/3 compatible solution, you can use ``sys.version_info[0] >= 3`` as a +-guard. +- +-Four, read all the approaches. Just because some bit of advice applies to one +-approach more than another doesn't mean that some advice doesn't apply to other +-strategies. +- +-Five, drop support for older Python versions if possible. `Python 2.5`_ ++Drop support for older Python versions if possible. `Python 2.5`_ + introduced a lot of useful syntax and libraries which have become idiomatic + in Python 3. `Python 2.6`_ introduced future statements which makes + compatibility much easier if you are going from Python 2 to 3. +-`Python 2.7`_ continues the trend in the stdlib. So choose the newest version ++`Python 2.7`_ continues the trend in the stdlib. Choose the newest version + of Python which you believe can be your minimum support version + and work from there. + ++Target the newest version of Python 3 that you can. Beyond just the usual ++bugfixes, compatibility has continued to improve between Python 2 and 3 as time ++has passed. E.g. Python 3.3 added back the ``u`` prefix for ++strings, making source-compatible Python code easier to write. + +-.. _tox: http://codespeak.net/tox/ +-.. _Cheeseshop: +-.. _PyPI: http://pypi.python.org/ +-.. _six: http://packages.python.org/six +-.. _Python 2.7: http://www.python.org/2.7.x +-.. _Python 2.6: http://www.python.org/2.6.x +-.. _Python 2.5: http://www.python.org/2.5.x +-.. _Python 2.4: http://www.python.org/2.4.x +-.. _Python 2.3: http://www.python.org/2.3.x +-.. _Python 2.2: http://www.python.org/2.2.x + ++Writing Source-Compatible Python 2/3 Code ++========================================= + +-.. _use_3to2: ++Over the years the Python community has discovered that the easiest way to ++support both Python 2 and 3 in parallel is to write Python code that works in ++either version. While this might sound counter-intuitive at first, it actually ++is not difficult and typically only requires following some select ++(non-idiomatic) practices and using some key projects to help make bridging ++between Python 2 and 3 easier. + +-Python 3 and 3to2 +-================= ++Projects to Consider ++-------------------- + +-If you are starting a new project or your codebase is small enough, you may +-want to consider writing your code for Python 3 and backporting to Python 2 +-using 3to2_. Thanks to Python 3 being more strict about things than Python 2 +-(e.g., bytes vs. strings), the source translation can be easier and more +-straightforward than from Python 2 to 3. Plus it gives you more direct +-experience developing in Python 3 which, since it is the future of Python, is a +-good thing long-term. ++The lowest level library for supporting Python 2 & 3 simultaneously is six_. ++Reading through its documentation will give you an idea of where exactly the ++Python language changed between versions 2 & 3 and thus what you will want the ++library to help you continue to support. + +-A drawback of this approach is that 3to2 is a third-party project. This means +-that the Python core developers (and thus this guide) can make no promises +-about how well 3to2 works at any time. There is nothing to suggest, though, +-that 3to2 is not a high-quality project. ++To help automate porting your code over to using six, you can use ++modernize_. This project will attempt to rewrite your code to be as modern as ++possible while using six to smooth out any differences between Python 2 & 3. + ++If you want to write your compatible code to feel more like Python 3 there is ++the future_ project. It tries to provide backports of objects from Python 3 so ++that you can use them from Python 2-compatible code, e.g. replacing the ++``bytes`` type from Python 2 with the one from Python 3. ++It also provides a translation script like modernize (its translation code is ++actually partially based on it) to help start working with a pre-existing code ++base. It is also unique in that its translation script will also port Python 3 ++code backwards as well as Python 2 code forwards. + +-.. _3to2: https://bitbucket.org/amentajo/lib3to2/overview + ++Tips & Tricks ++------------- + +-.. _use_2to3: +- +-Python 2 and 2to3 +-================= +- +-Included with Python since 2.6, the 2to3_ tool (and :mod:`lib2to3` module) +-helps with porting Python 2 to Python 3 by performing various source +-translations. This is a perfect solution for projects which wish to branch +-their Python 3 code from their Python 2 codebase and maintain them as +-independent codebases. You can even begin preparing to use this approach +-today by writing future-compatible Python code which works cleanly in +-Python 2 in conjunction with 2to3; all steps outlined below will work +-with Python 2 code up to the point when the actual use of 2to3 occurs. +- +-Use of 2to3 as an on-demand translation step at install time is also possible, +-preventing the need to maintain a separate Python 3 codebase, but this approach +-does come with some drawbacks. While users will only have to pay the +-translation cost once at installation, you as a developer will need to pay the +-cost regularly during development. If your codebase is sufficiently large +-enough then the translation step ends up acting like a compilation step, +-robbing you of the rapid development process you are used to with Python. +-Obviously the time required to translate a project will vary, so do an +-experimental translation just to see how long it takes to evaluate whether you +-prefer this approach compared to using :ref:`use_same_source` or simply keeping +-a separate Python 3 codebase. +- +-Below are the typical steps taken by a project which uses a 2to3-based approach +-to supporting Python 2 & 3. +- ++To help with writing source-compatible code using one of the projects mentioned ++in `Projects to Consider`_, consider following the below suggestions. Some of ++them are handled by the suggested projects, so if you do use one of them then ++read their documentation first to see which suggestions below will taken care of ++for you. + + Support Python 2.7 +------------------- ++////////////////// + + As a first step, make sure that your project is compatible with `Python 2.7`_. + This is just good to do as Python 2.7 is the last release of Python 2 and thus + will be used for a rather long time. It also allows for use of the ``-3`` flag +-to Python to help discover places in your code which 2to3 cannot handle but are +-known to cause issues. ++to Python to help discover places in your code where compatibility might be an ++issue (the ``-3`` flag is in Python 2.6 but Python 2.7 adds more warnings). + + Try to Support `Python 2.6`_ and Newer Only +-------------------------------------------- ++/////////////////////////////////////////// + + While not possible for all projects, if you can support `Python 2.6`_ and newer + **only**, your life will be much easier. Various future statements, stdlib + additions, etc. exist only in Python 2.6 and later which greatly assist in +-porting to Python 3. But if you project must keep support for `Python 2.5`_ (or +-even `Python 2.4`_) then it is still possible to port to Python 3. ++supporting Python 3. But if you project must keep support for `Python 2.5`_ then ++it is still possible to simultaneously support Python 3. + + Below are the benefits you gain if you only have to support Python 2.6 and + newer. Some of these options are personal choice while others are + **strongly** recommended (the ones that are more for personal choice are + labeled as such). If you continue to support older versions of Python then you +-at least need to watch out for situations that these solutions fix. ++at least need to watch out for situations that these solutions fix and handle ++them appropriately (which is where library help from e.g. six_ comes in handy). + + + ``from __future__ import print_function`` + ''''''''''''''''''''''''''''''''''''''''' + +-This is a personal choice. 2to3 handles the translation from the print +-statement to the print function rather well so this is an optional step. This +-future statement does help, though, with getting used to typing +-``print('Hello, World')`` instead of ``print 'Hello, World'``. ++It will not only get you used to typing ``print()`` as a function instead of a ++statement, but it will also give you the various benefits the function has over ++the Python 2 statement (six_ provides a function if you support Python 2.5 or ++older). + + + ``from __future__ import unicode_literals`` + ''''''''''''''''''''''''''''''''''''''''''' + +-Another personal choice. You can always mark what you want to be a (unicode) +-string with a ``u`` prefix to get the same effect. But regardless of whether +-you use this future statement or not, you **must** make sure you know exactly +-which Python 2 strings you want to be bytes, and which are to be strings. This +-means you should, **at minimum** mark all strings that are meant to be text +-strings with a ``u`` prefix if you do not use this future statement. ++If you choose to use this future statement then all string literals in ++Python 2 will be assumed to be Unicode (as is already the case in Python 3). ++If you choose not to use this future statement then you should mark all of your ++text strings with a ``u`` prefix and only support Python 3.3 or newer. But you ++are **strongly** advised to do one or the other (six_ provides a function in ++case you don't want to use the future statement **and** you want to support ++Python 3.2 or older). + + +-Bytes literals +-'''''''''''''' ++Bytes/string literals ++''''''''''''''''''''' + +-This is a **very** important one. The ability to prefix Python 2 strings that +-are meant to contain bytes with a ``b`` prefix help to very clearly delineate +-what is and is not a Python 3 string. When you run 2to3 on code, all Python 2 +-strings become Python 3 strings **unless** they are prefixed with ``b``. ++This is a **very** important one. Prefix Python 2 strings that ++are meant to contain bytes with a ``b`` prefix to very clearly delineate ++what is and is not a Python 3 text string (six_ provides a function to use for ++Python 2.5 compatibility). ++ ++This point cannot be stressed enough: make sure you know what all of your string ++literals in Python 2 are meant to be in Python 3. Any string literal that ++should be treated as bytes should have the ``b`` prefix. Any string literal ++that should be Unicode/text in Python 2 should either have the ``u`` literal ++(supported, but ignored, in Python 3.3 and later) or you should have ++``from __future__ import unicode_literals`` at the top of the file. But the key ++point is you should know how Python 3 will treat every one one of your string ++literals and you should mark them as appropriate. + + There are some differences between byte literals in Python 2 and those in + Python 3 thanks to the bytes type just being an alias to ``str`` in Python 2. +-Probably the biggest "gotcha" is that indexing results in different values. In +-Python 2, the value of ``b'py'[1]`` is ``'y'``, while in Python 3 it's ``121``. +-You can avoid this disparity by always slicing at the size of a single element: +-``b'py'[1:2]`` is ``'y'`` in Python 2 and ``b'y'`` in Python 3 (i.e., close +-enough). ++See the `Handle Common "Gotchas"`_ section for what to watch out for. + +-You cannot concatenate bytes and strings in Python 3. But since Python +-2 has bytes aliased to ``str``, it will succeed: ``b'a' + u'b'`` works in +-Python 2, but ``b'a' + 'b'`` in Python 3 is a :exc:`TypeError`. A similar issue +-also comes about when doing comparisons between bytes and strings. ++``from __future__ import absolute_import`` ++'''''''''''''''''''''''''''''''''''''''''' ++Discussed in more detail below, but you should use this future statement to ++prevent yourself from accidentally using implicit relative imports. + + + Supporting `Python 2.5`_ and Newer Only +---------------------------------------- ++/////////////////////////////////////// + + If you are supporting `Python 2.5`_ and newer there are still some features of + Python that you can utilize. +@@ -251,7 +224,7 @@ + '''''''''''''''''''''''''''''''''''''''''' + + Implicit relative imports (e.g., importing ``spam.bacon`` from within +-``spam.eggs`` with the statement ``import bacon``) does not work in Python 3. ++``spam.eggs`` with the statement ``import bacon``) do not work in Python 3. + This future statement moves away from that and allows the use of explicit + relative imports (e.g., ``from . import bacon``). + +@@ -261,16 +234,74 @@ + the statement, but you still want the __future__ statement to prevent implicit + relative imports. In `Python 2.7`_ the __future__ statement is not needed. In + other words, unless you are only supporting Python 2.7 or a version earlier +-than Python 2.5, use the __future__ statement. ++than Python 2.5, use this __future__ statement. + + ++Mark all Unicode strings with a ``u`` prefix ++''''''''''''''''''''''''''''''''''''''''''''' ++ ++While Python 2.6 has a ``__future__`` statement to automatically cause Python 2 ++to treat all string literals as Unicode, Python 2.5 does not have that shortcut. ++This means you should go through and mark all string literals with a ``u`` ++prefix to turn them explicitly into text strings where appropriate and only ++support Python 3.3 or newer. Otherwise use a project like six_ which provides a ++function to pass all text string literals through. ++ ++ ++Capturing the Currently Raised Exception ++'''''''''''''''''''''''''''''''''''''''' ++ ++In Python 2.5 and earlier the syntax to access the current exception is:: ++ ++ try: ++ raise Exception() ++ except Exception, exc: ++ # Current exception is 'exc'. ++ pass ++ ++This syntax changed in Python 3 (and backported to `Python 2.6`_ and later) ++to:: ++ ++ try: ++ raise Exception() ++ except Exception as exc: ++ # Current exception is 'exc'. ++ # In Python 3, 'exc' is restricted to the block; in Python 2.6/2.7 it will "leak". ++ pass ++ ++Because of this syntax change you must change how you capture the current ++exception in Python 2.5 and earlier to:: ++ ++ try: ++ raise Exception() ++ except Exception: ++ import sys ++ exc = sys.exc_info()[1] ++ # Current exception is 'exc'. ++ pass ++ ++You can get more information about the raised exception from ++:func:`sys.exc_info` than simply the current exception instance, but you most ++likely don't need it. ++ ++.. note:: ++ In Python 3, the traceback is attached to the exception instance ++ through the ``__traceback__`` attribute. If the instance is saved in ++ a local variable that persists outside of the ``except`` block, the ++ traceback will create a reference cycle with the current frame and its ++ dictionary of local variables. This will delay reclaiming dead ++ resources until the next cyclic :term:`garbage collection` pass. ++ ++ In Python 2, this problem only occurs if you save the traceback itself ++ (e.g. the third element of the tuple returned by :func:`sys.exc_info`) ++ in a variable. ++ + + Handle Common "Gotchas" +------------------------ ++/////////////////////// + +-There are a few things that just consistently come up as sticking points for +-people which 2to3 cannot handle automatically or can easily be done in Python 2 +-to help modernize your code. ++These are things to watch out for no matter what version of Python 2 you are ++supporting which are not syntactic considerations. + + + ``from __future__ import division`` +@@ -327,9 +358,9 @@ + the bytes/string dichotomy. Because Python 2 allowed the ``str`` type to hold + textual data, people have over the years been rather loose in their delineation + of what ``str`` instances held text compared to bytes. In Python 3 you cannot +-be so care-free anymore and need to properly handle the difference. The key ++be so care-free anymore and need to properly handle the difference. The key to + handling this issue is to make sure that **every** string literal in your +-Python 2 code is either syntactically of functionally marked as either bytes or ++Python 2 code is either syntactically or functionally marked as either bytes or + text data. After this is done you then need to make sure your APIs are designed + to either handle a specific type or made to be properly polymorphic. + +@@ -436,14 +467,7 @@ + happen to use the ``unicode(self).encode('utf8')`` idiom as the body of your + ``__str__()`` method). + +-There are two ways to solve this issue. One is to use a custom 2to3 fixer. The +-blog post at http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ +-specifies how to do this. That will allow 2to3 to change all instances of ``def +-__unicode(self): ...`` to ``def __str__(self): ...``. This does require that you +-define your ``__str__()`` method in Python 2 before your ``__unicode__()`` +-method. +- +-The other option is to use a mixin class. This allows you to only define a ++You can use a mixin class to work around this. This allows you to only define a + ``__unicode__()`` method for your class and let the mixin derive + ``__str__()`` for you (code from + http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/):: +@@ -486,6 +510,7 @@ + + Even better is to use the documented attributes the exception provides. + ++ + Don't use ``__getslice__`` & Friends + '''''''''''''''''''''''''''''''''''' + +@@ -497,189 +522,62 @@ + Updating doctests + ''''''''''''''''' + +-2to3_ will attempt to generate fixes for doctests that it comes across. It's +-not perfect, though. If you wrote a monolithic set of doctests (e.g., a single +-docstring containing all of your doctests), you should at least consider +-breaking the doctests up into smaller pieces to make it more manageable to fix. +-Otherwise it might very well be worth your time and effort to port your tests +-to :mod:`unittest`. ++Don't forget to make them Python 2/3 compatible as well. If you wrote a ++monolithic set of doctests (e.g., a single docstring containing all of your ++doctests), you should at least consider breaking the doctests up into smaller ++pieces to make it more manageable to fix. Otherwise it might very well be worth ++your time and effort to port your tests to :mod:`unittest`. + + ++Update ``map`` for imbalanced input sequences ++''''''''''''''''''''''''''''''''''''''''''''' ++ ++With Python 2, when ``map`` was given more than one input sequence it would pad ++the shorter sequences with `None` values, returning a sequence as long as the ++longest input sequence. ++ ++With Python 3, if the input sequences to ``map`` are of unequal length, ``map`` ++will stop at the termination of the shortest of the sequences. For full ++compatibility with ``map`` from Python 2.x, wrap the sequence arguments in ++:func:`itertools.zip_longest`, e.g. ``map(func, *sequences)`` becomes ++``list(map(func, itertools.zip_longest(*sequences)))``. ++ + Eliminate ``-3`` Warnings + ------------------------- + + When you run your application's test suite, run it using the ``-3`` flag passed + to Python. This will cause various warnings to be raised during execution about +-things that 2to3 cannot handle automatically (e.g., modules that have been +-removed). Try to eliminate those warnings to make your code even more portable +-to Python 3. ++things that are semantic changes between Python 2 and 3. Try to eliminate those ++warnings to make your code even more portable to Python 3. + + +-Run 2to3 +--------- ++Alternative Approaches ++====================== + +-Once you have made your Python 2 code future-compatible with Python 3, it's +-time to use 2to3_ to actually port your code. ++While supporting Python 2 & 3 simultaneously is typically the preferred choice ++by people so that they can continue to improve code and have it work for the ++most number of users, your life may be easier if you only have to support one ++major version of Python going forward. + ++Supporting Only Python 3 Going Forward From Python 2 Code ++--------------------------------------------------------- + +-Manually +-'''''''' ++If you have Python 2 code but going forward only want to improve it as Python 3 ++code, then you can use 2to3_ to translate your Python 2 code to Python 3 code. ++This is only recommended, though, if your current version of your project is ++going into maintenance mode and you want all new features to be exclusive to ++Python 3. + +-To manually convert source code using 2to3_, you use the ``2to3`` script that +-is installed with Python 2.6 and later.:: + +- 2to3 ++Backporting Python 3 code to Python 2 ++------------------------------------- + +-This will cause 2to3 to write out a diff with all of the fixers applied for the +-converted source code. If you would like 2to3 to go ahead and apply the changes +-you can pass it the ``-w`` flag:: +- +- 2to3 -w +- +-There are other flags available to control exactly which fixers are applied, +-etc. +- +- +-During Installation +-''''''''''''''''''' +- +-When a user installs your project for Python 3, you can have either +-:mod:`distutils` or Distribute_ run 2to3_ on your behalf. +-For distutils, use the following idiom:: +- +- try: # Python 3 +- from distutils.command.build_py import build_py_2to3 as build_py +- except ImportError: # Python 2 +- from distutils.command.build_py import build_py +- +- setup(cmdclass = {'build_py': build_py}, +- # ... +- ) +- +-For Distribute:: +- +- setup(use_2to3=True, +- # ... +- ) +- +-This will allow you to not have to distribute a separate Python 3 version of +-your project. It does require, though, that when you perform development that +-you at least build your project and use the built Python 3 source for testing. +- +- +-Verify & Test +-------------- +- +-At this point you should (hopefully) have your project converted in such a way +-that it works in Python 3. Verify it by running your unit tests and making sure +-nothing has gone awry. If you miss something then figure out how to fix it in +-Python 3, backport to your Python 2 code, and run your code through 2to3 again +-to verify the fix transforms properly. +- +- +-.. _2to3: http://docs.python.org/py3k/library/2to3.html +-.. _Distribute: http://packages.python.org/distribute/ +- +- +-.. _use_same_source: +- +-Python 2/3 Compatible Source +-============================ +- +-While it may seem counter-intuitive, you can write Python code which is +-source-compatible between Python 2 & 3. It does lead to code that is not +-entirely idiomatic Python (e.g., having to extract the currently raised +-exception from ``sys.exc_info()[1]``), but it can be run under Python 2 +-**and** Python 3 without using 2to3_ as a translation step (although the tool +-should be used to help find potential portability problems). This allows you to +-continue to have a rapid development process regardless of whether you are +-developing under Python 2 or Python 3. Whether this approach or using +-:ref:`use_2to3` works best for you will be a per-project decision. +- +-To get a complete idea of what issues you will need to deal with, see the +-`What's New in Python 3.0`_. Others have reorganized the data in other formats +-such as http://docs.pythonsprints.com/python3_porting/py-porting.html . +- +-The following are some steps to take to try to support both Python 2 & 3 from +-the same source code. +- +- +-.. _What's New in Python 3.0: http://docs.python.org/release/3.0/whatsnew/3.0.html +- +- +-Follow The Steps for Using 2to3_ +--------------------------------- +- +-All of the steps outlined in how to +-:ref:`port Python 2 code with 2to3 ` apply +-to creating a Python 2/3 codebase. This includes trying only support Python 2.6 +-or newer (the :mod:`__future__` statements work in Python 3 without issue), +-eliminating warnings that are triggered by ``-3``, etc. +- +-You should even consider running 2to3_ over your code (without committing the +-changes). This will let you know where potential pain points are within your +-code so that you can fix them properly before they become an issue. +- +- +-Use six_ +--------- +- +-The six_ project contains many things to help you write portable Python code. +-You should make sure to read its documentation from beginning to end and use +-any and all features it provides. That way you will minimize any mistakes you +-might make in writing cross-version code. +- +- +-Capturing the Currently Raised Exception +----------------------------------------- +- +-One change between Python 2 and 3 that will require changing how you code (if +-you support `Python 2.5`_ and earlier) is +-accessing the currently raised exception. In Python 2.5 and earlier the syntax +-to access the current exception is:: +- +- try: +- raise Exception() +- except Exception, exc: +- # Current exception is 'exc' +- pass +- +-This syntax changed in Python 3 (and backported to `Python 2.6`_ and later) +-to:: +- +- try: +- raise Exception() +- except Exception as exc: +- # Current exception is 'exc' +- # In Python 3, 'exc' is restricted to the block; Python 2.6 will "leak" +- pass +- +-Because of this syntax change you must change to capturing the current +-exception to:: +- +- try: +- raise Exception() +- except Exception: +- import sys +- exc = sys.exc_info()[1] +- # Current exception is 'exc' +- pass +- +-You can get more information about the raised exception from +-:func:`sys.exc_info` than simply the current exception instance, but you most +-likely don't need it. +- +-.. note:: +- In Python 3, the traceback is attached to the exception instance +- through the ``__traceback__`` attribute. If the instance is saved in +- a local variable that persists outside of the ``except`` block, the +- traceback will create a reference cycle with the current frame and its +- dictionary of local variables. This will delay reclaiming dead +- resources until the next cyclic :term:`garbage collection` pass. +- +- In Python 2, this problem only occurs if you save the traceback itself +- (e.g. the third element of the tuple returned by :func:`sys.exc_info`) +- in a variable. ++If you have Python 3 code and have little interest in supporting Python 2 you ++can use 3to2_ to translate from Python 3 code to Python 2 code. This is only ++recommended if you don't plan to heavily support Python 2 users. Otherwise ++write your code for Python 3 and then backport as far back as you want. This ++is typically easier than going from Python 2 to 3 as you will have worked out ++any difficulties with e.g. bytes/strings, etc. + + + Other Resources +@@ -687,17 +585,41 @@ + + The authors of the following blog posts, wiki pages, and books deserve special + thanks for making public their tips for porting Python 2 code to Python 3 (and +-thus helping provide information for this document): ++thus helping provide information for this document and its various revisions ++over the years): + ++* http://wiki.python.org/moin/PortingPythonToPy3k + * http://python3porting.com/ + * http://docs.pythonsprints.com/python3_porting/py-porting.html + * http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/ + * http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html + * http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ + * http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/ +-* http://wiki.python.org/moin/PortingPythonToPy3k ++* https://wiki.ubuntu.com/Python/3 + + If you feel there is something missing from this document that should be added, + please email the python-porting_ mailing list. + ++ ++ ++.. _2to3: http://docs.python.org/2/library/2to3.html ++.. _3to2: https://pypi.python.org/pypi/3to2 ++.. _Cheeseshop: PyPI_ ++.. _coverage: https://pypi.python.org/pypi/coverage ++.. _future: http://python-future.org/ ++.. _modernize: https://github.com/mitsuhiko/python-modernize ++.. _Porting to Python 3: http://python3porting.com/ ++.. _PyPI: http://pypi.python.org/ ++.. _Python 2.2: http://www.python.org/2.2.x ++.. _Python 2.5: http://www.python.org/2.5.x ++.. _Python 2.6: http://www.python.org/2.6.x ++.. _Python 2.7: http://www.python.org/2.7.x ++.. _Python 2.5: http://www.python.org/2.5.x ++.. _Python 3.3: http://www.python.org/3.3.x ++.. _Python 3 Packages: https://pypi.python.org/pypi?:action=browse&c=533&show=all ++.. _Python 3 Q & A: http://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html + .. _python-porting: http://mail.python.org/mailman/listinfo/python-porting ++.. _six: https://pypi.python.org/pypi/six ++.. _tox: https://pypi.python.org/pypi/tox ++.. _trove classifiers: https://pypi.python.org/pypi?%3Aaction=list_classifiers ++ +diff -r 3a1db0d2747e Doc/howto/urllib2.rst +--- a/Doc/howto/urllib2.rst ++++ b/Doc/howto/urllib2.rst +@@ -18,7 +18,7 @@ + .. sidebar:: Related Articles + + You may also find useful the following article on fetching web resources +- with Python : ++ with Python: + + * `Basic Authentication `_ + +@@ -150,7 +150,7 @@ + to your HTTP request. + + Some websites [#]_ dislike being browsed by programs, or send different versions +-to different browsers [#]_ . By default urllib2 identifies itself as ++to different browsers [#]_. By default urllib2 identifies itself as + ``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version + numbers of the Python release, + e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain +@@ -439,7 +439,7 @@ + + When authentication is required, the server sends a header (as well as the 401 + error code) requesting authentication. This specifies the authentication scheme +-and a 'realm'. The header looks like : ``WWW-Authenticate: SCHEME ++and a 'realm'. The header looks like: ``WWW-Authenticate: SCHEME + realm="REALM"``. + + e.g. :: +@@ -511,7 +511,7 @@ + setting is detected. Normally that's a good thing, but there are occasions + when it may not be helpful [#]_. One way to do this is to setup our own + ``ProxyHandler``, with no proxies defined. This is done using similar steps to +-setting up a `Basic Authentication`_ handler : :: ++setting up a `Basic Authentication`_ handler: :: + + >>> proxy_support = urllib2.ProxyHandler({}) + >>> opener = urllib2.build_opener(proxy_support) +diff -r 3a1db0d2747e Doc/install/index.rst +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -20,12 +20,20 @@ + Finally, it might be useful to include all the material from my "Care + and Feeding of a Python Installation" talk in here somewhere. Yow! + +-.. topic:: Abstract ++This document describes the Python Distribution Utilities ("Distutils") from the ++end-user's point-of-view, describing how to extend the capabilities of a ++standard Python installation by building and installing third-party Python ++modules and extensions. + +- This document describes the Python Distribution Utilities ("Distutils") from the +- end-user's point-of-view, describing how to extend the capabilities of a +- standard Python installation by building and installing third-party Python +- modules and extensions. ++ ++.. note:: ++ ++ This guide only covers the basic tools for installing extensions that are ++ provided as part of this version of Python. Third party tools offer easier ++ to use and more secure alternatives. Refer to the ++ `quick recommendations section ++ `__ ++ in the Python Packaging User Guide for more information. + + + .. _inst-intro: +@@ -50,7 +58,9 @@ + document; there will be some brief forays into using Python's interactive mode + to explore your installation, but that's it. If you're looking for information + on how to distribute your own Python modules so that others may use them, see +-the :ref:`distutils-index` manual. ++the :ref:`distutils-index` manual. :ref:`debug-setup-script` may also be of ++interest. ++ + + + .. _inst-trivial-install: +diff -r 3a1db0d2747e Doc/library/argparse.rst +--- a/Doc/library/argparse.rst ++++ b/Doc/library/argparse.rst +@@ -1351,12 +1351,14 @@ + >>> parser.parse_args(['--', '-f']) + Namespace(foo='-f', one=None) + ++.. _prefix-matching: + +-Argument abbreviations +-^^^^^^^^^^^^^^^^^^^^^^ ++Argument abbreviations (prefix matching) ++^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The :meth:`~ArgumentParser.parse_args` method allows long options to be +-abbreviated if the abbreviation is unambiguous:: ++abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches ++a unique option):: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('-bacon') +@@ -1822,6 +1824,12 @@ + >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) + (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) + ++.. warning:: ++ :ref:`Prefix matching ` rules apply to ++ :meth:`parse_known_args`. The parser may consume an option even if it's just ++ a prefix of one of its known options, instead of leaving it in the remaining ++ arguments list. ++ + + Customizing file parsing + ^^^^^^^^^^^^^^^^^^^^^^^^ +diff -r 3a1db0d2747e Doc/library/ast.rst +--- a/Doc/library/ast.rst ++++ b/Doc/library/ast.rst +@@ -257,6 +257,6 @@ + Return a formatted dump of the tree in *node*. This is mainly useful for + debugging purposes. The returned string will show the names and the values + for fields. This makes the code impossible to evaluate, so if evaluation is +- wanted *annotate_fields* must be set to False. Attributes such as line ++ wanted *annotate_fields* must be set to ``False``. Attributes such as line + numbers and column offsets are not dumped by default. If this is wanted, + *include_attributes* can be set to ``True``. +diff -r 3a1db0d2747e Doc/library/base64.rst +--- a/Doc/library/base64.rst ++++ b/Doc/library/base64.rst +@@ -93,7 +93,7 @@ + digit 0 is always mapped to the letter O). For security purposes the default is + ``None``, so that 0 and 1 are not allowed in the input. + +- The decoded string is returned. A :exc:`TypeError` is raised if *s* were ++ The decoded string is returned. A :exc:`TypeError` is raised if *s* is + incorrectly padded or if there are non-alphabet characters present in the + string. + +diff -r 3a1db0d2747e Doc/library/bdb.rst +--- a/Doc/library/bdb.rst ++++ b/Doc/library/bdb.rst +@@ -20,7 +20,7 @@ + + The :mod:`bdb` module also defines two classes: + +-.. class:: Breakpoint(self, file, line, temporary=0, cond=None , funcname=None) ++.. class:: Breakpoint(self, file, line, temporary=0, cond=None, funcname=None) + + This class implements temporary breakpoints, ignore counts, disabling and + (re-)enabling, and conditionals. +@@ -186,17 +186,17 @@ + .. method:: user_line(frame) + + This method is called from :meth:`dispatch_line` when either +- :meth:`stop_here` or :meth:`break_here` yields True. ++ :meth:`stop_here` or :meth:`break_here` yields ``True``. + + .. method:: user_return(frame, return_value) + + This method is called from :meth:`dispatch_return` when :meth:`stop_here` +- yields True. ++ yields ``True``. + + .. method:: user_exception(frame, exc_info) + + This method is called from :meth:`dispatch_exception` when +- :meth:`stop_here` yields True. ++ :meth:`stop_here` yields ``True``. + + .. method:: do_clear(arg) + +@@ -237,7 +237,7 @@ + + .. method:: set_quit() + +- Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in ++ Set the :attr:`quitting` attribute to ``True``. This raises :exc:`BdbQuit` in + the next call to one of the :meth:`dispatch_\*` methods. + + +diff -r 3a1db0d2747e Doc/library/bsddb.rst +--- a/Doc/library/bsddb.rst ++++ b/Doc/library/bsddb.rst +@@ -52,7 +52,7 @@ + Open the hash format file named *filename*. Files never intended to be + preserved on disk may be created by passing ``None`` as the *filename*. The + optional *flag* identifies the mode used to open the file. It may be ``'r'`` +- (read only), ``'w'`` (read-write) , ``'c'`` (read-write - create if necessary; ++ (read only), ``'w'`` (read-write), ``'c'`` (read-write - create if necessary; + the default) or ``'n'`` (read-write - truncate to zero length). The other + arguments are rarely used and are just passed to the low-level :c:func:`dbopen` + function. Consult the Berkeley DB documentation for their use and +diff -r 3a1db0d2747e Doc/library/codecs.rst +--- a/Doc/library/codecs.rst ++++ b/Doc/library/codecs.rst +@@ -23,6 +23,29 @@ + + It defines the following functions: + ++.. function:: encode(obj, encoding='ascii', errors='strict') ++ ++ Encodes *obj* using the codec registered for *encoding*. ++ ++ *Errors* may be given to set the desired error handling scheme. The ++ default error handler is ``strict`` meaning that encoding errors raise ++ :exc:`ValueError` (or a more codec specific subclass, such as ++ :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more ++ information on codec error handling. ++ ++ .. versionadded:: 2.4 ++ ++.. function:: decode(obj, encoding='ascii', errors='strict') ++ ++ Decodes *obj* using the codec registered for *encoding*. ++ ++ *Errors* may be given to set the desired error handling scheme. The ++ default error handler is ``strict`` meaning that decoding errors raise ++ :exc:`ValueError` (or a more codec specific subclass, such as ++ :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more ++ information on codec error handling. ++ ++ .. versionadded:: 2.4 + + .. function:: register(search_function) + +diff -r 3a1db0d2747e Doc/library/cookielib.rst +--- a/Doc/library/cookielib.rst ++++ b/Doc/library/cookielib.rst +@@ -98,7 +98,7 @@ + Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (ie. cookies + received in a :mailheader:`Set-Cookie` header with a version cookie-attribute of + 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling +- is turned off or :attr:`rfc2109_as_netscape` is True, RFC 2109 cookies are ++ is turned off or :attr:`rfc2109_as_netscape` is ``True``, RFC 2109 cookies are + 'downgraded' by the :class:`CookieJar` instance to Netscape cookies, by + setting the :attr:`version` attribute of the :class:`Cookie` instance to 0. + :class:`DefaultCookiePolicy` also provides some parameters to allow some +@@ -308,7 +308,7 @@ + ----------------------------------------------------------- + + The following :class:`CookieJar` subclasses are provided for reading and +-writing . ++writing. + + .. class:: MozillaCookieJar(filename, delayload=None, policy=None) + +@@ -652,7 +652,7 @@ + + .. attribute:: Cookie.secure + +- True if cookie should only be returned over a secure connection. ++ ``True`` if cookie should only be returned over a secure connection. + + + .. attribute:: Cookie.expires +@@ -663,7 +663,7 @@ + + .. attribute:: Cookie.discard + +- True if this is a session cookie. ++ ``True`` if this is a session cookie. + + + .. attribute:: Cookie.comment +@@ -680,7 +680,7 @@ + + .. attribute:: Cookie.rfc2109 + +- True if this cookie was received as an RFC 2109 cookie (ie. the cookie ++ ``True`` if this cookie was received as an RFC 2109 cookie (ie. the cookie + arrived in a :mailheader:`Set-Cookie` header, and the value of the Version + cookie-attribute in that header was 1). This attribute is provided because + :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in +@@ -691,18 +691,18 @@ + + .. attribute:: Cookie.port_specified + +- True if a port or set of ports was explicitly specified by the server (in the ++ ``True`` if a port or set of ports was explicitly specified by the server (in the + :mailheader:`Set-Cookie` / :mailheader:`Set-Cookie2` header). + + + .. attribute:: Cookie.domain_specified + +- True if a domain was explicitly specified by the server. ++ ``True`` if a domain was explicitly specified by the server. + + + .. attribute:: Cookie.domain_initial_dot + +- True if the domain explicitly specified by the server began with a dot ++ ``True`` if the domain explicitly specified by the server began with a dot + (``'.'``). + + Cookies may have additional non-standard cookie-attributes. These may be +@@ -729,7 +729,7 @@ + + .. method:: Cookie.is_expired([now=None]) + +- True if cookie has passed the time at which the server requested it should ++ ``True`` if cookie has passed the time at which the server requested it should + expire. If *now* is given (in seconds since the epoch), return whether the + cookie has expired at the specified time. + +diff -r 3a1db0d2747e Doc/library/csv.rst +--- a/Doc/library/csv.rst ++++ b/Doc/library/csv.rst +@@ -164,36 +164,43 @@ + The :mod:`csv` module defines the following classes: + + +-.. class:: DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds) ++.. class:: DictReader(csvfile, fieldnames=None, restkey=None, restval=None, \ ++ dialect='excel', *args, **kwds) + +- Create an object which operates like a regular reader but maps the information +- read into a dict whose keys are given by the optional *fieldnames* parameter. +- If the *fieldnames* parameter is omitted, the values in the first row of the +- *csvfile* will be used as the fieldnames. If the row read has more fields +- than the fieldnames sequence, the remaining data is added as a sequence +- keyed by the value of *restkey*. If the row read has fewer fields than the +- fieldnames sequence, the remaining keys take the value of the optional +- *restval* parameter. Any other optional or keyword arguments are passed to +- the underlying :class:`reader` instance. ++ Create an object which operates like a regular reader but maps the ++ information read into a dict whose keys are given by the optional ++ *fieldnames* parameter. The *fieldnames* parameter is a :ref:`sequence ++ ` whose elements are associated with the ++ fields of the input data in order. These elements become the keys of the ++ resulting dictionary. If the *fieldnames* parameter is omitted, the values ++ in the first row of the *csvfile* will be used as the fieldnames. If the ++ row read has more fields than the fieldnames sequence, the remaining data is ++ added as a sequence keyed by the value of *restkey*. If the row read has ++ fewer fields than the fieldnames sequence, the remaining keys take the value ++ of the optional *restval* parameter. Any other optional or keyword ++ arguments are passed to the underlying :class:`reader` instance. + + +-.. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds) ++.. class:: DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', \ ++ dialect='excel', *args, **kwds) + +- Create an object which operates like a regular writer but maps dictionaries onto +- output rows. The *fieldnames* parameter identifies the order in which values in +- the dictionary passed to the :meth:`writerow` method are written to the +- *csvfile*. The optional *restval* parameter specifies the value to be written +- if the dictionary is missing a key in *fieldnames*. If the dictionary passed to +- the :meth:`writerow` method contains a key not found in *fieldnames*, the +- optional *extrasaction* parameter indicates what action to take. If it is set +- to ``'raise'`` a :exc:`ValueError` is raised. If it is set to ``'ignore'``, +- extra values in the dictionary are ignored. Any other optional or keyword +- arguments are passed to the underlying :class:`writer` instance. ++ Create an object which operates like a regular writer but maps dictionaries ++ onto output rows. The *fieldnames* parameter is a :ref:`sequence ++ ` of keys that identify the order in ++ which values in the dictionary passed to the :meth:`writerow` method are ++ written to the *csvfile*. The optional *restval* parameter specifies the ++ value to be written if the dictionary is missing a key in *fieldnames*. If ++ the dictionary passed to the :meth:`writerow` method contains a key not ++ found in *fieldnames*, the optional *extrasaction* parameter indicates what ++ action to take. If it is set to ``'raise'`` a :exc:`ValueError` is raised. ++ If it is set to ``'ignore'``, extra values in the dictionary are ignored. ++ Any other optional or keyword arguments are passed to the underlying ++ :class:`writer` instance. + +- Note that unlike the :class:`DictReader` class, the *fieldnames* parameter of +- the :class:`DictWriter` is not optional. Since Python's :class:`dict` objects +- are not ordered, there is not enough information available to deduce the order +- in which the row should be written to the *csvfile*. ++ Note that unlike the :class:`DictReader` class, the *fieldnames* parameter ++ of the :class:`DictWriter` is not optional. Since Python's :class:`dict` ++ objects are not ordered, there is not enough information available to deduce ++ the order in which the row should be written to the *csvfile*. + + + .. class:: Dialect +diff -r 3a1db0d2747e Doc/library/ctypes.rst +--- a/Doc/library/ctypes.rst ++++ b/Doc/library/ctypes.rst +@@ -215,7 +215,7 @@ + Fundamental data types + ^^^^^^^^^^^^^^^^^^^^^^ + +-:mod:`ctypes` defines a number of primitive C compatible data types : ++:mod:`ctypes` defines a number of primitive C compatible data types: + + +----------------------+------------------------------------------+----------------------------+ + | ctypes type | C type | Python type | +@@ -1080,12 +1080,18 @@ + 1 5 7 33 99 + >>> + +-**Important note for callback functions:** +- +-Make sure you keep references to CFUNCTYPE objects as long as they are used from +-C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage collected, +-crashing your program when a callback is made. +- ++.. note:: ++ ++ Make sure you keep references to :func:`CFUNCTYPE` objects as long as they ++ are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be ++ garbage collected, crashing your program when a callback is made. ++ ++ Also, note that if the callback function is called in a thread created ++ outside of Python's control (e.g. by the foreign code that calls the ++ callback), ctypes creates a new dummy Python thread on every invocation. This ++ behavior is correct for most purposes, but it means that values stored with ++ `threading.local` will *not* survive across different callbacks, even when ++ those calls are made from the same C thread. + + .. _ctypes-accessing-values-exported-from-dlls: + +@@ -1714,7 +1720,7 @@ + + WINUSERAPI int WINAPI + MessageBoxA( +- HWND hWnd , ++ HWND hWnd, + LPCSTR lpText, + LPCSTR lpCaption, + UINT uType); +@@ -2351,7 +2357,7 @@ + .. class:: c_bool + + Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from +- C99). Its value can be True or False, and the constructor accepts any object ++ C99). Its value can be ``True`` or ``False``, and the constructor accepts any object + that has a truth value. + + .. versionadded:: 2.6 +diff -r 3a1db0d2747e Doc/library/curses.rst +--- a/Doc/library/curses.rst ++++ b/Doc/library/curses.rst +@@ -380,7 +380,7 @@ + is to be displayed. + + +-.. function:: newwin(begin_y, begin_x) ++.. function:: newwin(nlines, ncols) + newwin(nlines, ncols, begin_y, begin_x) + + Return a new window, whose left-upper corner is at ``(begin_y, begin_x)``, and +diff -r 3a1db0d2747e Doc/library/datetime.rst +--- a/Doc/library/datetime.rst ++++ b/Doc/library/datetime.rst +@@ -1720,7 +1720,7 @@ + making assumptions about the output value. Field orderings will vary (for + example, "month/day/year" versus "day/month/year"), and the output may + contain Unicode characters encoded using the locale's default encoding (for +- example, if the current locale is ``js_JP``, the default encoding could be ++ example, if the current locale is ``ja_JP``, the default encoding could be + any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale` + to determine the current locale's encoding). + +diff -r 3a1db0d2747e Doc/library/decimal.rst +--- a/Doc/library/decimal.rst ++++ b/Doc/library/decimal.rst +@@ -1226,52 +1226,52 @@ + + .. method:: is_canonical(x) + +- Returns True if *x* is canonical; otherwise returns False. ++ Returns ``True`` if *x* is canonical; otherwise returns ``False``. + + + .. method:: is_finite(x) + +- Returns True if *x* is finite; otherwise returns False. ++ Returns ``True`` if *x* is finite; otherwise returns ``False``. + + + .. method:: is_infinite(x) + +- Returns True if *x* is infinite; otherwise returns False. ++ Returns ``True`` if *x* is infinite; otherwise returns ``False``. + + + .. method:: is_nan(x) + +- Returns True if *x* is a qNaN or sNaN; otherwise returns False. ++ Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``. + + + .. method:: is_normal(x) + +- Returns True if *x* is a normal number; otherwise returns False. ++ Returns ``True`` if *x* is a normal number; otherwise returns ``False``. + + + .. method:: is_qnan(x) + +- Returns True if *x* is a quiet NaN; otherwise returns False. ++ Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``. + + + .. method:: is_signed(x) + +- Returns True if *x* is negative; otherwise returns False. ++ Returns ``True`` if *x* is negative; otherwise returns ``False``. + + + .. method:: is_snan(x) + +- Returns True if *x* is a signaling NaN; otherwise returns False. ++ Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``. + + + .. method:: is_subnormal(x) + +- Returns True if *x* is subnormal; otherwise returns False. ++ Returns ``True`` if *x* is subnormal; otherwise returns ``False``. + + + .. method:: is_zero(x) + +- Returns True if *x* is a zero; otherwise returns False. ++ Returns ``True`` if *x* is a zero; otherwise returns ``False``. + + + .. method:: ln(x) +@@ -1431,7 +1431,7 @@ + + .. method:: same_quantum(x, y) + +- Returns True if the two operands have the same exponent. ++ Returns ``True`` if the two operands have the same exponent. + + + .. method:: scaleb (x, y) +diff -r 3a1db0d2747e Doc/library/email.message.rst +--- a/Doc/library/email.message.rst ++++ b/Doc/library/email.message.rst +@@ -68,7 +68,7 @@ + + Return ``True`` if the message's payload is a list of sub-\ + :class:`Message` objects, otherwise return ``False``. When +- :meth:`is_multipart` returns False, the payload should be a string object. ++ :meth:`is_multipart` returns ``False``, the payload should be a string object. + + + .. method:: set_unixfrom(unixfrom) +diff -r 3a1db0d2747e Doc/library/exceptions.rst +--- a/Doc/library/exceptions.rst ++++ b/Doc/library/exceptions.rst +@@ -286,8 +286,7 @@ + + Raised when an error is detected that doesn't fall in any of the other + categories. The associated value is a string indicating what precisely went +- wrong. (This exception is mostly a relic from a previous version of the +- interpreter; it is not used very much any more.) ++ wrong. + + + .. exception:: StopIteration +diff -r 3a1db0d2747e Doc/library/fcntl.rst +--- a/Doc/library/fcntl.rst ++++ b/Doc/library/fcntl.rst +@@ -24,11 +24,11 @@ + + .. function:: fcntl(fd, op[, arg]) + +- Perform the requested operation on file descriptor *fd* (file objects providing +- a :meth:`~io.IOBase.fileno` method are accepted as well). The operation is +- defined by *op* +- and is operating system dependent. These codes are also found in the +- :mod:`fcntl` module. The argument *arg* is optional, and defaults to the integer ++ Perform the operation *op* on file descriptor *fd* (file objects providing ++ a :meth:`~io.IOBase.fileno` method are accepted as well). The values used ++ for for *op* are operating system dependent, and are available as constants ++ in the :mod:`fcntl` module, using the same names as used in the relevant C ++ header files. The argument *arg* is optional, and defaults to the integer + value ``0``. When present, it can either be an integer value, or a string. + With the argument missing or an integer value, the return value of this function + is the integer return value of the C :c:func:`fcntl` call. When the argument is +@@ -51,6 +51,9 @@ + argument handling is even more complicated. + + The op parameter is limited to values that can fit in 32-bits. ++ Additional constants of interest for use as the *op* argument can be ++ found in the :mod:`termios` module, under the same names as used in ++ the relevant C header files. + + The parameter *arg* can be one of an integer, absent (treated identically to the + integer ``0``), an object supporting the read-only buffer interface (most likely +diff -r 3a1db0d2747e Doc/library/functions.rst +--- a/Doc/library/functions.rst ++++ b/Doc/library/functions.rst +@@ -47,7 +47,7 @@ + + .. function:: all(iterable) + +- Return True if all elements of the *iterable* are true (or if the iterable ++ Return ``True`` if all elements of the *iterable* are true (or if the iterable + is empty). Equivalent to:: + + def all(iterable): +@@ -61,8 +61,8 @@ + + .. function:: any(iterable) + +- Return True if any element of the *iterable* is true. If the iterable +- is empty, return False. Equivalent to:: ++ Return ``True`` if any element of the *iterable* is true. If the iterable ++ is empty, return ``False``. Equivalent to:: + + def any(iterable): + for element in iterable: +@@ -596,8 +596,21 @@ + + .. function:: hex(x) + +- Convert an integer number (of any size) to a hexadecimal string. The result is a +- valid Python expression. ++ Convert an integer number (of any size) to a lowercase hexadecimal string ++ prefixed with "0x", for example: ++ ++ >>> hex(255) ++ '0xff' ++ >>> hex(-42) ++ '-0x2a' ++ >>> hex(1L) ++ '0x1L' ++ ++ If x is not a Python :class:`int` or :class:`long` object, it has to ++ define an __index__() method that returns an integer. ++ ++ See also :func:`int` for converting a hexadecimal string to an ++ integer using a base of 16. + + .. note:: + +@@ -880,8 +893,8 @@ + to use the system default, which is usually line buffered for tty devices and + fully buffered for other files. If omitted, the system default is used. [#]_ + +- Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note that +- ``'w+'`` truncates the file). Append ``'b'`` to the mode to open the file in ++ Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (reading and writing); ++ note that ``'w+'`` truncates the file. Append ``'b'`` to the mode to open the file in + binary mode, on systems that differentiate between binary and text files; on + systems that don't have this distinction, adding the ``'b'`` has no effect. + +diff -r 3a1db0d2747e Doc/library/future_builtins.rst +--- a/Doc/library/future_builtins.rst ++++ b/Doc/library/future_builtins.rst +@@ -50,6 +50,11 @@ + + Works like :func:`itertools.imap`. + ++ .. note:: ++ ++ In Python 3, :func:`map` does not accept ``None`` for the ++ function argument. ++ + .. function:: oct(object) + + Works like the built-in :func:`oct`, but instead of :meth:`__oct__` it will +diff -r 3a1db0d2747e Doc/library/gc.rst +--- a/Doc/library/gc.rst ++++ b/Doc/library/gc.rst +@@ -142,8 +142,8 @@ + + .. function:: is_tracked(obj) + +- Returns True if the object is currently tracked by the garbage collector, +- False otherwise. As a general rule, instances of atomic types aren't ++ Returns ``True`` if the object is currently tracked by the garbage collector, ++ ``False`` otherwise. As a general rule, instances of atomic types aren't + tracked and instances of non-atomic types (containers, user-defined + objects...) are. However, some type-specific optimizations can be present + in order to suppress the garbage collector footprint of simple instances +diff -r 3a1db0d2747e Doc/library/getopt.rst +--- a/Doc/library/getopt.rst ++++ b/Doc/library/getopt.rst +@@ -10,6 +10,7 @@ + -------------- + + .. note:: ++ + The :mod:`getopt` module is a parser for command line options whose API is + designed to be familiar to users of the C :c:func:`getopt` function. Users who + are unfamiliar with the C :c:func:`getopt` function or who would like to write +diff -r 3a1db0d2747e Doc/library/hashlib.rst +--- a/Doc/library/hashlib.rst ++++ b/Doc/library/hashlib.rst +@@ -110,7 +110,6 @@ + m.update(b)`` is equivalent to ``m.update(a+b)``. + + .. versionchanged:: 2.7 +- + The Python GIL is released to allow other threads to run while + hash updates on data larger than 2048 bytes is taking place when + using hash algorithms supplied by OpenSSL. +diff -r 3a1db0d2747e Doc/library/io.rst +--- a/Doc/library/io.rst ++++ b/Doc/library/io.rst +@@ -278,7 +278,7 @@ + + .. method:: readable() + +- Return ``True`` if the stream can be read from. If False, :meth:`read` ++ Return ``True`` if the stream can be read from. If ``False``, :meth:`read` + will raise :exc:`IOError`. + + .. method:: readline(limit=-1) +@@ -644,6 +644,7 @@ + :exc:`UnsupportedOperation`. + + .. warning:: ++ + :class:`BufferedRWPair` does not attempt to synchronize accesses to + its underlying raw streams. You should not pass it the same object + as reader and writer; use :class:`BufferedRandom` instead. +@@ -791,14 +792,14 @@ + Whether line buffering is enabled. + + +-.. class:: StringIO(initial_value=u'', newline=None) ++.. class:: StringIO(initial_value=u'', newline=u'\\n') + + An in-memory stream for unicode text. It inherits :class:`TextIOWrapper`. + + The initial value of the buffer (an empty unicode string by default) can + be set by providing *initial_value*. The *newline* argument works like +- that of :class:`TextIOWrapper`. The default is to do no newline +- translation. ++ that of :class:`TextIOWrapper`. The default is to consider only ``\n`` ++ characters as end of lines and to do no newline translation. + + :class:`StringIO` provides this method in addition to those from + :class:`TextIOWrapper` and its parents: +diff -r 3a1db0d2747e Doc/library/itertools.rst +--- a/Doc/library/itertools.rst ++++ b/Doc/library/itertools.rst +@@ -52,12 +52,12 @@ + :func:`compress` data, selectors (d[0] if s[0]), (d[1] if s[1]), ... ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F`` + :func:`dropwhile` pred, seq seq[n], seq[n+1], starting when pred fails ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1`` + :func:`groupby` iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v) +-:func:`ifilter` pred, seq elements of seq where pred(elem) is True ``ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9`` +-:func:`ifilterfalse` pred, seq elements of seq where pred(elem) is False ``ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8`` ++:func:`ifilter` pred, seq elements of seq where pred(elem) is true ``ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9`` ++:func:`ifilterfalse` pred, seq elements of seq where pred(elem) is false ``ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8`` + :func:`islice` seq, [start,] stop [, step] elements from seq[start:stop:step] ``islice('ABCDEFG', 2, None) --> C D E F G`` + :func:`imap` func, p, q, ... func(p0, q0), func(p1, q1), ... ``imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000`` + :func:`starmap` func, seq func(\*seq[0]), func(\*seq[1]), ... ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000`` +-:func:`tee` it, n it1, it2 , ... itn splits one iterator into n ++:func:`tee` it, n it1, it2, ... itn splits one iterator into n + :func:`takewhile` pred, seq seq[0], seq[1], until pred fails ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4`` + :func:`izip` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ``izip('ABCD', 'xy') --> Ax By`` + :func:`izip_longest` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ``izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-`` +diff -r 3a1db0d2747e Doc/library/logging.config.rst +--- a/Doc/library/logging.config.rst ++++ b/Doc/library/logging.config.rst +@@ -81,8 +81,9 @@ + .. function:: fileConfig(fname, defaults=None, disable_existing_loggers=True) + + Reads the logging configuration from a :mod:`configparser`\-format file +- named *fname*. This function can be called several times from an +- application, allowing an end user to select from various pre-canned ++ named *fname*. The format of the file should be as described in ++ :ref:`logging-config-fileformat`. This function can be called several times ++ from an application, allowing an end user to select from various pre-canned + configurations (if the developer provides a mechanism to present the choices + and load the chosen configuration). + +@@ -117,7 +118,9 @@ + send it to the socket as a string of bytes preceded by a four-byte length + string packed in binary using ``struct.pack('>L', n)``. + +- .. note:: Because portions of the configuration are passed through ++ .. note:: ++ ++ Because portions of the configuration are passed through + :func:`eval`, use of this function may open its users to a security risk. + While the function only binds to a socket on ``localhost``, and so does + not accept connections from remote machines, there are scenarios where +@@ -720,7 +723,9 @@ + :class:`~logging.Formatter` can present exception tracebacks in an expanded or + condensed format. + +-.. note:: Due to the use of :func:`eval` as described above, there are ++.. note:: ++ ++ Due to the use of :func:`eval` as described above, there are + potential security risks which result from using the :func:`listen` to send + and receive configurations via sockets. The risks are limited to where + multiple users with no mutual trust run code on the same machine; see the +diff -r 3a1db0d2747e Doc/library/logging.rst +--- a/Doc/library/logging.rst ++++ b/Doc/library/logging.rst +@@ -114,6 +114,8 @@ + If the root is reached, and it has a level of NOTSET, then all messages will be + processed. Otherwise, the root's level will be used as the effective level. + ++ See :ref:`levels` for a list of levels. ++ + + .. method:: Logger.isEnabledFor(lvl) + +@@ -281,6 +283,35 @@ + .. versionchanged:: 2.5 + *func* and *extra* were added. + ++ ++.. _levels: ++ ++Logging Levels ++-------------- ++ ++The numeric values of logging levels are given in the following table. These are ++primarily of interest if you want to define your own levels, and need them to ++have specific values relative to the predefined levels. If you define a level ++with the same numeric value, it overwrites the predefined value; the predefined ++name is lost. ++ +++--------------+---------------+ ++| Level | Numeric value | +++==============+===============+ ++| ``CRITICAL`` | 50 | +++--------------+---------------+ ++| ``ERROR`` | 40 | +++--------------+---------------+ ++| ``WARNING`` | 30 | +++--------------+---------------+ ++| ``INFO`` | 20 | +++--------------+---------------+ ++| ``DEBUG`` | 10 | +++--------------+---------------+ ++| ``NOTSET`` | 0 | +++--------------+---------------+ ++ ++ + .. _handler: + + Handler Objects +@@ -321,6 +352,7 @@ + severe than *lvl* will be ignored. When a handler is created, the level is set + to :const:`NOTSET` (which causes all messages to be processed). + ++ See :ref:`levels` for a list of levels. + + .. method:: Handler.setFormatter(form) + +@@ -659,7 +691,7 @@ + --------------------- + + :class:`LoggerAdapter` instances are used to conveniently pass contextual +-information into logging calls. For a usage example , see the section on ++information into logging calls. For a usage example, see the section on + :ref:`adding contextual information to your logging output `. + + .. versionadded:: 2.6 +@@ -679,16 +711,15 @@ + (possibly modified) versions of the arguments passed in. + + In addition to the above, :class:`LoggerAdapter` supports the following +-methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`, +-:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`, +-:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`, +-:meth:`hasHandlers`. These methods have the same signatures as their +-counterparts in :class:`Logger`, so you can use the two types of instances +-interchangeably. ++methods of :class:`Logger`: :meth:`~Logger.debug`, :meth:`~Logger.info`, ++:meth:`~Logger.warning`, :meth:`~Logger.error`, :meth:`~Logger.exception`, ++:meth:`~Logger.critical`, :meth:`~Logger.log` and :meth:`~Logger.isEnabledFor`. ++These methods have the same signatures as their counterparts in :class:`Logger`, ++so you can use the two types of instances interchangeably for these calls. + + .. versionchanged:: 2.7 +- The :meth:`isEnabledFor` method was added to :class:`LoggerAdapter`. This +- method delegates to the underlying logger. ++ The :meth:`~Logger.isEnabledFor` method was added to :class:`LoggerAdapter`. ++ This method delegates to the underlying logger. + + + Thread Safety +@@ -728,8 +759,8 @@ + + Return either the standard :class:`Logger` class, or the last class passed to + :func:`setLoggerClass`. This function may be called from within a new class +- definition, to ensure that installing a customised :class:`Logger` class will +- not undo customisations already applied by other code. For example:: ++ definition, to ensure that installing a customized :class:`Logger` class will ++ not undo customizations already applied by other code. For example:: + + class MyLogger(logging.getLoggerClass()): + # ... override behaviour here +@@ -821,14 +852,15 @@ + Logs a message with level *level* on the root logger. The other arguments are + interpreted as for :func:`debug`. + +- .. note:: The above module-level functions which delegate to the root +- logger should *not* be used in threads, in versions of Python earlier +- than 2.7.1 and 3.2, unless at least one handler has been added to the +- root logger *before* the threads are started. These convenience functions +- call :func:`basicConfig` to ensure that at least one handler is +- available; in earlier versions of Python, this can (under rare +- circumstances) lead to handlers being added multiple times to the root +- logger, which can in turn lead to multiple messages for the same event. ++ .. note:: The above module-level convenience functions, which delegate to the ++ root logger, call :func:`basicConfig` to ensure that at least one handler ++ is available. Because of this, they should *not* be used in threads, ++ in versions of Python earlier than 2.7.1 and 3.2, unless at least one ++ handler has been added to the root logger *before* the threads are ++ started. In earlier versions of Python, due to a thread safety shortcoming ++ in :func:`basicConfig`, this can (under rare circumstances) lead to ++ handlers being added multiple times to the root logger, which can in turn ++ lead to multiple messages for the same event. + + .. function:: disable(lvl) + +@@ -838,8 +870,10 @@ + effect is to disable all logging calls of severity *lvl* and below, so that + if you call it with a value of INFO, then all INFO and DEBUG events would be + discarded, whereas those of severity WARNING and above would be processed +- according to the logger's effective level. To undo the effect of a call to +- ``logging.disable(lvl)``, call ``logging.disable(logging.NOTSET)``. ++ according to the logger's effective level. If ++ ``logging.disable(logging.NOTSET)`` is called, it effectively removes this ++ overriding level, so that logging output again depends on the effective ++ levels of individual loggers. + + + .. function:: addLevelName(lvl, levelName) +diff -r 3a1db0d2747e Doc/library/mailbox.rst +--- a/Doc/library/mailbox.rst ++++ b/Doc/library/mailbox.rst +@@ -1664,7 +1664,7 @@ + due to malformed messages in the mailbox:: + + import mailbox +- import email.Errors ++ import email.errors + + list_names = ('python-list', 'python-dev', 'python-bugs') + +@@ -1674,7 +1674,7 @@ + for key in inbox.iterkeys(): + try: + message = inbox[key] +- except email.Errors.MessageParseError: ++ except email.errors.MessageParseError: + continue # The message is malformed. Just leave it. + + for name in list_names: +diff -r 3a1db0d2747e Doc/library/multiprocessing.rst +--- a/Doc/library/multiprocessing.rst ++++ b/Doc/library/multiprocessing.rst +@@ -960,12 +960,24 @@ + ctypes type or a one character typecode of the kind used by the :mod:`array` + module. *\*args* is passed on to the constructor for the type. + +- If *lock* is ``True`` (the default) then a new lock object is created to +- synchronize access to the value. If *lock* is a :class:`Lock` or +- :class:`RLock` object then that will be used to synchronize access to the +- value. If *lock* is ``False`` then access to the returned object will not be +- automatically protected by a lock, so it will not necessarily be +- "process-safe". ++ If *lock* is ``True`` (the default) then a new recursive lock ++ object is created to synchronize access to the value. If *lock* is ++ a :class:`Lock` or :class:`RLock` object then that will be used to ++ synchronize access to the value. If *lock* is ``False`` then ++ access to the returned object will not be automatically protected ++ by a lock, so it will not necessarily be "process-safe". ++ ++ Operations like ``+=`` which involve a read and write are not ++ atomic. So if, for instance, you want to atomically increment a ++ shared value it is insufficient to just do :: ++ ++ counter.value += 1 ++ ++ Assuming the associated lock is recursive (which it is by default) ++ you can instead do :: ++ ++ with counter.get_lock(): ++ counter.value += 1 + + Note that *lock* is a keyword-only argument. + +@@ -1245,7 +1257,7 @@ + + *exposed* is used to specify a sequence of method names which proxies for + this typeid should be allowed to access using +- :meth:`BaseProxy._callMethod`. (If *exposed* is ``None`` then ++ :meth:`BaseProxy._callmethod`. (If *exposed* is ``None`` then + :attr:`proxytype._exposed_` is used instead if it exists.) In the case + where no exposed list is specified, all "public methods" of the shared + object will be accessible. (Here a "public method" means any attribute +diff -r 3a1db0d2747e Doc/library/nntplib.rst +--- a/Doc/library/nntplib.rst ++++ b/Doc/library/nntplib.rst +@@ -234,25 +234,25 @@ + + .. method:: NNTP.next() + +- Send a ``NEXT`` command. Return as for :meth:`stat`. ++ Send a ``NEXT`` command. Return as for :meth:`.stat`. + + + .. method:: NNTP.last() + +- Send a ``LAST`` command. Return as for :meth:`stat`. ++ Send a ``LAST`` command. Return as for :meth:`.stat`. + + + .. method:: NNTP.head(id) + +- Send a ``HEAD`` command, where *id* has the same meaning as for :meth:`stat`. ++ Send a ``HEAD`` command, where *id* has the same meaning as for :meth:`.stat`. + Return a tuple ``(response, number, id, list)`` where the first three are the +- same as for :meth:`stat`, and *list* is a list of the article's headers (an ++ same as for :meth:`.stat`, and *list* is a list of the article's headers (an + uninterpreted list of lines, without trailing newlines). + + + .. method:: NNTP.body(id,[file]) + +- Send a ``BODY`` command, where *id* has the same meaning as for :meth:`stat`. ++ Send a ``BODY`` command, where *id* has the same meaning as for :meth:`.stat`. + If the *file* parameter is supplied, then the body is stored in a file. If + *file* is a string, then the method will open a file object with that name, + write to it then close it. If *file* is a file object, then it will start +@@ -263,7 +263,7 @@ + .. method:: NNTP.article(id) + + Send an ``ARTICLE`` command, where *id* has the same meaning as for +- :meth:`stat`. Return as for :meth:`head`. ++ :meth:`.stat`. Return as for :meth:`head`. + + + .. method:: NNTP.slave() +@@ -290,7 +290,7 @@ + .. method:: NNTP.post(file) + + Post an article using the ``POST`` command. The *file* argument is an open file +- object which is read until EOF using its :meth:`readline` method. It should be ++ object which is read until EOF using its :meth:`~file.readline` method. It should be + a well-formed news article, including the required headers. The :meth:`post` + method automatically escapes lines beginning with ``.``. + +diff -r 3a1db0d2747e Doc/library/operator.rst +--- a/Doc/library/operator.rst ++++ b/Doc/library/operator.rst +@@ -503,7 +503,7 @@ + ``(b.name, b.date)``. + + * After ``f = attrgetter('name.first', 'name.last')``, the call ``f(b)`` +- returns ``(r.name.first, r.name.last)``. ++ returns ``(b.name.first, b.name.last)``. + + Equivalent to:: + +diff -r 3a1db0d2747e Doc/library/os.path.rst +--- a/Doc/library/os.path.rst ++++ b/Doc/library/os.path.rst +@@ -127,7 +127,7 @@ + .. versionadded:: 1.5.2 + + .. versionchanged:: 2.3 +- If :func:`os.stat_float_times` returns True, the result is a floating point ++ If :func:`os.stat_float_times` returns ``True``, the result is a floating point + number. + + +@@ -140,7 +140,7 @@ + .. versionadded:: 1.5.2 + + .. versionchanged:: 2.3 +- If :func:`os.stat_float_times` returns True, the result is a floating point ++ If :func:`os.stat_float_times` returns ``True``, the result is a floating point + number. + + +@@ -345,7 +345,7 @@ + + .. data:: supports_unicode_filenames + +- True if arbitrary Unicode strings can be used as file names (within limitations ++ ``True`` if arbitrary Unicode strings can be used as file names (within limitations + imposed by the file system). + + .. versionadded:: 2.3 +diff -r 3a1db0d2747e Doc/library/os.rst +--- a/Doc/library/os.rst ++++ b/Doc/library/os.rst +@@ -157,7 +157,9 @@ + + Availability: Unix. + +- .. note:: On Mac OS X, :func:`getgroups` behavior differs somewhat from ++ .. note:: ++ ++ On Mac OS X, :func:`getgroups` behavior differs somewhat from + other Unix platforms. If the Python interpreter was built with a + deployment target of :const:`10.5` or earlier, :func:`getgroups` returns + the list of effective group ids associated with the current user process; +@@ -744,7 +746,7 @@ + by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the + beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the + current position; :const:`SEEK_END` or ``2`` to set it relative to the end of +- the file. ++ the file. Return the new cursor position in bytes, starting from the beginning. + + Availability: Unix, Windows. + +@@ -1936,6 +1938,10 @@ + Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have + known issues when using fork() from a thread. + ++ .. warning:: ++ ++ See :mod:`ssl` for applications that use the SSL module with fork(). ++ + Availability: Unix. + + +diff -r 3a1db0d2747e Doc/library/ossaudiodev.rst +--- a/Doc/library/ossaudiodev.rst ++++ b/Doc/library/ossaudiodev.rst +@@ -48,7 +48,7 @@ + the official documentation for the OSS C API + + The module defines a large number of constants supplied by the OSS device +- driver; see ```` on either Linux or FreeBSD for a listing . ++ driver; see ```` on either Linux or FreeBSD for a listing. + + :mod:`ossaudiodev` defines the following variables and functions: + +diff -r 3a1db0d2747e Doc/library/pyexpat.rst +--- a/Doc/library/pyexpat.rst ++++ b/Doc/library/pyexpat.rst +@@ -906,5 +906,5 @@ + .. [#] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl +- and http://www.iana.org/assignments/character-sets . ++ and http://www.iana.org/assignments/character-sets\ . + +diff -r 3a1db0d2747e Doc/library/repr.rst +--- a/Doc/library/repr.rst ++++ b/Doc/library/repr.rst +@@ -24,8 +24,9 @@ + .. class:: Repr() + + Class which provides formatting services useful in implementing functions +- similar to the built-in :func:`repr`; size limits for different object types +- are added to avoid the generation of representations which are excessively long. ++ similar to the built-in :ref:`repr() `; size limits for different ++ object types are added to avoid the generation of representations which are ++ excessively long. + + + .. data:: aRepr +@@ -96,8 +97,8 @@ + + .. method:: Repr.repr(obj) + +- The equivalent to the built-in :func:`repr` that uses the formatting imposed by +- the instance. ++ The equivalent to the built-in :ref:`repr() ` that uses the ++ formatting imposed by the instance. + + + .. method:: Repr.repr1(obj, level) +diff -r 3a1db0d2747e Doc/library/rexec.rst +--- a/Doc/library/rexec.rst ++++ b/Doc/library/rexec.rst +@@ -270,7 +270,7 @@ + if mode in ('r', 'rb'): + pass + elif mode in ('w', 'wb', 'a', 'ab'): +- # check filename : must begin with /tmp/ ++ # check filename: must begin with /tmp/ + if file[:5]!='/tmp/': + raise IOError("can't write outside /tmp") + elif (string.find(file, '/../') >= 0 or +diff -r 3a1db0d2747e Doc/library/simplexmlrpcserver.rst +--- a/Doc/library/simplexmlrpcserver.rst ++++ b/Doc/library/simplexmlrpcserver.rst +@@ -197,6 +197,38 @@ + # Print list of available methods + print s.system.listMethods() + ++The following :class:`SimpleXMLRPCServer` example is included in the module ++`Lib/SimpleXMLRPCServer.py`:: ++ ++ server = SimpleXMLRPCServer(("localhost", 8000)) ++ server.register_function(pow) ++ server.register_function(lambda x,y: x+y, 'add') ++ server.register_multicall_functions() ++ server.serve_forever() ++ ++This demo server can be run from the command line as:: ++ ++ python -m SimpleXMLRPCServer ++ ++Example client code which talks to the above server is included with ++`Lib/xmlrpclib.py`:: ++ ++ server = ServerProxy("http://localhost:8000") ++ print server ++ multi = MultiCall(server) ++ multi.pow(2, 9) ++ multi.add(5, 1) ++ multi.add(24, 11) ++ try: ++ for response in multi(): ++ print response ++ except Error, v: ++ print "ERROR", v ++ ++And the client can be invoked directly using the following command:: ++ ++ python -m xmlrpclib ++ + + CGIXMLRPCRequestHandler + ----------------------- +@@ -247,7 +279,7 @@ + Example:: + + class MyFuncs: +- def div(self, x, y) : return x // y ++ def div(self, x, y): return x // y + + + handler = CGIXMLRPCRequestHandler() +diff -r 3a1db0d2747e Doc/library/socket.rst +--- a/Doc/library/socket.rst ++++ b/Doc/library/socket.rst +@@ -562,6 +562,7 @@ + automatically closed when they are garbage-collected. + + .. note:: ++ + :meth:`close()` releases the resource associated with a connection but + does not necessarily close the connection immediately. If you want + to close the connection in a timely fashion, call :meth:`shutdown()` +diff -r 3a1db0d2747e Doc/library/sqlite3.rst +--- a/Doc/library/sqlite3.rst ++++ b/Doc/library/sqlite3.rst +@@ -97,7 +97,7 @@ + + .. seealso:: + +- http://code.google.com/p/pysqlite/ ++ https://github.com/ghaering/pysqlite + The pysqlite web page -- sqlite3 is developed externally under the name + "pysqlite". + +@@ -234,10 +234,10 @@ + .. function:: enable_callback_tracebacks(flag) + + By default you will not get any tracebacks in user-defined functions, +- aggregates, converters, authorizer callbacks etc. If you want to debug them, you +- can call this function with *flag* as True. Afterwards, you will get tracebacks +- from callbacks on ``sys.stderr``. Use :const:`False` to disable the feature +- again. ++ aggregates, converters, authorizer callbacks etc. If you want to debug them, ++ you can call this function with *flag* set to ``True``. Afterwards, you will ++ get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to ++ disable the feature again. + + + .. _sqlite3-connection-objects: +diff -r 3a1db0d2747e Doc/library/ssl.rst +--- a/Doc/library/ssl.rst ++++ b/Doc/library/ssl.rst +@@ -30,6 +30,18 @@ + operating system socket APIs. The installed version of OpenSSL may also + cause variations in behavior. + ++.. warning:: ++ The ssl module won't validate certificates by default. When used in ++ client mode, this means you are vulnerable to man-in-the-middle attacks. ++ ++.. warning:: ++ ++ OpenSSL's internal random number generator does not properly handle fork. ++ Applications must change the PRNG state of the parent process if they use ++ any SSL feature with :func:`os.fork`. Any successful call of ++ :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or ++ :func:`~ssl.RAND_pseudo_bytes` is sufficient. ++ + This section documents the objects and functions in the ``ssl`` module; for more + general information about TLS, SSL, and certificates, the reader is referred to + the documents in the "See Also" section at the bottom. +@@ -57,13 +69,16 @@ + + Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance + of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps +- the underlying socket in an SSL context. For client-side sockets, the +- context construction is lazy; if the underlying socket isn't connected yet, +- the context construction will be performed after :meth:`connect` is called on +- the socket. For server-side sockets, if the socket has no remote peer, it is +- assumed to be a listening socket, and the server-side SSL wrapping is +- automatically performed on client connections accepted via the :meth:`accept` +- method. :func:`wrap_socket` may raise :exc:`SSLError`. ++ the underlying socket in an SSL context. ``sock`` must be a ++ :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported. ++ ++ For client-side sockets, the context construction is lazy; if the ++ underlying socket isn't connected yet, the context construction will be ++ performed after :meth:`connect` is called on the socket. For ++ server-side sockets, if the socket has no remote peer, it is assumed ++ to be a listening socket, and the server-side SSL wrapping is ++ automatically performed on client connections accepted via the ++ :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`. + + The ``keyfile`` and ``certfile`` parameters specify optional files which + contain a certificate to be used to identify the local side of the +@@ -154,7 +169,7 @@ + + .. function:: RAND_status() + +- Returns True if the SSL pseudo-random number generator has been seeded with ++ Returns ``True`` if the SSL pseudo-random number generator has been seeded with + 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd` + and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random + number generator. +diff -r 3a1db0d2747e Doc/library/stdtypes.rst +--- a/Doc/library/stdtypes.rst ++++ b/Doc/library/stdtypes.rst +@@ -754,11 +754,11 @@ + +------------------+--------------------------------+----------+ + | ``max(s)`` | largest item of *s* | | + +------------------+--------------------------------+----------+ +-| ``s.index(i)`` | index of the first occurrence | | +-| | of *i* in *s* | | ++| ``s.index(x)`` | index of the first occurrence | | ++| | of *x* in *s* | | + +------------------+--------------------------------+----------+ +-| ``s.count(i)`` | total number of occurrences of | | +-| | *i* in *s* | | ++| ``s.count(x)`` | total number of occurrences of | | ++| | *x* in *s* | | + +------------------+--------------------------------+----------+ + + Sequence types also support comparisons. In particular, tuples and lists +@@ -1668,9 +1668,8 @@ + Previously, all negative indices were truncated to zero. + + (6) +- The :meth:`pop` method is only supported by the list and array types. The +- optional argument *i* defaults to ``-1``, so that by default the last item is +- removed and returned. ++ The :meth:`pop` method's optional argument *i* defaults to ``-1``, so that ++ by default the last item is removed and returned. + + (7) + The :meth:`sort` and :meth:`reverse` methods modify the list in place for +@@ -1783,7 +1782,7 @@ + + .. method:: isdisjoint(other) + +- Return True if the set has no elements in common with *other*. Sets are ++ Return ``True`` if the set has no elements in common with *other*. Sets are + disjoint if and only if their intersection is the empty set. + + .. versionadded:: 2.6 +diff -r 3a1db0d2747e Doc/library/string.rst +--- a/Doc/library/string.rst ++++ b/Doc/library/string.rst +@@ -330,7 +330,7 @@ + precision: `integer` + type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" + +-If a valid *align* value is specified, it can be preceeded by a *fill* ++If a valid *align* value is specified, it can be preceded by a *fill* + character that can be any character and defaults to a space if omitted. + Note that it is not possible to use ``{`` and ``}`` as *fill* char while + using the :meth:`str.format` method; this limitation however doesn't +diff -r 3a1db0d2747e Doc/library/stringprep.rst +--- a/Doc/library/stringprep.rst ++++ b/Doc/library/stringprep.rst +@@ -4,7 +4,6 @@ + + .. module:: stringprep + :synopsis: String preparation, as per RFC 3453 +- :deprecated: + .. moduleauthor:: Martin v. Löwis + .. sectionauthor:: Martin v. Löwis + +diff -r 3a1db0d2747e Doc/library/struct.rst +--- a/Doc/library/struct.rst ++++ b/Doc/library/struct.rst +@@ -284,7 +284,7 @@ + For the ``'?'`` format character, the return value is either :const:`True` or + :const:`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. ++any non-zero value will be ``True`` when unpacking. + + + +diff -r 3a1db0d2747e Doc/library/subprocess.rst +--- a/Doc/library/subprocess.rst ++++ b/Doc/library/subprocess.rst +@@ -12,7 +12,7 @@ + + The :mod:`subprocess` module allows you to spawn new processes, connect to their + input/output/error pipes, and obtain their return codes. This module intends to +-replace several other, older modules and functions, such as:: ++replace several older modules and functions:: + + os.system + os.spawn* +diff -r 3a1db0d2747e Doc/library/sys.rst +--- a/Doc/library/sys.rst ++++ b/Doc/library/sys.rst +@@ -1077,5 +1077,5 @@ + + .. rubric:: Citations + +-.. [C99] ISO/IEC 9899:1999. "Programming languages -- C." A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf . ++.. [C99] ISO/IEC 9899:1999. "Programming languages -- C." A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\ . + +diff -r 3a1db0d2747e Doc/library/telnetlib.rst +--- a/Doc/library/telnetlib.rst ++++ b/Doc/library/telnetlib.rst +@@ -208,7 +208,7 @@ + .. method:: Telnet.set_option_negotiation_callback(callback) + + Each time a telnet option is read on the input flow, this *callback* (if set) is +- called with the following parameters : callback(telnet socket, command ++ called with the following parameters: callback(telnet socket, command + (DO/DONT/WILL/WONT), option). No other action is done afterwards by telnetlib. + + +diff -r 3a1db0d2747e Doc/library/tkinter.rst +--- a/Doc/library/tkinter.rst ++++ b/Doc/library/tkinter.rst +@@ -19,7 +19,7 @@ + + .. seealso:: + +- `Python Tkinter Resources `_ ++ `Python Tkinter Resources `_ + The Python Tkinter Topic Guide provides a great deal of information on using Tk + from Python and links to other sources of information on Tk. + +@@ -188,7 +188,7 @@ + The Tk/Tcl development is largely taking place at ActiveState. + + `Tcl and the Tk Toolkit `_ +- The book by John Ousterhout, the inventor of Tcl . ++ The book by John Ousterhout, the inventor of Tcl. + + `Practical Programming in Tcl and Tk `_ + Brent Welch's encyclopedic book. +@@ -452,7 +452,7 @@ + Example:: + + >>> print fred.config() +- {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')} ++ {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')} + + Of course, the dictionary printed will include all the options available and + their values. This is meant only as an example. +@@ -625,7 +625,7 @@ + preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``. + + boolean +- You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"`` . ++ You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``. + + callback + This is any Python function that takes no arguments. For example:: +diff -r 3a1db0d2747e Doc/library/trace.rst +--- a/Doc/library/trace.rst ++++ b/Doc/library/trace.rst +@@ -41,7 +41,7 @@ + + At least one of the following options must be specified when invoking + :mod:`trace`. The :option:`--listfuncs <-l>` option is mutually exclusive with +-the :option:`--trace <-t>` and :option:`--counts <-c>` options . When ++the :option:`--trace <-t>` and :option:`--counts <-c>` options. When + :option:`--listfuncs <-l>` is provided, neither :option:`--counts <-c>` nor + :option:`--trace <-t>` are accepted, and vice versa. + +diff -r 3a1db0d2747e Doc/library/ttk.rst +--- a/Doc/library/ttk.rst ++++ b/Doc/library/ttk.rst +@@ -267,8 +267,8 @@ + + .. method:: instate(statespec, callback=None, *args, **kw) + +- Test the widget's state. If a callback is not specified, returns True +- if the widget state matches *statespec* and False otherwise. If callback ++ Test the widget's state. If a callback is not specified, returns ``True`` ++ if the widget state matches *statespec* and ``False`` otherwise. If callback + is specified then it is called with *args* if widget state matches + *statespec*. + +@@ -919,7 +919,7 @@ + + .. method:: exists(item) + +- Returns True if the specified *item* is present in the tree. ++ Returns ``True`` if the specified *item* is present in the tree. + + + .. method:: focus([item=None]) +@@ -1065,7 +1065,7 @@ + + Ensure that *item* is visible. + +- Sets all of *item*'s ancestors open option to True, and scrolls the ++ Sets all of *item*'s ancestors open option to ``True``, and scrolls the + widget if necessary so that *item* is within the visible portion of + the tree. + +diff -r 3a1db0d2747e Doc/library/turtle.rst +--- a/Doc/library/turtle.rst ++++ b/Doc/library/turtle.rst +@@ -1049,8 +1049,8 @@ + + Write text - the string representation of *arg* - at the current turtle + position according to *align* ("left", "center" or right") and with the given +- font. If *move* is True, the pen is moved to the bottom-right corner of the +- text. By default, *move* is False. ++ font. If *move* is true, the pen is moved to the bottom-right corner of the ++ text. By default, *move* is ``False``. + + >>> turtle.write("Home = ", True, align="center") + >>> turtle.write((0,0), True) +@@ -1086,7 +1086,7 @@ + + .. function:: isvisible() + +- Return True if the Turtle is shown, False if it's hidden. ++ Return ``True`` if the Turtle is shown, ``False`` if it's hidden. + + >>> turtle.hideturtle() + >>> turtle.isvisible() +diff -r 3a1db0d2747e Doc/library/unittest.rst +--- a/Doc/library/unittest.rst ++++ b/Doc/library/unittest.rst +@@ -1510,11 +1510,11 @@ + + .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None) + +- Find and return all test modules from the specified start directory, +- recursing into subdirectories to find them. Only test files that match +- *pattern* will be loaded. (Using shell style pattern matching.) Only +- module names that are importable (i.e. are valid Python identifiers) will +- be loaded. ++ Find all the test modules by recursing into subdirectories from the ++ specified start directory, and return a TestSuite object containing them. ++ Only test files that match *pattern* will be loaded. (Using shell style ++ pattern matching.) Only module names that are importable (i.e. are valid ++ Python identifiers) will be loaded. + + All test modules must be importable from the top level of the project. If + the start directory is not the top level directory then the top level +@@ -1808,6 +1808,10 @@ + if __name__ == '__main__': + unittest.main(verbosity=2) + ++ The *defaultTest* argument is the name of the test to run if no test names ++ are specified via *argv*. If not specified or ``None`` and no test names are ++ provided via *argv*, all tests found in *module* are run. ++ + The *argv* argument can be a list of options passed to the program, with the + first element being the program name. If not specified or ``None``, + the values of :data:`sys.argv` are used. +diff -r 3a1db0d2747e Doc/library/urllib.rst +--- a/Doc/library/urllib.rst ++++ b/Doc/library/urllib.rst +@@ -9,8 +9,9 @@ + Python 3 to :mod:`urllib.request`, :mod:`urllib.parse`, + and :mod:`urllib.error`. The :term:`2to3` tool will automatically adapt + imports when converting your sources to Python 3. +- Also note that the :func:`urllib.urlopen` function has been removed in +- Python 3 in favor of :func:`urllib2.urlopen`. ++ Also note that the :func:`urllib.request.urlopen` function in Python 3 is ++ equivalent to :func:`urllib2.urlopen` and that :func:`urllib.urlopen` has ++ been removed. + + .. index:: + single: WWW +diff -r 3a1db0d2747e Doc/library/urllib2.rst +--- a/Doc/library/urllib2.rst ++++ b/Doc/library/urllib2.rst +@@ -166,7 +166,7 @@ + should be the request-host of the request for the page containing the image. + + *unverifiable* should indicate whether the request is unverifiable, as defined +- by RFC 2965. It defaults to False. An unverifiable request is one whose URL ++ by RFC 2965. It defaults to ``False``. An unverifiable request is one whose URL + the user did not have the option to approve. For example, if the request is for + an image in an HTML document, and the user had no option to approve the + automatic fetching of the image, this should be true. +diff -r 3a1db0d2747e Doc/library/userdict.rst +--- a/Doc/library/userdict.rst ++++ b/Doc/library/userdict.rst +@@ -128,7 +128,7 @@ + A real Python list object used to store the contents of the :class:`UserList` + class. + +-**Subclassing requirements:** Subclasses of :class:`UserList` are expect to ++**Subclassing requirements:** Subclasses of :class:`UserList` are expected to + offer a constructor which can be called with either no arguments or one + argument. List operations which return a new sequence attempt to create an + instance of the actual implementation class. To do so, it assumes that the +diff -r 3a1db0d2747e Doc/library/weakref.rst +--- a/Doc/library/weakref.rst ++++ b/Doc/library/weakref.rst +@@ -163,7 +163,7 @@ + + .. method:: WeakKeyDictionary.iterkeyrefs() + +- Return an :term:`iterator` that yields the weak references to the keys. ++ Return an iterable of the weak references to the keys. + + .. versionadded:: 2.5 + +@@ -195,7 +195,7 @@ + + .. method:: WeakValueDictionary.itervaluerefs() + +- Return an :term:`iterator` that yields the weak references to the values. ++ Return an iterable of the weak references to the values. + + .. versionadded:: 2.5 + +diff -r 3a1db0d2747e Doc/library/xml.dom.minidom.rst +--- a/Doc/library/xml.dom.minidom.rst ++++ b/Doc/library/xml.dom.minidom.rst +@@ -276,4 +276,4 @@ + .. [#] The encoding string included in XML output should conform to the + appropriate standards. For example, "UTF-8" is valid, but "UTF8" is + not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl +- and http://www.iana.org/assignments/character-sets . ++ and http://www.iana.org/assignments/character-sets\ . +diff -r 3a1db0d2747e Doc/library/xml.rst +--- a/Doc/library/xml.rst ++++ b/Doc/library/xml.rst +@@ -28,11 +28,12 @@ + The XML handling submodules are: + + * :mod:`xml.etree.ElementTree`: the ElementTree API, a simple and lightweight ++ XML processor + + .. + + * :mod:`xml.dom`: the DOM API definition +-* :mod:`xml.dom.minidom`: a lightweight DOM implementation ++* :mod:`xml.dom.minidom`: a minimal DOM implementation + * :mod:`xml.dom.pulldom`: support for building partial DOM trees + + .. +@@ -94,7 +95,7 @@ + content into the XML document. + + DTD retrieval +- Some XML libraries like Python's mod:'xml.dom.pulldom' retrieve document type ++ Some XML libraries like Python's :mod:`xml.dom.pulldom` retrieve document type + definitions from remote or local locations. The feature has similar + implications as the external entity expansion issue. + +diff -r 3a1db0d2747e Doc/library/zipimport.rst +--- a/Doc/library/zipimport.rst ++++ b/Doc/library/zipimport.rst +@@ -115,7 +115,7 @@ + + .. method:: is_package(fullname) + +- Return True if the module specified by *fullname* is a package. Raise ++ Return ``True`` if the module specified by *fullname* is a package. Raise + :exc:`ZipImportError` if the module couldn't be found. + + +diff -r 3a1db0d2747e Doc/license.rst +--- a/Doc/license.rst ++++ b/Doc/license.rst +@@ -84,7 +84,7 @@ + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python |release| alone or in any derivative + version, provided, however, that PSF's License Agreement and PSF's notice of +- copyright, i.e., "Copyright © 2001-2013 Python Software Foundation; All Rights ++ copyright, i.e., "Copyright © 2001-2014 Python Software Foundation; All Rights + Reserved" are retained in Python |release| alone or in any derivative version + prepared by Licensee. + +@@ -746,8 +746,8 @@ + * + */ + +- Original SSLeay License +- ----------------------- ++ Original SSLeay License ++ ----------------------- + + /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. +diff -r 3a1db0d2747e Doc/reference/datamodel.rst +--- a/Doc/reference/datamodel.rst ++++ b/Doc/reference/datamodel.rst +@@ -207,7 +207,7 @@ + single: True + + These represent the truth values False and True. The two objects +- representing the values False and True are the only Boolean objects. ++ representing the values ``False`` and ``True`` are the only Boolean objects. + The Boolean type is a subtype of plain integers, and Boolean values + behave like the values 0 and 1, respectively, in almost all contexts, + the exception being that when converted to a string, the strings +@@ -486,44 +486,39 @@ + +-----------------------+-------------------------------+-----------+ + | Attribute | Meaning | | + +=======================+===============================+===========+ +- | :attr:`func_doc` | The function's documentation | Writable | +- | | string, or ``None`` if | | +- | | unavailable | | ++ | :attr:`__doc__` | The function's documentation | Writable | ++ | :attr:`func_doc` | string, or ``None`` if | | ++ | | unavailable. | | + +-----------------------+-------------------------------+-----------+ +- | :attr:`__doc__` | Another way of spelling | Writable | +- | | :attr:`func_doc` | | +- +-----------------------+-------------------------------+-----------+ +- | :attr:`func_name` | The function's name | Writable | +- +-----------------------+-------------------------------+-----------+ +- | :attr:`__name__` | Another way of spelling | Writable | +- | | :attr:`func_name` | | ++ | :attr:`__name__` | The function's name. | Writable | ++ | :attr:`func_name` | | | + +-----------------------+-------------------------------+-----------+ + | :attr:`__module__` | The name of the module the | Writable | + | | function was defined in, or | | + | | ``None`` if unavailable. | | + +-----------------------+-------------------------------+-----------+ +- | :attr:`func_defaults` | A tuple containing default | Writable | +- | | argument values for those | | ++ | :attr:`__defaults__` | A tuple containing default | Writable | ++ | :attr:`func_defaults` | argument values for those | | + | | arguments that have defaults, | | + | | or ``None`` if no arguments | | +- | | have a default value | | ++ | | have a default value. | | + +-----------------------+-------------------------------+-----------+ +- | :attr:`func_code` | The code object representing | Writable | +- | | the compiled function body. | | ++ | :attr:`__code__` | The code object representing | Writable | ++ | :attr:`func_code` | the compiled function body. | | + +-----------------------+-------------------------------+-----------+ +- | :attr:`func_globals` | A reference to the dictionary | Read-only | +- | | that holds the function's | | ++ | :attr:`__globals__` | A reference to the dictionary | Read-only | ++ | :attr:`func_globals` | that holds the function's | | + | | global variables --- the | | + | | global namespace of the | | + | | module in which the function | | + | | was defined. | | + +-----------------------+-------------------------------+-----------+ +- | :attr:`func_dict` | The namespace supporting | Writable | +- | | arbitrary function | | ++ | :attr:`__dict__` | The namespace supporting | Writable | ++ | :attr:`func_dict` | arbitrary function | | + | | attributes. | | + +-----------------------+-------------------------------+-----------+ +- | :attr:`func_closure` | ``None`` or a tuple of cells | Read-only | +- | | that contain bindings for the | | ++ | :attr:`__closure__` | ``None`` or a tuple of cells | Read-only | ++ | :attr:`func_closure` | that contain bindings for the | | + | | function's free variables. | | + +-----------------------+-------------------------------+-----------+ + +@@ -532,6 +527,12 @@ + .. versionchanged:: 2.4 + ``func_name`` is now writable. + ++ .. versionchanged:: 2.6 ++ The double-underscore attributes ``__closure__``, ``__code__``, ++ ``__defaults__``, and ``__globals__`` were introduced as aliases for ++ the corresponding ``func_*`` attributes for forwards compatibility ++ with Python 3. ++ + Function objects also support getting and setting arbitrary attributes, which + can be used, for example, to attach metadata to functions. Regular attribute + dot-notation is used to get and set such attributes. *Note that the current +@@ -542,16 +543,21 @@ + code object; see the description of internal types below. + + .. index:: +- single: func_doc (function attribute) + single: __doc__ (function attribute) + single: __name__ (function attribute) + single: __module__ (function attribute) + single: __dict__ (function attribute) ++ single: __defaults__ (function attribute) ++ single: __code__ (function attribute) ++ single: __globals__ (function attribute) ++ single: __closure__ (function attribute) ++ single: func_doc (function attribute) ++ single: func_name (function attribute) ++ single: func_dict (function attribute) + single: func_defaults (function attribute) +- single: func_closure (function attribute) + single: func_code (function attribute) + single: func_globals (function attribute) +- single: func_dict (function attribute) ++ single: func_closure (function attribute) + pair: global; namespace + + User-defined methods +diff -r 3a1db0d2747e Doc/tools/dailybuild.py +--- a/Doc/tools/dailybuild.py ++++ b/Doc/tools/dailybuild.py +@@ -29,6 +29,7 @@ + + + BUILDROOT = '/home/gbrandl/docbuild' ++SPHINXBUILD = os.path.join(BUILDROOT, 'sphinx-env/bin/sphinx-build') + WWWROOT = '/data/ftp.python.org/pub/docs.python.org' + + BRANCHES = [ +@@ -43,11 +44,11 @@ + print 'Doc autobuild started in %s' % checkout + os.chdir(checkout) + print 'Running hg pull --update' +- os.system('/usr/local/bin/hg pull --update') ++ os.system('hg pull --update') + print 'Running make autobuild' + maketarget = 'autobuild-' + ('html' if quick else + ('dev' if isdev else 'stable')) +- if os.WEXITSTATUS(os.system('cd Doc; make %s' % maketarget)) == 2: ++ if os.WEXITSTATUS(os.system('cd Doc; make SPHINXBUILD=%s %s' % (SPHINXBUILD, maketarget))) == 2: + print '*' * 80 + return + print 'Copying HTML files to %s' % target +diff -r 3a1db0d2747e Doc/tools/sphinx-build.py +--- a/Doc/tools/sphinx-build.py ++++ b/Doc/tools/sphinx-build.py +@@ -15,13 +15,13 @@ + + if __name__ == '__main__': + +- if sys.version_info[:3] < (2, 4, 0): +- print >>sys.stderr, """\ +-Error: Sphinx needs to be executed with Python 2.4 or newer ++ if sys.version_info[:3] < (2, 4, 0) or sys.version_info[:3] > (3, 0, 0): ++ sys.stderr.write("""\ ++Error: Sphinx needs to be executed with Python 2.4 or newer (not 3.x though). + (If you run this from the Makefile, you can set the PYTHON variable + to the path of an alternative interpreter executable, e.g., + ``make html PYTHON=python2.5``). +-""" ++""") + sys.exit(1) + + from sphinx import main +diff -r 3a1db0d2747e Doc/tools/sphinxext/pyspecific.py +--- a/Doc/tools/sphinxext/pyspecific.py ++++ b/Doc/tools/sphinxext/pyspecific.py +@@ -184,11 +184,11 @@ + 'bltin-null-object', 'bltin-type-objects', 'booleans', + 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound', + 'context-managers', 'continue', 'conversions', 'customization', 'debugger', +- 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel', ++ 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'exec', 'execmodel', + 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global', + 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers', + 'lambda', 'lists', 'naming', 'numbers', 'numeric-types', +- 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return', ++ 'objects', 'operator-summary', 'pass', 'power', 'print', 'raise', 'return', + 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames', + 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types', + 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules', +diff -r 3a1db0d2747e Doc/tools/sphinxext/static/version_switch.js +--- a/Doc/tools/sphinxext/static/version_switch.js ++++ b/Doc/tools/sphinxext/static/version_switch.js +@@ -2,7 +2,8 @@ + 'use strict'; + + var all_versions = { +- '3.4': 'dev (3.4)', ++ '3.5': 'dev (3.5)', ++ '3.4': '3.4', + '3.3': '3.3', + '3.2': '3.2', + '2.7': '2.7', +diff -r 3a1db0d2747e Doc/tools/sphinxext/susp-ignored.csv +--- a/Doc/tools/sphinxext/susp-ignored.csv ++++ b/Doc/tools/sphinxext/susp-ignored.csv +@@ -8,6 +8,10 @@ + extending/extending,,:myfunction,"PyArg_ParseTuple(args, ""D:myfunction"", &c);" + extending/newtypes,,:call,"if (!PyArg_ParseTuple(args, ""sss:call"", &arg1, &arg2, &arg3)) {" + extending/windows,,:initspam,/export:initspam ++faq/programming,,:reduce,"print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y," ++faq/programming,,:reduce,"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro," ++faq/programming,,:chr,">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(" ++faq/programming,,::,for x in sequence[::-1]: + howto/cporting,,:encode,"if (!PyArg_ParseTuple(args, ""O:encode_object"", &myobj))" + howto/cporting,,:say,"if (!PyArg_ParseTuple(args, ""U:say_hello"", &name))" + howto/curses,,:black,"They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and" +@@ -39,10 +43,15 @@ + howto/logging,,:logger,severity:logger name:message + howto/logging,,:message,severity:logger name:message + howto/logging,,:This,DEBUG:root:This message should go to the log file ++howto/pyporting,75,::,# make sure to use :: Python *and* :: Python :: 3 so ++howto/pyporting,75,::,"'Programming Language :: Python'," ++howto/pyporting,75,::,'Programming Language :: Python :: 3' + howto/regex,,::, + howto/regex,,:foo,(?:foo) + howto/urllib2,,:example,"for example ""joe@password:example.com""" + library/audioop,,:ipos,"# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)]," ++library/bisect,,:hi,all(val >= x for val in a[i:hi]) ++library/bisect,,:hi,all(val > x for val in a[i:hi]) + library/cookie,,`,!#$%&'*+-.^_`|~ + library/datetime,,:MM, + library/datetime,,:SS, +@@ -92,8 +101,9 @@ + library/profile,,:lineno,filename:lineno(function) + library/pyexpat,,:elem1, + library/pyexpat,,:py,"xmlns:py = ""http://www.python.org/ns/"">" +-library/smtplib,,:port,"as well as a regular host:port server." ++library/smtplib,,:port,method must support that as well as a regular host:port + library/socket,,::,'5aef:2b::8' ++library/socket,,::,"(10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]" + library/sqlite3,,:memory, + library/sqlite3,,:who,"cur.execute(""select * from people where name_last=:who and age=:age"", {""who"": who, ""age"": age})" + library/sqlite3,,:age,"cur.execute(""select * from people where name_last=:who and age=:age"", {""who"": who, ""age"": age})" +@@ -105,6 +115,7 @@ + library/ssl,,:Some,"Locality Name (eg, city) []:Some City" + library/ssl,,:US,Country Name (2 letter code) [AU]:US + library/stdtypes,,:len,s[len(s):len(s)] ++library/stdtypes,,:end,s[start:end] + library/string,,:end,s[start:end] + library/subprocess,,`,"output=`mycmd myarg`" + library/subprocess,,`,"output=`dmesg | grep hda`" +@@ -116,6 +127,7 @@ + library/turtle,,::,Example:: + library/urllib,,:port,:port + library/urllib2,,:password,"""joe:password@python.org""" ++library/urllib2,,:close,Connection:close + library/uuid,,:uuid,urn:uuid:12345678-1234-5678-1234-567812345678 + library/xmlrpclib,,:pass,http://user:pass@host:port/path + library/xmlrpclib,,:pass,user:pass +@@ -123,6 +135,10 @@ + license,,`,THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + license,,:zooko,mailto:zooko@zooko.com + license,,`,THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ++license,,`,* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY ++license,,`,* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND ++license,,`,"``Software''), to deal in the Software without restriction, including" ++license,,`,"THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND," + reference/datamodel,,:step,a[i:j:step] + reference/datamodel,,:max, + reference/expressions,,:index,x[index:index] +@@ -150,6 +166,7 @@ + using/cmdline,,:message,action:message:category:module:line + using/cmdline,,:module,action:message:category:module:line + using/cmdline,,:errorhandler,:errorhandler ++using/unix,,:Packaging,http://en.opensuse.org/Portal:Packaging + whatsnew/2.0,418,:len, + whatsnew/2.3,,::, + whatsnew/2.3,,:config, +@@ -163,24 +180,8 @@ + whatsnew/2.5,,:memory,:memory: + whatsnew/2.5,,:step,[start:stop:step] + whatsnew/2.5,,:stop,[start:stop:step] +-faq/programming,,:reduce,"print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y," +-faq/programming,,:reduce,"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro," +-faq/programming,,:chr,">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(" +-faq/programming,,::,for x in sequence[::-1]: +-library/bisect,,:hi,all(val >= x for val in a[i:hi]) +-library/bisect,,:hi,all(val > x for val in a[i:hi]) +-library/socket,,::,"(10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]" +-library/stdtypes,,:end,s[start:end] +-license,,`,* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY +-license,,`,* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND +-license,,`,"``Software''), to deal in the Software without restriction, including" +-license,,`,"THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND," + whatsnew/2.7,735,:Sunday,'2009:4:Sunday' + whatsnew/2.7,862,::,"export PYTHONWARNINGS=all,error:::Cookie:0" + whatsnew/2.7,862,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0" + whatsnew/2.7,,::,>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo') + whatsnew/2.7,,::,"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]'," +-howto/pyporting,75,::,# make sure to use :: Python *and* :: Python :: 3 so +-howto/pyporting,75,::,"'Programming Language :: Python'," +-howto/pyporting,75,::,'Programming Language :: Python :: 3' +-library/urllib2,67,:close,Connection:close +diff -r 3a1db0d2747e Doc/tutorial/controlflow.rst +--- a/Doc/tutorial/controlflow.rst ++++ b/Doc/tutorial/controlflow.rst +@@ -19,14 +19,14 @@ + >>> x = int(raw_input("Please enter an integer: ")) + Please enter an integer: 42 + >>> if x < 0: +- ... x = 0 +- ... print 'Negative changed to zero' ++ ... x = 0 ++ ... print 'Negative changed to zero' + ... elif x == 0: +- ... print 'Zero' ++ ... print 'Zero' + ... elif x == 1: +- ... print 'Single' ++ ... print 'Single' + ... else: +- ... print 'More' ++ ... print 'More' + ... + More + +diff -r 3a1db0d2747e Doc/tutorial/inputoutput.rst +--- a/Doc/tutorial/inputoutput.rst ++++ b/Doc/tutorial/inputoutput.rst +@@ -358,47 +358,64 @@ + Reference for a complete guide to file objects. + + +-.. _tut-pickle: ++.. _tut-json: + +-The :mod:`pickle` Module +------------------------- ++Saving structured data with :mod:`json` ++--------------------------------------- + +-.. index:: module: pickle ++.. index:: module: json + +-Strings can easily be written to and read from a file. Numbers take a bit more ++Strings can easily be written to and read from a file. Numbers take a bit more + effort, since the :meth:`read` method only returns strings, which will have to + be passed to a function like :func:`int`, which takes a string like ``'123'`` +-and returns its numeric value 123. However, when you want to save more complex +-data types like lists, dictionaries, or class instances, things get a lot more +-complicated. ++and returns its numeric value 123. When you want to save more complex data ++types like nested lists and dictionaries, parsing and serializing by hand ++becomes complicated. + +-Rather than have users be constantly writing and debugging code to save +-complicated data types, Python provides a standard module called :mod:`pickle`. +-This is an amazing module that can take almost any Python object (even some +-forms of Python code!), and convert it to a string representation; this process +-is called :dfn:`pickling`. Reconstructing the object from the string +-representation is called :dfn:`unpickling`. Between pickling and unpickling, +-the string representing the object may have been stored in a file or data, or ++Rather than having users constantly writing and debugging code to save ++complicated data types to files, Python allows you to use the popular data ++interchange format called `JSON (JavaScript Object Notation) ++`_. The standard module called :mod:`json` can take Python ++data hierarchies, and convert them to string representations; this process is ++called :dfn:`serializing`. Reconstructing the data from the string representation ++is called :dfn:`deserializing`. Between serializing and deserializing, the ++string representing the object may have been stored in a file or data, or + sent over a network connection to some distant machine. + +-If you have an object ``x``, and a file object ``f`` that's been opened for +-writing, the simplest way to pickle the object takes only one line of code:: ++.. note:: ++ The JSON format is commonly used by modern applications to allow for data ++ exchange. Many programmers are already familiar with it, which makes ++ it a good choice for interoperability. + +- pickle.dump(x, f) ++If you have an object ``x``, you can view its JSON string representation with a ++simple line of code:: + +-To unpickle the object again, if ``f`` is a file object which has been opened +-for reading:: ++ >>> json.dumps([1, 'simple', 'list']) ++ '[1, "simple", "list"]' + +- x = pickle.load(f) ++Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`, ++simply serializes the object to a file. So if ``f`` is a :term:`file object` ++opened for writing, we can do this:: + +-(There are other variants of this, used when pickling many objects or when you +-don't want to write the pickled data to a file; consult the complete +-documentation for :mod:`pickle` in the Python Library Reference.) ++ json.dump(x, f) + +-:mod:`pickle` is the standard way to make Python objects which can be stored and +-reused by other programs or by a future invocation of the same program; the +-technical term for this is a :dfn:`persistent` object. Because :mod:`pickle` is +-so widely used, many authors who write Python extensions take care to ensure +-that new data types such as matrices can be properly pickled and unpickled. ++To decode the object again, if ``f`` is a :term:`file object` which has ++been opened for reading:: + ++ x = json.load(f) + ++This simple serialization technique can handle lists and dictionaries, but ++serializing arbitrary class instances in JSON requires a bit of extra effort. ++The reference for the :mod:`json` module contains an explanation of this. ++ ++.. seealso:: ++ ++ :mod:`pickle` - the pickle module ++ ++ Contrary to :ref:`JSON `, *pickle* is a protocol which allows ++ the serialization of arbitrarily complex Python objects. As such, it is ++ specific to Python and cannot be used to communicate with applications ++ written in other languages. It is also insecure by default: ++ deserializing pickle data coming from an untrusted source can execute ++ arbitrary code, if the data was crafted by a skilled attacker. ++ +diff -r 3a1db0d2747e Doc/whatsnew/2.4.rst +--- a/Doc/whatsnew/2.4.rst ++++ b/Doc/whatsnew/2.4.rst +@@ -846,7 +846,7 @@ + ['A', 'b', 'c', 'D'] + + Finally, the *reverse* parameter takes a Boolean value. If the value is true, +- the list will be sorted into reverse order. Instead of ``L.sort() ; ++ the list will be sorted into reverse order. Instead of ``L.sort(); + L.reverse()``, you can now write ``L.sort(reverse=True)``. + + The results of sorting are now guaranteed to be stable. This means that two +diff -r 3a1db0d2747e Doc/whatsnew/2.5.rst +--- a/Doc/whatsnew/2.5.rst ++++ b/Doc/whatsnew/2.5.rst +@@ -286,7 +286,7 @@ + :mod:`pkg.string` and look for the standard module; generally you had to look at + the contents of ``sys.modules``, which is slightly unclean. Holger Krekel's + :mod:`py.std` package provides a tidier way to perform imports from the standard +-library, ``import py ; py.std.string.join()``, but that package isn't available ++library, ``import py; py.std.string.join()``, but that package isn't available + on all Python installations. + + Reading code which relies on relative imports is also less clear, because a +diff -r 3a1db0d2747e Doc/whatsnew/2.6.rst +--- a/Doc/whatsnew/2.6.rst ++++ b/Doc/whatsnew/2.6.rst +@@ -1887,7 +1887,7 @@ + >>> dq=deque(maxlen=3) + >>> dq + deque([], maxlen=3) +- >>> dq.append(1) ; dq.append(2) ; dq.append(3) ++ >>> dq.append(1); dq.append(2); dq.append(3) + >>> dq + deque([1, 2, 3], maxlen=3) + >>> dq.append(4) +@@ -2779,12 +2779,12 @@ + types. The following example encodes and decodes a dictionary:: + + >>> import json +- >>> data = {"spam" : "foo", "parrot" : 42} ++ >>> data = {"spam": "foo", "parrot": 42} + >>> in_json = json.dumps(data) # Encode the data + >>> in_json + '{"parrot": 42, "spam": "foo"}' + >>> json.loads(in_json) # Decode into a Python object +- {"spam" : "foo", "parrot" : 42} ++ {"spam": "foo", "parrot": 42} + + It's also possible to write your own decoders and encoders to support + more types. Pretty-printing of the JSON strings is also supported. +diff -r 3a1db0d2747e Include/import.h +--- a/Include/import.h ++++ b/Include/import.h +@@ -40,8 +40,8 @@ + PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr *); + PyAPI_FUNC(void) _PyImport_ReInitLock(void); + +-PyAPI_FUNC(PyObject *)_PyImport_FindExtension(char *, char *); +-PyAPI_FUNC(PyObject *)_PyImport_FixupExtension(char *, char *); ++PyAPI_FUNC(PyObject *) _PyImport_FindExtension(char *, char *); ++PyAPI_FUNC(PyObject *) _PyImport_FixupExtension(char *, char *); + + struct _inittab { + char *name; +diff -r 3a1db0d2747e LICENSE +--- a/LICENSE ++++ b/LICENSE +@@ -74,7 +74,7 @@ + distribute, and otherwise use Python alone or in any derivative version, + provided, however, that PSF's License Agreement and PSF's notice of copyright, + i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +-2011, 2012, 2013 Python Software Foundation; All Rights Reserved" are retained ++2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved" are retained + in Python alone or in any derivative version prepared by Licensee. + + 3. In the event Licensee prepares a derivative work that is based on +diff -r 3a1db0d2747e Lib/Cookie.py +--- a/Lib/Cookie.py ++++ b/Lib/Cookie.py +@@ -1,6 +1,3 @@ +-#!/usr/bin/env python +-# +- + #### + # Copyright 2000 by Timothy O'Malley + # +diff -r 3a1db0d2747e Lib/HTMLParser.py +--- a/Lib/HTMLParser.py ++++ b/Lib/HTMLParser.py +@@ -22,9 +22,12 @@ + starttagopen = re.compile('<[a-zA-Z]') + piclose = re.compile('>') + commentclose = re.compile(r'--\s*>') +-tagfind = re.compile('([a-zA-Z][-.a-zA-Z0-9:_]*)(?:\s|/(?!>))*') ++ + # see http://www.w3.org/TR/html5/tokenization.html#tag-open-state + # and http://www.w3.org/TR/html5/tokenization.html#tag-name-state ++# note: if you change tagfind/attrfind remember to update locatestarttagend too ++tagfind = re.compile('([a-zA-Z][^\t\n\r\f />\x00]*)(?:\s|/(?!>))*') ++# this regex is currently unused, but left for backward compatibility + tagfind_tolerant = re.compile('[a-zA-Z][^\t\n\r\f />\x00]*') + + attrfind = re.compile( +@@ -32,7 +35,7 @@ + r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?(?:\s|/(?!>))*') + + locatestarttagend = re.compile(r""" +- <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name ++ <[a-zA-Z][^\t\n\r\f />\x00]* # tag name + (?:[\s/]* # optional whitespace before attribute name + (?:(?<=['"\s/])[^\s/>][^\s/=>]* # attribute name + (?:\s*=+\s* # value indicator +@@ -192,9 +195,9 @@ + i = self.updatepos(i, k) + continue + else: +- if ";" in rawdata[i:]: #bail by consuming &# +- self.handle_data(rawdata[0:2]) +- i = self.updatepos(i, 2) ++ if ";" in rawdata[i:]: # bail by consuming '&#' ++ self.handle_data(rawdata[i:i+2]) ++ i = self.updatepos(i, i+2) + break + elif startswith('&', i): + match = entityref.match(rawdata, i) +@@ -373,14 +376,14 @@ + self.handle_data(rawdata[i:gtpos]) + return gtpos + # find the name: w3.org/TR/html5/tokenization.html#tag-name-state +- namematch = tagfind_tolerant.match(rawdata, i+2) ++ namematch = tagfind.match(rawdata, i+2) + if not namematch: + # w3.org/TR/html5/tokenization.html#end-tag-open-state + if rawdata[i:i+3] == '': + return i+3 + else: + return self.parse_bogus_comment(i) +- tagname = namematch.group().lower() ++ tagname = namematch.group(1).lower() + # consume and ignore other stuff between the name and the > + # Note: this is not 100% correct, since we might have things like + # , but looking for > after tha name should cover +diff -r 3a1db0d2747e Lib/SimpleHTTPServer.py +--- a/Lib/SimpleHTTPServer.py ++++ b/Lib/SimpleHTTPServer.py +@@ -43,8 +43,10 @@ + """Serve a GET request.""" + f = self.send_head() + if f: +- self.copyfile(f, self.wfile) +- f.close() ++ try: ++ self.copyfile(f, self.wfile) ++ finally: ++ f.close() + + def do_HEAD(self): + """Serve a HEAD request.""" +@@ -88,13 +90,17 @@ + except IOError: + self.send_error(404, "File not found") + return None +- self.send_response(200) +- self.send_header("Content-type", ctype) +- fs = os.fstat(f.fileno()) +- self.send_header("Content-Length", str(fs[6])) +- self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) +- self.end_headers() +- return f ++ try: ++ self.send_response(200) ++ self.send_header("Content-type", ctype) ++ fs = os.fstat(f.fileno()) ++ self.send_header("Content-Length", str(fs[6])) ++ self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) ++ self.end_headers() ++ return f ++ except: ++ f.close() ++ raise + + def list_directory(self, path): + """Helper to produce a directory listing (absent index.html). +diff -r 3a1db0d2747e Lib/SimpleXMLRPCServer.py +--- a/Lib/SimpleXMLRPCServer.py ++++ b/Lib/SimpleXMLRPCServer.py +@@ -704,4 +704,5 @@ + server = SimpleXMLRPCServer(("localhost", 8000)) + server.register_function(pow) + server.register_function(lambda x,y: x+y, 'add') ++ server.register_multicall_functions() + server.serve_forever() +diff -r 3a1db0d2747e Lib/_MozillaCookieJar.py +--- a/Lib/_MozillaCookieJar.py ++++ b/Lib/_MozillaCookieJar.py +@@ -39,7 +39,7 @@ + magic_re = "#( Netscape)? HTTP Cookie File" + header = """\ + # Netscape HTTP Cookie File +-# http://www.netscape.com/newsref/std/cookie_spec.html ++# http://curl.haxx.se/rfc/cookie_spec.html + # This is a generated file! Do not edit. + + """ +diff -r 3a1db0d2747e Lib/_abcoll.py +--- a/Lib/_abcoll.py ++++ b/Lib/_abcoll.py +@@ -165,12 +165,12 @@ + def __gt__(self, other): + if not isinstance(other, Set): + return NotImplemented +- return other < self ++ return other.__lt__(self) + + def __ge__(self, other): + if not isinstance(other, Set): + return NotImplemented +- return other <= self ++ return other.__le__(self) + + def __eq__(self, other): + if not isinstance(other, Set): +diff -r 3a1db0d2747e Lib/_pyio.py +--- a/Lib/_pyio.py ++++ b/Lib/_pyio.py +@@ -1997,7 +1997,13 @@ + + def getvalue(self): + self.flush() +- return self.buffer.getvalue().decode(self._encoding, self._errors) ++ decoder = self._decoder or self._get_decoder() ++ old_state = decoder.getstate() ++ decoder.reset() ++ try: ++ return decoder.decode(self.buffer.getvalue(), final=True) ++ finally: ++ decoder.setstate(old_state) + + def __repr__(self): + # TextIOWrapper tells the encoding in its repr. In StringIO, +diff -r 3a1db0d2747e Lib/_weakrefset.py +--- a/Lib/_weakrefset.py ++++ b/Lib/_weakrefset.py +@@ -60,6 +60,8 @@ + for itemref in self.data: + item = itemref() + if item is not None: ++ # Caveat: the iterator will keep a strong reference to ++ # `item` until it is resumed or closed. + yield item + + def __len__(self): +diff -r 3a1db0d2747e Lib/aifc.py +--- a/Lib/aifc.py ++++ b/Lib/aifc.py +@@ -778,7 +778,7 @@ + + def _ensure_header_written(self, datasize): + if not self._nframeswritten: +- if self._comptype in ('ULAW', 'ALAW'): ++ if self._comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw'): + if not self._sampwidth: + self._sampwidth = 2 + if self._sampwidth != 2: +@@ -844,7 +844,7 @@ + if self._datalength & 1: + self._datalength = self._datalength + 1 + if self._aifc: +- if self._comptype in ('ULAW', 'ALAW'): ++ if self._comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw'): + self._datalength = self._datalength // 2 + if self._datalength & 1: + self._datalength = self._datalength + 1 +@@ -852,7 +852,10 @@ + self._datalength = (self._datalength + 3) // 4 + if self._datalength & 1: + self._datalength = self._datalength + 1 +- self._form_length_pos = self._file.tell() ++ try: ++ self._form_length_pos = self._file.tell() ++ except (AttributeError, IOError): ++ self._form_length_pos = None + commlength = self._write_form_length(self._datalength) + if self._aifc: + self._file.write('AIFC') +@@ -864,7 +867,8 @@ + self._file.write('COMM') + _write_ulong(self._file, commlength) + _write_short(self._file, self._nchannels) +- self._nframes_pos = self._file.tell() ++ if self._form_length_pos is not None: ++ self._nframes_pos = self._file.tell() + _write_ulong(self._file, self._nframes) + if self._comptype in ('ULAW', 'ulaw', 'ALAW', 'alaw', 'G722'): + _write_short(self._file, 8) +@@ -875,7 +879,8 @@ + self._file.write(self._comptype) + _write_string(self._file, self._compname) + self._file.write('SSND') +- self._ssnd_length_pos = self._file.tell() ++ if self._form_length_pos is not None: ++ self._ssnd_length_pos = self._file.tell() + _write_ulong(self._file, self._datalength + 8) + _write_ulong(self._file, 0) + _write_ulong(self._file, 0) +diff -r 3a1db0d2747e Lib/argparse.py +--- a/Lib/argparse.py ++++ b/Lib/argparse.py +@@ -168,6 +168,8 @@ + self._prog = prog + self._indent_increment = indent_increment + self._max_help_position = max_help_position ++ self._max_help_position = min(max_help_position, ++ max(width - 20, indent_increment * 2)) + self._width = width + + self._current_indent = 0 +@@ -339,7 +341,7 @@ + else: + line_len = len(indent) - 1 + for part in parts: +- if line_len + 1 + len(part) > text_width: ++ if line_len + 1 + len(part) > text_width and line: + lines.append(indent + ' '.join(line)) + line = [] + line_len = len(indent) - 1 +@@ -478,7 +480,7 @@ + def _format_text(self, text): + if '%(prog)' in text: + text = text % dict(prog=self._prog) +- text_width = self._width - self._current_indent ++ text_width = max(self._width - self._current_indent, 11) + indent = ' ' * self._current_indent + return self._fill_text(text, text_width, indent) + '\n\n' + +@@ -486,7 +488,7 @@ + # determine the required width and the entry label + help_position = min(self._action_max_length + 2, + self._max_help_position) +- help_width = self._width - help_position ++ help_width = max(self._width - help_position, 11) + action_width = help_position - self._current_indent - 2 + action_header = self._format_action_invocation(action) + +diff -r 3a1db0d2747e Lib/bsddb/dbshelve.py +--- a/Lib/bsddb/dbshelve.py ++++ b/Lib/bsddb/dbshelve.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + #------------------------------------------------------------------------ + # Copyright (c) 1997-2001 by Total Control Software + # All Rights Reserved +diff -r 3a1db0d2747e Lib/bsddb/test/test_dbtables.py +--- a/Lib/bsddb/test/test_dbtables.py ++++ b/Lib/bsddb/test/test_dbtables.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +-# + #----------------------------------------------------------------------- + # A test suite for the table interface built on bsddb.db + #----------------------------------------------------------------------- +diff -r 3a1db0d2747e Lib/codecs.py +--- a/Lib/codecs.py ++++ b/Lib/codecs.py +@@ -456,15 +456,12 @@ + + # read until we get the required number of characters (if available) + while True: +- # can the request can be satisfied from the character buffer? +- if chars < 0: +- if size < 0: +- if self.charbuffer: +- break +- elif len(self.charbuffer) >= size: ++ # can the request be satisfied from the character buffer? ++ if chars >= 0: ++ if len(self.charbuffer) >= chars: + break +- else: +- if len(self.charbuffer) >= chars: ++ elif size >= 0: ++ if len(self.charbuffer) >= size: + break + # we need more data + if size < 0: +diff -r 3a1db0d2747e Lib/csv.py +--- a/Lib/csv.py ++++ b/Lib/csv.py +@@ -93,6 +93,10 @@ + self.line_num = self.reader.line_num + return self._fieldnames + ++ # Issue 20004: Because DictReader is a classic class, this setter is ++ # ignored. At this point in 2.7's lifecycle, it is too late to change the ++ # base class for fear of breaking working code. If you want to change ++ # fieldnames without overwriting the getter, set _fieldnames directly. + @fieldnames.setter + def fieldnames(self, value): + self._fieldnames = value +@@ -140,8 +144,8 @@ + if self.extrasaction == "raise": + wrong_fields = [k for k in rowdict if k not in self.fieldnames] + if wrong_fields: +- raise ValueError("dict contains fields not in fieldnames: " + +- ", ".join(wrong_fields)) ++ raise ValueError("dict contains fields not in fieldnames: " ++ + ", ".join([repr(x) for x in wrong_fields])) + return [rowdict.get(key, self.restval) for key in self.fieldnames] + + def writerow(self, rowdict): +diff -r 3a1db0d2747e Lib/ctypes/test/test_arrays.py +--- a/Lib/ctypes/test/test_arrays.py ++++ b/Lib/ctypes/test/test_arrays.py +@@ -87,8 +87,8 @@ + self.assertEqual(values, [1, 2, 3, 4, 5]) + + def test_classcache(self): +- self.assertTrue(not ARRAY(c_int, 3) is ARRAY(c_int, 4)) +- self.assertTrue(ARRAY(c_int, 3) is ARRAY(c_int, 3)) ++ self.assertIsNot(ARRAY(c_int, 3), ARRAY(c_int, 4)) ++ self.assertIs(ARRAY(c_int, 3), ARRAY(c_int, 3)) + + def test_from_address(self): + # Failed with 0.9.8, reported by JUrner +@@ -128,7 +128,7 @@ + # Create a new array type based on it: + t1 = my_int * 1 + t2 = my_int * 1 +- self.assertTrue(t1 is t2) ++ self.assertIs(t1, t2) + + if __name__ == '__main__': + unittest.main() +diff -r 3a1db0d2747e Lib/ctypes/test/test_as_parameter.py +--- a/Lib/ctypes/test/test_as_parameter.py ++++ b/Lib/ctypes/test/test_as_parameter.py +@@ -134,7 +134,7 @@ + f.argtypes = [c_longlong, MyCallback] + + def callback(value): +- self.assertTrue(isinstance(value, (int, long))) ++ self.assertIsInstance(value, (int, long)) + return value & 0x7FFFFFFF + + cb = MyCallback(callback) +diff -r 3a1db0d2747e Lib/ctypes/test/test_bitfields.py +--- a/Lib/ctypes/test/test_bitfields.py ++++ b/Lib/ctypes/test/test_bitfields.py +@@ -207,7 +207,7 @@ + class X(Structure): + _fields_ = [("a", c_byte, 4), + ("b", c_int, 32)] +- self.assertEqual(sizeof(X), sizeof(c_int)*2) ++ self.assertEqual(sizeof(X), alignment(c_int)+sizeof(c_int)) + + def test_mixed_3(self): + class X(Structure): +diff -r 3a1db0d2747e Lib/ctypes/test/test_buffers.py +--- a/Lib/ctypes/test/test_buffers.py ++++ b/Lib/ctypes/test/test_buffers.py +@@ -7,12 +7,12 @@ + b = create_string_buffer(32) + self.assertEqual(len(b), 32) + self.assertEqual(sizeof(b), 32 * sizeof(c_char)) +- self.assertTrue(type(b[0]) is str) ++ self.assertIs(type(b[0]), str) + + b = create_string_buffer("abc") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_char)) +- self.assertTrue(type(b[0]) is str) ++ self.assertIs(type(b[0]), str) + self.assertEqual(b[0], "a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") +@@ -45,12 +45,12 @@ + b = create_unicode_buffer(32) + self.assertEqual(len(b), 32) + self.assertEqual(sizeof(b), 32 * sizeof(c_wchar)) +- self.assertTrue(type(b[0]) is unicode) ++ self.assertIs(type(b[0]), unicode) + + b = create_unicode_buffer(u"abc") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_wchar)) +- self.assertTrue(type(b[0]) is unicode) ++ self.assertIs(type(b[0]), unicode) + self.assertEqual(b[0], u"a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") +@@ -62,7 +62,7 @@ + b = create_unicode_buffer("abc") + self.assertEqual(len(b), 4) # trailing nul char + self.assertEqual(sizeof(b), 4 * sizeof(c_wchar)) +- self.assertTrue(type(b[0]) is unicode) ++ self.assertIs(type(b[0]), unicode) + self.assertEqual(b[0], u"a") + self.assertEqual(b[:], "abc\0") + self.assertEqual(b[::], "abc\0") +diff -r 3a1db0d2747e Lib/ctypes/test/test_byteswap.py +--- a/Lib/ctypes/test/test_byteswap.py ++++ b/Lib/ctypes/test/test_byteswap.py +@@ -23,11 +23,11 @@ + + def test_endian_short(self): + if sys.byteorder == "little": +- self.assertTrue(c_short.__ctype_le__ is c_short) +- self.assertTrue(c_short.__ctype_be__.__ctype_le__ is c_short) ++ self.assertIs(c_short.__ctype_le__, c_short) ++ self.assertIs(c_short.__ctype_be__.__ctype_le__, c_short) + else: +- self.assertTrue(c_short.__ctype_be__ is c_short) +- self.assertTrue(c_short.__ctype_le__.__ctype_be__ is c_short) ++ self.assertIs(c_short.__ctype_be__, c_short) ++ self.assertIs(c_short.__ctype_le__.__ctype_be__, c_short) + s = c_short.__ctype_be__(0x1234) + self.assertEqual(bin(struct.pack(">h", 0x1234)), "1234") + self.assertEqual(bin(s), "1234") +@@ -50,11 +50,11 @@ + + def test_endian_int(self): + if sys.byteorder == "little": +- self.assertTrue(c_int.__ctype_le__ is c_int) +- self.assertTrue(c_int.__ctype_be__.__ctype_le__ is c_int) ++ self.assertIs(c_int.__ctype_le__, c_int) ++ self.assertIs(c_int.__ctype_be__.__ctype_le__, c_int) + else: +- self.assertTrue(c_int.__ctype_be__ is c_int) +- self.assertTrue(c_int.__ctype_le__.__ctype_be__ is c_int) ++ self.assertIs(c_int.__ctype_be__, c_int) ++ self.assertIs(c_int.__ctype_le__.__ctype_be__, c_int) + + s = c_int.__ctype_be__(0x12345678) + self.assertEqual(bin(struct.pack(">i", 0x12345678)), "12345678") +@@ -78,11 +78,11 @@ + + def test_endian_longlong(self): + if sys.byteorder == "little": +- self.assertTrue(c_longlong.__ctype_le__ is c_longlong) +- self.assertTrue(c_longlong.__ctype_be__.__ctype_le__ is c_longlong) ++ self.assertIs(c_longlong.__ctype_le__, c_longlong) ++ self.assertIs(c_longlong.__ctype_be__.__ctype_le__, c_longlong) + else: +- self.assertTrue(c_longlong.__ctype_be__ is c_longlong) +- self.assertTrue(c_longlong.__ctype_le__.__ctype_be__ is c_longlong) ++ self.assertIs(c_longlong.__ctype_be__, c_longlong) ++ self.assertIs(c_longlong.__ctype_le__.__ctype_be__, c_longlong) + + s = c_longlong.__ctype_be__(0x1234567890ABCDEF) + self.assertEqual(bin(struct.pack(">q", 0x1234567890ABCDEF)), "1234567890ABCDEF") +@@ -106,11 +106,11 @@ + + def test_endian_float(self): + if sys.byteorder == "little": +- self.assertTrue(c_float.__ctype_le__ is c_float) +- self.assertTrue(c_float.__ctype_be__.__ctype_le__ is c_float) ++ self.assertIs(c_float.__ctype_le__, c_float) ++ self.assertIs(c_float.__ctype_be__.__ctype_le__, c_float) + else: +- self.assertTrue(c_float.__ctype_be__ is c_float) +- self.assertTrue(c_float.__ctype_le__.__ctype_be__ is c_float) ++ self.assertIs(c_float.__ctype_be__, c_float) ++ self.assertIs(c_float.__ctype_le__.__ctype_be__, c_float) + s = c_float(math.pi) + self.assertEqual(bin(struct.pack("f", math.pi)), bin(s)) + # Hm, what's the precision of a float compared to a double? +@@ -124,11 +124,11 @@ + + def test_endian_double(self): + if sys.byteorder == "little": +- self.assertTrue(c_double.__ctype_le__ is c_double) +- self.assertTrue(c_double.__ctype_be__.__ctype_le__ is c_double) ++ self.assertIs(c_double.__ctype_le__, c_double) ++ self.assertIs(c_double.__ctype_be__.__ctype_le__, c_double) + else: +- self.assertTrue(c_double.__ctype_be__ is c_double) +- self.assertTrue(c_double.__ctype_le__.__ctype_be__ is c_double) ++ self.assertIs(c_double.__ctype_be__, c_double) ++ self.assertIs(c_double.__ctype_le__.__ctype_be__, c_double) + s = c_double(math.pi) + self.assertEqual(s.value, math.pi) + self.assertEqual(bin(struct.pack("d", math.pi)), bin(s)) +@@ -140,14 +140,14 @@ + self.assertEqual(bin(struct.pack(">d", math.pi)), bin(s)) + + def test_endian_other(self): +- self.assertTrue(c_byte.__ctype_le__ is c_byte) +- self.assertTrue(c_byte.__ctype_be__ is c_byte) ++ self.assertIs(c_byte.__ctype_le__, c_byte) ++ self.assertIs(c_byte.__ctype_be__, c_byte) + +- self.assertTrue(c_ubyte.__ctype_le__ is c_ubyte) +- self.assertTrue(c_ubyte.__ctype_be__ is c_ubyte) ++ self.assertIs(c_ubyte.__ctype_le__, c_ubyte) ++ self.assertIs(c_ubyte.__ctype_be__, c_ubyte) + +- self.assertTrue(c_char.__ctype_le__ is c_char) +- self.assertTrue(c_char.__ctype_be__ is c_char) ++ self.assertIs(c_char.__ctype_le__, c_char) ++ self.assertIs(c_char.__ctype_be__, c_char) + + def test_struct_fields_1(self): + if sys.byteorder == "little": +diff -r 3a1db0d2747e Lib/ctypes/test/test_cast.py +--- a/Lib/ctypes/test/test_cast.py ++++ b/Lib/ctypes/test/test_cast.py +@@ -38,14 +38,14 @@ + + p = cast(array, POINTER(c_char_p)) + # array and p share a common _objects attribute +- self.assertTrue(p._objects is array._objects) ++ self.assertIs(p._objects, array._objects) + self.assertEqual(array._objects, {'0': "foo bar", id(array): array}) + p[0] = "spam spam" + self.assertEqual(p._objects, {'0': "spam spam", id(array): array}) +- self.assertTrue(array._objects is p._objects) ++ self.assertIs(array._objects, p._objects) + p[1] = "foo bar" + self.assertEqual(p._objects, {'1': 'foo bar', '0': "spam spam", id(array): array}) +- self.assertTrue(array._objects is p._objects) ++ self.assertIs(array._objects, p._objects) + + def test_other(self): + p = cast((c_int * 4)(1, 2, 3, 4), POINTER(c_int)) +diff -r 3a1db0d2747e Lib/ctypes/test/test_frombuffer.py +--- a/Lib/ctypes/test/test_frombuffer.py ++++ b/Lib/ctypes/test/test_frombuffer.py +@@ -23,7 +23,7 @@ + a[0], a[-1] = 200, -200 + self.assertEqual(x[:], a.tolist()) + +- self.assertTrue(a in x._objects.values()) ++ self.assertIn(a, x._objects.values()) + + self.assertRaises(ValueError, + c_int.from_buffer, a, -1) +diff -r 3a1db0d2747e Lib/ctypes/test/test_funcptr.py +--- a/Lib/ctypes/test/test_funcptr.py ++++ b/Lib/ctypes/test/test_funcptr.py +@@ -75,7 +75,7 @@ + ## "lpfnWndProc", WNDPROC_2(wndproc)) + # instead: + +- self.assertTrue(WNDPROC is WNDPROC_2) ++ self.assertIs(WNDPROC, WNDPROC_2) + # 'wndclass.lpfnWndProc' leaks 94 references. Why? + self.assertEqual(wndclass.lpfnWndProc(1, 2, 3, 4), 10) + +diff -r 3a1db0d2747e Lib/ctypes/test/test_functions.py +--- a/Lib/ctypes/test/test_functions.py ++++ b/Lib/ctypes/test/test_functions.py +@@ -306,7 +306,7 @@ + f.argtypes = [c_longlong, MyCallback] + + def callback(value): +- self.assertTrue(isinstance(value, (int, long))) ++ self.assertIsInstance(value, (int, long)) + return value & 0x7FFFFFFF + + cb = MyCallback(callback) +diff -r 3a1db0d2747e Lib/ctypes/test/test_loading.py +--- a/Lib/ctypes/test/test_loading.py ++++ b/Lib/ctypes/test/test_loading.py +@@ -43,7 +43,7 @@ + + if os.name in ("nt", "ce"): + def test_load_library(self): +- self.assertFalse(libc_name is None) ++ self.assertIsNotNone(libc_name) + if is_resource_enabled("printing"): + print find_library("kernel32") + print find_library("user32") +diff -r 3a1db0d2747e Lib/ctypes/test/test_numbers.py +--- a/Lib/ctypes/test/test_numbers.py ++++ b/Lib/ctypes/test/test_numbers.py +@@ -181,10 +181,10 @@ + a = array(t._type_, [3.14]) + v = t.from_address(a.buffer_info()[0]) + self.assertEqual(v.value, a[0]) +- self.assertTrue(type(v) is t) ++ self.assertIs(type(v), t) + a[0] = 2.3456e17 + self.assertEqual(v.value, a[0]) +- self.assertTrue(type(v) is t) ++ self.assertIs(type(v), t) + + def test_char_from_address(self): + from ctypes import c_char +@@ -193,7 +193,7 @@ + a = array('c', 'x') + v = c_char.from_address(a.buffer_info()[0]) + self.assertEqual(v.value, a[0]) +- self.assertTrue(type(v) is c_char) ++ self.assertIs(type(v), c_char) + + a[0] = '?' + self.assertEqual(v.value, a[0]) +diff -r 3a1db0d2747e Lib/ctypes/test/test_parameters.py +--- a/Lib/ctypes/test/test_parameters.py ++++ b/Lib/ctypes/test/test_parameters.py +@@ -55,7 +55,7 @@ + # c_char_p.from_param on a Python String packs the string + # into a cparam object + s = "123" +- self.assertTrue(c_char_p.from_param(s)._obj is s) ++ self.assertIs(c_char_p.from_param(s)._obj, s) + + # new in 0.9.1: convert (encode) unicode to ascii + self.assertEqual(c_char_p.from_param(u"123")._obj, "123") +@@ -66,7 +66,7 @@ + # calling c_char_p.from_param with a c_char_p instance + # returns the argument itself: + a = c_char_p("123") +- self.assertTrue(c_char_p.from_param(a) is a) ++ self.assertIs(c_char_p.from_param(a), a) + + def test_cw_strings(self): + from ctypes import byref +diff -r 3a1db0d2747e Lib/ctypes/test/test_pointers.py +--- a/Lib/ctypes/test/test_pointers.py ++++ b/Lib/ctypes/test/test_pointers.py +@@ -78,7 +78,7 @@ + + ## i = c_int(42) + ## callback(byref(i)) +-## self.assertTrue(i.value == 84) ++## self.assertEqual(i.value, 84) + + doit(callback) + ## print self.result +@@ -91,11 +91,11 @@ + i = ct(42) + p = pointer(i) + ## print type(p.contents), ct +- self.assertTrue(type(p.contents) is ct) ++ self.assertIs(type(p.contents), ct) + # p.contents is the same as p[0] + ## print p.contents +-## self.assertTrue(p.contents == 42) +-## self.assertTrue(p[0] == 42) ++## self.assertEqual(p.contents, 42) ++## self.assertEqual(p[0], 42) + + self.assertRaises(TypeError, delitem, p, 0) + +diff -r 3a1db0d2747e Lib/ctypes/test/test_python_api.py +--- a/Lib/ctypes/test/test_python_api.py ++++ b/Lib/ctypes/test/test_python_api.py +@@ -61,7 +61,7 @@ + ref = grc(s) + # id(python-object) is the address + pyobj = PyObj_FromPtr(id(s)) +- self.assertTrue(s is pyobj) ++ self.assertIs(s, pyobj) + + self.assertEqual(grc(s), ref + 1) + del pyobj +diff -r 3a1db0d2747e Lib/ctypes/test/test_refcounts.py +--- a/Lib/ctypes/test/test_refcounts.py ++++ b/Lib/ctypes/test/test_refcounts.py +@@ -24,7 +24,7 @@ + self.assertEqual(grc(callback), 2) + cb = MyCallback(callback) + +- self.assertTrue(grc(callback) > 2) ++ self.assertGreater(grc(callback), 2) + result = f(-10, cb) + self.assertEqual(result, -18) + cb = None +@@ -43,15 +43,15 @@ + + # the CFuncPtr instance holds at least one refcount on func: + f = OtherCallback(func) +- self.assertTrue(grc(func) > 2) ++ self.assertGreater(grc(func), 2) + + # and may release it again + del f +- self.assertTrue(grc(func) >= 2) ++ self.assertGreaterEqual(grc(func), 2) + + # but now it must be gone + gc.collect() +- self.assertTrue(grc(func) == 2) ++ self.assertEqual(grc(func), 2) + + class X(ctypes.Structure): + _fields_ = [("a", OtherCallback)] +@@ -59,11 +59,11 @@ + x.a = OtherCallback(func) + + # the CFuncPtr instance holds at least one refcount on func: +- self.assertTrue(grc(func) > 2) ++ self.assertGreater(grc(func), 2) + + # and may release it again + del x +- self.assertTrue(grc(func) >= 2) ++ self.assertGreaterEqual(grc(func), 2) + + # and now it must be gone again + gc.collect() +@@ -72,7 +72,7 @@ + f = OtherCallback(func) + + # the CFuncPtr instance holds at least one refcount on func: +- self.assertTrue(grc(func) > 2) ++ self.assertGreater(grc(func), 2) + + # create a cycle + f.cycle = f +diff -r 3a1db0d2747e Lib/ctypes/test/test_strings.py +--- a/Lib/ctypes/test/test_strings.py ++++ b/Lib/ctypes/test/test_strings.py +@@ -115,24 +115,24 @@ + + # New in releases later than 0.4.0: + # c_string(number) returns an empty string of size number +- self.assertTrue(len(c_string(32).raw) == 32) ++ self.assertEqual(len(c_string(32).raw), 32) + self.assertRaises(ValueError, c_string, -1) + self.assertRaises(ValueError, c_string, 0) + + # These tests fail, because it is no longer initialized +-## self.assertTrue(c_string(2).value == "") +-## self.assertTrue(c_string(2).raw == "\000\000") +- self.assertTrue(c_string(2).raw[-1] == "\000") +- self.assertTrue(len(c_string(2).raw) == 2) ++## self.assertEqual(c_string(2).value, "") ++## self.assertEqual(c_string(2).raw, "\000\000") ++ self.assertEqual(c_string(2).raw[-1], "\000") ++ self.assertEqual(len(c_string(2).raw), 2) + + def XX_test_initialized_strings(self): + +- self.assertTrue(c_string("ab", 4).raw[:2] == "ab") +- self.assertTrue(c_string("ab", 4).raw[:2:] == "ab") +- self.assertTrue(c_string("ab", 4).raw[:2:-1] == "ba") +- self.assertTrue(c_string("ab", 4).raw[:2:2] == "a") +- self.assertTrue(c_string("ab", 4).raw[-1] == "\000") +- self.assertTrue(c_string("ab", 2).raw == "a\000") ++ self.assertEqual(c_string("ab", 4).raw[:2], "ab") ++ self.assertEqual(c_string("ab", 4).raw[:2:], "ab") ++ self.assertEqual(c_string("ab", 4).raw[:2:-1], "ba") ++ self.assertEqual(c_string("ab", 4).raw[:2:2], "a") ++ self.assertEqual(c_string("ab", 4).raw[-1], "\000") ++ self.assertEqual(c_string("ab", 2).raw, "a\000") + + def XX_test_toolong(self): + cs = c_string("abcdef") +@@ -163,22 +163,22 @@ + # XXX This behaviour is about to change: + # len returns the size of the internal buffer in bytes. + # This includes the terminating NUL character. +- self.assertTrue(sizeof(cs) == 14) ++ self.assertEqual(sizeof(cs), 14) + + # The value property is the string up to the first terminating NUL. +- self.assertTrue(cs.value == u"abcdef") +- self.assertTrue(c_wstring(u"abc\000def").value == u"abc") ++ self.assertEqual(cs.value, u"abcdef") ++ self.assertEqual(c_wstring(u"abc\000def").value, u"abc") + +- self.assertTrue(c_wstring(u"abc\000def").value == u"abc") ++ self.assertEqual(c_wstring(u"abc\000def").value, u"abc") + + # The raw property is the total buffer contents: +- self.assertTrue(cs.raw == u"abcdef\000") +- self.assertTrue(c_wstring(u"abc\000def").raw == u"abc\000def\000") ++ self.assertEqual(cs.raw, u"abcdef\000") ++ self.assertEqual(c_wstring(u"abc\000def").raw, u"abc\000def\000") + + # We can change the value: + cs.value = u"ab" +- self.assertTrue(cs.value == u"ab") +- self.assertTrue(cs.raw == u"ab\000\000\000\000\000") ++ self.assertEqual(cs.value, u"ab") ++ self.assertEqual(cs.raw, u"ab\000\000\000\000\000") + + self.assertRaises(TypeError, c_wstring, "123") + self.assertRaises(ValueError, c_wstring, 0) +diff -r 3a1db0d2747e Lib/ctypes/test/test_structures.py +--- a/Lib/ctypes/test/test_structures.py ++++ b/Lib/ctypes/test/test_structures.py +@@ -83,7 +83,7 @@ + class Y(Structure): + _fields_ = [("x", c_char * 3), + ("y", c_int)] +- self.assertEqual(alignment(Y), calcsize("i")) ++ self.assertEqual(alignment(Y), alignment(c_int)) + self.assertEqual(sizeof(Y), calcsize("3si")) + + class SI(Structure): +@@ -175,13 +175,6 @@ + self.assertEqual(sizeof(X), 10) + self.assertEqual(X.b.offset, 2) + +- class X(Structure): +- _fields_ = [("a", c_byte), +- ("b", c_longlong)] +- _pack_ = 4 +- self.assertEqual(sizeof(X), 12) +- self.assertEqual(X.b.offset, 4) +- + import struct + longlong_size = struct.calcsize("q") + longlong_align = struct.calcsize("bq") - longlong_size +@@ -189,9 +182,16 @@ + class X(Structure): + _fields_ = [("a", c_byte), + ("b", c_longlong)] ++ _pack_ = 4 ++ self.assertEqual(sizeof(X), min(4, longlong_align) + longlong_size) ++ self.assertEqual(X.b.offset, min(4, longlong_align)) ++ ++ class X(Structure): ++ _fields_ = [("a", c_byte), ++ ("b", c_longlong)] + _pack_ = 8 + +- self.assertEqual(sizeof(X), longlong_align + longlong_size) ++ self.assertEqual(sizeof(X), min(8, longlong_align) + longlong_size) + self.assertEqual(X.b.offset, min(8, longlong_align)) + + +@@ -380,9 +380,9 @@ + ## class X(Structure): + ## _fields_ = [] + +- self.assertTrue("in_dll" in dir(type(Structure))) +- self.assertTrue("from_address" in dir(type(Structure))) +- self.assertTrue("in_dll" in dir(type(Structure))) ++ self.assertIn("in_dll", dir(type(Structure))) ++ self.assertIn("from_address", dir(type(Structure))) ++ self.assertIn("in_dll", dir(type(Structure))) + + def test_positional_args(self): + # see also http://bugs.python.org/issue5042 +@@ -452,8 +452,8 @@ + try: + Recursive._fields_ = [("next", Recursive)] + except AttributeError, details: +- self.assertTrue("Structure or union cannot contain itself" in +- str(details)) ++ self.assertIn("Structure or union cannot contain itself", ++ str(details)) + else: + self.fail("Structure or union cannot contain itself") + +@@ -469,8 +469,7 @@ + try: + Second._fields_ = [("first", First)] + except AttributeError, details: +- self.assertTrue("_fields_ is final" in +- str(details)) ++ self.assertIn("_fields_ is final", str(details)) + else: + self.fail("AttributeError not raised") + +diff -r 3a1db0d2747e Lib/difflib.py +--- a/Lib/difflib.py ++++ b/Lib/difflib.py +@@ -1,5 +1,3 @@ +-#! /usr/bin/env python +- + """ + Module difflib -- helpers for computing deltas between objects. + +diff -r 3a1db0d2747e Lib/distutils/command/bdist_rpm.py +--- a/Lib/distutils/command/bdist_rpm.py ++++ b/Lib/distutils/command/bdist_rpm.py +@@ -12,6 +12,7 @@ + from distutils.core import Command + from distutils.debug import DEBUG + from distutils.file_util import write_file ++from distutils.sysconfig import get_python_version + from distutils.errors import (DistutilsOptionError, DistutilsPlatformError, + DistutilsFileError, DistutilsExecError) + from distutils import log +diff -r 3a1db0d2747e Lib/distutils/command/build_py.py +--- a/Lib/distutils/command/build_py.py ++++ b/Lib/distutils/command/build_py.py +@@ -128,7 +128,8 @@ + # Each pattern has to be converted to a platform-specific path + filelist = glob(os.path.join(src_dir, convert_path(pattern))) + # Files that match more than one pattern are only added once +- files.extend([fn for fn in filelist if fn not in files]) ++ files.extend([fn for fn in filelist if fn not in files ++ and os.path.isfile(fn)]) + return files + + def build_package_data(self): +diff -r 3a1db0d2747e Lib/distutils/command/upload.py +--- a/Lib/distutils/command/upload.py ++++ b/Lib/distutils/command/upload.py +@@ -177,7 +177,7 @@ + status = result.getcode() + reason = result.msg + if self.show_response: +- msg = '\n'.join(('-' * 75, r.read(), '-' * 75)) ++ msg = '\n'.join(('-' * 75, result.read(), '-' * 75)) + self.announce(msg, log.INFO) + except socket.error, e: + self.announce(str(e), log.ERROR) +diff -r 3a1db0d2747e Lib/distutils/config.py +--- a/Lib/distutils/config.py ++++ b/Lib/distutils/config.py +@@ -21,7 +21,7 @@ + class PyPIRCCommand(Command): + """Base command that knows how to handle the .pypirc file + """ +- DEFAULT_REPOSITORY = 'http://pypi.python.org/pypi' ++ DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi' + DEFAULT_REALM = 'pypi' + repository = None + realm = None +diff -r 3a1db0d2747e Lib/distutils/core.py +--- a/Lib/distutils/core.py ++++ b/Lib/distutils/core.py +@@ -14,7 +14,6 @@ + from distutils.debug import DEBUG + from distutils.errors import (DistutilsSetupError, DistutilsArgError, + DistutilsError, CCompilerError) +-from distutils.util import grok_environment_error + + # Mainly import these so setup scripts can "from distutils.core import" them. + from distutils.dist import Distribution +@@ -153,13 +152,11 @@ + except KeyboardInterrupt: + raise SystemExit, "interrupted" + except (IOError, os.error), exc: +- error = grok_environment_error(exc) +- + if DEBUG: +- sys.stderr.write(error + "\n") ++ sys.stderr.write("error: %s\n" % (exc,)) + raise + else: +- raise SystemExit, error ++ raise SystemExit, "error: %s" % (exc,) + + except (DistutilsError, + CCompilerError), msg: +diff -r 3a1db0d2747e Lib/distutils/dir_util.py +--- a/Lib/distutils/dir_util.py ++++ b/Lib/distutils/dir_util.py +@@ -185,7 +185,6 @@ + Any errors are ignored (apart from being reported to stdout if 'verbose' + is true). + """ +- from distutils.util import grok_environment_error + global _path_created + + if verbose >= 1: +@@ -202,8 +201,7 @@ + if abspath in _path_created: + del _path_created[abspath] + except (IOError, OSError), exc: +- log.warn(grok_environment_error( +- exc, "error removing %s: " % directory)) ++ log.warn("error removing %s: %s", directory, exc) + + def ensure_relative(path): + """Take the full path 'path', and make it a relative path. +diff -r 3a1db0d2747e Lib/distutils/spawn.py +--- a/Lib/distutils/spawn.py ++++ b/Lib/distutils/spawn.py +@@ -12,6 +12,7 @@ + import os + + from distutils.errors import DistutilsPlatformError, DistutilsExecError ++from distutils.debug import DEBUG + from distutils import log + + def spawn(cmd, search_path=1, verbose=0, dry_run=0): +@@ -30,6 +31,9 @@ + Raise DistutilsExecError if running the program fails in any way; just + return on success. + """ ++ # cmd is documented as a list, but just in case some code passes a tuple ++ # in, protect our %-formatting code against horrible death ++ cmd = list(cmd) + if os.name == 'posix': + _spawn_posix(cmd, search_path, dry_run=dry_run) + elif os.name == 'nt': +@@ -69,12 +73,16 @@ + rc = os.spawnv(os.P_WAIT, executable, cmd) + except OSError, exc: + # this seems to happen when the command isn't found ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "command '%s' failed: %s" % (cmd[0], exc[-1]) ++ "command %r failed: %s" % (cmd, exc[-1]) + if rc != 0: + # and this reflects the command running but failing ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "command '%s' failed with exit status %d" % (cmd[0], rc) ++ "command %r failed with exit status %d" % (cmd, rc) + + def _spawn_os2(cmd, search_path=1, verbose=0, dry_run=0): + executable = cmd[0] +@@ -88,13 +96,17 @@ + rc = os.spawnv(os.P_WAIT, executable, cmd) + except OSError, exc: + # this seems to happen when the command isn't found ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "command '%s' failed: %s" % (cmd[0], exc[-1]) ++ "command %r failed: %s" % (cmd, exc[-1]) + if rc != 0: + # and this reflects the command running but failing +- log.debug("command '%s' failed with exit status %d" % (cmd[0], rc)) ++ if not DEBUG: ++ cmd = executable ++ log.debug("command %r failed with exit status %d" % (cmd, rc)) + raise DistutilsExecError, \ +- "command '%s' failed with exit status %d" % (cmd[0], rc) ++ "command %r failed with exit status %d" % (cmd, rc) + + if sys.platform == 'darwin': + from distutils import sysconfig +@@ -105,8 +117,9 @@ + log.info(' '.join(cmd)) + if dry_run: + return ++ executable = cmd[0] + exec_fn = search_path and os.execvp or os.execv +- exec_args = [cmd[0], cmd] ++ env = None + if sys.platform == 'darwin': + global _cfg_target, _cfg_target_split + if _cfg_target is None: +@@ -127,18 +140,24 @@ + env = dict(os.environ, + MACOSX_DEPLOYMENT_TARGET=cur_target) + exec_fn = search_path and os.execvpe or os.execve +- exec_args.append(env) + pid = os.fork() + + if pid == 0: # in the child + try: +- exec_fn(*exec_args) ++ if env is None: ++ exec_fn(executable, cmd) ++ else: ++ exec_fn(executable, cmd, env) + except OSError, e: +- sys.stderr.write("unable to execute %s: %s\n" % +- (cmd[0], e.strerror)) ++ if not DEBUG: ++ cmd = executable ++ sys.stderr.write("unable to execute %r: %s\n" % ++ (cmd, e.strerror)) + os._exit(1) + +- sys.stderr.write("unable to execute %s for unknown reasons" % cmd[0]) ++ if not DEBUG: ++ cmd = executable ++ sys.stderr.write("unable to execute %r for unknown reasons" % cmd) + os._exit(1) + else: # in the parent + # Loop until the child either exits or is terminated by a signal +@@ -150,29 +169,37 @@ + import errno + if exc.errno == errno.EINTR: + continue ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "command '%s' failed: %s" % (cmd[0], exc[-1]) ++ "command %r failed: %s" % (cmd, exc[-1]) + if os.WIFSIGNALED(status): ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "command '%s' terminated by signal %d" % \ +- (cmd[0], os.WTERMSIG(status)) ++ "command %r terminated by signal %d" % \ ++ (cmd, os.WTERMSIG(status)) + + elif os.WIFEXITED(status): + exit_status = os.WEXITSTATUS(status) + if exit_status == 0: + return # hey, it succeeded! + else: ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "command '%s' failed with exit status %d" % \ +- (cmd[0], exit_status) ++ "command %r failed with exit status %d" % \ ++ (cmd, exit_status) + + elif os.WIFSTOPPED(status): + continue + + else: ++ if not DEBUG: ++ cmd = executable + raise DistutilsExecError, \ +- "unknown error executing '%s': termination status %d" % \ +- (cmd[0], status) ++ "unknown error executing %r: termination status %d" % \ ++ (cmd, status) + + def find_executable(executable, path=None): + """Tries to find 'executable' in the directories listed in 'path'. +diff -r 3a1db0d2747e Lib/distutils/tests/test_archive_util.py +--- a/Lib/distutils/tests/test_archive_util.py ++++ b/Lib/distutils/tests/test_archive_util.py +@@ -199,7 +199,7 @@ + dry_run=True) + finally: + os.chdir(old_dir) +- self.assertTrue(not os.path.exists(tarball)) ++ self.assertFalse(os.path.exists(tarball)) + self.assertEqual(len(w.warnings), 1) + + @unittest.skipUnless(zlib, "Requires zlib") +diff -r 3a1db0d2747e Lib/distutils/tests/test_bdist_rpm.py +--- a/Lib/distutils/tests/test_bdist_rpm.py ++++ b/Lib/distutils/tests/test_bdist_rpm.py +@@ -39,18 +39,15 @@ + sys.argv[:] = self.old_sys_argv[1] + super(BuildRpmTestCase, self).tearDown() + ++ # XXX I am unable yet to make this test work without ++ # spurious sdtout/stderr output under Mac OS X ++ @unittest.skipUnless(sys.platform.startswith('linux'), ++ 'spurious sdtout/stderr output under Mac OS X') ++ @unittest.skipIf(find_executable('rpm') is None, ++ 'the rpm command is not found') ++ @unittest.skipIf(find_executable('rpmbuild') is None, ++ 'the rpmbuild command is not found') + def test_quiet(self): +- +- # XXX I am unable yet to make this test work without +- # spurious sdtout/stderr output under Mac OS X +- if sys.platform != 'linux2': +- return +- +- # this test will run only if the rpm commands are found +- if (find_executable('rpm') is None or +- find_executable('rpmbuild') is None): +- return +- + # let's create a package + tmp_dir = self.mkdtemp() + pkg_dir = os.path.join(tmp_dir, 'foo') +@@ -77,25 +74,22 @@ + cmd.run() + + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) +- self.assertTrue('foo-0.1-1.noarch.rpm' in dist_created) ++ self.assertIn('foo-0.1-1.noarch.rpm', dist_created) + + # bug #2945: upload ignores bdist_rpm files + self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files) + self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files) + ++ # XXX I am unable yet to make this test work without ++ # spurious sdtout/stderr output under Mac OS X ++ @unittest.skipUnless(sys.platform.startswith('linux'), ++ 'spurious sdtout/stderr output under Mac OS X') ++ # http://bugs.python.org/issue1533164 ++ @unittest.skipIf(find_executable('rpm') is None, ++ 'the rpm command is not found') ++ @unittest.skipIf(find_executable('rpmbuild') is None, ++ 'the rpmbuild command is not found') + def test_no_optimize_flag(self): +- +- # XXX I am unable yet to make this test work without +- # spurious sdtout/stderr output under Mac OS X +- if sys.platform != 'linux2': +- return +- +- # http://bugs.python.org/issue1533164 +- # this test will run only if the rpm command is found +- if (find_executable('rpm') is None or +- find_executable('rpmbuild') is None): +- return +- + # let's create a package that brakes bdist_rpm + tmp_dir = self.mkdtemp() + pkg_dir = os.path.join(tmp_dir, 'foo') +@@ -121,7 +115,7 @@ + cmd.run() + + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) +- self.assertTrue('foo-0.1-1.noarch.rpm' in dist_created) ++ self.assertIn('foo-0.1-1.noarch.rpm', dist_created) + + # bug #2945: upload ignores bdist_rpm files + self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files) +diff -r 3a1db0d2747e Lib/distutils/tests/test_bdist_wininst.py +--- a/Lib/distutils/tests/test_bdist_wininst.py ++++ b/Lib/distutils/tests/test_bdist_wininst.py +@@ -23,7 +23,7 @@ + # and make sure it finds it and returns its content + # no matter what platform we have + exe_file = cmd.get_exe_bytes() +- self.assertTrue(len(exe_file) > 10) ++ self.assertGreater(len(exe_file), 10) + + def test_suite(): + return unittest.makeSuite(BuildWinInstTestCase) +diff -r 3a1db0d2747e Lib/distutils/tests/test_build_clib.py +--- a/Lib/distutils/tests/test_build_clib.py ++++ b/Lib/distutils/tests/test_build_clib.py +@@ -102,11 +102,8 @@ + cmd.distribution.libraries = 'WONTWORK' + self.assertRaises(DistutilsSetupError, cmd.finalize_options) + ++ @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") + def test_run(self): +- # can't test on windows +- if sys.platform == 'win32': +- return +- + pkg_dir, dist = self.create_dist() + cmd = build_clib(dist) + +@@ -131,13 +128,13 @@ + if ccmd is None: + continue + if find_executable(ccmd[0]) is None: +- return # can't test ++ self.skipTest('The %r command is not found' % ccmd[0]) + + # this should work + cmd.run() + + # let's check the result +- self.assertTrue('libfoo.a' in os.listdir(build_temp)) ++ self.assertIn('libfoo.a', os.listdir(build_temp)) + + def test_suite(): + return unittest.makeSuite(BuildCLibTestCase) +diff -r 3a1db0d2747e Lib/distutils/tests/test_build_ext.py +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -65,9 +65,9 @@ + sys.stdout = old_stdout + + if ALREADY_TESTED: +- return ++ self.skipTest('Already tested in %s' % ALREADY_TESTED) + else: +- ALREADY_TESTED = True ++ ALREADY_TESTED = type(self).__name__ + + import xx + +@@ -80,8 +80,8 @@ + if test_support.HAVE_DOCSTRINGS: + doc = 'This is a template module just for instruction.' + self.assertEqual(xx.__doc__, doc) +- self.assertTrue(isinstance(xx.Null(), xx.Null)) +- self.assertTrue(isinstance(xx.Str(), xx.Str)) ++ self.assertIsInstance(xx.Null(), xx.Null) ++ self.assertIsInstance(xx.Str(), xx.Str) + + def test_solaris_enable_shared(self): + dist = Distribution({'name': 'xx'}) +@@ -102,13 +102,11 @@ + _config_vars['Py_ENABLE_SHARED'] = old_var + + # make sure we get some library dirs under solaris +- self.assertTrue(len(cmd.library_dirs) > 0) ++ self.assertGreater(len(cmd.library_dirs), 0) + ++ @unittest.skipIf(sys.version < '2.6', ++ 'site.USER_SITE was introduced in 2.6') + def test_user_site(self): +- # site.USER_SITE was introduced in 2.6 +- if sys.version < '2.6': +- return +- + import site + dist = Distribution({'name': 'xx'}) + cmd = build_ext(dist) +@@ -143,10 +141,10 @@ + cmd.finalize_options() + + py_include = sysconfig.get_python_inc() +- self.assertTrue(py_include in cmd.include_dirs) ++ self.assertIn(py_include, cmd.include_dirs) + + plat_py_include = sysconfig.get_python_inc(plat_specific=1) +- self.assertTrue(plat_py_include in cmd.include_dirs) ++ self.assertIn(plat_py_include, cmd.include_dirs) + + # make sure cmd.libraries is turned into a list + # if it's a string +@@ -226,13 +224,13 @@ + 'some': 'bar'})] + cmd.check_extensions_list(exts) + ext = exts[0] +- self.assertTrue(isinstance(ext, Extension)) ++ self.assertIsInstance(ext, Extension) + + # check_extensions_list adds in ext the values passed + # when they are in ('include_dirs', 'library_dirs', 'libraries' + # 'extra_objects', 'extra_compile_args', 'extra_link_args') + self.assertEqual(ext.libraries, 'foo') +- self.assertTrue(not hasattr(ext, 'some')) ++ self.assertFalse(hasattr(ext, 'some')) + + # 'macros' element of build info dict must be 1- or 2-tuple + exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', +@@ -414,9 +412,8 @@ + wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext) + self.assertEqual(ext_path, wanted) + ++ @unittest.skipUnless(sys.platform == 'win32', 'these tests require Windows') + def test_build_ext_path_cross_platform(self): +- if sys.platform != 'win32': +- return + dist = Distribution({'name': 'UpdateManager'}) + cmd = build_ext(dist) + cmd.ensure_finalized() +diff -r 3a1db0d2747e Lib/distutils/tests/test_build_py.py +--- a/Lib/distutils/tests/test_build_py.py ++++ b/Lib/distutils/tests/test_build_py.py +@@ -99,6 +99,37 @@ + os.chdir(cwd) + sys.stdout = old_stdout + ++ def test_dir_in_package_data(self): ++ """ ++ A directory in package_data should not be added to the filelist. ++ """ ++ # See bug 19286 ++ sources = self.mkdtemp() ++ pkg_dir = os.path.join(sources, "pkg") ++ ++ os.mkdir(pkg_dir) ++ open(os.path.join(pkg_dir, "__init__.py"), "w").close() ++ ++ docdir = os.path.join(pkg_dir, "doc") ++ os.mkdir(docdir) ++ open(os.path.join(docdir, "testfile"), "w").close() ++ ++ # create the directory that could be incorrectly detected as a file ++ os.mkdir(os.path.join(docdir, 'otherdir')) ++ ++ os.chdir(sources) ++ dist = Distribution({"packages": ["pkg"], ++ "package_data": {"pkg": ["doc/*"]}}) ++ # script_name need not exist, it just need to be initialized ++ dist.script_name = os.path.join(sources, "setup.py") ++ dist.script_args = ["build"] ++ dist.parse_command_line() ++ ++ try: ++ dist.run_commands() ++ except DistutilsFileError: ++ self.fail("failed package_data when data dir includes a dir") ++ + def test_dont_write_bytecode(self): + # makes sure byte_compile is not used + pkg_dir, dist = self.create_dist() +diff -r 3a1db0d2747e Lib/distutils/tests/test_build_scripts.py +--- a/Lib/distutils/tests/test_build_scripts.py ++++ b/Lib/distutils/tests/test_build_scripts.py +@@ -17,8 +17,8 @@ + + def test_default_settings(self): + cmd = self.get_build_scripts_cmd("/foo/bar", []) +- self.assertTrue(not cmd.force) +- self.assertTrue(cmd.build_dir is None) ++ self.assertFalse(cmd.force) ++ self.assertIsNone(cmd.build_dir) + + cmd.finalize_options() + +@@ -38,7 +38,7 @@ + + built = os.listdir(target) + for name in expected: +- self.assertTrue(name in built) ++ self.assertIn(name, built) + + def get_build_scripts_cmd(self, target, scripts): + import sys +@@ -103,7 +103,7 @@ + + built = os.listdir(target) + for name in expected: +- self.assertTrue(name in built) ++ self.assertIn(name, built) + + def test_suite(): + return unittest.makeSuite(BuildScriptsTestCase) +diff -r 3a1db0d2747e Lib/distutils/tests/test_ccompiler.py +--- a/Lib/distutils/tests/test_ccompiler.py ++++ b/Lib/distutils/tests/test_ccompiler.py +@@ -55,12 +55,9 @@ + finally: + debug.DEBUG = False + ++ @unittest.skipUnless(get_default_compiler() == 'unix', ++ 'not testing if default compiler is not unix') + def test_customize_compiler(self): +- +- # not testing if default compiler is not unix +- if get_default_compiler() != 'unix': +- return +- + os.environ['AR'] = 'my_ar' + os.environ['ARFLAGS'] = '-arflags' + +diff -r 3a1db0d2747e Lib/distutils/tests/test_check.py +--- a/Lib/distutils/tests/test_check.py ++++ b/Lib/distutils/tests/test_check.py +@@ -56,9 +56,8 @@ + cmd = self._run(metadata) + self.assertEqual(cmd._warnings, 0) + ++ @unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils") + def test_check_document(self): +- if not HAS_DOCUTILS: # won't test without docutils +- return + pkg_info, dist = self.create_dist() + cmd = check(dist) + +@@ -72,9 +71,8 @@ + msgs = cmd._check_rst_data(rest) + self.assertEqual(len(msgs), 0) + ++ @unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils") + def test_check_restructuredtext(self): +- if not HAS_DOCUTILS: # won't test without docutils +- return + # let's see if it detects broken rest in long_description + broken_rest = 'title\n===\n\ntest' + pkg_info, dist = self.create_dist(long_description=broken_rest) +diff -r 3a1db0d2747e Lib/distutils/tests/test_clean.py +--- a/Lib/distutils/tests/test_clean.py ++++ b/Lib/distutils/tests/test_clean.py +@@ -36,7 +36,7 @@ + + # make sure the files where removed + for name, path in dirs: +- self.assertTrue(not os.path.exists(path), ++ self.assertFalse(os.path.exists(path), + '%s was not removed' % path) + + # let's run the command again (should spit warnings but succeed) +diff -r 3a1db0d2747e Lib/distutils/tests/test_config.py +--- a/Lib/distutils/tests/test_config.py ++++ b/Lib/distutils/tests/test_config.py +@@ -89,7 +89,7 @@ + config = config.items() + config.sort() + waited = [('password', 'secret'), ('realm', 'pypi'), +- ('repository', 'http://pypi.python.org/pypi'), ++ ('repository', 'https://pypi.python.org/pypi'), + ('server', 'server1'), ('username', 'me')] + self.assertEqual(config, waited) + +@@ -99,14 +99,14 @@ + config = config.items() + config.sort() + waited = [('password', 'secret'), ('realm', 'pypi'), +- ('repository', 'http://pypi.python.org/pypi'), ++ ('repository', 'https://pypi.python.org/pypi'), + ('server', 'server-login'), ('username', 'tarek')] + self.assertEqual(config, waited) + + def test_server_empty_registration(self): + cmd = self._cmd(self.dist) + rc = cmd._get_rc_file() +- self.assertTrue(not os.path.exists(rc)) ++ self.assertFalse(os.path.exists(rc)) + cmd._store_pypirc('tarek', 'xxx') + self.assertTrue(os.path.exists(rc)) + f = open(rc) +diff -r 3a1db0d2747e Lib/distutils/tests/test_config_cmd.py +--- a/Lib/distutils/tests/test_config_cmd.py ++++ b/Lib/distutils/tests/test_config_cmd.py +@@ -37,9 +37,8 @@ + dump_file(this_file, 'I am the header') + self.assertEqual(len(self._logs), numlines+1) + ++ @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") + def test_search_cpp(self): +- if sys.platform == 'win32': +- return + pkg_dir, dist = self.create_dist() + cmd = config(dist) + +@@ -81,7 +80,7 @@ + cmd._clean(f1, f2) + + for f in (f1, f2): +- self.assertTrue(not os.path.exists(f)) ++ self.assertFalse(os.path.exists(f)) + + def test_suite(): + return unittest.makeSuite(ConfigTestCase) +diff -r 3a1db0d2747e Lib/distutils/tests/test_install.py +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -65,11 +65,9 @@ + check_path(cmd.install_scripts, os.path.join(destination, "bin")) + check_path(cmd.install_data, destination) + ++ @unittest.skipIf(sys.version < '2.6', ++ 'site.USER_SITE was introduced in 2.6') + def test_user_site(self): +- # site.USER_SITE was introduced in 2.6 +- if sys.version < '2.6': +- return +- + # preparing the environment for the test + self.old_user_base = site.USER_BASE + self.old_user_site = site.USER_SITE +@@ -237,7 +235,7 @@ + self.test_record() + finally: + install_module.DEBUG = False +- self.assertTrue(len(self.logs) > old_logs_len) ++ self.assertGreater(len(self.logs), old_logs_len) + + + def test_suite(): +diff -r 3a1db0d2747e Lib/distutils/tests/test_install_lib.py +--- a/Lib/distutils/tests/test_install_lib.py ++++ b/Lib/distutils/tests/test_install_lib.py +@@ -65,7 +65,7 @@ + cmd.distribution.script_name = 'setup.py' + + # get_output should return 4 elements +- self.assertTrue(len(cmd.get_outputs()) >= 2) ++ self.assertGreaterEqual(len(cmd.get_outputs()), 2) + + def test_get_inputs(self): + pkg_dir, dist = self.create_dist() +@@ -98,7 +98,7 @@ + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + +- self.assertTrue('byte-compiling is disabled' in self.logs[0][1]) ++ self.assertIn('byte-compiling is disabled', self.logs[0][1]) + + def test_suite(): + return unittest.makeSuite(InstallLibTestCase) +diff -r 3a1db0d2747e Lib/distutils/tests/test_install_scripts.py +--- a/Lib/distutils/tests/test_install_scripts.py ++++ b/Lib/distutils/tests/test_install_scripts.py +@@ -24,10 +24,10 @@ + skip_build=1, + ) + cmd = install_scripts(dist) +- self.assertTrue(not cmd.force) +- self.assertTrue(not cmd.skip_build) +- self.assertTrue(cmd.build_dir is None) +- self.assertTrue(cmd.install_dir is None) ++ self.assertFalse(cmd.force) ++ self.assertFalse(cmd.skip_build) ++ self.assertIsNone(cmd.build_dir) ++ self.assertIsNone(cmd.install_dir) + + cmd.finalize_options() + +@@ -72,7 +72,7 @@ + + installed = os.listdir(target) + for name in expected: +- self.assertTrue(name in installed) ++ self.assertIn(name, installed) + + + def test_suite(): +diff -r 3a1db0d2747e Lib/distutils/tests/test_msvc9compiler.py +--- a/Lib/distutils/tests/test_msvc9compiler.py ++++ b/Lib/distutils/tests/test_msvc9compiler.py +@@ -128,7 +128,7 @@ + # windows registeries versions. + path = r'Control Panel\Desktop' + v = Reg.get_value(path, u'dragfullwindows') +- self.assertTrue(v in (u'0', u'1', u'2')) ++ self.assertIn(v, (u'0', u'1', u'2')) + + import _winreg + HKCU = _winreg.HKEY_CURRENT_USER +@@ -136,7 +136,7 @@ + self.assertEqual(keys, None) + + keys = Reg.read_keys(HKCU, r'Control Panel') +- self.assertTrue('Desktop' in keys) ++ self.assertIn('Desktop', keys) + + def test_remove_visual_c_ref(self): + from distutils.msvc9compiler import MSVCCompiler +@@ -174,7 +174,7 @@ + + compiler = MSVCCompiler() + got = compiler._remove_visual_c_ref(manifest) +- self.assertIs(got, None) ++ self.assertIsNone(got) + + + def test_suite(): +diff -r 3a1db0d2747e Lib/distutils/tests/test_register.py +--- a/Lib/distutils/tests/test_register.py ++++ b/Lib/distutils/tests/test_register.py +@@ -99,7 +99,7 @@ + cmd = self._get_cmd() + + # we shouldn't have a .pypirc file yet +- self.assertTrue(not os.path.exists(self.rc)) ++ self.assertFalse(os.path.exists(self.rc)) + + # patching raw_input and getpass.getpass + # so register gets happy +@@ -144,7 +144,7 @@ + req1 = dict(self.conn.reqs[0].headers) + req2 = dict(self.conn.reqs[1].headers) + self.assertEqual(req2['Content-length'], req1['Content-length']) +- self.assertTrue('xxx' in self.conn.reqs[1].data) ++ self.assertIn('xxx', self.conn.reqs[1].data) + + def test_password_not_in_file(self): + +@@ -174,7 +174,7 @@ + req = self.conn.reqs[0] + headers = dict(req.headers) + self.assertEqual(headers['Content-length'], '608') +- self.assertTrue('tarek' in req.data) ++ self.assertIn('tarek', req.data) + + def test_password_reset(self): + # this test runs choice 3 +@@ -192,7 +192,7 @@ + req = self.conn.reqs[0] + headers = dict(req.headers) + self.assertEqual(headers['Content-length'], '290') +- self.assertTrue('tarek' in req.data) ++ self.assertIn('tarek', req.data) + + @unittest.skipUnless(docutils is not None, 'needs docutils') + def test_strict(self): +diff -r 3a1db0d2747e Lib/distutils/tests/test_sdist.py +--- a/Lib/distutils/tests/test_sdist.py ++++ b/Lib/distutils/tests/test_sdist.py +@@ -134,12 +134,6 @@ + + @unittest.skipUnless(zlib, "requires zlib") + def test_make_distribution(self): +- +- # check if tar and gzip are installed +- if (find_executable('tar') is None or +- find_executable('gzip') is None): +- return +- + # now building a sdist + dist, cmd = self.get_cmd() + +@@ -325,13 +319,11 @@ + + @unittest.skipUnless(zlib, "requires zlib") + @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") ++ @unittest.skipIf(find_executable('tar') is None, ++ "The tar command is not found") ++ @unittest.skipIf(find_executable('gzip') is None, ++ "The gzip command is not found") + def test_make_distribution_owner_group(self): +- +- # check if tar and gzip are installed +- if (find_executable('tar') is None or +- find_executable('gzip') is None): +- return +- + # now building a sdist + dist, cmd = self.get_cmd() + +diff -r 3a1db0d2747e Lib/distutils/tests/test_sysconfig.py +--- a/Lib/distutils/tests/test_sysconfig.py ++++ b/Lib/distutils/tests/test_sysconfig.py +@@ -95,7 +95,7 @@ + + import sysconfig as global_sysconfig + if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'): +- return ++ self.skipTest('compiler flags customized') + self.assertEqual(global_sysconfig.get_config_var('LDSHARED'), sysconfig.get_config_var('LDSHARED')) + self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC')) + +diff -r 3a1db0d2747e Lib/distutils/tests/test_unixccompiler.py +--- a/Lib/distutils/tests/test_unixccompiler.py ++++ b/Lib/distutils/tests/test_unixccompiler.py +@@ -21,12 +21,8 @@ + sys.platform = self._backup_platform + sysconfig.get_config_var = self._backup_get_config_var + ++ @unittest.skipIf(sys.platform == 'win32', "can't test on Windows") + def test_runtime_libdir_option(self): +- +- # not tested under windows +- if sys.platform == 'win32': +- return +- + # Issue#5900 + # + # Ensure RUNPATH is added to extension modules with RPATH if +diff -r 3a1db0d2747e Lib/distutils/tests/test_upload.py +--- a/Lib/distutils/tests/test_upload.py ++++ b/Lib/distutils/tests/test_upload.py +@@ -78,7 +78,7 @@ + cmd.finalize_options() + for attr, waited in (('username', 'me'), ('password', 'secret'), + ('realm', 'pypi'), +- ('repository', 'http://pypi.python.org/pypi')): ++ ('repository', 'https://pypi.python.org/pypi')): + self.assertEqual(getattr(cmd, attr), waited) + + def test_saved_password(self): +@@ -119,10 +119,10 @@ + self.assertTrue(headers['Content-type'].startswith('multipart/form-data')) + self.assertEqual(self.last_open.req.get_method(), 'POST') + self.assertEqual(self.last_open.req.get_full_url(), +- 'http://pypi.python.org/pypi') +- self.assertTrue('xxx' in self.last_open.req.data) ++ 'https://pypi.python.org/pypi') ++ self.assertIn('xxx', self.last_open.req.data) + auth = self.last_open.req.headers['Authorization'] +- self.assertFalse('\n' in auth) ++ self.assertNotIn('\n', auth) + + def test_suite(): + return unittest.makeSuite(uploadTestCase) +diff -r 3a1db0d2747e Lib/distutils/tests/test_util.py +--- a/Lib/distutils/tests/test_util.py ++++ b/Lib/distutils/tests/test_util.py +@@ -3,8 +3,9 @@ + import unittest + from test.test_support import run_unittest + +-from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError +-from distutils.util import byte_compile ++from distutils.errors import DistutilsByteCompileError ++from distutils.util import byte_compile, grok_environment_error ++ + + class UtilTestCase(unittest.TestCase): + +@@ -18,6 +19,13 @@ + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + ++ def test_grok_environment_error(self): ++ # test obsolete function to ensure backward compat (#4931) ++ exc = IOError("Unable to find batch file") ++ msg = grok_environment_error(exc) ++ self.assertEqual(msg, "error: Unable to find batch file") ++ ++ + def test_suite(): + return unittest.makeSuite(UtilTestCase) + +diff -r 3a1db0d2747e Lib/distutils/util.py +--- a/Lib/distutils/util.py ++++ b/Lib/distutils/util.py +@@ -213,25 +213,10 @@ + + + def grok_environment_error (exc, prefix="error: "): +- """Generate a useful error message from an EnvironmentError (IOError or +- OSError) exception object. Handles Python 1.5.1 and 1.5.2 styles, and +- does what it can to deal with exception objects that don't have a +- filename (which happens when the error is due to a two-file operation, +- such as 'rename()' or 'link()'. Returns the error message as a string +- prefixed with 'prefix'. +- """ +- # check for Python 1.5.2-style {IO,OS}Error exception objects +- if hasattr(exc, 'filename') and hasattr(exc, 'strerror'): +- if exc.filename: +- error = prefix + "%s: %s" % (exc.filename, exc.strerror) +- else: +- # two-argument functions in posix module don't +- # include the filename in the exception object! +- error = prefix + "%s" % exc.strerror +- else: +- error = prefix + str(exc[-1]) +- +- return error ++ # Function kept for backward compatibility. ++ # Used to try clever things with EnvironmentErrors, ++ # but nowadays str(exception) produces good messages. ++ return prefix + str(exc) + + + # Needed by 'split_quoted()' +diff -r 3a1db0d2747e Lib/doctest.py +--- a/Lib/doctest.py ++++ b/Lib/doctest.py +@@ -326,6 +326,32 @@ + else: + return '#' + ++def _strip_exception_details(msg): ++ # Support for IGNORE_EXCEPTION_DETAIL. ++ # Get rid of everything except the exception name; in particular, drop ++ # the possibly dotted module path (if any) and the exception message (if ++ # any). We assume that a colon is never part of a dotted name, or of an ++ # exception name. ++ # E.g., given ++ # "foo.bar.MyError: la di da" ++ # return "MyError" ++ # Or for "abc.def" or "abc.def:\n" return "def". ++ ++ start, end = 0, len(msg) ++ # The exception name must appear on the first line. ++ i = msg.find("\n") ++ if i >= 0: ++ end = i ++ # retain up to the first colon (if any) ++ i = msg.find(':', 0, end) ++ if i >= 0: ++ end = i ++ # retain just the exception name ++ i = msg.rfind('.', 0, end) ++ if i >= 0: ++ start = i+1 ++ return msg[start: end] ++ + class _OutputRedirectingPdb(pdb.Pdb): + """ + A specialized version of the python debugger that redirects stdout +@@ -1323,10 +1349,9 @@ + + # Another chance if they didn't care about the detail. + elif self.optionflags & IGNORE_EXCEPTION_DETAIL: +- m1 = re.match(r'(?:[^:]*\.)?([^:]*:)', example.exc_msg) +- m2 = re.match(r'(?:[^:]*\.)?([^:]*:)', exc_msg) +- if m1 and m2 and check(m1.group(1), m2.group(1), +- self.optionflags): ++ if check(_strip_exception_details(example.exc_msg), ++ _strip_exception_details(exc_msg), ++ self.optionflags): + outcome = SUCCESS + + # Report the outcome. +diff -r 3a1db0d2747e Lib/email/generator.py +--- a/Lib/email/generator.py ++++ b/Lib/email/generator.py +@@ -231,9 +231,8 @@ + # body-part + self._fp.write(body_part) + # close-delimiter transport-padding +- self._fp.write('\n--' + boundary + '--') ++ self._fp.write('\n--' + boundary + '--' + NL) + if msg.epilogue is not None: +- print >> self._fp + if self._mangle_from_: + epilogue = fcre.sub('>From ', msg.epilogue) + else: +diff -r 3a1db0d2747e Lib/email/test/data/msg_02.txt +--- a/Lib/email/test/data/msg_02.txt ++++ b/Lib/email/test/data/msg_02.txt +@@ -119,6 +119,7 @@ + + + --__--__---- ++ + --192.168.1.2.889.32614.987812255.500.21814 + Content-type: text/plain; charset=us-ascii + Content-description: Digest Footer +diff -r 3a1db0d2747e Lib/email/test/test_email.py +--- a/Lib/email/test/test_email.py ++++ b/Lib/email/test/test_email.py +@@ -267,12 +267,12 @@ + msg['From'] = 'Me' + msg['to'] = 'You' + # Check for case insensitivity +- self.assertTrue('from' in msg) +- self.assertTrue('From' in msg) +- self.assertTrue('FROM' in msg) +- self.assertTrue('to' in msg) +- self.assertTrue('To' in msg) +- self.assertTrue('TO' in msg) ++ self.assertIn('from', msg) ++ self.assertIn('From', msg) ++ self.assertIn('FROM', msg) ++ self.assertIn('to', msg) ++ self.assertIn('To', msg) ++ self.assertIn('TO', msg) + + def test_as_string(self): + eq = self.assertEqual +@@ -1002,7 +1002,6 @@ + + def test_add_header(self): + eq = self.assertEqual +- unless = self.assertTrue + self._au.add_header('Content-Disposition', 'attachment', + filename='audiotest.au') + eq(self._au['content-disposition'], +@@ -1013,12 +1012,12 @@ + 'audiotest.au') + missing = [] + eq(self._au.get_param('attachment', header='content-disposition'), '') +- unless(self._au.get_param('foo', failobj=missing, +- header='content-disposition') is missing) ++ self.assertIs(self._au.get_param('foo', failobj=missing, ++ header='content-disposition'), missing) + # Try some missing stuff +- unless(self._au.get_param('foobar', missing) is missing) +- unless(self._au.get_param('attachment', missing, +- header='foobar') is missing) ++ self.assertIs(self._au.get_param('foobar', missing), missing) ++ self.assertIs(self._au.get_param('attachment', missing, ++ header='foobar'), missing) + + + +@@ -1045,7 +1044,6 @@ + + def test_add_header(self): + eq = self.assertEqual +- unless = self.assertTrue + self._im.add_header('Content-Disposition', 'attachment', + filename='dingusfish.gif') + eq(self._im['content-disposition'], +@@ -1056,12 +1054,12 @@ + 'dingusfish.gif') + missing = [] + eq(self._im.get_param('attachment', header='content-disposition'), '') +- unless(self._im.get_param('foo', failobj=missing, +- header='content-disposition') is missing) ++ self.assertIs(self._im.get_param('foo', failobj=missing, ++ header='content-disposition'), missing) + # Try some missing stuff +- unless(self._im.get_param('foobar', missing) is missing) +- unless(self._im.get_param('attachment', missing, +- header='foobar') is missing) ++ self.assertIs(self._im.get_param('foobar', missing), missing) ++ self.assertIs(self._im.get_param('attachment', missing, ++ header='foobar'), missing) + + + +@@ -1072,17 +1070,16 @@ + + def test_types(self): + eq = self.assertEqual +- unless = self.assertTrue + eq(self._msg.get_content_type(), 'text/plain') + eq(self._msg.get_param('charset'), 'us-ascii') + missing = [] +- unless(self._msg.get_param('foobar', missing) is missing) +- unless(self._msg.get_param('charset', missing, header='foobar') +- is missing) ++ self.assertIs(self._msg.get_param('foobar', missing), missing) ++ self.assertIs(self._msg.get_param('charset', missing, header='foobar'), ++ missing) + + def test_payload(self): + self.assertEqual(self._msg.get_payload(), 'hello there') +- self.assertTrue(not self._msg.is_multipart()) ++ self.assertFalse(self._msg.is_multipart()) + + def test_charset(self): + eq = self.assertEqual +@@ -1101,7 +1098,7 @@ + msg = MIMEText(u'hello there') + eq(msg.get_charset(), 'us-ascii') + eq(msg['content-type'], 'text/plain; charset="us-ascii"') +- self.assertTrue('hello there' in msg.as_string()) ++ self.assertIn('hello there', msg.as_string()) + + def test_8bit_unicode_input(self): + teststr = u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430' +@@ -1162,21 +1159,20 @@ + def test_hierarchy(self): + # convenience + eq = self.assertEqual +- unless = self.assertTrue + raises = self.assertRaises + # tests + m = self._msg +- unless(m.is_multipart()) ++ self.assertTrue(m.is_multipart()) + eq(m.get_content_type(), 'multipart/mixed') + eq(len(m.get_payload()), 2) + raises(IndexError, m.get_payload, 2) + m0 = m.get_payload(0) + m1 = m.get_payload(1) +- unless(m0 is self._txt) +- unless(m1 is self._im) ++ self.assertIs(m0, self._txt) ++ self.assertIs(m1, self._im) + eq(m.get_payload(), [m0, m1]) +- unless(not m0.is_multipart()) +- unless(not m1.is_multipart()) ++ self.assertFalse(m0.is_multipart()) ++ self.assertFalse(m1.is_multipart()) + + def test_empty_multipart_idempotent(self): + text = """\ +@@ -1210,7 +1206,8 @@ + + --BOUNDARY + +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + def test_no_parts_in_a_multipart_with_empty_epilogue(self): + outer = MIMEBase('multipart', 'mixed') +@@ -1255,7 +1252,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + def test_seq_parts_in_a_multipart_with_empty_preamble(self): + eq = self.ndiffAssertEqual +@@ -1281,7 +1279,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + + def test_seq_parts_in_a_multipart_with_none_preamble(self): +@@ -1307,7 +1306,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + + def test_seq_parts_in_a_multipart_with_none_epilogue(self): +@@ -1333,7 +1333,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + + def test_seq_parts_in_a_multipart_with_empty_epilogue(self): +@@ -1506,23 +1507,22 @@ + eq(msg.get_content_subtype(), 'plain') + + def test_same_boundary_inner_outer(self): +- unless = self.assertTrue + msg = self._msgobj('msg_15.txt') + # XXX We can probably eventually do better + inner = msg.get_payload(0) +- unless(hasattr(inner, 'defects')) ++ self.assertTrue(hasattr(inner, 'defects')) + self.assertEqual(len(inner.defects), 1) +- unless(isinstance(inner.defects[0], +- Errors.StartBoundaryNotFoundDefect)) ++ self.assertIsInstance(inner.defects[0], ++ Errors.StartBoundaryNotFoundDefect) + + def test_multipart_no_boundary(self): +- unless = self.assertTrue + msg = self._msgobj('msg_25.txt') +- unless(isinstance(msg.get_payload(), str)) ++ self.assertIsInstance(msg.get_payload(), str) + self.assertEqual(len(msg.defects), 2) +- unless(isinstance(msg.defects[0], Errors.NoBoundaryInMultipartDefect)) +- unless(isinstance(msg.defects[1], +- Errors.MultipartInvariantViolationDefect)) ++ self.assertIsInstance(msg.defects[0], ++ Errors.NoBoundaryInMultipartDefect) ++ self.assertIsInstance(msg.defects[1], ++ Errors.MultipartInvariantViolationDefect) + + def test_invalid_content_type(self): + eq = self.assertEqual +@@ -1574,13 +1574,13 @@ + """) + + def test_lying_multipart(self): +- unless = self.assertTrue + msg = self._msgobj('msg_41.txt') +- unless(hasattr(msg, 'defects')) ++ self.assertTrue(hasattr(msg, 'defects')) + self.assertEqual(len(msg.defects), 2) +- unless(isinstance(msg.defects[0], Errors.NoBoundaryInMultipartDefect)) +- unless(isinstance(msg.defects[1], +- Errors.MultipartInvariantViolationDefect)) ++ self.assertIsInstance(msg.defects[0], ++ Errors.NoBoundaryInMultipartDefect) ++ self.assertIsInstance(msg.defects[1], ++ Errors.MultipartInvariantViolationDefect) + + def test_missing_start_boundary(self): + outer = self._msgobj('msg_42.txt') +@@ -1594,8 +1594,8 @@ + # [*] This message is missing its start boundary + bad = outer.get_payload(1).get_payload(0) + self.assertEqual(len(bad.defects), 1) +- self.assertTrue(isinstance(bad.defects[0], +- Errors.StartBoundaryNotFoundDefect)) ++ self.assertIsInstance(bad.defects[0], ++ Errors.StartBoundaryNotFoundDefect) + + def test_first_line_is_continuation_header(self): + eq = self.assertEqual +@@ -1604,8 +1604,8 @@ + eq(msg.keys(), []) + eq(msg.get_payload(), 'Line 2\nLine 3') + eq(len(msg.defects), 1) +- self.assertTrue(isinstance(msg.defects[0], +- Errors.FirstHeaderLineIsContinuationDefect)) ++ self.assertIsInstance(msg.defects[0], ++ Errors.FirstHeaderLineIsContinuationDefect) + eq(msg.defects[0].line, ' Line 1\n') + + +@@ -1687,17 +1687,16 @@ + + def test_valid_argument(self): + eq = self.assertEqual +- unless = self.assertTrue + subject = 'A sub-message' + m = Message() + m['Subject'] = subject + r = MIMEMessage(m) + eq(r.get_content_type(), 'message/rfc822') + payload = r.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + subpart = payload[0] +- unless(subpart is m) ++ self.assertIs(subpart, m) + eq(subpart['subject'], subject) + + def test_bad_multipart(self): +@@ -1731,24 +1730,22 @@ + + def test_parse_message_rfc822(self): + eq = self.assertEqual +- unless = self.assertTrue + msg = self._msgobj('msg_11.txt') + eq(msg.get_content_type(), 'message/rfc822') + payload = msg.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + submsg = payload[0] +- self.assertTrue(isinstance(submsg, Message)) ++ self.assertIsInstance(submsg, Message) + eq(submsg['subject'], 'An enclosed message') + eq(submsg.get_payload(), 'Here is the body of the message.\n') + + def test_dsn(self): + eq = self.assertEqual +- unless = self.assertTrue + # msg 16 is a Delivery Status Notification, see RFC 1894 + msg = self._msgobj('msg_16.txt') + eq(msg.get_content_type(), 'multipart/report') +- unless(msg.is_multipart()) ++ self.assertTrue(msg.is_multipart()) + eq(len(msg.get_payload()), 3) + # Subpart 1 is a text/plain, human readable section + subpart = msg.get_payload(0) +@@ -1777,13 +1774,13 @@ + # message/delivery-status should treat each block as a bunch of + # headers, i.e. a bunch of Message objects. + dsn1 = subpart.get_payload(0) +- unless(isinstance(dsn1, Message)) ++ self.assertIsInstance(dsn1, Message) + eq(dsn1['original-envelope-id'], '0GK500B4HD0888@cougar.noc.ucla.edu') + eq(dsn1.get_param('dns', header='reporting-mta'), '') + # Try a missing one + eq(dsn1.get_param('nsd', header='reporting-mta'), None) + dsn2 = subpart.get_payload(1) +- unless(isinstance(dsn2, Message)) ++ self.assertIsInstance(dsn2, Message) + eq(dsn2['action'], 'failed') + eq(dsn2.get_params(header='original-recipient'), + [('rfc822', ''), ('jangel1@cougar.noc.ucla.edu', '')]) +@@ -1792,10 +1789,10 @@ + subpart = msg.get_payload(2) + eq(subpart.get_content_type(), 'message/rfc822') + payload = subpart.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + subsubpart = payload[0] +- unless(isinstance(subsubpart, Message)) ++ self.assertIsInstance(subsubpart, Message) + eq(subsubpart.get_content_type(), 'text/plain') + eq(subsubpart['message-id'], + '<002001c144a6$8752e060$56104586@oxy.edu>') +@@ -2094,7 +2091,6 @@ + + def test_content_type(self): + eq = self.assertEqual +- unless = self.assertTrue + # Get a message object and reset the seek pointer for other tests + msg, text = self._msgobj('msg_05.txt') + eq(msg.get_content_type(), 'multipart/report') +@@ -2116,29 +2112,28 @@ + eq(msg2.get_payload(), 'Yadda yadda yadda\n') + msg3 = msg.get_payload(2) + eq(msg3.get_content_type(), 'message/rfc822') +- self.assertTrue(isinstance(msg3, Message)) ++ self.assertIsInstance(msg3, Message) + payload = msg3.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + msg4 = payload[0] +- unless(isinstance(msg4, Message)) ++ self.assertIsInstance(msg4, Message) + eq(msg4.get_payload(), 'Yadda yadda yadda\n') + + def test_parser(self): + eq = self.assertEqual +- unless = self.assertTrue + msg, text = self._msgobj('msg_06.txt') + # Check some of the outer headers + eq(msg.get_content_type(), 'message/rfc822') + # Make sure the payload is a list of exactly one sub-Message, and that + # that submessage has a type of text/plain + payload = msg.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + msg1 = payload[0] +- self.assertTrue(isinstance(msg1, Message)) ++ self.assertIsInstance(msg1, Message) + eq(msg1.get_content_type(), 'text/plain') +- self.assertTrue(isinstance(msg1.get_payload(), str)) ++ self.assertIsInstance(msg1.get_payload(), str) + eq(msg1.get_payload(), '\n') + + +@@ -2175,7 +2170,6 @@ + fp.close() + + def test_message_from_string_with_class(self): +- unless = self.assertTrue + fp = openfile('msg_01.txt') + try: + text = fp.read() +@@ -2186,7 +2180,7 @@ + pass + + msg = email.message_from_string(text, MyMessage) +- unless(isinstance(msg, MyMessage)) ++ self.assertIsInstance(msg, MyMessage) + # Try something more complicated + fp = openfile('msg_02.txt') + try: +@@ -2195,10 +2189,9 @@ + fp.close() + msg = email.message_from_string(text, MyMessage) + for subpart in msg.walk(): +- unless(isinstance(subpart, MyMessage)) ++ self.assertIsInstance(subpart, MyMessage) + + def test_message_from_file_with_class(self): +- unless = self.assertTrue + # Create a subclass + class MyMessage(Message): + pass +@@ -2208,7 +2201,7 @@ + msg = email.message_from_file(fp, MyMessage) + finally: + fp.close() +- unless(isinstance(msg, MyMessage)) ++ self.assertIsInstance(msg, MyMessage) + # Try something more complicated + fp = openfile('msg_02.txt') + try: +@@ -2216,7 +2209,7 @@ + finally: + fp.close() + for subpart in msg.walk(): +- unless(isinstance(subpart, MyMessage)) ++ self.assertIsInstance(subpart, MyMessage) + + def test__all__(self): + module = __import__('email') +@@ -2591,9 +2584,9 @@ + break + om.append(ol) + n1 += 1 +- self.assertTrue(n == n1) +- self.assertTrue(len(om) == nt) +- self.assertTrue(''.join([il for il, n in imt]) == ''.join(om)) ++ self.assertEqual(n, n1) ++ self.assertEqual(len(om), nt) ++ self.assertEqual(''.join([il for il, n in imt]), ''.join(om)) + + + +@@ -2610,7 +2603,7 @@ + eq(msg['to'], 'ppp@zzz.org') + eq(msg.get_content_type(), 'multipart/mixed') + self.assertFalse(msg.is_multipart()) +- self.assertTrue(isinstance(msg.get_payload(), str)) ++ self.assertIsInstance(msg.get_payload(), str) + + def test_whitespace_continuation(self): + eq = self.assertEqual +@@ -3027,7 +3020,7 @@ + h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", + maxlinelen=76) + for l in h.encode(splitchars=' ').split('\n '): +- self.assertTrue(len(l) <= 76) ++ self.assertLessEqual(len(l), 76) + + def test_multilingual(self): + eq = self.ndiffAssertEqual +@@ -3279,7 +3272,7 @@ + ''' + msg = email.message_from_string(m) + param = msg.get_param('NAME') +- self.assertFalse(isinstance(param, tuple)) ++ self.assertNotIsInstance(param, tuple) + self.assertEqual( + param, + 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm') +@@ -3432,7 +3425,7 @@ + """ + msg = email.message_from_string(m) + param = msg.get_param('name') +- self.assertFalse(isinstance(param, tuple)) ++ self.assertNotIsInstance(param, tuple) + self.assertEqual(param, "Frank's Document") + + def test_rfc2231_tick_attack_extended(self): +@@ -3456,7 +3449,7 @@ + """ + msg = email.message_from_string(m) + param = msg.get_param('name') +- self.assertFalse(isinstance(param, tuple)) ++ self.assertNotIsInstance(param, tuple) + self.assertEqual(param, "us-ascii'en-us'Frank's Document") + + def test_rfc2231_no_extended_values(self): +diff -r 3a1db0d2747e Lib/email/test/test_email_renamed.py +--- a/Lib/email/test/test_email_renamed.py ++++ b/Lib/email/test/test_email_renamed.py +@@ -231,12 +231,12 @@ + msg['From'] = 'Me' + msg['to'] = 'You' + # Check for case insensitivity +- self.assertTrue('from' in msg) +- self.assertTrue('From' in msg) +- self.assertTrue('FROM' in msg) +- self.assertTrue('to' in msg) +- self.assertTrue('To' in msg) +- self.assertTrue('TO' in msg) ++ self.assertIn('from', msg) ++ self.assertIn('From', msg) ++ self.assertIn('FROM', msg) ++ self.assertIn('to', msg) ++ self.assertIn('To', msg) ++ self.assertIn('TO', msg) + + def test_as_string(self): + eq = self.assertEqual +@@ -916,7 +916,6 @@ + + def test_add_header(self): + eq = self.assertEqual +- unless = self.assertTrue + self._au.add_header('Content-Disposition', 'attachment', + filename='audiotest.au') + eq(self._au['content-disposition'], +@@ -927,12 +926,13 @@ + 'audiotest.au') + missing = [] + eq(self._au.get_param('attachment', header='content-disposition'), '') +- unless(self._au.get_param('foo', failobj=missing, +- header='content-disposition') is missing) ++ self.assertIs(self._au.get_param('foo', failobj=missing, ++ header='content-disposition'), ++ missing) + # Try some missing stuff +- unless(self._au.get_param('foobar', missing) is missing) +- unless(self._au.get_param('attachment', missing, +- header='foobar') is missing) ++ self.assertIs(self._au.get_param('foobar', missing), missing) ++ self.assertIs(self._au.get_param('attachment', missing, ++ header='foobar'), missing) + + + +@@ -959,7 +959,6 @@ + + def test_add_header(self): + eq = self.assertEqual +- unless = self.assertTrue + self._im.add_header('Content-Disposition', 'attachment', + filename='dingusfish.gif') + eq(self._im['content-disposition'], +@@ -970,12 +969,13 @@ + 'dingusfish.gif') + missing = [] + eq(self._im.get_param('attachment', header='content-disposition'), '') +- unless(self._im.get_param('foo', failobj=missing, +- header='content-disposition') is missing) ++ self.assertIs(self._im.get_param('foo', failobj=missing, ++ header='content-disposition'), ++ missing) + # Try some missing stuff +- unless(self._im.get_param('foobar', missing) is missing) +- unless(self._im.get_param('attachment', missing, +- header='foobar') is missing) ++ self.assertIs(self._im.get_param('foobar', missing), missing) ++ self.assertIs(self._im.get_param('attachment', missing, ++ header='foobar'), missing) + + + +@@ -1035,17 +1035,16 @@ + + def test_types(self): + eq = self.assertEqual +- unless = self.assertTrue + eq(self._msg.get_content_type(), 'text/plain') + eq(self._msg.get_param('charset'), 'us-ascii') + missing = [] +- unless(self._msg.get_param('foobar', missing) is missing) +- unless(self._msg.get_param('charset', missing, header='foobar') +- is missing) ++ self.assertIs(self._msg.get_param('foobar', missing), missing) ++ self.assertIs(self._msg.get_param('charset', missing, header='foobar'), ++ missing) + + def test_payload(self): + self.assertEqual(self._msg.get_payload(), 'hello there') +- self.assertTrue(not self._msg.is_multipart()) ++ self.assertFalse(self._msg.is_multipart()) + + def test_charset(self): + eq = self.assertEqual +@@ -1100,21 +1099,20 @@ + def test_hierarchy(self): + # convenience + eq = self.assertEqual +- unless = self.assertTrue + raises = self.assertRaises + # tests + m = self._msg +- unless(m.is_multipart()) ++ self.assertTrue(m.is_multipart()) + eq(m.get_content_type(), 'multipart/mixed') + eq(len(m.get_payload()), 2) + raises(IndexError, m.get_payload, 2) + m0 = m.get_payload(0) + m1 = m.get_payload(1) +- unless(m0 is self._txt) +- unless(m1 is self._im) ++ self.assertIs(m0, self._txt) ++ self.assertIs(m1, self._im) + eq(m.get_payload(), [m0, m1]) +- unless(not m0.is_multipart()) +- unless(not m1.is_multipart()) ++ self.assertFalse(m0.is_multipart()) ++ self.assertFalse(m1.is_multipart()) + + def test_empty_multipart_idempotent(self): + text = """\ +@@ -1148,7 +1146,8 @@ + + --BOUNDARY + +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + def test_no_parts_in_a_multipart_with_empty_epilogue(self): + outer = MIMEBase('multipart', 'mixed') +@@ -1193,7 +1192,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + def test_seq_parts_in_a_multipart_with_empty_preamble(self): + eq = self.ndiffAssertEqual +@@ -1219,7 +1219,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + + def test_seq_parts_in_a_multipart_with_none_preamble(self): +@@ -1245,7 +1246,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + + def test_seq_parts_in_a_multipart_with_none_epilogue(self): +@@ -1271,7 +1273,8 @@ + Content-Transfer-Encoding: 7bit + + hello world +---BOUNDARY--''') ++--BOUNDARY-- ++''') + + + def test_seq_parts_in_a_multipart_with_empty_epilogue(self): +@@ -1444,23 +1447,22 @@ + eq(msg.get_content_subtype(), 'plain') + + def test_same_boundary_inner_outer(self): +- unless = self.assertTrue + msg = self._msgobj('msg_15.txt') + # XXX We can probably eventually do better + inner = msg.get_payload(0) +- unless(hasattr(inner, 'defects')) ++ self.assertTrue(hasattr(inner, 'defects')) + self.assertEqual(len(inner.defects), 1) +- unless(isinstance(inner.defects[0], +- errors.StartBoundaryNotFoundDefect)) ++ self.assertIsInstance(inner.defects[0], ++ errors.StartBoundaryNotFoundDefect) + + def test_multipart_no_boundary(self): +- unless = self.assertTrue + msg = self._msgobj('msg_25.txt') +- unless(isinstance(msg.get_payload(), str)) ++ self.assertIsInstance(msg.get_payload(), str) + self.assertEqual(len(msg.defects), 2) +- unless(isinstance(msg.defects[0], errors.NoBoundaryInMultipartDefect)) +- unless(isinstance(msg.defects[1], +- errors.MultipartInvariantViolationDefect)) ++ self.assertIsInstance(msg.defects[0], ++ errors.NoBoundaryInMultipartDefect) ++ self.assertIsInstance(msg.defects[1], ++ errors.MultipartInvariantViolationDefect) + + def test_invalid_content_type(self): + eq = self.assertEqual +@@ -1512,13 +1514,13 @@ + """) + + def test_lying_multipart(self): +- unless = self.assertTrue + msg = self._msgobj('msg_41.txt') +- unless(hasattr(msg, 'defects')) ++ self.assertTrue(hasattr(msg, 'defects')) + self.assertEqual(len(msg.defects), 2) +- unless(isinstance(msg.defects[0], errors.NoBoundaryInMultipartDefect)) +- unless(isinstance(msg.defects[1], +- errors.MultipartInvariantViolationDefect)) ++ self.assertIsInstance(msg.defects[0], ++ errors.NoBoundaryInMultipartDefect) ++ self.assertIsInstance(msg.defects[1], ++ errors.MultipartInvariantViolationDefect) + + def test_missing_start_boundary(self): + outer = self._msgobj('msg_42.txt') +@@ -1532,8 +1534,8 @@ + # [*] This message is missing its start boundary + bad = outer.get_payload(1).get_payload(0) + self.assertEqual(len(bad.defects), 1) +- self.assertTrue(isinstance(bad.defects[0], +- errors.StartBoundaryNotFoundDefect)) ++ self.assertIsInstance(bad.defects[0], ++ errors.StartBoundaryNotFoundDefect) + + def test_first_line_is_continuation_header(self): + eq = self.assertEqual +@@ -1542,8 +1544,8 @@ + eq(msg.keys(), []) + eq(msg.get_payload(), 'Line 2\nLine 3') + eq(len(msg.defects), 1) +- self.assertTrue(isinstance(msg.defects[0], +- errors.FirstHeaderLineIsContinuationDefect)) ++ self.assertIsInstance(msg.defects[0], ++ errors.FirstHeaderLineIsContinuationDefect) + eq(msg.defects[0].line, ' Line 1\n') + + +@@ -1609,17 +1611,16 @@ + + def test_valid_argument(self): + eq = self.assertEqual +- unless = self.assertTrue + subject = 'A sub-message' + m = Message() + m['Subject'] = subject + r = MIMEMessage(m) + eq(r.get_content_type(), 'message/rfc822') + payload = r.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + subpart = payload[0] +- unless(subpart is m) ++ self.assertIs(subpart, m) + eq(subpart['subject'], subject) + + def test_bad_multipart(self): +@@ -1653,24 +1654,22 @@ + + def test_parse_message_rfc822(self): + eq = self.assertEqual +- unless = self.assertTrue + msg = self._msgobj('msg_11.txt') + eq(msg.get_content_type(), 'message/rfc822') + payload = msg.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + submsg = payload[0] +- self.assertTrue(isinstance(submsg, Message)) ++ self.assertIsInstance(submsg, Message) + eq(submsg['subject'], 'An enclosed message') + eq(submsg.get_payload(), 'Here is the body of the message.\n') + + def test_dsn(self): + eq = self.assertEqual +- unless = self.assertTrue + # msg 16 is a Delivery Status Notification, see RFC 1894 + msg = self._msgobj('msg_16.txt') + eq(msg.get_content_type(), 'multipart/report') +- unless(msg.is_multipart()) ++ self.assertTrue(msg.is_multipart()) + eq(len(msg.get_payload()), 3) + # Subpart 1 is a text/plain, human readable section + subpart = msg.get_payload(0) +@@ -1699,13 +1698,13 @@ + # message/delivery-status should treat each block as a bunch of + # headers, i.e. a bunch of Message objects. + dsn1 = subpart.get_payload(0) +- unless(isinstance(dsn1, Message)) ++ self.assertIsInstance(dsn1, Message) + eq(dsn1['original-envelope-id'], '0GK500B4HD0888@cougar.noc.ucla.edu') + eq(dsn1.get_param('dns', header='reporting-mta'), '') + # Try a missing one + eq(dsn1.get_param('nsd', header='reporting-mta'), None) + dsn2 = subpart.get_payload(1) +- unless(isinstance(dsn2, Message)) ++ self.assertIsInstance(dsn2, Message) + eq(dsn2['action'], 'failed') + eq(dsn2.get_params(header='original-recipient'), + [('rfc822', ''), ('jangel1@cougar.noc.ucla.edu', '')]) +@@ -1714,10 +1713,10 @@ + subpart = msg.get_payload(2) + eq(subpart.get_content_type(), 'message/rfc822') + payload = subpart.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + subsubpart = payload[0] +- unless(isinstance(subsubpart, Message)) ++ self.assertIsInstance(subsubpart, Message) + eq(subsubpart.get_content_type(), 'text/plain') + eq(subsubpart['message-id'], + '<002001c144a6$8752e060$56104586@oxy.edu>') +@@ -2013,7 +2012,6 @@ + + def test_content_type(self): + eq = self.assertEqual +- unless = self.assertTrue + # Get a message object and reset the seek pointer for other tests + msg, text = self._msgobj('msg_05.txt') + eq(msg.get_content_type(), 'multipart/report') +@@ -2035,29 +2033,28 @@ + eq(msg2.get_payload(), 'Yadda yadda yadda\n') + msg3 = msg.get_payload(2) + eq(msg3.get_content_type(), 'message/rfc822') +- self.assertTrue(isinstance(msg3, Message)) ++ self.assertIsInstance(msg3, Message) + payload = msg3.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + msg4 = payload[0] +- unless(isinstance(msg4, Message)) ++ self.assertIsInstance(msg4, Message) + eq(msg4.get_payload(), 'Yadda yadda yadda\n') + + def test_parser(self): + eq = self.assertEqual +- unless = self.assertTrue + msg, text = self._msgobj('msg_06.txt') + # Check some of the outer headers + eq(msg.get_content_type(), 'message/rfc822') + # Make sure the payload is a list of exactly one sub-Message, and that + # that submessage has a type of text/plain + payload = msg.get_payload() +- unless(isinstance(payload, list)) ++ self.assertIsInstance(payload, list) + eq(len(payload), 1) + msg1 = payload[0] +- self.assertTrue(isinstance(msg1, Message)) ++ self.assertIsInstance(msg1, Message) + eq(msg1.get_content_type(), 'text/plain') +- self.assertTrue(isinstance(msg1.get_payload(), str)) ++ self.assertIsInstance(msg1.get_payload(), str) + eq(msg1.get_payload(), '\n') + + +@@ -2094,7 +2091,6 @@ + fp.close() + + def test_message_from_string_with_class(self): +- unless = self.assertTrue + fp = openfile('msg_01.txt') + try: + text = fp.read() +@@ -2105,7 +2101,7 @@ + pass + + msg = email.message_from_string(text, MyMessage) +- unless(isinstance(msg, MyMessage)) ++ self.assertIsInstance(msg, MyMessage) + # Try something more complicated + fp = openfile('msg_02.txt') + try: +@@ -2114,10 +2110,9 @@ + fp.close() + msg = email.message_from_string(text, MyMessage) + for subpart in msg.walk(): +- unless(isinstance(subpart, MyMessage)) ++ self.assertIsInstance(subpart, MyMessage) + + def test_message_from_file_with_class(self): +- unless = self.assertTrue + # Create a subclass + class MyMessage(Message): + pass +@@ -2127,7 +2122,7 @@ + msg = email.message_from_file(fp, MyMessage) + finally: + fp.close() +- unless(isinstance(msg, MyMessage)) ++ self.assertIsInstance(msg, MyMessage) + # Try something more complicated + fp = openfile('msg_02.txt') + try: +@@ -2135,7 +2130,7 @@ + finally: + fp.close() + for subpart in msg.walk(): +- unless(isinstance(subpart, MyMessage)) ++ self.assertIsInstance(subpart, MyMessage) + + def test__all__(self): + module = __import__('email') +@@ -2460,7 +2455,7 @@ + eq(msg['to'], 'ppp@zzz.org') + eq(msg.get_content_type(), 'multipart/mixed') + self.assertFalse(msg.is_multipart()) +- self.assertTrue(isinstance(msg.get_payload(), str)) ++ self.assertIsInstance(msg.get_payload(), str) + + def test_whitespace_continuation(self): + eq = self.assertEqual +@@ -2856,7 +2851,7 @@ + h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", + maxlinelen=76) + for l in h.encode(splitchars=' ').split('\n '): +- self.assertTrue(len(l) <= 76) ++ self.assertLessEqual(len(l), 76) + + def test_multilingual(self): + eq = self.ndiffAssertEqual +diff -r 3a1db0d2747e Lib/fileinput.py +--- a/Lib/fileinput.py ++++ b/Lib/fileinput.py +@@ -387,9 +387,10 @@ + + + def hook_encoded(encoding): +- import codecs ++ import io + def openhook(filename, mode): +- return codecs.open(filename, mode, encoding) ++ mode = mode.replace('U', '').replace('b', '') or 'r' ++ return io.open(filename, mode, encoding=encoding, newline='') + return openhook + + +diff -r 3a1db0d2747e Lib/httplib.py +--- a/Lib/httplib.py ++++ b/Lib/httplib.py +@@ -565,7 +565,7 @@ + # connection, and the user is reading more bytes than will be provided + # (for example, reading in 1k chunks) + s = self.fp.read(amt) +- if not s: ++ if not s and amt: + # Ideally, we would raise IncompleteRead if the content-length + # wasn't satisfied, but it might break compatibility. + self.close() +diff -r 3a1db0d2747e Lib/idlelib/CallTipWindow.py +--- a/Lib/idlelib/CallTipWindow.py ++++ b/Lib/idlelib/CallTipWindow.py +@@ -48,13 +48,7 @@ + def showtip(self, text, parenleft, parenright): + """Show the calltip, bind events which will close it and reposition it. + """ +- # truncate overly long calltip +- if len(text) >= 79: +- textlines = text.splitlines() +- for i, line in enumerate(textlines): +- if len(line) > 79: +- textlines[i] = line[:75] + ' ...' +- text = '\n'.join(textlines) ++ # Only called in CallTips, where lines are truncated + self.text = text + if self.tipwindow or not self.text: + return +diff -r 3a1db0d2747e Lib/idlelib/CallTips.py +--- a/Lib/idlelib/CallTips.py ++++ b/Lib/idlelib/CallTips.py +@@ -5,14 +5,15 @@ + which disappear when you type a closing parenthesis. + + """ ++import __main__ + import re + import sys ++import textwrap + import types + + from idlelib import CallTipWindow + from idlelib.HyperParser import HyperParser + +-import __main__ + + class CallTips: + +@@ -130,99 +131,83 @@ + if rc is not None: return rc + return None + ++# The following are used in get_arg_text ++_MAX_COLS = 85 ++_MAX_LINES = 5 # enough for bytes ++_INDENT = ' '*4 # for wrapped signatures ++ + def get_arg_text(ob): +- """Get a string describing the arguments for the given object, +- only if it is callable.""" +- arg_text = "" +- if ob is not None and hasattr(ob, '__call__'): +- 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: +- 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 ++ '''Return a string describing the signature of a callable object, or ''. ++ ++ For Python-coded functions and methods, the first line is introspected. ++ Delete 'self' parameter for classes (.__init__) and bound methods. ++ The next lines are the first lines of the doc string up to the first ++ empty line or _MAX_LINES. For builtins, this typically includes ++ the arguments in addition to the return value. ++ ''' ++ argspec = "" ++ try: ++ ob_call = ob.__call__ ++ except BaseException: ++ if type(ob) is types.ClassType: # old-style ++ ob_call = ob ++ else: ++ return argspec ++ ++ arg_offset = 0 ++ if type(ob) in (types.ClassType, types.TypeType): ++ # Look for the first __init__ in the class chain with .im_func. ++ # Slot wrappers (builtins, classes defined in funcs) do not. ++ fob = _find_constructor(ob) ++ if fob is None: ++ fob = lambda: None ++ else: + arg_offset = 1 +- else: +- 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 [] +- 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("(?", arg_text) +- # See if we can use the docstring ++ elif type(ob) == types.MethodType: ++ # bit of a hack for methods - turn it into a function ++ # and drop the "self" param for bound methods ++ fob = ob.im_func ++ if ob.im_self: ++ arg_offset = 1 ++ elif type(ob_call) == types.MethodType: ++ # a callable class instance ++ fob = ob_call.im_func ++ arg_offset = 1 ++ else: ++ 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 [] ++ 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("*args") ++ if fob.func_code.co_flags & 0x8: ++ items.append("**kwds") ++ argspec = ", ".join(items) ++ argspec = "(%s)" % re.sub("(?", argspec) ++ ++ lines = (textwrap.wrap(argspec, _MAX_COLS, subsequent_indent=_INDENT) ++ if len(argspec) > _MAX_COLS else [argspec] if argspec else []) ++ ++ if isinstance(ob_call, types.MethodType): ++ doc = ob_call.__doc__ ++ else: + doc = getattr(ob, "__doc__", "") +- if doc: +- doc = doc.lstrip() +- pos = doc.find("\n") +- if pos < 0 or pos > 70: +- pos = 70 +- if arg_text: +- arg_text += "\n" +- arg_text += doc[:pos] +- return arg_text ++ if doc: ++ for line in doc.split('\n', _MAX_LINES)[:_MAX_LINES]: ++ line = line.strip() ++ if not line: ++ break ++ if len(line) > _MAX_COLS: ++ line = line[: _MAX_COLS - 3] + '...' ++ lines.append(line) ++ argspec = '\n'.join(lines) ++ return argspec + +-################################################# +-# +-# Test code +-# +-if __name__=='__main__': +- +- def t1(): "()" +- def t2(a, b=None): "(a, b=None)" +- def t3(a, *args): "(a, ...)" +- 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(object): +- "(ai=None, ...)" +- def __init__(self, ai=None, *b): "(ai=None, ...)" +- def t1(self): "()" +- def t2(self, ai, b=None): "(ai, b=None)" +- def t3(self, ai, *args): "(ai, ...)" +- def t4(self, *args): "(...)" +- 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() +- failed=[] +- for t in tests: +- expected = t.__doc__ + "\n" + t.__doc__ +- name = t.__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) +- 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, t7, +- TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7) +- +- # test(tests) ++if __name__ == '__main__': + from unittest import main +- main('idlelib.idle_test.test_calltips', verbosity=2, exit=False) ++ main('idlelib.idle_test.test_calltips', verbosity=2) +diff -r 3a1db0d2747e Lib/idlelib/Debugger.py +--- a/Lib/idlelib/Debugger.py ++++ b/Lib/idlelib/Debugger.py +@@ -253,8 +253,8 @@ + if self.vsource.get(): + self.sync_source_line() + +- def show_frame(self, (frame, lineno)): +- self.frame = frame ++ def show_frame(self, stackitem): ++ self.frame = stackitem[0] # lineno is stackitem[1] + self.show_variables() + + localsviewer = None +diff -r 3a1db0d2747e Lib/idlelib/EditorWindow.py +--- a/Lib/idlelib/EditorWindow.py ++++ b/Lib/idlelib/EditorWindow.py +@@ -1,5 +1,6 @@ + import sys + import os ++from platform import python_version + import re + import imp + from Tkinter import * +@@ -965,11 +966,14 @@ + self.undo.reset_undo() + + def short_title(self): ++ pyversion = "Python " + python_version() + ": " + filename = self.io.filename + if filename: + filename = os.path.basename(filename) ++ else: ++ filename = "Untitled" + # return unicode string to display non-ASCII chars correctly +- return self._filename_to_unicode(filename) ++ return pyversion + self._filename_to_unicode(filename) + + def long_title(self): + # return unicode string to display non-ASCII chars correctly +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle.ico +Binary file Lib/idlelib/Icons/idle.ico has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle_16.gif +Binary file Lib/idlelib/Icons/idle_16.gif has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle_16.png +Binary file Lib/idlelib/Icons/idle_16.png has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle_32.gif +Binary file Lib/idlelib/Icons/idle_32.gif has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle_32.png +Binary file Lib/idlelib/Icons/idle_32.png has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle_48.gif +Binary file Lib/idlelib/Icons/idle_48.gif has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/idle_48.png +Binary file Lib/idlelib/Icons/idle_48.png has changed +diff -r 3a1db0d2747e Lib/idlelib/Icons/python.gif +Binary file Lib/idlelib/Icons/python.gif has changed +diff -r 3a1db0d2747e Lib/idlelib/PyShell.py +--- a/Lib/idlelib/PyShell.py ++++ b/Lib/idlelib/PyShell.py +@@ -15,7 +15,7 @@ + + import linecache + from code import InteractiveInterpreter +-from platform import python_version ++from platform import python_version, system + + try: + from Tkinter import * +@@ -1338,8 +1338,16 @@ + def write(self, s): + if self.closed: + raise ValueError("write to closed file") +- if not isinstance(s, (basestring, bytearray)): +- raise TypeError('must be string, not ' + type(s).__name__) ++ if type(s) not in (unicode, str, bytearray): ++ # See issue #19481 ++ if isinstance(s, unicode): ++ s = unicode.__getslice__(s, None, None) ++ elif isinstance(s, str): ++ s = str.__str__(s) ++ elif isinstance(s, bytearray): ++ s = bytearray.__str__(s) ++ else: ++ raise TypeError('must be string, not ' + type(s).__name__) + return self.shell.write(s, self.tags) + + +@@ -1385,6 +1393,9 @@ + line = self._line_buffer or self.shell.readline() + if size < 0: + size = len(line) ++ eol = line.find('\n', 0, size) ++ if eol >= 0: ++ size = eol + 1 + self._line_buffer = line[size:] + return line[:size] + +@@ -1525,6 +1536,18 @@ + # start editor and/or shell windows: + root = Tk(className="Idle") + ++ # set application icon ++ icondir = os.path.join(os.path.dirname(__file__), 'Icons') ++ if system() == 'Windows': ++ iconfile = os.path.join(icondir, 'idle.ico') ++ root.wm_iconbitmap(default=iconfile) ++ elif TkVersion >= 8.5: ++ ext = '.png' if TkVersion >= 8.6 else '.gif' ++ iconfiles = [os.path.join(icondir, 'idle_%d%s' % (size, ext)) ++ for size in (16, 32, 48)] ++ icons = [PhotoImage(file=iconfile) for iconfile in iconfiles] ++ root.tk.call('wm', 'iconphoto', str(root), "-default", *icons) ++ + fixwordbreaks(root) + root.withdraw() + flist = PyShellFileList(root) +@@ -1538,20 +1561,22 @@ + args.remove(filename) + if not args: + flist.new() ++ + if enable_shell: + shell = flist.open_shell() + if not shell: + return # couldn't open shell +- + if macosxSupport.runningAsOSXApp() and flist.dict: + # On OSX: when the user has double-clicked on a file that causes + # IDLE to be launched the shell window will open just in front of + # the file she wants to see. Lower the interpreter window when + # there are open files. + shell.top.lower() ++ else: ++ shell = flist.pyshell + +- shell = flist.pyshell +- # handle remaining options: ++ # Handle remaining options. If any of these are set, enable_shell ++ # was set also, so shell must be true to reach here. + if debug: + shell.open_debugger() + if startup: +@@ -1559,7 +1584,7 @@ + os.environ.get("PYTHONSTARTUP") + if filename and os.path.isfile(filename): + shell.interp.execfile(filename) +- if shell and cmd or script: ++ if cmd or script: + shell.interp.runcommand("""if 1: + import sys as _sys + _sys.argv = %r +@@ -1570,13 +1595,14 @@ + elif script: + shell.interp.prepend_syspath(script) + shell.interp.execfile(script) +- +- # Check for problematic OS X Tk versions and print a warning message +- # in the IDLE shell window; this is less intrusive than always opening +- # a separate window. +- tkversionwarning = macosxSupport.tkVersionWarning(root) +- if tkversionwarning: +- shell.interp.runcommand(''.join(("print('", tkversionwarning, "')"))) ++ elif shell: ++ # If there is a shell window and no cmd or script in progress, ++ # check for problematic OS X Tk versions and print a warning ++ # message in the IDLE shell window; this is less intrusive ++ # than always opening a separate window. ++ tkversionwarning = macosxSupport.tkVersionWarning(root) ++ if tkversionwarning: ++ shell.interp.runcommand("print('%s')" % tkversionwarning) + + while flist.inversedict: # keep IDLE running while files are open. + root.mainloop() +diff -r 3a1db0d2747e Lib/idlelib/SearchEngine.py +--- a/Lib/idlelib/SearchEngine.py ++++ b/Lib/idlelib/SearchEngine.py +@@ -83,11 +83,9 @@ + try: + prog = re.compile(pat, flags) + except re.error as what: +- try: +- msg, col = what +- except: +- msg = str(what) +- col = -1 ++ args = what.args ++ msg = args[0] ++ col = arg[1] if len(args) >= 2 else -1 + self.report_error(pat, msg, col) + return None + return prog +@@ -231,6 +229,6 @@ + return line, col + + if __name__ == "__main__": +- from test import support; support.use_resources = ['gui'] ++ from test import test_support; test_support.use_resources = ['gui'] + import unittest + unittest.main('idlelib.idle_test.test_searchengine', verbosity=2, exit=False) +diff -r 3a1db0d2747e Lib/idlelib/configDialog.py +--- a/Lib/idlelib/configDialog.py ++++ b/Lib/idlelib/configDialog.py +@@ -78,9 +78,10 @@ + else: + paddingArgs={'padx':6, 'pady':3} + +- self.buttonHelp = Button(frameActionButtons,text='Help', +- command=self.Help,takefocus=FALSE, +- **paddingArgs) ++# Comment out button creation and packing until implement self.Help ++## self.buttonHelp = Button(frameActionButtons,text='Help', ++## command=self.Help,takefocus=FALSE, ++## **paddingArgs) + self.buttonOk = Button(frameActionButtons,text='Ok', + command=self.Ok,takefocus=FALSE, + **paddingArgs) +@@ -94,7 +95,7 @@ + self.CreatePageHighlight() + self.CreatePageKeys() + self.CreatePageGeneral() +- self.buttonHelp.pack(side=RIGHT,padx=5) ++## self.buttonHelp.pack(side=RIGHT,padx=5) + self.buttonOk.pack(side=LEFT,padx=5) + self.buttonApply.pack(side=LEFT,padx=5) + self.buttonCancel.pack(side=LEFT,padx=5) +diff -r 3a1db0d2747e Lib/idlelib/idle_test/README.txt +--- a/Lib/idlelib/idle_test/README.txt ++++ b/Lib/idlelib/idle_test/README.txt +@@ -41,9 +41,10 @@ + screen, gui tests must be 'guarded' by "requires('gui')" in a setUp + function or method. This will typically be setUpClass. + +-All gui objects must be destroyed by the end of the test, perhaps in a tearDown +-function. Creating the Tk root directly in a setUp allows a reference to be saved +-so it can be properly destroyed in the corresponding tearDown. ++To avoid interfering with other gui tests, all gui objects must be destroyed ++and deleted by the end of the test. If a widget, such as a Tk root, is created ++in a setUpX function, destroy it in the corresponding tearDownX. For module ++and class attributes, also delete the widget. + --- + @classmethod + def setUpClass(cls): +@@ -53,6 +54,7 @@ + @classmethod + def tearDownClass(cls): + cls.root.destroy() ++ del cls.root + --- + + Support.requires('gui') returns true if it is either called in a main module +@@ -105,4 +107,4 @@ + To run an individual Testcase or test method, extend the dotted name given to + unittest on the command line. (But gui tests will not this way.) + +-python -m unittest -v idlelib.idle_test.text_xyz.Test_case.test_meth ++python -m unittest -v idlelib.idle_test.test_xyz.Test_case.test_meth +diff -r 3a1db0d2747e Lib/idlelib/idle_test/test_calltips.py +--- a/Lib/idlelib/idle_test/test_calltips.py ++++ b/Lib/idlelib/idle_test/test_calltips.py +@@ -1,6 +1,157 @@ + import unittest + import idlelib.CallTips as ct +-CTi = ct.CallTips() ++CTi = ct.CallTips() # needed for get_entity test in 2.7 ++import textwrap ++import types ++import warnings ++ ++default_tip = '' ++ ++# Test Class TC is used in multiple get_argspec test methods ++class TC(object): ++ 'doc' ++ tip = "(ai=None, *args)" ++ def __init__(self, ai=None, *b): 'doc' ++ __init__.tip = "(self, ai=None, *args)" ++ def t1(self): 'doc' ++ t1.tip = "(self)" ++ def t2(self, ai, b=None): 'doc' ++ t2.tip = "(self, ai, b=None)" ++ def t3(self, ai, *args): 'doc' ++ t3.tip = "(self, ai, *args)" ++ def t4(self, *args): 'doc' ++ t4.tip = "(self, *args)" ++ def t5(self, ai, b=None, *args, **kw): 'doc' ++ t5.tip = "(self, ai, b=None, *args, **kwds)" ++ def t6(no, self): 'doc' ++ t6.tip = "(no, self)" ++ def __call__(self, ci): 'doc' ++ __call__.tip = "(self, ci)" ++ # attaching .tip to wrapped methods does not work ++ @classmethod ++ def cm(cls, a): 'doc' ++ @staticmethod ++ def sm(b): 'doc' ++ ++tc = TC() ++ ++signature = ct.get_arg_text # 2.7 and 3.x use different functions ++class Get_signatureTest(unittest.TestCase): ++ # The signature function must return a string, even if blank. ++ # Test a variety of objects to be sure that none cause it to raise ++ # (quite aside from getting as correct an answer as possible). ++ # The tests of builtins may break if the docstrings change, ++ # but a red buildbot is better than a user crash (as has happened). ++ # For a simple mismatch, change the expected output to the actual. ++ ++ def test_builtins(self): ++ # 2.7 puts '()\n' where 3.x does not, other minor differences ++ ++ # Python class that inherits builtin methods ++ class List(list): "List() doc" ++ # Simulate builtin with no docstring for default argspec test ++ class SB: __call__ = None ++ ++ def gtest(obj, out): ++ self.assertEqual(signature(obj), out) ++ ++ gtest(List, '()\n' + List.__doc__) ++ gtest(list.__new__, ++ 'T.__new__(S, ...) -> a new object with type S, a subtype of T') ++ gtest(list.__init__, ++ 'x.__init__(...) initializes x; see help(type(x)) for signature') ++ append_doc = "L.append(object) -- append object to end" ++ gtest(list.append, append_doc) ++ gtest([].append, append_doc) ++ gtest(List.append, append_doc) ++ ++ gtest(types.MethodType, '()\ninstancemethod(function, instance, class)') ++ gtest(SB(), default_tip) ++ ++ def test_signature_wrap(self): ++ # This is also a test of an old-style class ++ self.assertEqual(signature(textwrap.TextWrapper), '''\ ++(width=70, initial_indent='', subsequent_indent='', expand_tabs=True, ++ replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, ++ drop_whitespace=True, break_on_hyphens=True)''') ++ ++ def test_docline_truncation(self): ++ def f(): pass ++ f.__doc__ = 'a'*300 ++ self.assertEqual(signature(f), '()\n' + 'a' * (ct._MAX_COLS-3) + '...') ++ ++ def test_multiline_docstring(self): ++ # Test fewer lines than max. ++ self.assertEqual(signature(list), ++ "()\nlist() -> new empty list\n" ++ "list(iterable) -> new list initialized from iterable's items") ++ ++ # Test max lines and line (currently) too long. ++ def f(): ++ pass ++ s = 'a\nb\nc\nd\n' ++ f.__doc__ = s + 300 * 'e' + 'f' ++ self.assertEqual(signature(f), ++ '()\n' + s + (ct._MAX_COLS - 3) * 'e' + '...') ++ ++ def test_functions(self): ++ def t1(): 'doc' ++ t1.tip = "()" ++ def t2(a, b=None): 'doc' ++ t2.tip = "(a, b=None)" ++ def t3(a, *args): 'doc' ++ t3.tip = "(a, *args)" ++ def t4(*args): 'doc' ++ t4.tip = "(*args)" ++ def t5(a, b=None, *args, **kwds): 'doc' ++ t5.tip = "(a, b=None, *args, **kwds)" ++ ++ for func in (t1, t2, t3, t4, t5, TC): ++ self.assertEqual(signature(func), func.tip + '\ndoc') ++ ++ def test_methods(self): ++ for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__): ++ self.assertEqual(signature(meth), meth.tip + "\ndoc") ++ self.assertEqual(signature(TC.cm), "(a)\ndoc") ++ self.assertEqual(signature(TC.sm), "(b)\ndoc") ++ ++ def test_bound_methods(self): ++ # test that first parameter is correctly removed from argspec ++ for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"), (tc.t6, "(self)"), ++ (tc.__call__, '(ci)'), (tc, '(ci)'), (TC.cm, "(a)"),): ++ self.assertEqual(signature(meth), mtip + "\ndoc") ++ ++ def test_starred_parameter(self): ++ # test that starred first parameter is *not* removed from argspec ++ class C: ++ def m1(*args): pass ++ def m2(**kwds): pass ++ c = C() ++ for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"), ++ (C.m2, "(**kwds)"), (c.m2, "(**kwds)"),): ++ self.assertEqual(signature(meth), mtip) ++ ++ def test_no_docstring(self): ++ def nd(s): pass ++ TC.nd = nd ++ self.assertEqual(signature(nd), "(s)") ++ self.assertEqual(signature(TC.nd), "(s)") ++ self.assertEqual(signature(tc.nd), "()") ++ ++ def test_attribute_exception(self): ++ class NoCall(object): ++ def __getattr__(self, name): ++ raise BaseException ++ class Call(NoCall): ++ def __call__(self, ci): ++ pass ++ for meth, mtip in ((NoCall, '()'), (Call, '()'), ++ (NoCall(), ''), (Call(), '(ci)')): ++ self.assertEqual(signature(meth), mtip) ++ ++ def test_non_callables(self): ++ for obj in (0, 0.0, '0', b'0', [], {}): ++ self.assertEqual(signature(obj), '') + + class Get_entityTest(unittest.TestCase): + # In 3.x, get_entity changed from 'instance method' to module function +@@ -12,9 +163,12 @@ + + class Py2Test(unittest.TestCase): + def test_paramtuple_float(self): +- # 18539: (a,b) becomes '.0' in code object; change that but not float +- def f((a,b), c=0.0): pass +- self.assertEqual(ct.get_arg_text(f), '(, c=0.0)') ++ # 18539: (a,b) becomes '.0' in code object; change that but not 0.0 ++ with warnings.catch_warnings(): ++ # Suppess message of py3 deprecation of parameter unpacking ++ warnings.simplefilter("ignore") ++ exec "def f((a,b), c=0.0): pass" ++ self.assertEqual(signature(f), '(, c=0.0)') + + if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) +diff -r 3a1db0d2747e Lib/idlelib/idle_test/test_formatparagraph.py +--- a/Lib/idlelib/idle_test/test_formatparagraph.py ++++ b/Lib/idlelib/idle_test/test_formatparagraph.py +@@ -277,6 +277,9 @@ + @classmethod + def tearDownClass(cls): + cls.root.destroy() ++ del cls.root ++ del cls.text ++ del cls.formatter + + def test_short_line(self): + self.text.insert('1.0', "Short line\n") +diff -r 3a1db0d2747e Lib/idlelib/idle_test/test_idlehistory.py +--- a/Lib/idlelib/idle_test/test_idlehistory.py ++++ b/Lib/idlelib/idle_test/test_idlehistory.py +@@ -80,6 +80,7 @@ + @classmethod + def tearDownClass(cls): + cls.root.destroy() ++ del cls.root + + def fetch_test(self, reverse, line, prefix, index, bell=False): + # Perform one fetch as invoked by Alt-N or Alt-P +diff -r 3a1db0d2747e Lib/idlelib/idle_test/test_searchengine.py +--- a/Lib/idlelib/idle_test/test_searchengine.py ++++ b/Lib/idlelib/idle_test/test_searchengine.py +@@ -64,6 +64,7 @@ + ## @classmethod + ## def tearDownClass(cls): + ## cls.root.destroy() ++## del cls.root + + def test_get_selection(self): + # text = Text(master=self.root) +@@ -219,6 +220,7 @@ + ## @classmethod + ## def tearDownClass(cls): + ## cls.root.destroy() ++## del cls.root + + def test_search(self): + Equal = self.assertEqual +@@ -261,6 +263,7 @@ + ## @classmethod + ## def tearDownClass(cls): + ## cls.root.destroy() ++## del cls.root + + @classmethod + def setUpClass(cls): +diff -r 3a1db0d2747e Lib/idlelib/idle_test/test_text.py +--- a/Lib/idlelib/idle_test/test_text.py ++++ b/Lib/idlelib/idle_test/test_text.py +@@ -221,6 +221,7 @@ + @classmethod + def tearDownClass(cls): + cls.root.destroy() ++ del cls.root + + + if __name__ == '__main__': +diff -r 3a1db0d2747e Lib/imaplib.py +--- a/Lib/imaplib.py ++++ b/Lib/imaplib.py +@@ -35,6 +35,15 @@ + IMAP4_SSL_PORT = 993 + AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first + ++# Maximal line length when calling readline(). This is to prevent ++# reading arbitrary length lines. RFC 3501 and 2060 (IMAP 4rev1) ++# don't specify a line length. RFC 2683 however suggests limiting client ++# command lines to 1000 octets and server command lines to 8000 octets. ++# We have selected 10000 for some extra margin and since that is supposedly ++# also what UW and Panda IMAP does. ++_MAXLINE = 10000 ++ ++ + # Commands + + Commands = { +@@ -237,7 +246,10 @@ + + def readline(self): + """Read line from remote.""" +- return self.file.readline() ++ line = self.file.readline(_MAXLINE + 1) ++ if len(line) > _MAXLINE: ++ raise self.error("got more than %d bytes" % _MAXLINE) ++ return line + + + def send(self, data): +@@ -990,6 +1002,11 @@ + del self.tagged_commands[tag] + return result + ++ # If we've seen a BYE at this point, the socket will be ++ # closed, so report the BYE now. ++ ++ self._check_bye() ++ + # Some have reported "unexpected response" exceptions. + # Note that ignoring them here causes loops. + # Instead, send me details of the unexpected response and +diff -r 3a1db0d2747e Lib/imghdr.py +--- a/Lib/imghdr.py ++++ b/Lib/imghdr.py +@@ -7,18 +7,16 @@ + #-------------------------# + + def what(file, h=None): +- if h is None: +- if isinstance(file, basestring): +- f = open(file, 'rb') +- h = f.read(32) +- else: +- location = file.tell() +- h = file.read(32) +- file.seek(location) +- f = None +- else: +- f = None ++ f = None + try: ++ if h is None: ++ if isinstance(file, basestring): ++ f = open(file, 'rb') ++ h = f.read(32) ++ else: ++ location = file.tell() ++ h = file.read(32) ++ file.seek(location) + for tf in tests: + res = tf(h, f) + if res: +diff -r 3a1db0d2747e Lib/json/decoder.py +--- a/Lib/json/decoder.py ++++ b/Lib/json/decoder.py +@@ -62,6 +62,16 @@ + + DEFAULT_ENCODING = "utf-8" + ++def _decode_uXXXX(s, pos): ++ esc = s[pos + 1:pos + 5] ++ if len(esc) == 4 and esc[1] not in 'xX': ++ try: ++ return int(esc, 16) ++ except ValueError: ++ pass ++ msg = "Invalid \\uXXXX escape" ++ raise ValueError(errmsg(msg, s, pos)) ++ + def py_scanstring(s, end, encoding=None, strict=True, + _b=BACKSLASH, _m=STRINGCHUNK.match): + """Scan the string s for a JSON string. End is the index of the +@@ -116,25 +126,16 @@ + end += 1 + else: + # Unicode escape sequence +- esc = s[end + 1:end + 5] +- next_end = end + 5 +- if len(esc) != 4: +- msg = "Invalid \\uXXXX escape" +- raise ValueError(errmsg(msg, s, end)) +- uni = int(esc, 16) ++ uni = _decode_uXXXX(s, end) ++ end += 5 + # Check for surrogate pair on UCS-4 systems +- if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: +- msg = "Invalid \\uXXXX\\uXXXX surrogate pair" +- if not s[end + 5:end + 7] == '\\u': +- raise ValueError(errmsg(msg, s, end)) +- esc2 = s[end + 7:end + 11] +- if len(esc2) != 4: +- raise ValueError(errmsg(msg, s, end)) +- uni2 = int(esc2, 16) +- uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) +- next_end += 6 ++ if sys.maxunicode > 65535 and \ ++ 0xd800 <= uni <= 0xdbff and s[end:end + 2] == '\\u': ++ uni2 = _decode_uXXXX(s, end + 1) ++ if 0xdc00 <= uni2 <= 0xdfff: ++ uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) ++ end += 6 + char = unichr(uni) +- end = next_end + # Append the unescaped character + _append(char) + return u''.join(chunks), end +diff -r 3a1db0d2747e Lib/json/tests/test_scanstring.py +--- a/Lib/json/tests/test_scanstring.py ++++ b/Lib/json/tests/test_scanstring.py +@@ -5,10 +5,6 @@ + class TestScanstring(object): + def test_scanstring(self): + scanstring = self.json.decoder.scanstring +- self.assertEqual( +- scanstring('"z\\ud834\\udd20x"', 1, None, True), +- (u'z\U0001d120x', 16)) +- + if sys.maxunicode == 65535: + self.assertEqual( + scanstring(u'"z\U0001d120x"', 1, None, True), +@@ -94,6 +90,58 @@ + scanstring('["Bad value", truth]', 2, None, True), + (u'Bad value', 12)) + ++ def test_surrogates(self): ++ scanstring = self.json.decoder.scanstring ++ def assertScan(given, expect): ++ self.assertEqual(scanstring(given, 1, None, True), ++ (expect, len(given))) ++ if not isinstance(given, unicode): ++ given = unicode(given) ++ self.assertEqual(scanstring(given, 1, None, True), ++ (expect, len(given))) ++ ++ surrogates = unichr(0xd834) + unichr(0xdd20) ++ assertScan('"z\\ud834\\u0079x"', u'z\ud834yx') ++ assertScan('"z\\ud834\\udd20x"', u'z\U0001d120x') ++ assertScan('"z\\ud834\\ud834\\udd20x"', u'z\ud834\U0001d120x') ++ assertScan('"z\\ud834x"', u'z\ud834x') ++ assertScan(u'"z\\ud834\udd20x12345"', u'z%sx12345' % surrogates) ++ assertScan('"z\\udd20x"', u'z\udd20x') ++ assertScan(u'"z\ud834\udd20x"', u'z\ud834\udd20x') ++ assertScan(u'"z\ud834\\udd20x"', u'z%sx' % surrogates) ++ assertScan(u'"z\ud834x"', u'z\ud834x') ++ ++ def test_bad_escapes(self): ++ scanstring = self.json.decoder.scanstring ++ bad_escapes = [ ++ '"\\"', ++ '"\\x"', ++ '"\\u"', ++ '"\\u0"', ++ '"\\u01"', ++ '"\\u012"', ++ '"\\uz012"', ++ '"\\u0z12"', ++ '"\\u01z2"', ++ '"\\u012z"', ++ '"\\u0x12"', ++ '"\\u0X12"', ++ '"\\ud834\\"', ++ '"\\ud834\\u"', ++ '"\\ud834\\ud"', ++ '"\\ud834\\udd"', ++ '"\\ud834\\udd2"', ++ '"\\ud834\\uzdd2"', ++ '"\\ud834\\udzd2"', ++ '"\\ud834\\uddz2"', ++ '"\\ud834\\udd2z"', ++ '"\\ud834\\u0x20"', ++ '"\\ud834\\u0X20"', ++ ] ++ for s in bad_escapes: ++ with self.assertRaises(ValueError): ++ scanstring(s, 1, None, True) ++ + def test_issue3623(self): + self.assertRaises(ValueError, self.json.decoder.scanstring, b"xxx", 1, + "xxx") +diff -r 3a1db0d2747e Lib/lib-tk/Tix.py +--- a/Lib/lib-tk/Tix.py ++++ b/Lib/lib-tk/Tix.py +@@ -122,13 +122,9 @@ + elif cnf: + cnf = _cnfmerge(cnf) + if cnf is None: +- cnf = {} +- for x in self.tk.split(self.tk.call('tix', 'configure')): +- cnf[x[0][1:]] = (x[0][1:],) + x[1:] +- return cnf ++ return self._getconfigure('tix', 'configure') + if isinstance(cnf, StringType): +- x = self.tk.split(self.tk.call('tix', 'configure', '-'+cnf)) +- return (x[0][1:],) + x[1:] ++ return self._getconfigure1('tix', 'configure', '-'+cnf) + return self.tk.call(('tix', 'configure') + self._options(cnf)) + + def tix_filedialog(self, dlgclass=None): +@@ -380,7 +376,7 @@ + """Return the name of all subwidgets.""" + try: + x = self.tk.call(self._w, 'subwidgets', '-all') +- return self.tk.split(x) ++ return self.tk.splitlist(x) + except TclError: + return None + +@@ -473,13 +469,6 @@ + self.tk.call('destroy', self._w) + + +-# Useful func. to split Tcl lists and return as a dict. From Tkinter.py +-def _lst2dict(lst): +- dict = {} +- for x in lst: +- dict[x[0][1:]] = (x[0][1:],) + x[1:] +- return dict +- + # Useful class to create a display style - later shared by many items. + # Contributed by Steffen Kremser + class DisplayStyle: +@@ -515,10 +504,8 @@ + self.tk.call(self.stylename, 'configure', '-%s'%key, value) + + def config(self, cnf={}, **kw): +- return _lst2dict( +- self.tk.split( +- self.tk.call( +- self.stylename, 'configure', *self._options(cnf,kw)))) ++ return self._getconfigure( ++ self.stylename, 'configure', *self._options(cnf,kw)) + + def __getitem__(self,key): + return self.tk.call(self.stylename, 'cget', '-%s'%key) +@@ -928,9 +915,7 @@ + + def header_configure(self, col, cnf={}, **kw): + if cnf is None: +- return _lst2dict( +- self.tk.split( +- self.tk.call(self._w, 'header', 'configure', col))) ++ return self._getconfigure(self._w, 'header', 'configure', col) + self.tk.call(self._w, 'header', 'configure', col, + *self._options(cnf, kw)) + +@@ -955,9 +940,8 @@ + + def indicator_configure(self, entry, cnf={}, **kw): + if cnf is None: +- return _lst2dict( +- self.tk.split( +- self.tk.call(self._w, 'indicator', 'configure', entry))) ++ return self._getconfigure( ++ self._w, 'indicator', 'configure', entry) + self.tk.call( + self._w, 'indicator', 'configure', entry, *self._options(cnf, kw)) + +@@ -1017,9 +1001,7 @@ + + def item_configure(self, entry, col, cnf={}, **kw): + if cnf is None: +- return _lst2dict( +- self.tk.split( +- self.tk.call(self._w, 'item', 'configure', entry, col))) ++ return self._getconfigure(self._w, 'item', 'configure', entry, col) + self.tk.call(self._w, 'item', 'configure', entry, col, + *self._options(cnf, kw)) + +@@ -1038,9 +1020,7 @@ + + def entryconfigure(self, entry, cnf={}, **kw): + if cnf is None: +- return _lst2dict( +- self.tk.split( +- self.tk.call(self._w, 'entryconfigure', entry))) ++ return self._getconfigure(self._w, 'entryconfigure', entry) + self.tk.call(self._w, 'entryconfigure', entry, + *self._options(cnf, kw)) + +@@ -1255,9 +1235,7 @@ + + def paneconfigure(self, entry, cnf={}, **kw): + if cnf is None: +- return _lst2dict( +- self.tk.split( +- self.tk.call(self._w, 'paneconfigure', entry))) ++ return self._getconfigure(self._w, 'paneconfigure', entry) + self.tk.call(self._w, 'paneconfigure', entry, *self._options(cnf, kw)) + + def panes(self): +diff -r 3a1db0d2747e Lib/lib-tk/Tkinter.py +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -76,9 +76,9 @@ + else: + value = '{%s}' % _join(value) + else: +- if isinstance(value, basestring): +- value = unicode(value) +- else: ++ if isinstance(value, str): ++ value = unicode(value, 'utf-8') ++ elif not isinstance(value, unicode): + value = str(value) + if not value: + value = '{}' +@@ -223,11 +223,13 @@ + _varnum += 1 + if value is not None: + self.set(value) +- elif not self._tk.call("info", "exists", self._name): ++ elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)): + self.set(self._default) + def __del__(self): + """Unset the variable in Tcl.""" +- self._tk.globalunsetvar(self._name) ++ if (self._tk is not None and ++ self._tk.getboolean(self._tk.call("info", "exists", self._name))): ++ self._tk.globalunsetvar(self._name) + def __str__(self): + """Return the name of the variable in Tcl.""" + return self._name +@@ -1234,6 +1236,19 @@ + exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback + root = self._root() + root.report_callback_exception(exc, val, tb) ++ ++ def _getconfigure(self, *args): ++ """Call Tcl configure command and return the result as a dict.""" ++ cnf = {} ++ for x in self.tk.splitlist(self.tk.call(*args)): ++ x = self.tk.splitlist(x) ++ cnf[x[0][1:]] = (x[0][1:],) + x[1:] ++ return cnf ++ ++ def _getconfigure1(self, *args): ++ x = self.tk.splitlist(self.tk.call(*args)) ++ return (x[0][1:],) + x[1:] ++ + def _configure(self, cmd, cnf, kw): + """Internal function.""" + if kw: +@@ -1241,15 +1256,9 @@ + elif cnf: + cnf = _cnfmerge(cnf) + if cnf is None: +- cnf = {} +- for x in self.tk.split( +- self.tk.call(_flatten((self._w, cmd)))): +- cnf[x[0][1:]] = (x[0][1:],) + x[1:] +- return cnf ++ return self._getconfigure(_flatten((self._w, cmd))) + if type(cnf) is StringType: +- x = self.tk.split( +- self.tk.call(_flatten((self._w, cmd, '-'+cnf)))) +- return (x[0][1:],) + x[1:] ++ return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf))) + self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) + # These used to be defined in Widget: + def configure(self, cnf=None, **kw): +@@ -1271,8 +1280,8 @@ + raise TypeError("Tkinter objects don't support 'in' tests.") + def keys(self): + """Return a list of all resource names of this widget.""" +- return map(lambda x: x[0][1:], +- self.tk.split(self.tk.call(self._w, 'configure'))) ++ return [x[0][1:] for x in ++ self.tk.splitlist(self.tk.call(self._w, 'configure'))] + def __str__(self): + """Return the window path name of this widget.""" + return self._w +@@ -1327,6 +1336,21 @@ + return self._getints(self.tk.call(*args)) or None + + bbox = grid_bbox ++ ++ def _gridconvvalue(self, value): ++ if isinstance(value, (str, _tkinter.Tcl_Obj)): ++ try: ++ svalue = str(value) ++ if not svalue: ++ return None ++ elif '.' in svalue: ++ return getdouble(svalue) ++ else: ++ return getint(svalue) ++ except ValueError: ++ pass ++ return value ++ + def _grid_configure(self, command, index, cnf, kw): + """Internal function.""" + if type(cnf) is StringType and not kw: +@@ -1345,22 +1369,14 @@ + for i in range(0, len(words), 2): + key = words[i][1:] + value = words[i+1] +- if not value: +- value = None +- elif '.' in str(value): +- value = getdouble(value) +- else: +- value = getint(value) +- dict[key] = value ++ dict[key] = self._gridconvvalue(value) + return dict + res = self.tk.call( + ('grid', command, self._w, index) + + options) + if len(options) == 1: +- if not res: return None +- # In Tk 7.5, -width can be a float +- if '.' in res: return getdouble(res) +- return getint(res) ++ return self._gridconvvalue(res) ++ + def grid_columnconfigure(self, index, cnf={}, **kw): + """Configure column INDEX of a grid. + +@@ -1447,11 +1463,11 @@ + + def image_names(self): + """Return a list of all existing image names.""" +- return self.tk.call('image', 'names') ++ return self.tk.splitlist(self.tk.call('image', 'names')) + + def image_types(self): + """Return a list of all available image types (e.g. phote bitmap).""" +- return self.tk.call('image', 'types') ++ return self.tk.splitlist(self.tk.call('image', 'types')) + + + class CallWrapper: +@@ -1565,7 +1581,10 @@ + if len(wlist) > 1: + wlist = (wlist,) # Tk needs a list of windows here + args = ('wm', 'colormapwindows', self._w) + wlist +- return map(self._nametowidget, self.tk.call(args)) ++ if wlist: ++ self.tk.call(args) ++ else: ++ return map(self._nametowidget, self.tk.splitlist(self.tk.call(args))) + colormapwindows = wm_colormapwindows + def wm_command(self, value=None): + """Store VALUE in WM_COMMAND property. It is the command +@@ -2908,8 +2927,9 @@ + def debug(self, boolean=None): + """Turn on the internal consistency checks of the B-Tree inside the text + widget according to BOOLEAN.""" +- return self.tk.getboolean(self.tk.call( +- self._w, 'debug', boolean)) ++ if boolean is None: ++ return self.tk.getboolean(self.tk.call(self._w, 'debug')) ++ self.tk.call(self._w, 'debug', boolean) + def delete(self, index1, index2=None): + """Delete the characters between INDEX1 and INDEX2 (not included).""" + self.tk.call(self._w, 'delete', index1, index2) +@@ -3364,8 +3384,11 @@ + Valid resource names: background, data, file, foreground, maskdata, maskfile.""" + Image.__init__(self, 'bitmap', name, cnf, master, **kw) + +-def image_names(): return _default_root.tk.call('image', 'names') +-def image_types(): return _default_root.tk.call('image', 'types') ++def image_names(): ++ return _default_root.tk.splitlist(_default_root.tk.call('image', 'names')) ++ ++def image_types(): ++ return _default_root.tk.splitlist(_default_root.tk.call('image', 'types')) + + + class Spinbox(Widget, XView): +@@ -3411,7 +3434,7 @@ + bounding box may refer to a region outside the + visible area of the window. + """ +- return self.tk.call(self._w, 'bbox', index) ++ return self._getints(self.tk.call(self._w, 'bbox', index)) or None + + def delete(self, first, last=None): + """Delete one or more elements of the spinbox. +@@ -3724,23 +3747,17 @@ + + """ + if cnf is None and not kw: +- cnf = {} +- for x in self.tk.split( +- self.tk.call(self._w, +- 'paneconfigure', tagOrId)): +- cnf[x[0][1:]] = (x[0][1:],) + x[1:] +- return cnf ++ return self._getconfigure(self._w, 'paneconfigure', tagOrId) + if type(cnf) == StringType and not kw: +- x = self.tk.split(self.tk.call( +- self._w, 'paneconfigure', tagOrId, '-'+cnf)) +- return (x[0][1:],) + x[1:] ++ return self._getconfigure1( ++ self._w, 'paneconfigure', tagOrId, '-'+cnf) + self.tk.call((self._w, 'paneconfigure', tagOrId) + + self._options(cnf, kw)) + paneconfig = paneconfigure + + def panes(self): + """Returns an ordered list of the child panes.""" +- return self.tk.call(self._w, 'panes') ++ return self.tk.splitlist(self.tk.call(self._w, 'panes')) + + ###################################################################### + # Extensions: +diff -r 3a1db0d2747e Lib/lib-tk/test/test_tkinter/test_text.py +--- a/Lib/lib-tk/test/test_tkinter/test_text.py ++++ b/Lib/lib-tk/test/test_tkinter/test_text.py +@@ -14,6 +14,17 @@ + def tearDown(self): + self.text.destroy() + ++ def test_debug(self): ++ text = self.text ++ olddebug = text.debug() ++ try: ++ text.debug(0) ++ self.assertEqual(text.debug(), 0) ++ text.debug(1) ++ self.assertEqual(text.debug(), 1) ++ finally: ++ text.debug(olddebug) ++ self.assertEqual(text.debug(), olddebug) + + def test_search(self): + text = self.text +diff -r 3a1db0d2747e Lib/lib-tk/test/test_tkinter/test_variables.py +--- /dev/null ++++ b/Lib/lib-tk/test/test_tkinter/test_variables.py +@@ -0,0 +1,166 @@ ++import unittest ++ ++from Tkinter import Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tk, TclError ++ ++ ++class TestBase(unittest.TestCase): ++ ++ def setUp(self): ++ self.root = Tk() ++ ++ def tearDown(self): ++ self.root.destroy() ++ ++ ++class TestVariable(TestBase): ++ ++ def info_exists(self, *args): ++ return self.root.getboolean(self.root.call("info", "exists", *args)) ++ ++ def test_default(self): ++ v = Variable(self.root) ++ self.assertEqual("", v.get()) ++ self.assertRegexpMatches(str(v), r"^PY_VAR(\d+)$") ++ ++ def test_name_and_value(self): ++ v = Variable(self.root, "sample string", "varname") ++ self.assertEqual("sample string", v.get()) ++ self.assertEqual("varname", str(v)) ++ ++ def test___del__(self): ++ self.assertFalse(self.info_exists("varname")) ++ v = Variable(self.root, "sample string", "varname") ++ self.assertTrue(self.info_exists("varname")) ++ del v ++ self.assertFalse(self.info_exists("varname")) ++ ++ def test_dont_unset_not_existing(self): ++ self.assertFalse(self.info_exists("varname")) ++ v1 = Variable(self.root, name="name") ++ v2 = Variable(self.root, name="name") ++ del v1 ++ self.assertFalse(self.info_exists("name")) ++ # shouldn't raise exception ++ del v2 ++ self.assertFalse(self.info_exists("name")) ++ ++ def test___eq__(self): ++ # values doesn't matter, only class and name are checked ++ v1 = Variable(self.root, name="abc") ++ v2 = Variable(self.root, name="abc") ++ self.assertEqual(v1, v2) ++ ++ v3 = Variable(self.root, name="abc") ++ v4 = StringVar(self.root, name="abc") ++ self.assertNotEqual(v3, v4) ++ ++ def test_invalid_name(self): ++ with self.assertRaises(TypeError): ++ Variable(self.root, name=123) ++ ++ def test_null_in_name(self): ++ with self.assertRaises(ValueError): ++ Variable(self.root, name='var\x00name') ++ with self.assertRaises(ValueError): ++ self.root.globalsetvar('var\x00name', "value") ++ with self.assertRaises(ValueError): ++ self.root.setvar('var\x00name', "value") ++ ++ ++class TestStringVar(TestBase): ++ ++ def test_default(self): ++ v = StringVar(self.root) ++ self.assertEqual("", v.get()) ++ ++ def test_get(self): ++ v = StringVar(self.root, "abc", "name") ++ self.assertEqual("abc", v.get()) ++ self.root.globalsetvar("name", "value") ++ self.assertEqual("value", v.get()) ++ ++ def test_get_null(self): ++ v = StringVar(self.root, "abc\x00def", "name") ++ self.assertEqual("abc\x00def", v.get()) ++ self.root.globalsetvar("name", "val\x00ue") ++ self.assertEqual("val\x00ue", v.get()) ++ ++ ++class TestIntVar(TestBase): ++ ++ def test_default(self): ++ v = IntVar(self.root) ++ self.assertEqual(0, v.get()) ++ ++ def test_get(self): ++ v = IntVar(self.root, 123, "name") ++ self.assertEqual(123, v.get()) ++ self.root.globalsetvar("name", "345") ++ self.assertEqual(345, v.get()) ++ ++ def test_invalid_value(self): ++ v = IntVar(self.root, name="name") ++ self.root.globalsetvar("name", "value") ++ with self.assertRaises(ValueError): ++ v.get() ++ self.root.globalsetvar("name", "345.0") ++ with self.assertRaises(ValueError): ++ v.get() ++ ++ ++class TestDoubleVar(TestBase): ++ ++ def test_default(self): ++ v = DoubleVar(self.root) ++ self.assertEqual(0.0, v.get()) ++ ++ def test_get(self): ++ v = DoubleVar(self.root, 1.23, "name") ++ self.assertAlmostEqual(1.23, v.get()) ++ self.root.globalsetvar("name", "3.45") ++ self.assertAlmostEqual(3.45, v.get()) ++ ++ def test_get_from_int(self): ++ v = DoubleVar(self.root, 1.23, "name") ++ self.assertAlmostEqual(1.23, v.get()) ++ self.root.globalsetvar("name", "3.45") ++ self.assertAlmostEqual(3.45, v.get()) ++ self.root.globalsetvar("name", "456") ++ self.assertAlmostEqual(456, v.get()) ++ ++ def test_invalid_value(self): ++ v = DoubleVar(self.root, name="name") ++ self.root.globalsetvar("name", "value") ++ with self.assertRaises(ValueError): ++ v.get() ++ ++ ++class TestBooleanVar(TestBase): ++ ++ def test_default(self): ++ v = BooleanVar(self.root) ++ self.assertEqual(False, v.get()) ++ ++ def test_get(self): ++ v = BooleanVar(self.root, True, "name") ++ self.assertAlmostEqual(True, v.get()) ++ self.root.globalsetvar("name", "0") ++ self.assertAlmostEqual(False, v.get()) ++ ++ def test_invalid_value_domain(self): ++ v = BooleanVar(self.root, name="name") ++ self.root.globalsetvar("name", "value") ++ with self.assertRaises(TclError): ++ v.get() ++ self.root.globalsetvar("name", "1.0") ++ with self.assertRaises(TclError): ++ v.get() ++ ++ ++tests_gui = (TestVariable, TestStringVar, TestIntVar, ++ TestDoubleVar, TestBooleanVar) ++ ++ ++if __name__ == "__main__": ++ from test.support import run_unittest ++ run_unittest(*tests_gui) +diff -r 3a1db0d2747e Lib/lib-tk/test/test_tkinter/test_widgets.py +--- /dev/null ++++ b/Lib/lib-tk/test/test_tkinter/test_widgets.py +@@ -0,0 +1,952 @@ ++import unittest ++import Tkinter ++import os ++import sys ++from test.test_support import requires, run_unittest ++ ++from test_ttk.support import (tcl_version, requires_tcl, get_tk_patchlevel, ++ widget_eq) ++from widget_tests import ( ++ add_standard_options, noconv, noconv_meth, int_round, pixels_round, ++ AbstractWidgetTest, StandardOptionsTests, ++ IntegerSizeTests, PixelSizeTests, ++ setUpModule) ++ ++requires('gui') ++ ++ ++class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): ++ _conv_pad_pixels = noconv_meth ++ ++ def test_class(self): ++ widget = self.create() ++ self.assertEqual(widget['class'], ++ widget.__class__.__name__.title()) ++ self.checkInvalidParam(widget, 'class', 'Foo', ++ errmsg="can't modify -class option after widget is created") ++ widget2 = self.create(class_='Foo') ++ self.assertEqual(widget2['class'], 'Foo') ++ ++ def test_colormap(self): ++ widget = self.create() ++ self.assertEqual(widget['colormap'], '') ++ self.checkInvalidParam(widget, 'colormap', 'new', ++ errmsg="can't modify -colormap option after widget is created") ++ widget2 = self.create(colormap='new') ++ self.assertEqual(widget2['colormap'], 'new') ++ ++ def test_container(self): ++ widget = self.create() ++ self.assertEqual(widget['container'], 0 if self.wantobjects else '0') ++ self.checkInvalidParam(widget, 'container', 1, ++ errmsg="can't modify -container option after widget is created") ++ widget2 = self.create(container=True) ++ self.assertEqual(widget2['container'], 1 if self.wantobjects else '1') ++ ++ def test_visual(self): ++ widget = self.create() ++ self.assertEqual(widget['visual'], '') ++ self.checkInvalidParam(widget, 'visual', 'default', ++ errmsg="can't modify -visual option after widget is created") ++ widget2 = self.create(visual='default') ++ self.assertEqual(widget2['visual'], 'default') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class ToplevelTest(AbstractToplevelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'borderwidth', ++ 'class', 'colormap', 'container', 'cursor', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'menu', 'padx', 'pady', 'relief', 'screen', ++ 'takefocus', 'use', 'visual', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Toplevel(self.root, **kwargs) ++ ++ def test_menu(self): ++ widget = self.create() ++ menu = Tkinter.Menu(self.root) ++ self.checkParam(widget, 'menu', menu, eq=widget_eq) ++ self.checkParam(widget, 'menu', '') ++ ++ def test_screen(self): ++ widget = self.create() ++ self.assertEqual(widget['screen'], '') ++ try: ++ display = os.environ['DISPLAY'] ++ except KeyError: ++ self.skipTest('No $DISPLAY set.') ++ self.checkInvalidParam(widget, 'screen', display, ++ errmsg="can't modify -screen option after widget is created") ++ widget2 = self.create(screen=display) ++ self.assertEqual(widget2['screen'], display) ++ ++ def test_use(self): ++ widget = self.create() ++ self.assertEqual(widget['use'], '') ++ parent = self.create(container=True) ++ wid = parent.winfo_id() ++ widget2 = self.create(use=wid) ++ self.assertEqual(int(widget2['use']), wid) ++ ++ ++@add_standard_options(StandardOptionsTests) ++class FrameTest(AbstractToplevelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'borderwidth', ++ 'class', 'colormap', 'container', 'cursor', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'relief', 'takefocus', 'visual', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Frame(self.root, **kwargs) ++ ++ ++@add_standard_options(StandardOptionsTests) ++class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'borderwidth', ++ 'class', 'colormap', 'container', 'cursor', ++ 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'labelanchor', 'labelwidget', 'padx', 'pady', 'relief', ++ 'takefocus', 'text', 'visual', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.LabelFrame(self.root, **kwargs) ++ ++ def test_labelanchor(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'labelanchor', ++ 'e', 'en', 'es', 'n', 'ne', 'nw', ++ 's', 'se', 'sw', 'w', 'wn', 'ws') ++ self.checkInvalidParam(widget, 'labelanchor', 'center') ++ ++ def test_labelwidget(self): ++ widget = self.create() ++ label = Tkinter.Label(self.root, text='Mupp', name='foo') ++ self.checkParam(widget, 'labelwidget', label, expected='.foo') ++ label.destroy() ++ ++ ++class AbstractLabelTest(AbstractWidgetTest, IntegerSizeTests): ++ _conv_pixels = noconv_meth ++ ++ def test_highlightthickness(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'highlightthickness', ++ 0, 1.3, 2.6, 6, -2, '10p') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class LabelTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activeforeground', 'anchor', ++ 'background', 'bitmap', 'borderwidth', 'compound', 'cursor', ++ 'disabledforeground', 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'image', 'justify', 'padx', 'pady', 'relief', 'state', ++ 'takefocus', 'text', 'textvariable', ++ 'underline', 'width', 'wraplength', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Label(self.root, **kwargs) ++ ++ ++@add_standard_options(StandardOptionsTests) ++class ButtonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activeforeground', 'anchor', ++ 'background', 'bitmap', 'borderwidth', ++ 'command', 'compound', 'cursor', 'default', ++ 'disabledforeground', 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', ++ 'repeatdelay', 'repeatinterval', ++ 'state', 'takefocus', 'text', 'textvariable', ++ 'underline', 'width', 'wraplength') ++ ++ def _create(self, **kwargs): ++ return Tkinter.Button(self.root, **kwargs) ++ ++ def test_default(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'default', 'active', 'disabled', 'normal') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activeforeground', 'anchor', ++ 'background', 'bitmap', 'borderwidth', ++ 'command', 'compound', 'cursor', ++ 'disabledforeground', 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'image', 'indicatoron', 'justify', ++ 'offrelief', 'offvalue', 'onvalue', 'overrelief', ++ 'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state', ++ 'takefocus', 'text', 'textvariable', ++ 'tristateimage', 'tristatevalue', ++ 'underline', 'variable', 'width', 'wraplength', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Checkbutton(self.root, **kwargs) ++ ++ ++ def test_offvalue(self): ++ widget = self.create() ++ self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') ++ ++ def test_onvalue(self): ++ widget = self.create() ++ self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activeforeground', 'anchor', ++ 'background', 'bitmap', 'borderwidth', ++ 'command', 'compound', 'cursor', ++ 'disabledforeground', 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'image', 'indicatoron', 'justify', 'offrelief', 'overrelief', ++ 'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state', ++ 'takefocus', 'text', 'textvariable', ++ 'tristateimage', 'tristatevalue', ++ 'underline', 'value', 'variable', 'width', 'wraplength', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Radiobutton(self.root, **kwargs) ++ ++ def test_value(self): ++ widget = self.create() ++ self.checkParams(widget, 'value', 1, 2.3, '', 'any string') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class MenubuttonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activeforeground', 'anchor', ++ 'background', 'bitmap', 'borderwidth', ++ 'compound', 'cursor', 'direction', ++ 'disabledforeground', 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'image', 'indicatoron', 'justify', 'menu', ++ 'padx', 'pady', 'relief', 'state', ++ 'takefocus', 'text', 'textvariable', ++ 'underline', 'width', 'wraplength', ++ ) ++ _conv_pixels = staticmethod(pixels_round) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Menubutton(self.root, **kwargs) ++ ++ def test_direction(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'direction', ++ 'above', 'below', 'flush', 'left', 'right') ++ ++ def test_height(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'height', 100, -100, 0, conv=str) ++ ++ test_highlightthickness = StandardOptionsTests.test_highlightthickness.im_func ++ ++ @unittest.skipIf(sys.platform == 'darwin', ++ 'crashes with Cocoa Tk (issue19733)') ++ def test_image(self): ++ widget = self.create() ++ image = Tkinter.PhotoImage('image1') ++ self.checkParam(widget, 'image', image, conv=str) ++ errmsg = 'image "spam" doesn\'t exist' ++ with self.assertRaises(Tkinter.TclError) as cm: ++ widget['image'] = 'spam' ++ if errmsg is not None: ++ self.assertEqual(str(cm.exception), errmsg) ++ with self.assertRaises(Tkinter.TclError) as cm: ++ widget.configure({'image': 'spam'}) ++ if errmsg is not None: ++ self.assertEqual(str(cm.exception), errmsg) ++ ++ def test_menu(self): ++ widget = self.create() ++ menu = Tkinter.Menu(widget, name='menu') ++ self.checkParam(widget, 'menu', menu, eq=widget_eq) ++ menu.destroy() ++ ++ def test_padx(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, '12m') ++ self.checkParam(widget, 'padx', -2, expected=0) ++ ++ def test_pady(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, '12m') ++ self.checkParam(widget, 'pady', -2, expected=0) ++ ++ def test_width(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'width', 402, -402, 0, conv=str) ++ ++ ++class OptionMenuTest(MenubuttonTest, unittest.TestCase): ++ ++ def _create(self, default='b', values=('a', 'b', 'c'), **kwargs): ++ return Tkinter.OptionMenu(self.root, None, default, *values, **kwargs) ++ ++ ++@add_standard_options(IntegerSizeTests, StandardOptionsTests) ++class EntryTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'borderwidth', 'cursor', ++ 'disabledbackground', 'disabledforeground', ++ 'exportselection', 'font', 'foreground', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'insertbackground', 'insertborderwidth', ++ 'insertofftime', 'insertontime', 'insertwidth', ++ 'invalidcommand', 'justify', 'readonlybackground', 'relief', ++ 'selectbackground', 'selectborderwidth', 'selectforeground', ++ 'show', 'state', 'takefocus', 'textvariable', ++ 'validate', 'validatecommand', 'width', 'xscrollcommand', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Entry(self.root, **kwargs) ++ ++ def test_disabledbackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'disabledbackground') ++ ++ def test_insertborderwidth(self): ++ widget = self.create(insertwidth=100) ++ self.checkPixelsParam(widget, 'insertborderwidth', ++ 0, 1.3, 2.6, 6, -2, '10p') ++ # insertborderwidth is bounded above by a half of insertwidth. ++ self.checkParam(widget, 'insertborderwidth', 60, expected=100//2) ++ ++ def test_insertwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'insertwidth', 1.3, 3.6, '10p') ++ self.checkParam(widget, 'insertwidth', 0.1, expected=2) ++ self.checkParam(widget, 'insertwidth', -2, expected=2) ++ if pixels_round(0.9) <= 0: ++ self.checkParam(widget, 'insertwidth', 0.9, expected=2) ++ else: ++ self.checkParam(widget, 'insertwidth', 0.9, expected=1) ++ ++ def test_invalidcommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'invalidcommand') ++ self.checkCommandParam(widget, 'invcmd') ++ ++ def test_readonlybackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'readonlybackground') ++ ++ def test_show(self): ++ widget = self.create() ++ self.checkParam(widget, 'show', '*') ++ self.checkParam(widget, 'show', '') ++ self.checkParam(widget, 'show', ' ') ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'state', ++ 'disabled', 'normal', 'readonly') ++ ++ def test_validate(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'validate', ++ 'all', 'key', 'focus', 'focusin', 'focusout', 'none') ++ ++ def test_validatecommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'validatecommand') ++ self.checkCommandParam(widget, 'vcmd') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class SpinboxTest(EntryTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'background', 'borderwidth', ++ 'buttonbackground', 'buttoncursor', 'buttondownrelief', 'buttonuprelief', ++ 'command', 'cursor', 'disabledbackground', 'disabledforeground', ++ 'exportselection', 'font', 'foreground', 'format', 'from', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'increment', ++ 'insertbackground', 'insertborderwidth', ++ 'insertofftime', 'insertontime', 'insertwidth', ++ 'invalidcommand', 'justify', 'relief', 'readonlybackground', ++ 'repeatdelay', 'repeatinterval', ++ 'selectbackground', 'selectborderwidth', 'selectforeground', ++ 'state', 'takefocus', 'textvariable', 'to', ++ 'validate', 'validatecommand', 'values', ++ 'width', 'wrap', 'xscrollcommand', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Spinbox(self.root, **kwargs) ++ ++ test_show = None ++ ++ def test_buttonbackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'buttonbackground') ++ ++ def test_buttoncursor(self): ++ widget = self.create() ++ self.checkCursorParam(widget, 'buttoncursor') ++ ++ def test_buttondownrelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'buttondownrelief') ++ ++ def test_buttonuprelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'buttonuprelief') ++ ++ def test_format(self): ++ widget = self.create() ++ self.checkParam(widget, 'format', '%2f') ++ self.checkParam(widget, 'format', '%2.2f') ++ self.checkParam(widget, 'format', '%.2f') ++ self.checkParam(widget, 'format', '%2.f') ++ self.checkInvalidParam(widget, 'format', '%2e-1f') ++ self.checkInvalidParam(widget, 'format', '2.2') ++ self.checkInvalidParam(widget, 'format', '%2.-2f') ++ self.checkParam(widget, 'format', '%-2.02f') ++ self.checkParam(widget, 'format', '% 2.02f') ++ self.checkParam(widget, 'format', '% -2.200f') ++ self.checkParam(widget, 'format', '%09.200f') ++ self.checkInvalidParam(widget, 'format', '%d') ++ ++ def test_from(self): ++ widget = self.create() ++ self.checkParam(widget, 'to', 100.0) ++ self.checkFloatParam(widget, 'from', -10, 10.2, 11.7) ++ self.checkInvalidParam(widget, 'from', 200, ++ errmsg='-to value must be greater than -from value') ++ ++ def test_increment(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'increment', -1, 1, 10.2, 12.8, 0) ++ ++ def test_to(self): ++ widget = self.create() ++ self.checkParam(widget, 'from', -100.0) ++ self.checkFloatParam(widget, 'to', -10, 10.2, 11.7) ++ self.checkInvalidParam(widget, 'to', -200, ++ errmsg='-to value must be greater than -from value') ++ ++ def test_values(self): ++ # XXX ++ widget = self.create() ++ self.assertEqual(widget['values'], '') ++ self.checkParam(widget, 'values', 'mon tue wed thur') ++ self.checkParam(widget, 'values', ('mon', 'tue', 'wed', 'thur'), ++ expected='mon tue wed thur') ++ self.checkParam(widget, 'values', (42, 3.14, '', 'any string'), ++ expected='42 3.14 {} {any string}') ++ self.checkParam(widget, 'values', '') ++ ++ def test_wrap(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'wrap') ++ ++ def test_bbox(self): ++ widget = self.create() ++ bbox = widget.bbox(0) ++ self.assertEqual(len(bbox), 4) ++ for item in bbox: ++ self.assertIsInstance(item, int) ++ ++ self.assertRaises(Tkinter.TclError, widget.bbox, 'noindex') ++ self.assertRaises(Tkinter.TclError, widget.bbox, None) ++ self.assertRaises(TypeError, widget.bbox) ++ self.assertRaises(TypeError, widget.bbox, 0, 1) ++ ++ ++@add_standard_options(StandardOptionsTests) ++class TextTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'autoseparators', 'background', 'blockcursor', 'borderwidth', ++ 'cursor', 'endline', 'exportselection', ++ 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'inactiveselectbackground', 'insertbackground', 'insertborderwidth', ++ 'insertofftime', 'insertontime', 'insertunfocussed', 'insertwidth', ++ 'maxundo', 'padx', 'pady', 'relief', ++ 'selectbackground', 'selectborderwidth', 'selectforeground', ++ 'setgrid', 'spacing1', 'spacing2', 'spacing3', 'startline', 'state', ++ 'tabs', 'tabstyle', 'takefocus', 'undo', 'width', 'wrap', ++ 'xscrollcommand', 'yscrollcommand', ++ ) ++ if tcl_version < (8, 5): ++ wantobjects = False ++ ++ def _create(self, **kwargs): ++ return Tkinter.Text(self.root, **kwargs) ++ ++ def test_autoseparators(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'autoseparators') ++ ++ @requires_tcl(8, 5) ++ def test_blockcursor(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'blockcursor') ++ ++ @requires_tcl(8, 5) ++ def test_endline(self): ++ widget = self.create() ++ text = '\n'.join('Line %d' for i in range(100)) ++ widget.insert('end', text) ++ self.checkParam(widget, 'endline', 200, expected='') ++ self.checkParam(widget, 'endline', -10, expected='') ++ self.checkInvalidParam(widget, 'endline', 'spam', ++ errmsg='expected integer but got "spam"') ++ self.checkParam(widget, 'endline', 50) ++ self.checkParam(widget, 'startline', 15) ++ self.checkInvalidParam(widget, 'endline', 10, ++ errmsg='-startline must be less than or equal to -endline') ++ ++ def test_height(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, '3c') ++ self.checkParam(widget, 'height', -100, expected=1) ++ self.checkParam(widget, 'height', 0, expected=1) ++ ++ def test_maxundo(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'maxundo', 0, 5, -1) ++ ++ @requires_tcl(8, 5) ++ def test_inactiveselectbackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'inactiveselectbackground') ++ ++ @requires_tcl(8, 6) ++ def test_insertunfocussed(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'insertunfocussed', ++ 'hollow', 'none', 'solid') ++ ++ def test_selectborderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'selectborderwidth', ++ 1.3, 2.6, -2, '10p', conv=noconv, ++ keep_orig=tcl_version >= (8, 5)) ++ ++ def test_spacing1(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'spacing1', 20, 21.4, 22.6, '0.5c') ++ self.checkParam(widget, 'spacing1', -5, expected=0) ++ ++ def test_spacing2(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'spacing2', 5, 6.4, 7.6, '0.1c') ++ self.checkParam(widget, 'spacing2', -1, expected=0) ++ ++ def test_spacing3(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'spacing3', 20, 21.4, 22.6, '0.5c') ++ self.checkParam(widget, 'spacing3', -10, expected=0) ++ ++ @requires_tcl(8, 5) ++ def test_startline(self): ++ widget = self.create() ++ text = '\n'.join('Line %d' for i in range(100)) ++ widget.insert('end', text) ++ self.checkParam(widget, 'startline', 200, expected='') ++ self.checkParam(widget, 'startline', -10, expected='') ++ self.checkInvalidParam(widget, 'startline', 'spam', ++ errmsg='expected integer but got "spam"') ++ self.checkParam(widget, 'startline', 10) ++ self.checkParam(widget, 'endline', 50) ++ self.checkInvalidParam(widget, 'startline', 70, ++ errmsg='-startline must be less than or equal to -endline') ++ ++ def test_state(self): ++ widget = self.create() ++ if tcl_version < (8, 5): ++ self.checkParams(widget, 'state', 'disabled', 'normal') ++ else: ++ self.checkEnumParam(widget, 'state', 'disabled', 'normal') ++ ++ def test_tabs(self): ++ widget = self.create() ++ if get_tk_patchlevel() < (8, 5, 11): ++ self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i'), ++ expected=('10.2', '20.7', '1i', '2i')) ++ else: ++ self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i')) ++ self.checkParam(widget, 'tabs', '10.2 20.7 1i 2i', ++ expected=('10.2', '20.7', '1i', '2i')) ++ self.checkParam(widget, 'tabs', '2c left 4c 6c center', ++ expected=('2c', 'left', '4c', '6c', 'center')) ++ self.checkInvalidParam(widget, 'tabs', 'spam', ++ errmsg='bad screen distance "spam"', ++ keep_orig=tcl_version >= (8, 5)) ++ ++ @requires_tcl(8, 5) ++ def test_tabstyle(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'tabstyle', 'tabular', 'wordprocessor') ++ ++ def test_undo(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'undo') ++ ++ def test_width(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'width', 402) ++ self.checkParam(widget, 'width', -402, expected=1) ++ self.checkParam(widget, 'width', 0, expected=1) ++ ++ def test_wrap(self): ++ widget = self.create() ++ if tcl_version < (8, 5): ++ self.checkParams(widget, 'wrap', 'char', 'none', 'word') ++ else: ++ self.checkEnumParam(widget, 'wrap', 'char', 'none', 'word') ++ ++ def test_bbox(self): ++ widget = self.create() ++ bbox = widget.bbox('1.1') ++ self.assertEqual(len(bbox), 4) ++ for item in bbox: ++ self.assertIsInstance(item, int) ++ ++ self.assertIsNone(widget.bbox('end')) ++ self.assertRaises(Tkinter.TclError, widget.bbox, 'noindex') ++ self.assertRaises(Tkinter.TclError, widget.bbox, None) ++ self.assertRaises(Tkinter.TclError, widget.bbox) ++ self.assertRaises(Tkinter.TclError, widget.bbox, '1.1', 'end') ++ ++ ++@add_standard_options(PixelSizeTests, StandardOptionsTests) ++class CanvasTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'borderwidth', ++ 'closeenough', 'confine', 'cursor', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'insertbackground', 'insertborderwidth', ++ 'insertofftime', 'insertontime', 'insertwidth', ++ 'relief', 'scrollregion', ++ 'selectbackground', 'selectborderwidth', 'selectforeground', ++ 'state', 'takefocus', ++ 'xscrollcommand', 'xscrollincrement', ++ 'yscrollcommand', 'yscrollincrement', 'width', ++ ) ++ ++ _conv_pixels = staticmethod(int_round) ++ wantobjects = False ++ ++ def _create(self, **kwargs): ++ return Tkinter.Canvas(self.root, **kwargs) ++ ++ def test_closeenough(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'closeenough', 24, 2.4, 3.6, -3, ++ conv=float) ++ ++ def test_confine(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'confine') ++ ++ def test_scrollregion(self): ++ widget = self.create() ++ self.checkParam(widget, 'scrollregion', '0 0 200 150') ++ self.checkParam(widget, 'scrollregion', (0, 0, 200, 150), ++ expected='0 0 200 150') ++ self.checkParam(widget, 'scrollregion', '') ++ self.checkInvalidParam(widget, 'scrollregion', 'spam', ++ errmsg='bad scrollRegion "spam"') ++ self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 'spam')) ++ self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200)) ++ self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 150, 0)) ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'state', 'disabled', 'normal', ++ errmsg='bad state value "{}": must be normal or disabled') ++ ++ def test_xscrollincrement(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'xscrollincrement', ++ 40, 0, 41.2, 43.6, -40, '0.5i') ++ ++ def test_yscrollincrement(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'yscrollincrement', ++ 10, 0, 11.2, 13.6, -10, '0.1i') ++ ++ ++@add_standard_options(IntegerSizeTests, StandardOptionsTests) ++class ListboxTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activestyle', 'background', 'borderwidth', 'cursor', ++ 'disabledforeground', 'exportselection', ++ 'font', 'foreground', 'height', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'listvariable', 'relief', ++ 'selectbackground', 'selectborderwidth', 'selectforeground', ++ 'selectmode', 'setgrid', 'state', ++ 'takefocus', 'width', 'xscrollcommand', 'yscrollcommand', ++ ) ++ ++ def _create(self, **kwargs): ++ return Tkinter.Listbox(self.root, **kwargs) ++ ++ def test_activestyle(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'activestyle', ++ 'dotbox', 'none', 'underline') ++ ++ def test_listvariable(self): ++ widget = self.create() ++ var = Tkinter.DoubleVar() ++ self.checkVariableParam(widget, 'listvariable', var) ++ ++ def test_selectmode(self): ++ widget = self.create() ++ self.checkParam(widget, 'selectmode', 'single') ++ self.checkParam(widget, 'selectmode', 'browse') ++ self.checkParam(widget, 'selectmode', 'multiple') ++ self.checkParam(widget, 'selectmode', 'extended') ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'state', 'disabled', 'normal') ++ ++@add_standard_options(PixelSizeTests, StandardOptionsTests) ++class ScaleTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'background', 'bigincrement', 'borderwidth', ++ 'command', 'cursor', 'digits', 'font', 'foreground', 'from', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'label', 'length', 'orient', 'relief', ++ 'repeatdelay', 'repeatinterval', ++ 'resolution', 'showvalue', 'sliderlength', 'sliderrelief', 'state', ++ 'takefocus', 'tickinterval', 'to', 'troughcolor', 'variable', 'width', ++ ) ++ default_orient = 'vertical' ++ ++ def _create(self, **kwargs): ++ return Tkinter.Scale(self.root, **kwargs) ++ ++ def test_bigincrement(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'bigincrement', 12.4, 23.6, -5) ++ ++ def test_digits(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'digits', 5, 0) ++ ++ def test_from(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=round) ++ ++ def test_label(self): ++ widget = self.create() ++ self.checkParam(widget, 'label', 'any string') ++ self.checkParam(widget, 'label', '') ++ ++ def test_length(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') ++ ++ def test_resolution(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'resolution', 4.2, 0, 6.7, -2) ++ ++ def test_showvalue(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'showvalue') ++ ++ def test_sliderlength(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'sliderlength', ++ 10, 11.2, 15.6, -3, '3m') ++ ++ def test_sliderrelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'sliderrelief') ++ ++ def test_tickinterval(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'tickinterval', 1, 4.3, 7.6, 0, ++ conv=round) ++ self.checkParam(widget, 'tickinterval', -2, expected=2, ++ conv=round) ++ ++ def test_to(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, ++ conv=round) ++ ++ ++@add_standard_options(PixelSizeTests, StandardOptionsTests) ++class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activerelief', ++ 'background', 'borderwidth', ++ 'command', 'cursor', 'elementborderwidth', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'jump', 'orient', 'relief', ++ 'repeatdelay', 'repeatinterval', ++ 'takefocus', 'troughcolor', 'width', ++ ) ++ _conv_pixels = staticmethod(int_round) ++ wantobjects = False ++ default_orient = 'vertical' ++ ++ def _create(self, **kwargs): ++ return Tkinter.Scrollbar(self.root, **kwargs) ++ ++ def test_activerelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'activerelief') ++ ++ def test_elementborderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'elementborderwidth', 4.3, 5.6, -2, '1m') ++ ++ def test_orient(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'orient', 'vertical', 'horizontal', ++ errmsg='bad orientation "{}": must be vertical or horizontal') ++ ++ ++@add_standard_options(StandardOptionsTests) ++class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'borderwidth', 'cursor', ++ 'handlepad', 'handlesize', 'height', ++ 'opaqueresize', 'orient', 'relief', ++ 'sashcursor', 'sashpad', 'sashrelief', 'sashwidth', ++ 'showhandle', 'width', ++ ) ++ default_orient = 'horizontal' ++ ++ def _create(self, **kwargs): ++ return Tkinter.PanedWindow(self.root, **kwargs) ++ ++ def test_handlepad(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'handlepad', 5, 6.4, 7.6, -3, '1m') ++ ++ def test_handlesize(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'handlesize', 8, 9.4, 10.6, -3, '2m', ++ conv=noconv) ++ ++ def test_height(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i', ++ conv=noconv) ++ ++ def test_opaqueresize(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'opaqueresize') ++ ++ def test_sashcursor(self): ++ widget = self.create() ++ self.checkCursorParam(widget, 'sashcursor') ++ ++ def test_sashpad(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'sashpad', 8, 1.3, 2.6, -2, '2m') ++ ++ def test_sashrelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'sashrelief') ++ ++ def test_sashwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'sashwidth', 10, 11.1, 15.6, -3, '1m', ++ conv=noconv) ++ ++ def test_showhandle(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'showhandle') ++ ++ def test_width(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i', ++ conv=noconv) ++ ++ ++@add_standard_options(StandardOptionsTests) ++class MenuTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'activebackground', 'activeborderwidth', 'activeforeground', ++ 'background', 'borderwidth', 'cursor', ++ 'disabledforeground', 'font', 'foreground', ++ 'postcommand', 'relief', 'selectcolor', 'takefocus', ++ 'tearoff', 'tearoffcommand', 'title', 'type', ++ ) ++ _conv_pixels = noconv_meth ++ ++ def _create(self, **kwargs): ++ return Tkinter.Menu(self.root, **kwargs) ++ ++ def test_postcommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'postcommand') ++ ++ def test_tearoff(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'tearoff') ++ ++ def test_tearoffcommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'tearoffcommand') ++ ++ def test_title(self): ++ widget = self.create() ++ self.checkParam(widget, 'title', 'any string') ++ ++ def test_type(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'type', ++ 'normal', 'tearoff', 'menubar') ++ ++ ++@add_standard_options(PixelSizeTests, StandardOptionsTests) ++class MessageTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'anchor', 'aspect', 'background', 'borderwidth', ++ 'cursor', 'font', 'foreground', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'justify', 'padx', 'pady', 'relief', ++ 'takefocus', 'text', 'textvariable', 'width', ++ ) ++ _conv_pad_pixels = noconv_meth ++ ++ def _create(self, **kwargs): ++ return Tkinter.Message(self.root, **kwargs) ++ ++ def test_aspect(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'aspect', 250, 0, -300) ++ ++ ++tests_gui = [ ++ ButtonTest, CanvasTest, CheckbuttonTest, EntryTest, ++ FrameTest, LabelFrameTest,LabelTest, ListboxTest, ++ MenubuttonTest, MenuTest, MessageTest, OptionMenuTest, ++ PanedWindowTest, RadiobuttonTest, ScaleTest, ScrollbarTest, ++ SpinboxTest, TextTest, ToplevelTest, ++] ++ ++if __name__ == '__main__': ++ run_unittest(*tests_gui) +diff -r 3a1db0d2747e Lib/lib-tk/test/test_ttk/support.py +--- a/Lib/lib-tk/test/test_ttk/support.py ++++ b/Lib/lib-tk/test/test_ttk/support.py +@@ -1,3 +1,4 @@ ++import unittest + import Tkinter + + def get_tk_root(): +@@ -31,3 +32,57 @@ + widget.event_generate('', x=x, y=y) + widget.event_generate('', x=x, y=y) + widget.event_generate('', x=x, y=y) ++ ++ ++import _tkinter ++tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) ++ ++def requires_tcl(*version): ++ return unittest.skipUnless(tcl_version >= version, ++ 'requires Tcl version >= ' + '.'.join(map(str, version))) ++ ++_tk_patchlevel = None ++def get_tk_patchlevel(): ++ global _tk_patchlevel ++ if _tk_patchlevel is None: ++ tcl = Tkinter.Tcl() ++ patchlevel = [] ++ for x in tcl.call('info', 'patchlevel').split('.'): ++ try: ++ x = int(x, 10) ++ except ValueError: ++ x = -1 ++ patchlevel.append(x) ++ _tk_patchlevel = tuple(patchlevel) ++ return _tk_patchlevel ++ ++units = { ++ 'c': 72 / 2.54, # centimeters ++ 'i': 72, # inches ++ 'm': 72 / 25.4, # millimeters ++ 'p': 1, # points ++} ++ ++def pixels_conv(value): ++ return float(value[:-1]) * units[value[-1:]] ++ ++def tcl_obj_eq(actual, expected): ++ if actual == expected: ++ return True ++ if isinstance(actual, _tkinter.Tcl_Obj): ++ if isinstance(expected, str): ++ return str(actual) == expected ++ if isinstance(actual, tuple): ++ if isinstance(expected, tuple): ++ return (len(actual) == len(expected) and ++ all(tcl_obj_eq(act, exp) ++ for act, exp in zip(actual, expected))) ++ return False ++ ++def widget_eq(actual, expected): ++ if actual == expected: ++ return True ++ if isinstance(actual, (str, Tkinter.Widget)): ++ if isinstance(expected, (str, Tkinter.Widget)): ++ return str(actual) == str(expected) ++ return False +diff -r 3a1db0d2747e Lib/lib-tk/test/test_ttk/test_extensions.py +--- a/Lib/lib-tk/test/test_ttk/test_extensions.py ++++ b/Lib/lib-tk/test/test_ttk/test_extensions.py +@@ -29,7 +29,10 @@ + name = myvar._name + x = ttk.LabeledScale(variable=myvar) + x.destroy() +- self.assertEqual(x.tk.globalgetvar(name), myvar.get()) ++ if x.tk.wantobjects(): ++ self.assertEqual(x.tk.globalgetvar(name), myvar.get()) ++ else: ++ self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get()) + del myvar + self.assertRaises(Tkinter.TclError, x.tk.globalgetvar, name) + +@@ -45,7 +48,7 @@ + # it tries calling instance attributes not yet defined. + ttk.LabeledScale(variable=myvar) + if hasattr(sys, 'last_type'): +- self.assertFalse(sys.last_type == Tkinter.TclError) ++ self.assertNotEqual(sys.last_type, Tkinter.TclError) + + + def test_initialization(self): +@@ -59,8 +62,10 @@ + x.destroy() + + # variable initialization/passing +- passed_expected = ((2.5, 2), ('0', 0), (0, 0), (10, 10), ++ passed_expected = (('0', 0), (0, 0), (10, 10), + (-1, -1), (sys.maxint + 1, sys.maxint + 1)) ++ if x.tk.wantobjects(): ++ passed_expected += ((2.5, 2),) + for pair in passed_expected: + x = ttk.LabeledScale(from_=pair[0]) + self.assertEqual(x.value, pair[1]) +@@ -120,14 +125,14 @@ + # at the same time this shouldn't affect test outcome + lscale.update() + curr_xcoord = lscale.scale.coords()[0] +- self.assertTrue(prev_xcoord != curr_xcoord) ++ self.assertNotEqual(prev_xcoord, curr_xcoord) + # the label widget should have been repositioned too + linfo_2 = lscale.label.place_info() +- self.assertEqual(lscale.label['text'], 0) ++ self.assertEqual(lscale.label['text'], 0 if lscale.tk.wantobjects() else '0') + self.assertEqual(curr_xcoord, int(linfo_2['x'])) + # change the range back + lscale.scale.configure(from_=0, to=10) +- self.assertTrue(prev_xcoord != curr_xcoord) ++ self.assertNotEqual(prev_xcoord, curr_xcoord) + self.assertEqual(prev_xcoord, int(linfo_1['x'])) + + lscale.destroy() +@@ -145,15 +150,20 @@ + # The following update is needed since the test doesn't use mainloop, + # at the same time this shouldn't affect test outcome + x.update() +- self.assertEqual(x.label['text'], newval) +- self.assertTrue(x.scale.coords()[0] > curr_xcoord) ++ self.assertEqual(x.label['text'], ++ newval if x.tk.wantobjects() else str(newval)) ++ self.assertGreater(x.scale.coords()[0], curr_xcoord) + self.assertEqual(x.scale.coords()[0], + int(x.label.place_info()['x'])) + + # value outside range +- x.value = x.scale['to'] + 1 # no changes shouldn't happen ++ if x.tk.wantobjects(): ++ conv = lambda x: x ++ else: ++ conv = int ++ x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen + x.update() +- self.assertEqual(x.label['text'], newval) ++ self.assertEqual(conv(x.label['text']), newval) + self.assertEqual(x.scale.coords()[0], + int(x.label.place_info()['x'])) + +@@ -238,7 +248,7 @@ + if last == curr: + # no more menu entries + break +- self.assertFalse(curr == default) ++ self.assertNotEqual(curr, default) + i += 1 + self.assertEqual(i, len(items)) + +diff -r 3a1db0d2747e Lib/lib-tk/test/test_ttk/test_functions.py +--- a/Lib/lib-tk/test/test_ttk/test_functions.py ++++ b/Lib/lib-tk/test/test_ttk/test_functions.py +@@ -394,8 +394,10 @@ + ('name', 'no_minus', 'value')) + self.assertRaises(ValueError, ttk._list_from_layouttuple, + ('something', '-children')) # no children +- self.assertRaises(ValueError, ttk._list_from_layouttuple, +- ('something', '-children', 'value')) # invalid children ++ import Tkinter ++ if not Tkinter._default_root or Tkinter._default_root.wantobjects(): ++ self.assertRaises(ValueError, ttk._list_from_layouttuple, ++ ('something', '-children', 'value')) # invalid children + + + def test_val_or_dict(self): +diff -r 3a1db0d2747e Lib/lib-tk/test/test_ttk/test_style.py +--- a/Lib/lib-tk/test/test_ttk/test_style.py ++++ b/Lib/lib-tk/test/test_ttk/test_style.py +@@ -18,15 +18,16 @@ + style.configure('TButton', background='yellow') + self.assertEqual(style.configure('TButton', 'background'), + 'yellow') +- self.assertTrue(isinstance(style.configure('TButton'), dict)) ++ self.assertIsInstance(style.configure('TButton'), dict) + + + def test_map(self): + style = self.style + style.map('TButton', background=[('active', 'background', 'blue')]) + self.assertEqual(style.map('TButton', 'background'), +- [('active', 'background', 'blue')]) +- self.assertTrue(isinstance(style.map('TButton'), dict)) ++ [('active', 'background', 'blue')] if style.tk.wantobjects() else ++ [('active background', 'blue')]) ++ self.assertIsInstance(style.map('TButton'), dict) + + + def test_lookup(self): +@@ -57,7 +58,7 @@ + self.assertEqual(style.layout('Treeview'), tv_style) + + # should return a list +- self.assertTrue(isinstance(style.layout('TButton'), list)) ++ self.assertIsInstance(style.layout('TButton'), list) + + # correct layout, but "option" doesn't exist as option + self.assertRaises(Tkinter.TclError, style.layout, 'Treeview', +diff -r 3a1db0d2747e Lib/lib-tk/test/test_ttk/test_widgets.py +--- a/Lib/lib-tk/test/test_ttk/test_widgets.py ++++ b/Lib/lib-tk/test/test_ttk/test_widgets.py +@@ -6,9 +6,54 @@ + + import support + from test_functions import MockTclObj, MockStateSpec ++from support import tcl_version, get_tk_patchlevel ++from widget_tests import (add_standard_options, noconv, noconv_meth, ++ AbstractWidgetTest, StandardOptionsTests, ++ IntegerSizeTests, PixelSizeTests, ++ setUpModule) + + requires('gui') + ++ ++class StandardTtkOptionsTests(StandardOptionsTests): ++ ++ def test_class(self): ++ widget = self.create() ++ self.assertEqual(widget['class'], '') ++ errmsg='attempt to change read-only option' ++ if get_tk_patchlevel() < (8, 6, 0): # actually this was changed in 8.6b3 ++ errmsg='Attempt to change read-only option' ++ self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg) ++ widget2 = self.create(class_='Foo') ++ self.assertEqual(widget2['class'], 'Foo') ++ ++ def test_padding(self): ++ widget = self.create() ++ self.checkParam(widget, 'padding', 0, expected=('0',)) ++ self.checkParam(widget, 'padding', 5, expected=('5',)) ++ self.checkParam(widget, 'padding', (5, 6), expected=('5', '6')) ++ self.checkParam(widget, 'padding', (5, 6, 7), ++ expected=('5', '6', '7')) ++ self.checkParam(widget, 'padding', (5, 6, 7, 8), ++ expected=('5', '6', '7', '8')) ++ self.checkParam(widget, 'padding', ('5p', '6p', '7p', '8p')) ++ self.checkParam(widget, 'padding', (), expected='') ++ ++ def test_style(self): ++ widget = self.create() ++ self.assertEqual(widget['style'], '') ++ errmsg = 'Layout Foo not found' ++ if hasattr(self, 'default_orient'): ++ errmsg = ('Layout %s.Foo not found' % ++ getattr(self, 'default_orient').title()) ++ self.checkInvalidParam(widget, 'style', 'Foo', ++ errmsg=errmsg) ++ widget2 = self.create(class_='Foo') ++ self.assertEqual(widget2['class'], 'Foo') ++ # XXX ++ pass ++ ++ + class WidgetTest(unittest.TestCase): + """Tests methods available in every ttk widget.""" + +@@ -72,7 +117,112 @@ + self.assertEqual(self.widget.state(), ('active', )) + + +-class ButtonTest(unittest.TestCase): ++class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): ++ _conv_pixels = noconv_meth ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class FrameTest(AbstractToplevelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'borderwidth', 'class', 'cursor', 'height', ++ 'padding', 'relief', 'style', 'takefocus', ++ 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return ttk.Frame(self.root, **kwargs) ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'borderwidth', 'class', 'cursor', 'height', ++ 'labelanchor', 'labelwidget', ++ 'padding', 'relief', 'style', 'takefocus', ++ 'text', 'underline', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return ttk.LabelFrame(self.root, **kwargs) ++ ++ def test_labelanchor(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'labelanchor', ++ 'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws', ++ errmsg='Bad label anchor specification {}') ++ self.checkInvalidParam(widget, 'labelanchor', 'center') ++ ++ def test_labelwidget(self): ++ widget = self.create() ++ label = ttk.Label(self.root, text='Mupp', name='foo') ++ self.checkParam(widget, 'labelwidget', label, expected='.foo') ++ label.destroy() ++ ++ ++class AbstractLabelTest(AbstractWidgetTest): ++ ++ def checkImageParam(self, widget, name): ++ image = Tkinter.PhotoImage('image1') ++ image2 = Tkinter.PhotoImage('image2') ++ self.checkParam(widget, name, image, expected=('image1',)) ++ self.checkParam(widget, name, 'image1', expected=('image1',)) ++ self.checkParam(widget, name, (image,), expected=('image1',)) ++ self.checkParam(widget, name, (image, 'active', image2), ++ expected=('image1', 'active', 'image2')) ++ self.checkParam(widget, name, 'image1 active image2', ++ expected=('image1', 'active', 'image2')) ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='image "spam" doesn\'t exist') ++ ++ def test_compound(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'compound', ++ 'none', 'text', 'image', 'center', ++ 'top', 'bottom', 'left', 'right') ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkParams(widget, 'state', 'active', 'disabled', 'normal') ++ ++ def test_width(self): ++ widget = self.create() ++ self.checkParams(widget, 'width', 402, -402, 0) ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class LabelTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'anchor', 'background', ++ 'class', 'compound', 'cursor', 'font', 'foreground', ++ 'image', 'justify', 'padding', 'relief', 'state', 'style', ++ 'takefocus', 'text', 'textvariable', ++ 'underline', 'width', 'wraplength', ++ ) ++ _conv_pixels = noconv_meth ++ ++ def _create(self, **kwargs): ++ return ttk.Label(self.root, **kwargs) ++ ++ def test_font(self): ++ widget = self.create() ++ self.checkParam(widget, 'font', ++ '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*') ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class ButtonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'command', 'compound', 'cursor', 'default', ++ 'image', 'state', 'style', 'takefocus', 'text', 'textvariable', ++ 'underline', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return ttk.Button(self.root, **kwargs) ++ ++ def test_default(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'default', 'normal', 'active', 'disabled') + + def test_invoke(self): + success = [] +@@ -81,7 +231,27 @@ + self.assertTrue(success) + + +-class CheckbuttonTest(unittest.TestCase): ++@add_standard_options(StandardTtkOptionsTests) ++class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'command', 'compound', 'cursor', ++ 'image', ++ 'offvalue', 'onvalue', ++ 'state', 'style', ++ 'takefocus', 'text', 'textvariable', ++ 'underline', 'variable', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return ttk.Checkbutton(self.root, **kwargs) ++ ++ def test_offvalue(self): ++ widget = self.create() ++ self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') ++ ++ def test_onvalue(self): ++ widget = self.create() ++ self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') + + def test_invoke(self): + success = [] +@@ -104,21 +274,40 @@ + + cbtn['command'] = '' + res = cbtn.invoke() +- self.assertEqual(str(res), '') +- self.assertFalse(len(success) > 1) ++ self.assertFalse(str(res)) ++ self.assertLessEqual(len(success), 1) + self.assertEqual(cbtn['offvalue'], + cbtn.tk.globalgetvar(cbtn['variable'])) + + +-class ComboboxTest(unittest.TestCase): ++@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) ++class ComboboxTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'cursor', 'exportselection', 'height', ++ 'justify', 'postcommand', 'state', 'style', ++ 'takefocus', 'textvariable', 'values', 'width', ++ ) + + def setUp(self): ++ super(ComboboxTest, self).setUp() + support.root_deiconify() +- self.combo = ttk.Combobox() ++ self.combo = self.create() + + def tearDown(self): + self.combo.destroy() + support.root_withdraw() ++ super(ComboboxTest, self).tearDown() ++ ++ def _create(self, **kwargs): ++ return ttk.Combobox(self.root, **kwargs) ++ ++ def test_height(self): ++ widget = self.create() ++ self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i') ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkParams(widget, 'state', 'active', 'disabled', 'normal') + + def _show_drop_down_listbox(self): + width = self.combo.winfo_width() +@@ -166,8 +355,16 @@ + self.assertEqual(self.combo.get(), getval) + self.assertEqual(self.combo.current(), currval) + ++ self.assertEqual(self.combo['values'], ++ () if tcl_version < (8, 5) else '') + check_get_current('', -1) + ++ self.checkParam(self.combo, 'values', 'mon tue wed thur', ++ expected=('mon', 'tue', 'wed', 'thur')) ++ self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur')) ++ self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string')) ++ self.checkParam(self.combo, 'values', () if tcl_version < (8, 5) else '') ++ + self.combo['values'] = ['a', 1, 'c'] + + self.combo.set('c') +@@ -186,15 +383,21 @@ + + # testing values with empty string set through configure + self.combo.configure(values=[1, '', 2]) +- self.assertEqual(self.combo['values'], ('1', '', '2')) ++ self.assertEqual(self.combo['values'], ++ ('1', '', '2') if self.wantobjects else ++ '1 {} 2') + + # testing values with spaces + self.combo['values'] = ['a b', 'a\tb', 'a\nb'] +- self.assertEqual(self.combo['values'], ('a b', 'a\tb', 'a\nb')) ++ self.assertEqual(self.combo['values'], ++ ('a b', 'a\tb', 'a\nb') if self.wantobjects else ++ '{a b} {a\tb} {a\nb}') + + # testing values with special characters + self.combo['values'] = [r'a\tb', '"a"', '} {'] +- self.assertEqual(self.combo['values'], (r'a\tb', '"a"', '} {')) ++ self.assertEqual(self.combo['values'], ++ (r'a\tb', '"a"', '} {') if self.wantobjects else ++ r'a\\tb {"a"} \}\ \{') + + # out of range + self.assertRaises(Tkinter.TclError, self.combo.current, +@@ -204,25 +407,63 @@ + + # testing creating combobox with empty string in values + combo2 = ttk.Combobox(values=[1, 2, '']) +- self.assertEqual(combo2['values'], ('1', '2', '')) ++ self.assertEqual(combo2['values'], ++ ('1', '2', '') if self.wantobjects else '1 2 {}') + combo2.destroy() + + +-class EntryTest(unittest.TestCase): ++@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) ++class EntryTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'class', 'cursor', ++ 'exportselection', 'font', ++ 'invalidcommand', 'justify', ++ 'show', 'state', 'style', 'takefocus', 'textvariable', ++ 'validate', 'validatecommand', 'width', 'xscrollcommand', ++ ) + + def setUp(self): ++ super(EntryTest, self).setUp() + support.root_deiconify() +- self.entry = ttk.Entry() ++ self.entry = self.create() + + def tearDown(self): + self.entry.destroy() + support.root_withdraw() ++ super(EntryTest, self).tearDown() ++ ++ def _create(self, **kwargs): ++ return ttk.Entry(self.root, **kwargs) ++ ++ def test_invalidcommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'invalidcommand') ++ ++ def test_show(self): ++ widget = self.create() ++ self.checkParam(widget, 'show', '*') ++ self.checkParam(widget, 'show', '') ++ self.checkParam(widget, 'show', ' ') ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkParams(widget, 'state', ++ 'disabled', 'normal', 'readonly') ++ ++ def test_validate(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'validate', ++ 'all', 'key', 'focus', 'focusin', 'focusout', 'none') ++ ++ def test_validatecommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'validatecommand') + + + def test_bbox(self): + self.assertEqual(len(self.entry.bbox(0)), 4) + for item in self.entry.bbox(0): +- self.assertTrue(isinstance(item, int)) ++ self.assertIsInstance(item, int) + + self.assertRaises(Tkinter.TclError, self.entry.bbox, 'noindex') + self.assertRaises(Tkinter.TclError, self.entry.bbox, None) +@@ -312,16 +553,36 @@ + self.assertEqual(self.entry.state(), ()) + + +-class PanedwindowTest(unittest.TestCase): ++@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) ++class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'cursor', 'height', ++ 'orient', 'style', 'takefocus', 'width', ++ ) + + def setUp(self): ++ super(PanedWindowTest, self).setUp() + support.root_deiconify() +- self.paned = ttk.Panedwindow() ++ self.paned = self.create() + + def tearDown(self): + self.paned.destroy() + support.root_withdraw() ++ super(PanedWindowTest, self).tearDown() + ++ def _create(self, **kwargs): ++ return ttk.PanedWindow(self.root, **kwargs) ++ ++ def test_orient(self): ++ widget = self.create() ++ self.assertEqual(str(widget['orient']), 'vertical') ++ errmsg='attempt to change read-only option' ++ if get_tk_patchlevel() < (8, 6, 0): # actually this was changed in 8.6b3 ++ errmsg='Attempt to change read-only option' ++ self.checkInvalidParam(widget, 'orient', 'horizontal', ++ errmsg=errmsg) ++ widget2 = self.create(orient='horizontal') ++ self.assertEqual(str(widget2['orient']), 'horizontal') + + def test_add(self): + # attempt to add a child that is not a direct child of the paned window +@@ -400,10 +661,12 @@ + + child = ttk.Label() + self.paned.add(child) +- self.assertTrue(isinstance(self.paned.pane(0), dict)) +- self.assertEqual(self.paned.pane(0, weight=None), 0) ++ self.assertIsInstance(self.paned.pane(0), dict) ++ self.assertEqual(self.paned.pane(0, weight=None), ++ 0 if self.wantobjects else '0') + # newer form for querying a single option +- self.assertEqual(self.paned.pane(0, 'weight'), 0) ++ self.assertEqual(self.paned.pane(0, 'weight'), ++ 0 if self.wantobjects else '0') + self.assertEqual(self.paned.pane(0), self.paned.pane(str(child))) + + self.assertRaises(Tkinter.TclError, self.paned.pane, 0, +@@ -427,11 +690,26 @@ + + curr_pos = self.paned.sashpos(0) + self.paned.sashpos(0, 1000) +- self.assertTrue(curr_pos != self.paned.sashpos(0)) +- self.assertTrue(isinstance(self.paned.sashpos(0), int)) ++ self.assertNotEqual(curr_pos, self.paned.sashpos(0)) ++ self.assertIsInstance(self.paned.sashpos(0), int) + + +-class RadiobuttonTest(unittest.TestCase): ++@add_standard_options(StandardTtkOptionsTests) ++class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'command', 'compound', 'cursor', ++ 'image', ++ 'state', 'style', ++ 'takefocus', 'text', 'textvariable', ++ 'underline', 'value', 'variable', 'width', ++ ) ++ ++ def _create(self, **kwargs): ++ return ttk.Radiobutton(self.root, **kwargs) ++ ++ def test_value(self): ++ widget = self.create() ++ self.checkParams(widget, 'value', 1, 2.3, '', 'any string') + + def test_invoke(self): + success = [] +@@ -443,37 +721,91 @@ + cbtn = ttk.Radiobutton(command=cb_test, variable=myvar, value=0) + cbtn2 = ttk.Radiobutton(command=cb_test, variable=myvar, value=1) + ++ if self.wantobjects: ++ conv = lambda x: x ++ else: ++ conv = int ++ + res = cbtn.invoke() + self.assertEqual(res, "cb test called") +- self.assertEqual(cbtn['value'], myvar.get()) ++ self.assertEqual(conv(cbtn['value']), myvar.get()) + self.assertEqual(myvar.get(), +- cbtn.tk.globalgetvar(cbtn['variable'])) ++ conv(cbtn.tk.globalgetvar(cbtn['variable']))) + self.assertTrue(success) + + cbtn2['command'] = '' + res = cbtn2.invoke() + self.assertEqual(str(res), '') +- self.assertFalse(len(success) > 1) +- self.assertEqual(cbtn2['value'], myvar.get()) ++ self.assertLessEqual(len(success), 1) ++ self.assertEqual(conv(cbtn2['value']), myvar.get()) + self.assertEqual(myvar.get(), +- cbtn.tk.globalgetvar(cbtn['variable'])) ++ conv(cbtn.tk.globalgetvar(cbtn['variable']))) + + self.assertEqual(str(cbtn['variable']), str(cbtn2['variable'])) + + ++class MenubuttonTest(AbstractLabelTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'compound', 'cursor', 'direction', ++ 'image', 'menu', 'state', 'style', ++ 'takefocus', 'text', 'textvariable', ++ 'underline', 'width', ++ ) + +-class ScaleTest(unittest.TestCase): ++ def _create(self, **kwargs): ++ return ttk.Menubutton(self.root, **kwargs) ++ ++ def test_direction(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'direction', ++ 'above', 'below', 'left', 'right', 'flush') ++ ++ def test_menu(self): ++ widget = self.create() ++ menu = Tkinter.Menu(widget, name='menu') ++ self.checkParam(widget, 'menu', menu, conv=str) ++ menu.destroy() ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class ScaleTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'command', 'cursor', 'from', 'length', ++ 'orient', 'style', 'takefocus', 'to', 'value', 'variable', ++ ) ++ _conv_pixels = noconv_meth ++ default_orient = 'horizontal' + + def setUp(self): ++ super(ScaleTest, self).setUp() + support.root_deiconify() +- self.scale = ttk.Scale() ++ self.scale = self.create() + self.scale.pack() + self.scale.update() + + def tearDown(self): + self.scale.destroy() + support.root_withdraw() ++ super(ScaleTest, self).tearDown() + ++ def _create(self, **kwargs): ++ return ttk.Scale(self.root, **kwargs) ++ ++ def test_from(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=False) ++ ++ def test_length(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') ++ ++ def test_to(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=False) ++ ++ def test_value(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'value', 300, 14.9, 15.1, -10, conv=False) + + def test_custom_event(self): + failure = [1, 1, 1] # will need to be empty +@@ -495,10 +827,15 @@ + + + def test_get(self): ++ if self.wantobjects: ++ conv = lambda x: x ++ else: ++ conv = float ++ + scale_width = self.scale.winfo_width() + self.assertEqual(self.scale.get(scale_width, 0), self.scale['to']) + +- self.assertEqual(self.scale.get(0, 0), self.scale['from']) ++ self.assertEqual(conv(self.scale.get(0, 0)), conv(self.scale['from'])) + self.assertEqual(self.scale.get(), self.scale['value']) + self.scale['value'] = 30 + self.assertEqual(self.scale.get(), self.scale['value']) +@@ -508,41 +845,99 @@ + + + def test_set(self): ++ if self.wantobjects: ++ conv = lambda x: x ++ else: ++ conv = float ++ + # set restricts the max/min values according to the current range +- max = self.scale['to'] ++ max = conv(self.scale['to']) + new_max = max + 10 + self.scale.set(new_max) +- self.assertEqual(self.scale.get(), max) +- min = self.scale['from'] ++ self.assertEqual(conv(self.scale.get()), max) ++ min = conv(self.scale['from']) + self.scale.set(min - 1) +- self.assertEqual(self.scale.get(), min) ++ self.assertEqual(conv(self.scale.get()), min) + + # changing directly the variable doesn't impose this limitation tho + var = Tkinter.DoubleVar() + self.scale['variable'] = var + var.set(max + 5) +- self.assertEqual(self.scale.get(), var.get()) +- self.assertEqual(self.scale.get(), max + 5) ++ self.assertEqual(conv(self.scale.get()), var.get()) ++ self.assertEqual(conv(self.scale.get()), max + 5) + del var + + # the same happens with the value option + self.scale['value'] = max + 10 +- self.assertEqual(self.scale.get(), max + 10) +- self.assertEqual(self.scale.get(), self.scale['value']) ++ self.assertEqual(conv(self.scale.get()), max + 10) ++ self.assertEqual(conv(self.scale.get()), conv(self.scale['value'])) + + # nevertheless, note that the max/min values we can get specifying + # x, y coords are the ones according to the current range +- self.assertEqual(self.scale.get(0, 0), min) +- self.assertEqual(self.scale.get(self.scale.winfo_width(), 0), max) ++ self.assertEqual(conv(self.scale.get(0, 0)), min) ++ self.assertEqual(conv(self.scale.get(self.scale.winfo_width(), 0)), max) + + self.assertRaises(Tkinter.TclError, self.scale.set, None) + + +-class NotebookTest(unittest.TestCase): ++@add_standard_options(StandardTtkOptionsTests) ++class ProgressbarTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'cursor', 'orient', 'length', ++ 'mode', 'maximum', 'phase', ++ 'style', 'takefocus', 'value', 'variable', ++ ) ++ _conv_pixels = noconv_meth ++ default_orient = 'horizontal' ++ ++ def _create(self, **kwargs): ++ return ttk.Progressbar(self.root, **kwargs) ++ ++ def test_length(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'length', 100.1, 56.7, '2i') ++ ++ def test_maximum(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'maximum', 150.2, 77.7, 0, -10, conv=False) ++ ++ def test_mode(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'mode', 'determinate', 'indeterminate') ++ ++ def test_phase(self): ++ # XXX ++ pass ++ ++ def test_value(self): ++ widget = self.create() ++ self.checkFloatParam(widget, 'value', 150.2, 77.7, 0, -10, ++ conv=False) ++ ++ ++@unittest.skipIf(sys.platform == 'darwin', ++ 'ttk.Scrollbar is special on MacOSX') ++@add_standard_options(StandardTtkOptionsTests) ++class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'command', 'cursor', 'orient', 'style', 'takefocus', ++ ) ++ default_orient = 'vertical' ++ ++ def _create(self, **kwargs): ++ return ttk.Scrollbar(self.root, **kwargs) ++ ++ ++@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) ++class NotebookTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', ++ ) + + def setUp(self): ++ super(NotebookTest, self).setUp() + support.root_deiconify() +- self.nb = ttk.Notebook(padding=0) ++ self.nb = self.create(padding=0) + self.child1 = ttk.Label() + self.child2 = ttk.Label() + self.nb.add(self.child1, text='a') +@@ -553,7 +948,10 @@ + self.child2.destroy() + self.nb.destroy() + support.root_withdraw() ++ super(NotebookTest, self).tearDown() + ++ def _create(self, **kwargs): ++ return ttk.Notebook(self.root, **kwargs) + + def test_tab_identifiers(self): + self.nb.forget(0) +@@ -610,7 +1008,7 @@ + self.nb.add(self.child2) + self.assertEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.index(self.child2), child2_index) +- self.assertTrue(str(self.child2) == self.nb.tabs()[child2_index]) ++ self.assertEqual(str(self.child2), self.nb.tabs()[child2_index]) + # but the tab next to it (not hidden) is the one selected now + self.assertEqual(self.nb.index('current'), curr + 1) + +@@ -623,19 +1021,19 @@ + tabs = self.nb.tabs() + child1_index = self.nb.index(self.child1) + self.nb.forget(self.child1) +- self.assertFalse(str(self.child1) in self.nb.tabs()) ++ self.assertNotIn(str(self.child1), self.nb.tabs()) + self.assertEqual(len(tabs) - 1, len(self.nb.tabs())) + + self.nb.add(self.child1) + self.assertEqual(self.nb.index(self.child1), 1) +- self.assertFalse(child1_index == self.nb.index(self.child1)) ++ self.assertNotEqual(child1_index, self.nb.index(self.child1)) + + + def test_index(self): + self.assertRaises(Tkinter.TclError, self.nb.index, -1) + self.assertRaises(Tkinter.TclError, self.nb.index, None) + +- self.assertTrue(isinstance(self.nb.index('end'), int)) ++ self.assertIsInstance(self.nb.index('end'), int) + self.assertEqual(self.nb.index(self.child1), 0) + self.assertEqual(self.nb.index(self.child2), 1) + self.assertEqual(self.nb.index('end'), 2) +@@ -699,7 +1097,7 @@ + self.assertRaises(Tkinter.TclError, self.nb.tab, 'notab') + self.assertRaises(Tkinter.TclError, self.nb.tab, None) + +- self.assertTrue(isinstance(self.nb.tab(self.child1), dict)) ++ self.assertIsInstance(self.nb.tab(self.child1), dict) + self.assertEqual(self.nb.tab(self.child1, text=None), 'a') + # newer form for querying a single option + self.assertEqual(self.nb.tab(self.child1, 'text'), 'a') +@@ -745,16 +1143,68 @@ + self.assertEqual(self.nb.select(), str(self.child1)) + + +-class TreeviewTest(unittest.TestCase): ++@add_standard_options(StandardTtkOptionsTests) ++class TreeviewTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'columns', 'cursor', 'displaycolumns', ++ 'height', 'padding', 'selectmode', 'show', ++ 'style', 'takefocus', 'xscrollcommand', 'yscrollcommand', ++ ) + + def setUp(self): ++ super(TreeviewTest, self).setUp() + support.root_deiconify() +- self.tv = ttk.Treeview(padding=0) ++ self.tv = self.create(padding=0) + + def tearDown(self): + self.tv.destroy() + support.root_withdraw() ++ super(TreeviewTest, self).tearDown() + ++ def _create(self, **kwargs): ++ return ttk.Treeview(self.root, **kwargs) ++ ++ def test_columns(self): ++ widget = self.create() ++ self.checkParam(widget, 'columns', 'a b c', ++ expected=('a', 'b', 'c')) ++ self.checkParam(widget, 'columns', ('a', 'b', 'c')) ++ self.checkParam(widget, 'columns', () if tcl_version < (8, 5) else '') ++ ++ def test_displaycolumns(self): ++ widget = self.create() ++ widget['columns'] = ('a', 'b', 'c') ++ self.checkParam(widget, 'displaycolumns', 'b a c', ++ expected=('b', 'a', 'c')) ++ self.checkParam(widget, 'displaycolumns', ('b', 'a', 'c')) ++ self.checkParam(widget, 'displaycolumns', '#all', ++ expected=('#all',)) ++ self.checkParam(widget, 'displaycolumns', (2, 1, 0)) ++ self.checkInvalidParam(widget, 'displaycolumns', ('a', 'b', 'd'), ++ errmsg='Invalid column index d') ++ self.checkInvalidParam(widget, 'displaycolumns', (1, 2, 3), ++ errmsg='Column index 3 out of bounds') ++ self.checkInvalidParam(widget, 'displaycolumns', (1, -2), ++ errmsg='Column index -2 out of bounds') ++ ++ def test_height(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'height', 100, -100, 0, '3c', conv=False) ++ self.checkPixelsParam(widget, 'height', 101.2, 102.6, conv=noconv) ++ ++ def test_selectmode(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'selectmode', ++ 'none', 'browse', 'extended') ++ ++ def test_show(self): ++ widget = self.create() ++ self.checkParam(widget, 'show', 'tree headings', ++ expected=('tree', 'headings')) ++ self.checkParam(widget, 'show', ('tree', 'headings')) ++ self.checkParam(widget, 'show', ('headings', 'tree')) ++ self.checkParam(widget, 'show', 'tree', expected=('tree',)) ++ self.checkParam(widget, 'show', 'headings', expected=('headings',)) + + def test_bbox(self): + self.tv.pack() +@@ -768,7 +1218,7 @@ + + bbox = self.tv.bbox(children[0]) + self.assertEqual(len(bbox), 4) +- self.assertTrue(isinstance(bbox, tuple)) ++ self.assertIsInstance(bbox, tuple) + for item in bbox: + if not isinstance(item, int): + self.fail("Invalid bounding box: %s" % bbox) +@@ -779,6 +1229,8 @@ + self.tv.column('test', width=50) + bbox_column0 = self.tv.bbox(children[0], 0) + root_width = self.tv.column('#0', width=None) ++ if not self.wantobjects: ++ root_width = int(root_width) + self.assertEqual(bbox_column0[0], bbox[0] + root_width) + + # verify that bbox of a closed item is the empty string +@@ -791,7 +1243,7 @@ + self.assertEqual(self.tv.get_children(), ()) + + item_id = self.tv.insert('', 'end') +- self.assertTrue(isinstance(self.tv.get_children(), tuple)) ++ self.assertIsInstance(self.tv.get_children(), tuple) + self.assertEqual(self.tv.get_children()[0], item_id) + + # add item_id and child3 as children of child2 +@@ -816,14 +1268,17 @@ + + def test_column(self): + # return a dict with all options/values +- self.assertTrue(isinstance(self.tv.column('#0'), dict)) ++ self.assertIsInstance(self.tv.column('#0'), dict) + # return a single value of the given option +- self.assertTrue(isinstance(self.tv.column('#0', width=None), int)) ++ if self.wantobjects: ++ self.assertIsInstance(self.tv.column('#0', width=None), int) + # set a new value for an option + self.tv.column('#0', width=10) + # testing new way to get option value +- self.assertEqual(self.tv.column('#0', 'width'), 10) +- self.assertEqual(self.tv.column('#0', width=None), 10) ++ self.assertEqual(self.tv.column('#0', 'width'), ++ 10 if self.wantobjects else '10') ++ self.assertEqual(self.tv.column('#0', width=None), ++ 10 if self.wantobjects else '10') + # check read-only option + self.assertRaises(Tkinter.TclError, self.tv.column, '#0', id='X') + +@@ -931,7 +1386,7 @@ + + def test_heading(self): + # check a dict is returned +- self.assertTrue(isinstance(self.tv.heading('#0'), dict)) ++ self.assertIsInstance(self.tv.heading('#0'), dict) + + # check a value is returned + self.tv.heading('#0', text='hi') +@@ -945,12 +1400,10 @@ + self.assertRaises(Tkinter.TclError, self.tv.heading, '#0', + anchor=1) + +- # XXX skipping for now; should be fixed to work with newer ttk +- @unittest.skip("skipping pending resolution of Issue #10734") + def test_heading_callback(self): + def simulate_heading_click(x, y): + support.simulate_mouse_click(self.tv, x, y) +- self.tv.update_idletasks() ++ self.tv.update() + + success = [] # no success for now + +@@ -1038,13 +1491,16 @@ + # unicode values + value = u'\xe1ba' + item = self.tv.insert('', 'end', values=(value, )) +- self.assertEqual(self.tv.item(item, 'values'), (value, )) +- self.assertEqual(self.tv.item(item, values=None), (value, )) ++ self.assertEqual(self.tv.item(item, 'values'), ++ (value,) if self.wantobjects else value) ++ self.assertEqual(self.tv.item(item, values=None), ++ (value,) if self.wantobjects else value) + +- self.tv.item(item, values=list(self.tv.item(item, values=None))) +- self.assertEqual(self.tv.item(item, values=None), (value, )) ++ self.tv.item(item, values=self.root.splitlist(self.tv.item(item, values=None))) ++ self.assertEqual(self.tv.item(item, values=None), ++ (value,) if self.wantobjects else value) + +- self.assertTrue(isinstance(self.tv.item(item), dict)) ++ self.assertIsInstance(self.tv.item(item), dict) + + # erase item values + self.tv.item(item, values='') +@@ -1052,17 +1508,21 @@ + + # item tags + item = self.tv.insert('', 'end', tags=[1, 2, value]) +- self.assertEqual(self.tv.item(item, tags=None), ('1', '2', value)) ++ self.assertEqual(self.tv.item(item, tags=None), ++ ('1', '2', value) if self.wantobjects else ++ '1 2 %s' % value) + self.tv.item(item, tags=[]) + self.assertFalse(self.tv.item(item, tags=None)) + self.tv.item(item, tags=(1, 2)) +- self.assertEqual(self.tv.item(item, tags=None), ('1', '2')) ++ self.assertEqual(self.tv.item(item, tags=None), ++ ('1', '2') if self.wantobjects else '1 2') + + # values with spaces + item = self.tv.insert('', 'end', values=('a b c', + '%s %s' % (value, value))) + self.assertEqual(self.tv.item(item, values=None), +- ('a b c', '%s %s' % (value, value))) ++ ('a b c', '%s %s' % (value, value)) if self.wantobjects else ++ '{a b c} {%s %s}' % (value, value)) + + # text + self.assertEqual(self.tv.item( +@@ -1079,19 +1539,24 @@ + self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'}) + + self.tv.set(item, 'B', 'a') +- self.assertEqual(self.tv.item(item, values=None), ('a', 'a')) ++ self.assertEqual(self.tv.item(item, values=None), ++ ('a', 'a') if self.wantobjects else 'a a') + + self.tv['columns'] = ['B'] + self.assertEqual(self.tv.set(item), {'B': 'a'}) + + self.tv.set(item, 'B', 'b') + self.assertEqual(self.tv.set(item, column='B'), 'b') +- self.assertEqual(self.tv.item(item, values=None), ('b', 'a')) ++ self.assertEqual(self.tv.item(item, values=None), ++ ('b', 'a') if self.wantobjects else 'b a') + + self.tv.set(item, 'B', 123) +- self.assertEqual(self.tv.set(item, 'B'), 123) +- self.assertEqual(self.tv.item(item, values=None), (123, 'a')) +- self.assertEqual(self.tv.set(item), {'B': 123}) ++ self.assertEqual(self.tv.set(item, 'B'), ++ 123 if self.wantobjects else '123') ++ self.assertEqual(self.tv.item(item, values=None), ++ (123, 'a') if self.wantobjects else '123 a') ++ self.assertEqual(self.tv.set(item), ++ {'B': 123} if self.wantobjects else {'B': '123'}) + + # inexistent column + self.assertRaises(Tkinter.TclError, self.tv.set, item, 'A') +@@ -1145,13 +1610,38 @@ + 'blue') + self.assertEqual(str(self.tv.tag_configure('test', foreground=None)), + 'blue') +- self.assertTrue(isinstance(self.tv.tag_configure('test'), dict)) ++ self.assertIsInstance(self.tv.tag_configure('test'), dict) ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class SeparatorTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'cursor', 'orient', 'style', 'takefocus', ++ # 'state'? ++ ) ++ default_orient = 'horizontal' ++ ++ def _create(self, **kwargs): ++ return ttk.Separator(self.root, **kwargs) ++ ++ ++@add_standard_options(StandardTtkOptionsTests) ++class SizegripTest(AbstractWidgetTest, unittest.TestCase): ++ OPTIONS = ( ++ 'class', 'cursor', 'style', 'takefocus', ++ # 'state'? ++ ) ++ ++ def _create(self, **kwargs): ++ return ttk.Sizegrip(self.root, **kwargs) + + + tests_gui = ( +- WidgetTest, ButtonTest, CheckbuttonTest, RadiobuttonTest, +- ComboboxTest, EntryTest, PanedwindowTest, ScaleTest, NotebookTest, +- TreeviewTest ++ ButtonTest, CheckbuttonTest, ComboboxTest, EntryTest, ++ FrameTest, LabelFrameTest, LabelTest, MenubuttonTest, ++ NotebookTest, PanedWindowTest, ProgressbarTest, ++ RadiobuttonTest, ScaleTest, ScrollbarTest, SeparatorTest, ++ SizegripTest, TreeviewTest, WidgetTest, + ) + + if __name__ == "__main__": +diff -r 3a1db0d2747e Lib/lib-tk/test/widget_tests.py +--- /dev/null ++++ b/Lib/lib-tk/test/widget_tests.py +@@ -0,0 +1,526 @@ ++# Common tests for test_tkinter/test_widgets.py and test_ttk/test_widgets.py ++ ++import unittest ++import sys ++import Tkinter ++from ttk import setup_master, Scale ++from test_ttk.support import (tcl_version, requires_tcl, get_tk_patchlevel, ++ pixels_conv, tcl_obj_eq) ++import test.test_support ++ ++ ++noconv = noconv_meth = False ++if get_tk_patchlevel() < (8, 5, 11): ++ noconv = str ++noconv_meth = noconv and staticmethod(noconv) ++ ++def int_round(x): ++ return int(round(x)) ++ ++pixels_round = int_round ++if get_tk_patchlevel()[:3] == (8, 5, 11): ++ # Issue #19085: Workaround a bug in Tk ++ # http://core.tcl.tk/tk/info/3497848 ++ pixels_round = int ++ ++ ++_sentinel = object() ++ ++class AbstractWidgetTest(object): ++ _conv_pixels = staticmethod(pixels_round) ++ _conv_pad_pixels = None ++ wantobjects = True ++ ++ def setUp(self): ++ self.root = setup_master() ++ self.scaling = float(self.root.call('tk', 'scaling')) ++ if not self.root.wantobjects(): ++ self.wantobjects = False ++ ++ def create(self, **kwargs): ++ widget = self._create(**kwargs) ++ self.addCleanup(widget.destroy) ++ return widget ++ ++ def assertEqual2(self, actual, expected, msg=None, eq=object.__eq__): ++ if eq(actual, expected): ++ return ++ self.assertEqual(actual, expected, msg) ++ ++ def checkParam(self, widget, name, value, expected=_sentinel, ++ conv=False, eq=None): ++ widget[name] = value ++ if expected is _sentinel: ++ expected = value ++ if conv: ++ expected = conv(expected) ++ if not self.wantobjects: ++ if isinstance(expected, tuple): ++ expected = Tkinter._join(expected) ++ else: ++ expected = str(expected) ++ if eq is None: ++ eq = tcl_obj_eq ++ self.assertEqual2(widget[name], expected, eq=eq) ++ self.assertEqual2(widget.cget(name), expected, eq=eq) ++ # XXX ++ if not isinstance(widget, Scale): ++ t = widget.configure(name) ++ self.assertEqual(len(t), 5) ++ self.assertEqual2(t[4], expected, eq=eq) ++ ++ def checkInvalidParam(self, widget, name, value, errmsg=None, ++ keep_orig=True): ++ orig = widget[name] ++ if errmsg is not None: ++ errmsg = errmsg.format(value) ++ with self.assertRaises(Tkinter.TclError) as cm: ++ widget[name] = value ++ if errmsg is not None: ++ self.assertEqual(str(cm.exception), errmsg) ++ if keep_orig: ++ self.assertEqual(widget[name], orig) ++ else: ++ widget[name] = orig ++ with self.assertRaises(Tkinter.TclError) as cm: ++ widget.configure({name: value}) ++ if errmsg is not None: ++ self.assertEqual(str(cm.exception), errmsg) ++ if keep_orig: ++ self.assertEqual(widget[name], orig) ++ else: ++ widget[name] = orig ++ ++ def checkParams(self, widget, name, *values, **kwargs): ++ for value in values: ++ self.checkParam(widget, name, value, **kwargs) ++ ++ def checkIntegerParam(self, widget, name, *values, **kwargs): ++ self.checkParams(widget, name, *values, **kwargs) ++ self.checkInvalidParam(widget, name, '', ++ errmsg='expected integer but got ""') ++ self.checkInvalidParam(widget, name, '10p', ++ errmsg='expected integer but got "10p"') ++ self.checkInvalidParam(widget, name, 3.2, ++ errmsg='expected integer but got "3.2"') ++ ++ def checkFloatParam(self, widget, name, *values, **kwargs): ++ if 'conv' in kwargs: ++ conv = kwargs.pop('conv') ++ else: ++ conv = float ++ for value in values: ++ self.checkParam(widget, name, value, conv=conv, **kwargs) ++ self.checkInvalidParam(widget, name, '', ++ errmsg='expected floating-point number but got ""') ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='expected floating-point number but got "spam"') ++ ++ def checkBooleanParam(self, widget, name): ++ for value in (False, 0, 'false', 'no', 'off'): ++ self.checkParam(widget, name, value, expected=0) ++ for value in (True, 1, 'true', 'yes', 'on'): ++ self.checkParam(widget, name, value, expected=1) ++ self.checkInvalidParam(widget, name, '', ++ errmsg='expected boolean value but got ""') ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='expected boolean value but got "spam"') ++ ++ def checkColorParam(self, widget, name, allow_empty=None, **kwargs): ++ self.checkParams(widget, name, ++ '#ff0000', '#00ff00', '#0000ff', '#123456', ++ 'red', 'green', 'blue', 'white', 'black', 'grey', ++ **kwargs) ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='unknown color name "spam"') ++ ++ def checkCursorParam(self, widget, name, **kwargs): ++ self.checkParams(widget, name, 'arrow', 'watch', 'cross', '',**kwargs) ++ if tcl_version >= (8, 5): ++ self.checkParam(widget, name, 'none') ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='bad cursor spec "spam"') ++ ++ def checkCommandParam(self, widget, name): ++ def command(*args): ++ pass ++ widget[name] = command ++ self.assertTrue(widget[name]) ++ self.checkParams(widget, name, '') ++ ++ def checkEnumParam(self, widget, name, *values, **kwargs): ++ if 'errmsg' in kwargs: ++ errmsg = kwargs.pop('errmsg') ++ else: ++ errmsg = None ++ self.checkParams(widget, name, *values, **kwargs) ++ if errmsg is None: ++ errmsg2 = ' %s "{}": must be %s%s or %s' % ( ++ name, ++ ', '.join(values[:-1]), ++ ',' if len(values) > 2 else '', ++ values[-1]) ++ self.checkInvalidParam(widget, name, '', ++ errmsg='ambiguous' + errmsg2) ++ errmsg = 'bad' + errmsg2 ++ self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) ++ ++ def checkPixelsParam(self, widget, name, *values, **kwargs): ++ if 'conv' in kwargs: ++ conv = kwargs.pop('conv') ++ else: ++ conv = None ++ if conv is None: ++ conv = self._conv_pixels ++ if 'keep_orig' in kwargs: ++ keep_orig = kwargs.pop('keep_orig') ++ else: ++ keep_orig = True ++ for value in values: ++ expected = _sentinel ++ conv1 = conv ++ if isinstance(value, str): ++ if conv1 and conv1 is not str: ++ expected = pixels_conv(value) * self.scaling ++ conv1 = int_round ++ self.checkParam(widget, name, value, expected=expected, ++ conv=conv1, **kwargs) ++ self.checkInvalidParam(widget, name, '6x', ++ errmsg='bad screen distance "6x"', keep_orig=keep_orig) ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='bad screen distance "spam"', keep_orig=keep_orig) ++ ++ def checkReliefParam(self, widget, name): ++ self.checkParams(widget, name, ++ 'flat', 'groove', 'raised', 'ridge', 'solid', 'sunken') ++ errmsg='bad relief "spam": must be '\ ++ 'flat, groove, raised, ridge, solid, or sunken' ++ if tcl_version < (8, 6): ++ errmsg = None ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg=errmsg) ++ ++ def checkImageParam(self, widget, name): ++ image = Tkinter.PhotoImage('image1') ++ self.checkParam(widget, name, image, conv=str) ++ self.checkInvalidParam(widget, name, 'spam', ++ errmsg='image "spam" doesn\'t exist') ++ widget[name] = '' ++ ++ def checkVariableParam(self, widget, name, var): ++ self.checkParam(widget, name, var, conv=str) ++ ++ ++class StandardOptionsTests(object): ++ STANDARD_OPTIONS = ( ++ 'activebackground', 'activeborderwidth', 'activeforeground', 'anchor', ++ 'background', 'bitmap', 'borderwidth', 'compound', 'cursor', ++ 'disabledforeground', 'exportselection', 'font', 'foreground', ++ 'highlightbackground', 'highlightcolor', 'highlightthickness', ++ 'image', 'insertbackground', 'insertborderwidth', ++ 'insertofftime', 'insertontime', 'insertwidth', ++ 'jump', 'justify', 'orient', 'padx', 'pady', 'relief', ++ 'repeatdelay', 'repeatinterval', ++ 'selectbackground', 'selectborderwidth', 'selectforeground', ++ 'setgrid', 'takefocus', 'text', 'textvariable', 'troughcolor', ++ 'underline', 'wraplength', 'xscrollcommand', 'yscrollcommand', ++ ) ++ ++ def test_activebackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'activebackground') ++ ++ def test_activeborderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'activeborderwidth', ++ 0, 1.3, 2.9, 6, -2, '10p') ++ ++ def test_activeforeground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'activeforeground') ++ ++ def test_anchor(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'anchor', ++ 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') ++ ++ def test_background(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'background') ++ if 'bg' in self.OPTIONS: ++ self.checkColorParam(widget, 'bg') ++ ++ def test_bitmap(self): ++ widget = self.create() ++ self.checkParam(widget, 'bitmap', 'questhead') ++ self.checkParam(widget, 'bitmap', 'gray50') ++ filename = test.test_support.findfile('python.xbm', subdir='imghdrdata') ++ self.checkParam(widget, 'bitmap', '@' + filename) ++ # Cocoa Tk widgets don't detect invalid -bitmap values ++ # See https://core.tcl.tk/tk/info/31cd33dbf0 ++ if not ('aqua' in self.root.tk.call('tk', 'windowingsystem') and ++ 'AppKit' in self.root.winfo_server()): ++ self.checkInvalidParam(widget, 'bitmap', 'spam', ++ errmsg='bitmap "spam" not defined') ++ ++ def test_borderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'borderwidth', ++ 0, 1.3, 2.6, 6, -2, '10p') ++ if 'bd' in self.OPTIONS: ++ self.checkPixelsParam(widget, 'bd', 0, 1.3, 2.6, 6, -2, '10p') ++ ++ def test_compound(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'compound', ++ 'bottom', 'center', 'left', 'none', 'right', 'top') ++ ++ def test_cursor(self): ++ widget = self.create() ++ self.checkCursorParam(widget, 'cursor') ++ ++ def test_disabledforeground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'disabledforeground') ++ ++ def test_exportselection(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'exportselection') ++ ++ def test_font(self): ++ widget = self.create() ++ self.checkParam(widget, 'font', ++ '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*') ++ self.checkInvalidParam(widget, 'font', '', ++ errmsg='font "" doesn\'t exist') ++ ++ def test_foreground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'foreground') ++ if 'fg' in self.OPTIONS: ++ self.checkColorParam(widget, 'fg') ++ ++ def test_highlightbackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'highlightbackground') ++ ++ def test_highlightcolor(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'highlightcolor') ++ ++ def test_highlightthickness(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'highlightthickness', ++ 0, 1.3, 2.6, 6, '10p') ++ self.checkParam(widget, 'highlightthickness', -2, expected=0, ++ conv=self._conv_pixels) ++ ++ @unittest.skipIf(sys.platform == 'darwin', ++ 'crashes with Cocoa Tk (issue19733)') ++ def test_image(self): ++ widget = self.create() ++ self.checkImageParam(widget, 'image') ++ ++ def test_insertbackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'insertbackground') ++ ++ def test_insertborderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'insertborderwidth', ++ 0, 1.3, 2.6, 6, -2, '10p') ++ ++ def test_insertofftime(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'insertofftime', 100) ++ ++ def test_insertontime(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'insertontime', 100) ++ ++ def test_insertwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'insertwidth', 1.3, 2.6, -2, '10p') ++ ++ def test_jump(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'jump') ++ ++ def test_justify(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'justify', 'left', 'right', 'center', ++ errmsg='bad justification "{}": must be ' ++ 'left, right, or center') ++ self.checkInvalidParam(widget, 'justify', '', ++ errmsg='ambiguous justification "": must be ' ++ 'left, right, or center') ++ ++ def test_orient(self): ++ widget = self.create() ++ self.assertEqual(str(widget['orient']), self.default_orient) ++ self.checkEnumParam(widget, 'orient', 'horizontal', 'vertical') ++ ++ def test_padx(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, -2, '12m', ++ conv=self._conv_pad_pixels) ++ ++ def test_pady(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, -2, '12m', ++ conv=self._conv_pad_pixels) ++ ++ def test_relief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'relief') ++ ++ def test_repeatdelay(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'repeatdelay', -500, 500) ++ ++ def test_repeatinterval(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'repeatinterval', -500, 500) ++ ++ def test_selectbackground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'selectbackground') ++ ++ def test_selectborderwidth(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'selectborderwidth', 1.3, 2.6, -2, '10p') ++ ++ def test_selectforeground(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'selectforeground') ++ ++ def test_setgrid(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'setgrid') ++ ++ def test_state(self): ++ widget = self.create() ++ self.checkEnumParam(widget, 'state', 'active', 'disabled', 'normal') ++ ++ def test_takefocus(self): ++ widget = self.create() ++ self.checkParams(widget, 'takefocus', '0', '1', '') ++ ++ def test_text(self): ++ widget = self.create() ++ self.checkParams(widget, 'text', '', 'any string') ++ ++ def test_textvariable(self): ++ widget = self.create() ++ var = Tkinter.StringVar() ++ self.checkVariableParam(widget, 'textvariable', var) ++ ++ def test_troughcolor(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'troughcolor') ++ ++ def test_underline(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'underline', 0, 1, 10) ++ ++ def test_wraplength(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'wraplength', 100) ++ ++ def test_xscrollcommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'xscrollcommand') ++ ++ def test_yscrollcommand(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'yscrollcommand') ++ ++ # non-standard but common options ++ ++ def test_command(self): ++ widget = self.create() ++ self.checkCommandParam(widget, 'command') ++ ++ def test_indicatoron(self): ++ widget = self.create() ++ self.checkBooleanParam(widget, 'indicatoron') ++ ++ def test_offrelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'offrelief') ++ ++ def test_overrelief(self): ++ widget = self.create() ++ self.checkReliefParam(widget, 'overrelief') ++ ++ def test_selectcolor(self): ++ widget = self.create() ++ self.checkColorParam(widget, 'selectcolor') ++ ++ def test_selectimage(self): ++ widget = self.create() ++ self.checkImageParam(widget, 'selectimage') ++ ++ @requires_tcl(8, 5) ++ def test_tristateimage(self): ++ widget = self.create() ++ self.checkImageParam(widget, 'tristateimage') ++ ++ @requires_tcl(8, 5) ++ def test_tristatevalue(self): ++ widget = self.create() ++ self.checkParam(widget, 'tristatevalue', 'unknowable') ++ ++ def test_variable(self): ++ widget = self.create() ++ var = Tkinter.DoubleVar() ++ self.checkVariableParam(widget, 'variable', var) ++ ++ ++class IntegerSizeTests(object): ++ def test_height(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'height', 100, -100, 0) ++ ++ def test_width(self): ++ widget = self.create() ++ self.checkIntegerParam(widget, 'width', 402, -402, 0) ++ ++ ++class PixelSizeTests(object): ++ def test_height(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '3c') ++ ++ def test_width(self): ++ widget = self.create() ++ self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i') ++ ++ ++def add_standard_options(*source_classes): ++ # This decorator adds test_xxx methods from source classes for every xxx ++ # option in the OPTIONS class attribute if they are not defined explicitly. ++ def decorator(cls): ++ for option in cls.OPTIONS: ++ methodname = 'test_' + option ++ if not hasattr(cls, methodname): ++ for source_class in source_classes: ++ if hasattr(source_class, methodname): ++ setattr(cls, methodname, ++ getattr(source_class, methodname).im_func) ++ break ++ else: ++ def test(self, option=option): ++ widget = self.create() ++ widget[option] ++ raise AssertionError('Option "%s" is not tested in %s' % ++ (option, cls.__name__)) ++ test.__name__ = methodname ++ setattr(cls, methodname, test) ++ return cls ++ return decorator ++ ++def setUpModule(): ++ if test.test_support.verbose: ++ tcl = Tkinter.Tcl() ++ print 'patchlevel =', tcl.call('info', 'patchlevel') +diff -r 3a1db0d2747e Lib/lib-tk/ttk.py +--- a/Lib/lib-tk/ttk.py ++++ b/Lib/lib-tk/ttk.py +@@ -295,6 +295,9 @@ + indx += 2 + + if opt == 'children': ++ if (Tkinter._default_root and ++ not Tkinter._default_root.wantobjects()): ++ val = Tkinter._default_root.splitlist(val) + val = _list_from_layouttuple(val) + + opts[opt] = val +@@ -315,6 +318,8 @@ + if len(options) % 2: # option specified without a value, return its value + return res + ++ if Tkinter._default_root: ++ res = Tkinter._default_root.splitlist(res) + return _dict_from_tcltuple(res) + + def _convert_stringval(value): +@@ -327,6 +332,14 @@ + + return value + ++def _to_number(x): ++ if isinstance(x, str): ++ if '.' in x: ++ x = float(x) ++ else: ++ x = int(x) ++ return x ++ + def tclobjs_to_py(adict): + """Returns adict with its values converted from Tcl objects to Python + objects.""" +@@ -397,8 +410,8 @@ + or something else of your preference. A statespec is compound of + one or more states and then a value.""" + if query_opt is not None: +- return _list_from_statespec( +- self.tk.call(self._name, "map", style, '-%s' % query_opt)) ++ return _list_from_statespec(self.tk.splitlist( ++ self.tk.call(self._name, "map", style, '-%s' % query_opt))) + + return _dict_from_tcltuple( + self.tk.call(self._name, "map", style, *(_format_mapdict(kw)))) +@@ -455,8 +468,8 @@ + lspec = "null" # could be any other word, but this may make sense + # when calling layout(style) later + +- return _list_from_layouttuple( +- self.tk.call(self._name, "layout", style, lspec)) ++ return _list_from_layouttuple(self.tk.splitlist( ++ self.tk.call(self._name, "layout", style, lspec))) + + + def element_create(self, elementname, etype, *args, **kw): +@@ -468,12 +481,12 @@ + + def element_names(self): + """Returns the list of elements defined in the current theme.""" +- return self.tk.call(self._name, "element", "names") ++ return self.tk.splitlist(self.tk.call(self._name, "element", "names")) + + + def element_options(self, elementname): + """Return the list of elementname's options.""" +- return self.tk.call(self._name, "element", "options", elementname) ++ return self.tk.splitlist(self.tk.call(self._name, "element", "options", elementname)) + + + def theme_create(self, themename, parent=None, settings=None): +@@ -507,7 +520,7 @@ + + def theme_names(self): + """Returns a list of all known themes.""" +- return self.tk.call(self._name, "theme", "names") ++ return self.tk.splitlist(self.tk.call(self._name, "theme", "names")) + + + def theme_use(self, themename=None): +@@ -570,7 +583,8 @@ + matches statespec and False otherwise. If callback is specified, + then it will be invoked with *args, **kw if the widget state + matches statespec. statespec is expected to be a sequence.""" +- ret = self.tk.call(self._w, "instate", ' '.join(statespec)) ++ ret = self.tk.getboolean( ++ self.tk.call(self._w, "instate", ' '.join(statespec))) + if ret and callback: + return callback(*args, **kw) + +@@ -669,7 +683,7 @@ + def bbox(self, index): + """Return a tuple of (x, y, width, height) which describes the + bounding box of the character given by index.""" +- return self.tk.call(self._w, "bbox", index) ++ return self._getints(self.tk.call(self._w, "bbox", index)) + + + def identify(self, x, y): +@@ -682,7 +696,7 @@ + """Force revalidation, independent of the conditions specified + by the validate option. Returns False if validation fails, True + if it succeeds. Sets or clears the invalid state accordingly.""" +- return bool(self.tk.call(self._w, "validate")) ++ return bool(self.tk.getboolean(self.tk.call(self._w, "validate"))) + + + class Combobox(Entry): +@@ -709,6 +723,8 @@ + element at position newindex in the list of values. Otherwise, + returns the index of the current value in the list of values + or -1 if the current value does not appear in the list.""" ++ if newindex is None: ++ return self.tk.getint(self.tk.call(self._w, "current")) + return self.tk.call(self._w, "current", newindex) + + +@@ -863,7 +879,7 @@ + def index(self, tab_id): + """Returns the numeric index of the tab specified by tab_id, or + the total number of tabs if tab_id is the string "end".""" +- return self.tk.call(self._w, "index", tab_id) ++ return self.tk.getint(self.tk.call(self._w, "index", tab_id)) + + + def insert(self, pos, child, **kw): +@@ -898,7 +914,7 @@ + + def tabs(self): + """Returns a list of windows managed by the notebook.""" +- return self.tk.call(self._w, "tabs") or () ++ return self.tk.splitlist(self.tk.call(self._w, "tabs") or ()) + + + def enable_traversal(self): +@@ -981,7 +997,7 @@ + constrained to be between 0 and the total size of the widget. + + Returns the new position of sash number index.""" +- return self.tk.call(self._w, "sashpos", index, newpos) ++ return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos)) + + PanedWindow = Panedwindow # Tkinter name compatibility + +@@ -1181,14 +1197,15 @@ + If column is specified, returns the bounding box of that cell. + If the item is not visible (i.e., if it is a descendant of a + closed item or is scrolled offscreen), returns an empty string.""" +- return self.tk.call(self._w, "bbox", item, column) ++ return self._getints(self.tk.call(self._w, "bbox", item, column)) or '' + + + def get_children(self, item=None): + """Returns a tuple of children belonging to item. + + If item is not specified, returns root children.""" +- return self.tk.call(self._w, "children", item or '') or () ++ return self.tk.splitlist( ++ self.tk.call(self._w, "children", item or '') or ()) + + + def set_children(self, item, *newchildren): +@@ -1229,7 +1246,7 @@ + def exists(self, item): + """Returns True if the specified item is present in the tree, + False otherwise.""" +- return bool(self.tk.call(self._w, "exists", item)) ++ return bool(self.tk.getboolean(self.tk.call(self._w, "exists", item))) + + + def focus(self, item=None): +@@ -1311,7 +1328,7 @@ + def index(self, item): + """Returns the integer index of item within its parent's list + of children.""" +- return self.tk.call(self._w, "index", item) ++ return self.tk.getint(self.tk.call(self._w, "index", item)) + + + def insert(self, parent, index, iid=None, **kw): +@@ -1420,7 +1437,7 @@ + value of given column in given item to the specified value.""" + res = self.tk.call(self._w, "set", item, column, value) + if column is None and value is None: +- return _dict_from_tcltuple(res, False) ++ return _dict_from_tcltuple(self.tk.splitlist(res), False) + else: + return res + +@@ -1451,7 +1468,8 @@ + all items which have the specified tag. + + * Availability: Tk 8.6""" +- return self.tk.call(self._w, "tag", "has", tagname, item) ++ return self.tk.getboolean( ++ self.tk.call(self._w, "tag", "has", tagname, item)) + + + # Extensions +@@ -1523,7 +1541,8 @@ + + self.label.place_configure(x=x, y=y) + +- from_, to = self.scale['from'], self.scale['to'] ++ from_ = _to_number(self.scale['from']) ++ to = _to_number(self.scale['to']) + if to < from_: + from_, to = to, from_ + newval = self._variable.get() +diff -r 3a1db0d2747e Lib/lib-tk/turtle.py +--- a/Lib/lib-tk/turtle.py ++++ b/Lib/lib-tk/turtle.py +@@ -835,7 +835,7 @@ + if isinstance(data, list): + data = tuple(data) + elif type_ == "image": +- if isinstance(data, str): ++ if isinstance(data, basestring): + if data.lower().endswith(".gif") and isfile(data): + data = TurtleScreen._image(data) + # else data assumed to be Photoimage +@@ -1098,7 +1098,7 @@ + """ + if len(color) == 1: + color = color[0] +- if isinstance(color, str): ++ if isinstance(color, basestring): + if self._iscolorstring(color) or color == "": + return color + else: +@@ -2602,7 +2602,7 @@ + def _cc(self, args): + """Convert colortriples to hexstrings. + """ +- if isinstance(args, str): ++ if isinstance(args, basestring): + return args + try: + r, g, b = args +@@ -3228,7 +3228,7 @@ + """ + #print "dot-1:", size, color + if not color: +- if isinstance(size, (str, tuple)): ++ if isinstance(size, (basestring, tuple)): + color = self._colorstr(size) + size = self._pensize + max(self._pensize, 4) + else: +@@ -3913,7 +3913,7 @@ + down() + # some text + write("startstart", 1) +- write("start", 1) ++ write(u"start", 1) + color("red") + # staircase + for i in range(5): +@@ -3988,7 +3988,7 @@ + tri = getturtle() + tri.resizemode("auto") + turtle = Turtle() +- turtle.resizemode("auto") ++ turtle.resizemode(u"auto") + turtle.shape("turtle") + turtle.reset() + turtle.left(90) +@@ -3998,7 +3998,7 @@ + turtle.lt(30) + turtle.down() + turtle.speed(6) +- turtle.color("blue","orange") ++ turtle.color("blue",u"orange") + turtle.pensize(2) + tri.speed(6) + setheading(towards(turtle)) +@@ -4013,9 +4013,9 @@ + tri.stamp() + switchpen() + count += 1 +- tri.write("CAUGHT! ", font=("Arial", 16, "bold"), align="right") ++ tri.write("CAUGHT! ", font=("Arial", 16, "bold"), align=u"right") + tri.pencolor("black") +- tri.pencolor("red") ++ tri.pencolor(u"red") + + def baba(xdummy, ydummy): + clearscreen() +diff -r 3a1db0d2747e Lib/lib2to3/fixes/fix_import.py +--- a/Lib/lib2to3/fixes/fix_import.py ++++ b/Lib/lib2to3/fixes/fix_import.py +@@ -32,7 +32,7 @@ + elif node.type == syms.dotted_as_names: + pending.extend(node.children[::-2]) + else: +- raise AssertionError("unkown node type") ++ raise AssertionError("unknown node type") + + + class FixImport(fixer_base.BaseFix): +diff -r 3a1db0d2747e Lib/lib2to3/pgen2/tokenize.py +--- a/Lib/lib2to3/pgen2/tokenize.py ++++ b/Lib/lib2to3/pgen2/tokenize.py +@@ -252,7 +252,7 @@ + def detect_encoding(readline): + """ + The detect_encoding() function is used to detect the encoding that should +- be used to decode a Python source file. It requires one argment, readline, ++ be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used +@@ -343,7 +343,7 @@ + + def generate_tokens(readline): + """ +- The generate_tokens() generator requires one argment, readline, which ++ The generate_tokens() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as a string. Alternately, readline +diff -r 3a1db0d2747e Lib/lib2to3/tests/test_fixers.py +--- a/Lib/lib2to3/tests/test_fixers.py ++++ b/Lib/lib2to3/tests/test_fixers.py +@@ -41,7 +41,7 @@ + + def warns(self, before, after, message, unchanged=False): + tree = self._check(before, after) +- self.assertTrue(message in "".join(self.fixer_log)) ++ self.assertIn(message, "".join(self.fixer_log)) + if not unchanged: + self.assertTrue(tree.was_changed) + +diff -r 3a1db0d2747e Lib/lib2to3/tests/test_main.py +--- a/Lib/lib2to3/tests/test_main.py ++++ b/Lib/lib2to3/tests/test_main.py +@@ -59,9 +59,9 @@ + ret = self.run_2to3_capture(["-"], input_stream, out_enc, err) + self.assertEqual(ret, 0) + output = out.getvalue() +- self.assertTrue("-print 'nothing'" in output) +- self.assertTrue("WARNING: couldn't encode 's diff for " +- "your terminal" in err.getvalue()) ++ self.assertIn("-print 'nothing'", output) ++ self.assertIn("WARNING: couldn't encode 's diff for " ++ "your terminal", err.getvalue()) + + def setup_test_source_trees(self): + """Setup a test source tree and output destination tree.""" +diff -r 3a1db0d2747e Lib/lib2to3/tests/test_parser.py +--- a/Lib/lib2to3/tests/test_parser.py ++++ b/Lib/lib2to3/tests/test_parser.py +@@ -165,8 +165,8 @@ + for filepath in support.all_project_files(): + with open(filepath, "rb") as fp: + encoding = tokenize.detect_encoding(fp.readline)[0] +- self.assertTrue(encoding is not None, +- "can't detect encoding for %s" % filepath) ++ self.assertIsNotNone(encoding, ++ "can't detect encoding for %s" % filepath) + with open(filepath, "r") as fp: + source = fp.read() + source = source.decode(encoding) +diff -r 3a1db0d2747e Lib/lib2to3/tests/test_pytree.py +--- a/Lib/lib2to3/tests/test_pytree.py ++++ b/Lib/lib2to3/tests/test_pytree.py +@@ -160,12 +160,12 @@ + l3 = pytree.Leaf(100, "bar") + n1 = pytree.Node(1000, [l1, l2, l3]) + self.assertEqual(n1.children, [l1, l2, l3]) +- self.assertTrue(isinstance(n1.children, list)) ++ self.assertIsInstance(n1.children, list) + self.assertFalse(n1.was_changed) + l2new = pytree.Leaf(100, "-") + l2.replace(l2new) + self.assertEqual(n1.children, [l1, l2new, l3]) +- self.assertTrue(isinstance(n1.children, list)) ++ self.assertIsInstance(n1.children, list) + self.assertTrue(n1.was_changed) + + def test_replace_with_list(self): +@@ -176,7 +176,7 @@ + + l2.replace([pytree.Leaf(100, "*"), pytree.Leaf(100, "*")]) + self.assertEqual(str(n1), "foo**bar") +- self.assertTrue(isinstance(n1.children, list)) ++ self.assertIsInstance(n1.children, list) + + def test_leaves(self): + l1 = pytree.Leaf(100, "foo") +@@ -347,7 +347,7 @@ + n2 = pytree.Node(1000, []) + p1 = pytree.Node(1000, [n1, n2]) + +- self.assertTrue(n1.next_sibling is n2) ++ self.assertIs(n1.next_sibling, n2) + self.assertEqual(n2.next_sibling, None) + self.assertEqual(p1.next_sibling, None) + +@@ -356,7 +356,7 @@ + l2 = pytree.Leaf(100, "b") + p1 = pytree.Node(1000, [l1, l2]) + +- self.assertTrue(l1.next_sibling is l2) ++ self.assertIs(l1.next_sibling, l2) + self.assertEqual(l2.next_sibling, None) + self.assertEqual(p1.next_sibling, None) + +@@ -365,7 +365,7 @@ + n2 = pytree.Node(1000, []) + p1 = pytree.Node(1000, [n1, n2]) + +- self.assertTrue(n2.prev_sibling is n1) ++ self.assertIs(n2.prev_sibling, n1) + self.assertEqual(n1.prev_sibling, None) + self.assertEqual(p1.prev_sibling, None) + +@@ -374,7 +374,7 @@ + l2 = pytree.Leaf(100, "b") + p1 = pytree.Node(1000, [l1, l2]) + +- self.assertTrue(l2.prev_sibling is l1) ++ self.assertIs(l2.prev_sibling, l1) + self.assertEqual(l1.prev_sibling, None) + self.assertEqual(p1.prev_sibling, None) + +@@ -447,7 +447,7 @@ + r = {} + self.assertTrue(pw.match_seq([l1, l3], r)) + self.assertEqual(r, {"pl": l3, "pw": [l1, l3]}) +- self.assertTrue(r["pl"] is l3) ++ self.assertIs(r["pl"], l3) + r = {} + + def test_generate_matches(self): +diff -r 3a1db0d2747e Lib/lib2to3/tests/test_refactor.py +--- a/Lib/lib2to3/tests/test_refactor.py ++++ b/Lib/lib2to3/tests/test_refactor.py +@@ -49,9 +49,9 @@ + + def test_print_function_option(self): + rt = self.rt({"print_function" : True}) +- self.assertTrue(rt.grammar is pygram.python_grammar_no_print_statement) +- self.assertTrue(rt.driver.grammar is +- pygram.python_grammar_no_print_statement) ++ self.assertIs(rt.grammar, pygram.python_grammar_no_print_statement) ++ self.assertIs(rt.driver.grammar, ++ pygram.python_grammar_no_print_statement) + + def test_write_unchanged_files_option(self): + rt = self.rt() +diff -r 3a1db0d2747e Lib/locale.py +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -344,6 +344,22 @@ + for x in range(256) + ) + ++def _replace_encoding(code, encoding): ++ if '.' in code: ++ langname = code[:code.index('.')] ++ else: ++ langname = code ++ # Convert the encoding to a C lib compatible encoding string ++ norm_encoding = encodings.normalize_encoding(encoding) ++ #print('norm encoding: %r' % norm_encoding) ++ norm_encoding = encodings.aliases.aliases.get(norm_encoding, ++ norm_encoding) ++ #print('aliased encoding: %r' % norm_encoding) ++ encoding = locale_encoding_alias.get(norm_encoding, ++ norm_encoding) ++ #print('found encoding %r' % encoding) ++ return langname + '.' + encoding ++ + def normalize(localename): + + """ Returns a normalized locale code for the given locale +@@ -360,57 +376,73 @@ + does. + + """ +- # Normalize the locale name and extract the encoding ++ # Normalize the locale name and extract the encoding and modifier + if isinstance(localename, _unicode): + localename = localename.encode('ascii') +- fullname = localename.translate(_ascii_lower_map) +- if ':' in fullname: ++ code = localename.translate(_ascii_lower_map) ++ if ':' in code: + # ':' is sometimes used as encoding delimiter. +- fullname = fullname.replace(':', '.') +- if '.' in fullname: +- langname, encoding = fullname.split('.')[:2] +- fullname = langname + '.' + encoding ++ code = code.replace(':', '.') ++ if '@' in code: ++ code, modifier = code.split('@', 1) + else: +- langname = fullname ++ modifier = '' ++ if '.' in code: ++ langname, encoding = code.split('.')[:2] ++ else: ++ langname = code + encoding = '' + +- # First lookup: fullname (possibly with encoding) +- norm_encoding = encoding.replace('-', '') +- norm_encoding = norm_encoding.replace('_', '') +- lookup_name = langname + '.' + encoding ++ # First lookup: fullname (possibly with encoding and modifier) ++ lang_enc = langname ++ if encoding: ++ norm_encoding = encoding.replace('-', '') ++ norm_encoding = norm_encoding.replace('_', '') ++ lang_enc += '.' + norm_encoding ++ lookup_name = lang_enc ++ if modifier: ++ lookup_name += '@' + modifier + code = locale_alias.get(lookup_name, None) + if code is not None: + return code +- #print 'first lookup failed' ++ #print('first lookup failed') + +- # Second try: langname (without encoding) +- code = locale_alias.get(langname, None) +- if code is not None: +- #print 'langname lookup succeeded' +- if '.' in code: +- langname, defenc = code.split('.') +- else: +- langname = code +- defenc = '' +- if encoding: +- # Convert the encoding to a C lib compatible encoding string +- norm_encoding = encodings.normalize_encoding(encoding) +- #print 'norm encoding: %r' % norm_encoding +- norm_encoding = encodings.aliases.aliases.get(norm_encoding, +- norm_encoding) +- #print 'aliased encoding: %r' % norm_encoding +- encoding = locale_encoding_alias.get(norm_encoding, +- norm_encoding) +- else: +- encoding = defenc +- #print 'found encoding %r' % encoding +- if encoding: +- return langname + '.' + encoding +- else: +- return langname ++ if modifier: ++ # Second try: fullname without modifier (possibly with encoding) ++ code = locale_alias.get(lang_enc, None) ++ if code is not None: ++ #print('lookup without modifier succeeded') ++ if '@' not in code: ++ return code + '@' + modifier ++ if code.split('@', 1)[1].translate(_ascii_lower_map) == modifier: ++ return code ++ #print('second lookup failed') + +- else: +- return localename ++ if encoding: ++ # Third try: langname (without encoding, possibly with modifier) ++ lookup_name = langname ++ if modifier: ++ lookup_name += '@' + modifier ++ code = locale_alias.get(lookup_name, None) ++ if code is not None: ++ #print('lookup without encoding succeeded') ++ if '@' not in code: ++ return _replace_encoding(code, encoding) ++ code, modifier = code.split('@', 1) ++ return _replace_encoding(code, encoding) + '@' + modifier ++ ++ if modifier: ++ # Fourth try: langname (without encoding and modifier) ++ code = locale_alias.get(langname, None) ++ if code is not None: ++ #print('lookup without modifier and encoding succeeded') ++ if '@' not in code: ++ return _replace_encoding(code, encoding) + '@' + modifier ++ code, defmod = code.split('@', 1) ++ if defmod.translate(_ascii_lower_map) == modifier: ++ return _replace_encoding(code, encoding) + '@' + defmod ++ ++ return localename + + def _parse_localename(localename): + +@@ -429,7 +461,7 @@ + code = normalize(localename) + if '@' in code: + # Deal with locale modifiers +- code, modifier = code.split('@') ++ code, modifier = code.split('@', 1) + if modifier == 'euro' and '.' not in code: + # Assume Latin-9 for @euro locales. This is bogus, + # since some systems may use other encodings for these +@@ -734,11 +766,30 @@ + # updated 'sr_yu.utf8@cyrillic' -> 'sr_CS.UTF-8' to 'sr_RS.UTF-8' + # updated 'sr_yu@cyrillic' -> 'sr_CS.ISO8859-5' to 'sr_RS.UTF-8' + # ++# SS 2013-12-20: ++# Updated alias mapping to most recent locale.alias file ++# from X.org distribution using makelocalealias.py. ++# ++# These are the differences compared to the old mapping (Python 2.7.6 ++# and older): ++# ++# updated 'a3' -> 'a3_AZ.KOI8-C' to 'az_AZ.KOI8-C' ++# updated 'a3_az' -> 'a3_AZ.KOI8-C' to 'az_AZ.KOI8-C' ++# updated 'a3_az.koi8c' -> 'a3_AZ.KOI8-C' to 'az_AZ.KOI8-C' ++# updated 'cs_cs.iso88592' -> 'cs_CS.ISO8859-2' to 'cs_CZ.ISO8859-2' ++# updated 'hebrew' -> 'iw_IL.ISO8859-8' to 'he_IL.ISO8859-8' ++# updated 'hebrew.iso88598' -> 'iw_IL.ISO8859-8' to 'he_IL.ISO8859-8' ++# updated 'sd' -> 'sd_IN@devanagari.UTF-8' to 'sd_IN.UTF-8' ++# updated 'sr@latn' -> 'sr_RS.UTF-8@latin' to 'sr_CS.UTF-8@latin' ++# updated 'sr_cs' -> 'sr_RS.UTF-8' to 'sr_CS.UTF-8' ++# updated 'sr_cs.utf8@latn' -> 'sr_RS.UTF-8@latin' to 'sr_CS.UTF-8@latin' ++# updated 'sr_cs@latn' -> 'sr_RS.UTF-8@latin' to 'sr_CS.UTF-8@latin' + + locale_alias = { +- 'a3': 'a3_AZ.KOI8-C', +- 'a3_az': 'a3_AZ.KOI8-C', +- 'a3_az.koi8c': 'a3_AZ.KOI8-C', ++ 'a3': 'az_AZ.KOI8-C', ++ 'a3_az': 'az_AZ.KOI8-C', ++ 'a3_az.koi8c': 'az_AZ.KOI8-C', ++ 'a3_az.koic': 'az_AZ.KOI8-C', + 'af': 'af_ZA.ISO8859-1', + 'af_za': 'af_ZA.ISO8859-1', + 'af_za.iso88591': 'af_ZA.ISO8859-1', +@@ -757,6 +808,7 @@ + 'ar_dz.iso88596': 'ar_DZ.ISO8859-6', + 'ar_eg': 'ar_EG.ISO8859-6', + 'ar_eg.iso88596': 'ar_EG.ISO8859-6', ++ 'ar_in': 'ar_IN.UTF-8', + 'ar_iq': 'ar_IQ.ISO8859-6', + 'ar_iq.iso88596': 'ar_IQ.ISO8859-6', + 'ar_jo': 'ar_JO.ISO8859-6', +@@ -786,6 +838,7 @@ + 'arabic': 'ar_AA.ISO8859-6', + 'arabic.iso88596': 'ar_AA.ISO8859-6', + 'as': 'as_IN.UTF-8', ++ 'as_in': 'as_IN.UTF-8', + 'az': 'az_AZ.ISO8859-9E', + 'az_az': 'az_AZ.ISO8859-9E', + 'az_az.iso88599e': 'az_AZ.ISO8859-9E', +@@ -803,6 +856,7 @@ + 'bg_bg.koi8r': 'bg_BG.KOI8-R', + 'bg_bg.microsoftcp1251': 'bg_BG.CP1251', + 'bn_in': 'bn_IN.UTF-8', ++ 'bo_in': 'bo_IN.UTF-8', + 'bokmal': 'nb_NO.ISO8859-1', + 'bokm\xe5l': 'nb_NO.ISO8859-1', + 'br': 'br_FR.ISO8859-1', +@@ -820,6 +874,7 @@ + 'c': 'C', + 'c-french': 'fr_CA.ISO8859-1', + 'c-french.iso88591': 'fr_CA.ISO8859-1', ++ 'c.ascii': 'C', + 'c.en': 'C', + 'c.iso88591': 'en_US.ISO8859-1', + 'c_c': 'C', +@@ -857,7 +912,7 @@ + 'croatian': 'hr_HR.ISO8859-2', + 'cs': 'cs_CZ.ISO8859-2', + 'cs_cs': 'cs_CZ.ISO8859-2', +- 'cs_cs.iso88592': 'cs_CS.ISO8859-2', ++ 'cs_cs.iso88592': 'cs_CZ.ISO8859-2', + 'cs_cz': 'cs_CZ.ISO8859-2', + 'cs_cz.iso88592': 'cs_CZ.ISO8859-2', + 'cy': 'cy_GB.ISO8859-1', +@@ -1161,12 +1216,13 @@ + 'he_il.cp1255': 'he_IL.CP1255', + 'he_il.iso88598': 'he_IL.ISO8859-8', + 'he_il.microsoftcp1255': 'he_IL.CP1255', +- 'hebrew': 'iw_IL.ISO8859-8', +- 'hebrew.iso88598': 'iw_IL.ISO8859-8', ++ 'hebrew': 'he_IL.ISO8859-8', ++ 'hebrew.iso88598': 'he_IL.ISO8859-8', + 'hi': 'hi_IN.ISCII-DEV', + 'hi_in': 'hi_IN.ISCII-DEV', + 'hi_in.isciidev': 'hi_IN.ISCII-DEV', + 'hne': 'hne_IN.UTF-8', ++ 'hne_in': 'hne_IN.UTF-8', + 'hr': 'hr_HR.ISO8859-2', + 'hr_hr': 'hr_HR.ISO8859-2', + 'hr_hr.iso88592': 'hr_HR.ISO8859-2', +@@ -1254,7 +1310,8 @@ + 'korean': 'ko_KR.eucKR', + 'korean.euc': 'ko_KR.eucKR', + 'ks': 'ks_IN.UTF-8', +- 'ks_in@devanagari': 'ks_IN@devanagari.UTF-8', ++ 'ks_in': 'ks_IN.UTF-8', ++ 'ks_in@devanagari': 'ks_IN.UTF-8@devanagari', + 'kw': 'kw_GB.ISO8859-1', + 'kw_gb': 'kw_GB.ISO8859-1', + 'kw_gb.iso88591': 'kw_GB.ISO8859-1', +@@ -1278,6 +1335,7 @@ + 'lv_lv.iso885913': 'lv_LV.ISO8859-13', + 'lv_lv.iso88594': 'lv_LV.ISO8859-4', + 'mai': 'mai_IN.UTF-8', ++ 'mai_in': 'mai_IN.UTF-8', + 'mi': 'mi_NZ.ISO8859-1', + 'mi_nz': 'mi_NZ.ISO8859-1', + 'mi_nz.iso88591': 'mi_NZ.ISO8859-1', +@@ -1287,6 +1345,7 @@ + 'mk_mk.iso88595': 'mk_MK.ISO8859-5', + 'mk_mk.microsoftcp1251': 'mk_MK.CP1251', + 'ml': 'ml_IN.UTF-8', ++ 'ml_in': 'ml_IN.UTF-8', + 'mr': 'mr_IN.UTF-8', + 'mr_in': 'mr_IN.UTF-8', + 'ms': 'ms_MY.ISO8859-1', +@@ -1301,6 +1360,7 @@ + 'nb_no.iso88591': 'nb_NO.ISO8859-1', + 'nb_no.iso885915': 'nb_NO.ISO8859-15', + 'nb_no@euro': 'nb_NO.ISO8859-15', ++ 'ne_np': 'ne_NP.UTF-8', + 'nl': 'nl_NL.ISO8859-1', + 'nl.iso885915': 'nl_NL.ISO8859-15', + 'nl_be': 'nl_BE.ISO8859-1', +@@ -1353,6 +1413,7 @@ + 'oc_fr.iso885915': 'oc_FR.ISO8859-15', + 'oc_fr@euro': 'oc_FR.ISO8859-15', + 'or': 'or_IN.UTF-8', ++ 'or_in': 'or_IN.UTF-8', + 'pa': 'pa_IN.UTF-8', + 'pa_in': 'pa_IN.UTF-8', + 'pd': 'pd_US.ISO8859-1', +@@ -1414,7 +1475,10 @@ + 'rw': 'rw_RW.ISO8859-1', + 'rw_rw': 'rw_RW.ISO8859-1', + 'rw_rw.iso88591': 'rw_RW.ISO8859-1', +- 'sd': 'sd_IN@devanagari.UTF-8', ++ 'sd': 'sd_IN.UTF-8', ++ 'sd@devanagari': 'sd_IN.UTF-8@devanagari', ++ 'sd_in': 'sd_IN.UTF-8', ++ 'sd_in@devanagari': 'sd_IN.UTF-8@devanagari', + 'se_no': 'se_NO.UTF-8', + 'serbocroatian': 'sr_RS.UTF-8@latin', + 'sh': 'sr_RS.UTF-8@latin', +@@ -1448,13 +1512,13 @@ + 'sr': 'sr_RS.UTF-8', + 'sr@cyrillic': 'sr_RS.UTF-8', + 'sr@latin': 'sr_RS.UTF-8@latin', +- 'sr@latn': 'sr_RS.UTF-8@latin', +- 'sr_cs': 'sr_RS.UTF-8', ++ 'sr@latn': 'sr_CS.UTF-8@latin', ++ 'sr_cs': 'sr_CS.UTF-8', + 'sr_cs.iso88592': 'sr_CS.ISO8859-2', + 'sr_cs.iso88592@latn': 'sr_CS.ISO8859-2', + 'sr_cs.iso88595': 'sr_CS.ISO8859-5', +- 'sr_cs.utf8@latn': 'sr_RS.UTF-8@latin', +- 'sr_cs@latn': 'sr_RS.UTF-8@latin', ++ 'sr_cs.utf8@latn': 'sr_CS.UTF-8@latin', ++ 'sr_cs@latn': 'sr_CS.UTF-8@latin', + 'sr_me': 'sr_ME.UTF-8', + 'sr_rs': 'sr_RS.UTF-8', + 'sr_rs.utf8@latn': 'sr_RS.UTF-8@latin', +@@ -1532,6 +1596,7 @@ + 'universal': 'en_US.utf', + 'universal.utf8@ucs4': 'en_US.UTF-8', + 'ur': 'ur_PK.CP1256', ++ 'ur_in': 'ur_IN.UTF-8', + 'ur_pk': 'ur_PK.CP1256', + 'ur_pk.cp1256': 'ur_PK.CP1256', + 'ur_pk.microsoftcp1256': 'ur_PK.CP1256', +diff -r 3a1db0d2747e Lib/logging/__init__.py +--- a/Lib/logging/__init__.py ++++ b/Lib/logging/__init__.py +@@ -912,8 +912,10 @@ + self.flush() + if hasattr(self.stream, "close"): + self.stream.close() +- StreamHandler.close(self) + self.stream = None ++ # Issue #19523: call unconditionally to ++ # prevent a handler leak when delay is set ++ StreamHandler.close(self) + finally: + self.release() + +diff -r 3a1db0d2747e Lib/logging/config.py +--- a/Lib/logging/config.py ++++ b/Lib/logging/config.py +@@ -1,4 +1,4 @@ +-# Copyright 2001-2013 by Vinay Sajip. All Rights Reserved. ++# Copyright 2001-2014 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, +@@ -19,13 +19,23 @@ + is based on PEP 282 and comments thereto in comp.lang.python, and influenced + by Apache's log4j system. + +-Copyright (C) 2001-2013 Vinay Sajip. All Rights Reserved. ++Copyright (C) 2001-2014 Vinay Sajip. All Rights Reserved. + + To use, simply 'import logging' and log away! + """ + +-import sys, logging, logging.handlers, socket, struct, os, traceback, re +-import types, cStringIO ++import cStringIO ++import errno ++import io ++import logging ++import logging.handlers ++import os ++import re ++import socket ++import struct ++import sys ++import traceback ++import types + + try: + import thread +@@ -38,10 +48,7 @@ + + DEFAULT_LOGGING_CONFIG_PORT = 9030 + +-if sys.platform == "win32": +- RESET_ERROR = 10054 #WSAECONNRESET +-else: +- RESET_ERROR = 104 #ECONNRESET ++RESET_ERROR = errno.ECONNRESET + + # + # The following code implements a socket listener for on-the-fly +@@ -275,6 +282,30 @@ + return True + + ++class ConvertingMixin(object): ++ """For ConvertingXXX's, this mixin class provides common functions""" ++ ++ def convert_with_key(self, key, value, replace=True): ++ result = self.configurator.convert(value) ++ #If the converted value is different, save for next time ++ if value is not result: ++ if replace: ++ self[key] = result ++ if type(result) in (ConvertingDict, ConvertingList, ++ ConvertingTuple): ++ result.parent = self ++ result.key = key ++ return result ++ ++ def convert(self, value): ++ result = self.configurator.convert(value) ++ if value is not result: ++ if type(result) in (ConvertingDict, ConvertingList, ++ ConvertingTuple): ++ result.parent = self ++ return result ++ ++ + # The ConvertingXXX classes are wrappers around standard Python containers, + # and they serve to convert any suitable values in the container. The + # conversion converts base dicts, lists and tuples to their wrapped +@@ -284,77 +315,37 @@ + # Each wrapper should have a configurator attribute holding the actual + # configurator to use for conversion. + +-class ConvertingDict(dict): ++class ConvertingDict(dict, ConvertingMixin): + """A converting dictionary wrapper.""" + + def __getitem__(self, key): + value = dict.__getitem__(self, key) +- result = self.configurator.convert(value) +- #If the converted value is different, save for next time +- if value is not result: +- self[key] = result +- if type(result) in (ConvertingDict, ConvertingList, +- ConvertingTuple): +- result.parent = self +- result.key = key +- return result ++ return self.convert_with_key(key, value) + + def get(self, key, default=None): + value = dict.get(self, key, default) +- result = self.configurator.convert(value) +- #If the converted value is different, save for next time +- if value is not result: +- self[key] = result +- if type(result) in (ConvertingDict, ConvertingList, +- ConvertingTuple): +- result.parent = self +- result.key = key +- return result ++ return self.convert_with_key(key, value) + + def pop(self, key, default=None): + value = dict.pop(self, key, default) +- result = self.configurator.convert(value) +- if value is not result: +- if type(result) in (ConvertingDict, ConvertingList, +- ConvertingTuple): +- result.parent = self +- result.key = key +- return result ++ return self.convert_with_key(key, value, replace=False) + +-class ConvertingList(list): ++class ConvertingList(list, ConvertingMixin): + """A converting list wrapper.""" + def __getitem__(self, key): + value = list.__getitem__(self, key) +- result = self.configurator.convert(value) +- #If the converted value is different, save for next time +- if value is not result: +- self[key] = result +- if type(result) in (ConvertingDict, ConvertingList, +- ConvertingTuple): +- result.parent = self +- result.key = key +- return result ++ return self.convert_with_key(key, value) + + def pop(self, idx=-1): + value = list.pop(self, idx) +- result = self.configurator.convert(value) +- if value is not result: +- if type(result) in (ConvertingDict, ConvertingList, +- ConvertingTuple): +- result.parent = self +- return result ++ return self.convert(value) + +-class ConvertingTuple(tuple): ++class ConvertingTuple(tuple, ConvertingMixin): + """A converting tuple wrapper.""" + def __getitem__(self, key): + value = tuple.__getitem__(self, key) +- result = self.configurator.convert(value) +- if value is not result: +- if type(result) in (ConvertingDict, ConvertingList, +- ConvertingTuple): +- result.parent = self +- result.key = key +- return result ++ # Can't replace a tuple entry. ++ return self.convert_with_key(key, value, replace=False) + + class BaseConfigurator(object): + """ +@@ -526,21 +517,21 @@ + level = handler_config.get('level', None) + if level: + handler.setLevel(logging._checkLevel(level)) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure handler ' + '%r: %s' % (name, e)) + loggers = config.get('loggers', EMPTY_DICT) + for name in loggers: + try: + self.configure_logger(name, loggers[name], True) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure logger ' + '%r: %s' % (name, e)) + root = config.get('root', None) + if root: + try: + self.configure_root(root, True) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure root ' + 'logger: %s' % e) + else: +@@ -555,7 +546,7 @@ + try: + formatters[name] = self.configure_formatter( + formatters[name]) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure ' + 'formatter %r: %s' % (name, e)) + # Next, do filters - they don't refer to anything else, either +@@ -563,7 +554,7 @@ + for name in filters: + try: + filters[name] = self.configure_filter(filters[name]) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure ' + 'filter %r: %s' % (name, e)) + +@@ -577,7 +568,7 @@ + handler = self.configure_handler(handlers[name]) + handler.name = name + handlers[name] = handler +- except StandardError, e: ++ except StandardError as e: + if 'target not configured yet' in str(e): + deferred.append(name) + else: +@@ -590,7 +581,7 @@ + handler = self.configure_handler(handlers[name]) + handler.name = name + handlers[name] = handler +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure handler ' + '%r: %s' % (name, e)) + +@@ -631,7 +622,7 @@ + existing.remove(name) + try: + self.configure_logger(name, loggers[name]) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure logger ' + '%r: %s' % (name, e)) + +@@ -654,7 +645,7 @@ + if root: + try: + self.configure_root(root) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to configure root ' + 'logger: %s' % e) + finally: +@@ -666,7 +657,7 @@ + factory = config['()'] # for use in exception handler + try: + result = self.configure_custom(config) +- except TypeError, te: ++ except TypeError as te: + if "'format'" not in str(te): + raise + #Name of parameter changed from fmt to format. +@@ -696,7 +687,7 @@ + for f in filters: + try: + filterer.addFilter(self.config['filters'][f]) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to add filter %r: %s' % (f, e)) + + def configure_handler(self, config): +@@ -705,7 +696,7 @@ + if formatter: + try: + formatter = self.config['formatters'][formatter] +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to set formatter ' + '%r: %s' % (formatter, e)) + level = config.pop('level', None) +@@ -727,7 +718,7 @@ + config['class'] = cname # restore for deferred configuration + raise StandardError('target not configured yet') + config['target'] = th +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to set target handler ' + '%r: %s' % (config['target'], e)) + elif issubclass(klass, logging.handlers.SMTPHandler) and\ +@@ -740,7 +731,7 @@ + kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) + try: + result = factory(**kwargs) +- except TypeError, te: ++ except TypeError as te: + if "'stream'" not in str(te): + raise + #The argument name changed from strm to stream +@@ -762,7 +753,7 @@ + for h in handlers: + try: + logger.addHandler(self.config['handlers'][h]) +- except StandardError, e: ++ except StandardError as e: + raise ValueError('Unable to add handler %r: %s' % (h, e)) + + def common_logger_config(self, logger, config, incremental=False): +@@ -857,13 +848,9 @@ + traceback.print_exc() + if self.server.ready: + self.server.ready.set() +- except socket.error, e: +- if not isinstance(e.args, tuple): ++ except socket.error as e: ++ if e.errno != RESET_ERROR: + raise +- else: +- errcode = e.args[0] +- if errcode != RESET_ERROR: +- raise + + class ConfigSocketReceiver(ThreadingTCPServer): + """ +diff -r 3a1db0d2747e Lib/mailbox.py +--- a/Lib/mailbox.py ++++ b/Lib/mailbox.py +@@ -1,5 +1,3 @@ +-#! /usr/bin/env python +- + """Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes.""" + + # Notes for authors of new mailbox subclasses: +diff -r 3a1db0d2747e Lib/mailcap.py +--- a/Lib/mailcap.py ++++ b/Lib/mailcap.py +@@ -22,8 +22,8 @@ + fp = open(mailcap, 'r') + except IOError: + continue +- morecaps = readmailcapfile(fp) +- fp.close() ++ with fp: ++ morecaps = readmailcapfile(fp) + for key, value in morecaps.iteritems(): + if not key in caps: + caps[key] = value +diff -r 3a1db0d2747e Lib/mimetypes.py +--- a/Lib/mimetypes.py ++++ b/Lib/mimetypes.py +@@ -373,9 +373,10 @@ + f = open(file) + except IOError: + return None +- db = MimeTypes() +- db.readfp(f, True) +- return db.types_map[True] ++ with f: ++ db = MimeTypes() ++ db.readfp(f, True) ++ return db.types_map[True] + + + def _default_mime_types(): +diff -r 3a1db0d2747e Lib/multiprocessing/pool.py +--- a/Lib/multiprocessing/pool.py ++++ b/Lib/multiprocessing/pool.py +@@ -169,7 +169,8 @@ + + self._task_handler = threading.Thread( + target=Pool._handle_tasks, +- args=(self._taskqueue, self._quick_put, self._outqueue, self._pool) ++ args=(self._taskqueue, self._quick_put, self._outqueue, ++ self._pool, self._cache) + ) + self._task_handler.daemon = True + self._task_handler._state = RUN +@@ -329,7 +330,7 @@ + debug('worker handler exiting') + + @staticmethod +- def _handle_tasks(taskqueue, put, outqueue, pool): ++ def _handle_tasks(taskqueue, put, outqueue, pool, cache): + thread = threading.current_thread() + + for taskseq, set_length in iter(taskqueue.get, None): +@@ -340,9 +341,12 @@ + break + try: + put(task) +- except IOError: +- debug('could not put task on queue') +- break ++ except Exception as e: ++ job, ind = task[:2] ++ try: ++ cache[job]._set(ind, (False, e)) ++ except KeyError: ++ pass + else: + if set_length: + debug('doing set_length()') +diff -r 3a1db0d2747e Lib/multiprocessing/process.py +--- a/Lib/multiprocessing/process.py ++++ b/Lib/multiprocessing/process.py +@@ -267,7 +267,7 @@ + else: + sys.stderr.write(str(e.args[0]) + '\n') + sys.stderr.flush() +- exitcode = 0 if isinstance(e.args[0], str) else 1 ++ exitcode = 1 + except: + exitcode = 1 + import traceback +diff -r 3a1db0d2747e Lib/multiprocessing/util.py +--- a/Lib/multiprocessing/util.py ++++ b/Lib/multiprocessing/util.py +@@ -32,6 +32,7 @@ + # SUCH DAMAGE. + # + ++import os + import itertools + import weakref + import atexit +@@ -184,6 +185,7 @@ + self._args = args + self._kwargs = kwargs or {} + self._key = (exitpriority, _finalizer_counter.next()) ++ self._pid = os.getpid() + + _finalizer_registry[self._key] = self + +@@ -196,9 +198,13 @@ + except KeyError: + sub_debug('finalizer no longer registered') + else: +- sub_debug('finalizer calling %s with args %s and kwargs %s', +- self._callback, self._args, self._kwargs) +- res = self._callback(*self._args, **self._kwargs) ++ if self._pid != os.getpid(): ++ sub_debug('finalizer ignored because different process') ++ res = None ++ else: ++ sub_debug('finalizer calling %s with args %s and kwargs %s', ++ self._callback, self._args, self._kwargs) ++ res = self._callback(*self._args, **self._kwargs) + self._weakref = self._callback = self._args = \ + self._kwargs = self._key = None + return res +diff -r 3a1db0d2747e Lib/ntpath.py +--- a/Lib/ntpath.py ++++ b/Lib/ntpath.py +@@ -59,61 +59,30 @@ + + + # Join two (or more) paths. +- +-def join(a, *p): +- """Join two or more pathname components, inserting "\\" as needed. +- If any component is an absolute path, all previous path components +- will be discarded.""" +- path = a +- for b in p: +- b_wins = 0 # set to 1 iff b makes path irrelevant +- if path == "": +- b_wins = 1 +- +- elif isabs(b): +- # This probably wipes out path so far. However, it's more +- # complicated if path begins with a drive letter: +- # 1. join('c:', '/a') == 'c:/a' +- # 2. join('c:/', '/a') == 'c:/a' +- # But +- # 3. join('c:/a', '/b') == '/b' +- # 4. join('c:', 'd:/') = 'd:/' +- # 5. join('c:/', 'd:/') = 'd:/' +- if path[1:2] != ":" or b[1:2] == ":": +- # Path doesn't start with a drive letter, or cases 4 and 5. +- b_wins = 1 +- +- # Else path has a drive letter, and b doesn't but is absolute. +- elif len(path) > 3 or (len(path) == 3 and +- path[-1] not in "/\\"): +- # case 3 +- b_wins = 1 +- +- if b_wins: +- path = b +- else: +- # Join, and ensure there's a separator. +- assert len(path) > 0 +- if path[-1] in "/\\": +- if b and b[0] in "/\\": +- path += b[1:] +- else: +- path += b +- elif path[-1] == ":": +- path += b +- elif b: +- if b[0] in "/\\": +- path += b +- else: +- path += "\\" + b +- else: +- # path is not empty and does not end with a backslash, +- # but b is empty; since, e.g., split('a/') produces +- # ('a', ''), it's best if join() adds a backslash in +- # this case. +- path += '\\' +- +- return path ++def join(path, *paths): ++ """Join two or more pathname components, inserting "\\" as needed.""" ++ result_drive, result_path = splitdrive(path) ++ for p in paths: ++ p_drive, p_path = splitdrive(p) ++ if p_path and p_path[0] in '\\/': ++ # Second path is absolute ++ if p_drive or not result_drive: ++ result_drive = p_drive ++ result_path = p_path ++ continue ++ elif p_drive and p_drive != result_drive: ++ if p_drive.lower() != result_drive.lower(): ++ # Different drives => ignore the first path entirely ++ result_drive = p_drive ++ result_path = p_path ++ continue ++ # Same drive in different case ++ result_drive = p_drive ++ # Second path is relative to the first ++ if result_path and result_path[-1] not in '\\/': ++ result_path = result_path + '\\' ++ result_path = result_path + p_path ++ return result_drive + result_path + + + # Split a path in a drive specification (a drive letter followed by a +@@ -144,15 +113,18 @@ + # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter + # \\machine\mountpoint\directories... + # directory ^^^^^^^^^^^^^^^ +- normp = normcase(p) +- index = normp.find('\\', 2) +- if index == -1: +- ##raise RuntimeError, 'illegal UNC path: "' + p + '"' +- return ("", p) +- index = normp.find('\\', index + 1) +- if index == -1: +- index = len(p) +- return p[:index], p[index:] ++ normp = p.replace('\\', '/') ++ index = normp.find('/', 2) ++ if index <= 2: ++ return '', p ++ index2 = normp.find('/', index + 1) ++ # a UNC path can't have two slashes in a row ++ # (after the initial two) ++ if index2 == index + 1: ++ return '', p ++ if index2 == -1: ++ index2 = len(p) ++ return p[:index2], p[index2:] + return '', p + + +@@ -322,6 +294,13 @@ + return path + import string + varchars = string.ascii_letters + string.digits + '_-' ++ if isinstance(path, unicode): ++ encoding = sys.getfilesystemencoding() ++ def getenv(var): ++ return os.environ[var.encode(encoding)].decode(encoding) ++ else: ++ def getenv(var): ++ return os.environ[var] + res = '' + index = 0 + pathlen = len(path) +@@ -350,9 +329,9 @@ + index = pathlen - 1 + else: + var = path[:index] +- if var in os.environ: +- res = res + os.environ[var] +- else: ++ try: ++ res = res + getenv(var) ++ except KeyError: + res = res + '%' + var + '%' + elif c == '$': # variable or '$$' + if path[index + 1:index + 2] == '$': +@@ -364,9 +343,9 @@ + try: + index = path.index('}') + var = path[:index] +- if var in os.environ: +- res = res + os.environ[var] +- else: ++ try: ++ res = res + getenv(var) ++ except KeyError: + res = res + '${' + var + '}' + except ValueError: + res = res + '${' + path +@@ -379,9 +358,9 @@ + var = var + c + index = index + 1 + c = path[index:index + 1] +- if var in os.environ: +- res = res + os.environ[var] +- else: ++ try: ++ res = res + getenv(var) ++ except KeyError: + res = res + '$' + var + if c != '': + index = index - 1 +diff -r 3a1db0d2747e Lib/optparse.py +--- a/Lib/optparse.py ++++ b/Lib/optparse.py +@@ -204,7 +204,6 @@ + short_first): + self.parser = None + self.indent_increment = indent_increment +- self.help_position = self.max_help_position = max_help_position + if width is None: + try: + width = int(os.environ['COLUMNS']) +@@ -212,6 +211,8 @@ + width = 80 + width -= 2 + self.width = width ++ self.help_position = self.max_help_position = \ ++ min(max_help_position, max(width - 20, indent_increment * 2)) + self.current_indent = 0 + self.level = 0 + self.help_width = None # computed later +@@ -256,7 +257,7 @@ + Format a paragraph of free-form text for inclusion in the + help output at the current indentation level. + """ +- text_width = self.width - self.current_indent ++ text_width = max(self.width - self.current_indent, 11) + indent = " "*self.current_indent + return textwrap.fill(text, + text_width, +@@ -337,7 +338,7 @@ + self.dedent() + self.dedent() + self.help_position = min(max_len + 2, self.max_help_position) +- self.help_width = self.width - self.help_position ++ self.help_width = max(self.width - self.help_position, 11) + + def format_option_strings(self, option): + """Return a comma-separated list of option strings & metavariables.""" +diff -r 3a1db0d2747e Lib/pickle.py +--- a/Lib/pickle.py ++++ b/Lib/pickle.py +@@ -269,7 +269,7 @@ + def save(self, obj): + # Check for persistent id (defined by a subclass) + pid = self.persistent_id(obj) +- if pid: ++ if pid is not None: + self.save_pers(pid) + return + +diff -r 3a1db0d2747e Lib/posixpath.py +--- a/Lib/posixpath.py ++++ b/Lib/posixpath.py +@@ -285,28 +285,43 @@ + # Non-existent variables are left unchanged. + + _varprog = None ++_uvarprog = None + + def expandvars(path): + """Expand shell variables of form $var and ${var}. Unknown variables + are left unchanged.""" +- global _varprog ++ global _varprog, _uvarprog + if '$' not in path: + return path +- if not _varprog: +- import re +- _varprog = re.compile(r'\$(\w+|\{[^}]*\})') ++ if isinstance(path, _unicode): ++ if not _varprog: ++ import re ++ _varprog = re.compile(r'\$(\w+|\{[^}]*\})') ++ varprog = _varprog ++ encoding = sys.getfilesystemencoding() ++ else: ++ if not _uvarprog: ++ import re ++ _uvarprog = re.compile(_unicode(r'\$(\w+|\{[^}]*\})'), re.UNICODE) ++ varprog = _uvarprog ++ encoding = None + i = 0 + while True: +- m = _varprog.search(path, i) ++ m = varprog.search(path, i) + if not m: + break + i, j = m.span(0) + name = m.group(1) + if name.startswith('{') and name.endswith('}'): + name = name[1:-1] ++ if encoding: ++ name = name.encode(encoding) + if name in os.environ: + tail = path[j:] +- path = path[:i] + os.environ[name] ++ value = os.environ[name] ++ if encoding: ++ value = value.decode(encoding) ++ path = path[:i] + value + i = len(path) + path += tail + else: +diff -r 3a1db0d2747e Lib/pydoc.py +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -81,6 +81,7 @@ + def getdoc(object): + """Get the doc string or comments for an object.""" + result = inspect.getdoc(object) or inspect.getcomments(object) ++ result = _encode(result) + return result and re.sub('^ *\n', '', rstrip(result)) or '' + + def splitdoc(doc): +@@ -182,6 +183,36 @@ + return name, kind, cls, value + return map(fixup, inspect.classify_class_attrs(object)) + ++# ----------------------------------------------------- Unicode support helpers ++ ++try: ++ _unicode = unicode ++except NameError: ++ # If Python is built without Unicode support, the unicode type ++ # will not exist. Fake one that nothing will match, and make ++ # the _encode function that do nothing. ++ class _unicode(object): ++ pass ++ _encoding = 'ascii' ++ def _encode(text, encoding='ascii'): ++ return text ++else: ++ import locale ++ _encoding = locale.getpreferredencoding() ++ ++ def _encode(text, encoding=None): ++ if isinstance(text, unicode): ++ return text.encode(encoding or _encoding, 'xmlcharrefreplace') ++ else: ++ return text ++ ++def _binstr(obj): ++ # Ensure that we have an encoded (binary) string representation of obj, ++ # even if it is a unicode string. ++ if isinstance(obj, _unicode): ++ return obj.encode(_encoding, 'xmlcharrefreplace') ++ return str(obj) ++ + # ----------------------------------------------------- module manipulation + + def ispackage(path): +@@ -424,12 +455,13 @@ + + def page(self, title, contents): + """Format an HTML page.""" +- return ''' ++ return _encode(''' + + Python: %s ++ + + %s +-''' % (title, contents) ++''' % (title, contents), 'ascii') + + def heading(self, title, fgcol, bgcol, extras=''): + """Format a page heading.""" +@@ -606,12 +638,12 @@ + filelink = '(built-in)' + info = [] + if hasattr(object, '__version__'): +- version = str(object.__version__) ++ version = _binstr(object.__version__) + if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': + version = strip(version[11:-1]) + info.append('version %s' % self.escape(version)) + if hasattr(object, '__date__'): +- info.append(self.escape(str(object.__date__))) ++ info.append(self.escape(_binstr(object.__date__))) + if info: + head = head + ' (%s)' % join(info, ', ') + docloc = self.getdocloc(object) +@@ -694,11 +726,11 @@ + result = result + self.bigsection( + 'Data', '#ffffff', '#55aa55', join(contents, '
\n')) + if hasattr(object, '__author__'): +- contents = self.markup(str(object.__author__), self.preformat) ++ contents = self.markup(_binstr(object.__author__), self.preformat) + result = result + self.bigsection( + 'Author', '#ffffff', '#7799ee', contents) + if hasattr(object, '__credits__'): +- contents = self.markup(str(object.__credits__), self.preformat) ++ contents = self.markup(_binstr(object.__credits__), self.preformat) + result = result + self.bigsection( + 'Credits', '#ffffff', '#7799ee', contents) + +@@ -1116,16 +1148,16 @@ + result = result + self.section('DATA', join(contents, '\n')) + + if hasattr(object, '__version__'): +- version = str(object.__version__) ++ version = _binstr(object.__version__) + if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': + version = strip(version[11:-1]) + result = result + self.section('VERSION', version) + if hasattr(object, '__date__'): +- result = result + self.section('DATE', str(object.__date__)) ++ result = result + self.section('DATE', _binstr(object.__date__)) + if hasattr(object, '__author__'): +- result = result + self.section('AUTHOR', str(object.__author__)) ++ result = result + self.section('AUTHOR', _binstr(object.__author__)) + if hasattr(object, '__credits__'): +- result = result + self.section('CREDITS', str(object.__credits__)) ++ result = result + self.section('CREDITS', _binstr(object.__credits__)) + return result + + def docclass(self, object, name=None, mod=None, *ignored): +@@ -1375,7 +1407,7 @@ + """Page through text by feeding it to another program.""" + pipe = os.popen(cmd, 'w') + try: +- pipe.write(text) ++ pipe.write(_encode(text)) + pipe.close() + except IOError: + pass # Ignore broken pipes caused by quitting the pager program. +@@ -1385,7 +1417,7 @@ + import tempfile + filename = tempfile.mktemp() + file = open(filename, 'w') +- file.write(text) ++ file.write(_encode(text)) + file.close() + try: + os.system(cmd + ' "' + filename + '"') +@@ -1394,7 +1426,7 @@ + + def ttypager(text): + """Page through text on a text terminal.""" +- lines = split(plain(text), '\n') ++ lines = plain(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))).split('\n') + try: + import tty + fd = sys.stdin.fileno() +@@ -1432,7 +1464,7 @@ + + def plainpager(text): + """Simply print unformatted text. This is the ultimate fallback.""" +- sys.stdout.write(plain(text)) ++ sys.stdout.write(_encode(plain(text), getattr(sys.stdout, 'encoding', _encoding))) + + def describe(thing): + """Produce a short description of the given thing.""" +diff -r 3a1db0d2747e Lib/pydoc_data/topics.py +--- a/Lib/pydoc_data/topics.py ++++ b/Lib/pydoc_data/topics.py +@@ -1,4 +1,4 @@ +-# Autogenerated by Sphinx on Sat Oct 26 13:44:16 2013 ++# Autogenerated by Sphinx on Fri Feb 14 06:59:30 2014 + topics = {'assert': '\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n if __debug__:\n if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names. In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O). The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime. Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n', + 'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n target_list ::= target ("," target)* [","]\n target ::= identifier\n | "(" target_list ")"\n | "[" target_list "]"\n | attributeref\n | subscription\n | slicing\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable. The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list is recursively defined as\nfollows.\n\n* If the target list is a single target: The object is assigned to\n that target.\n\n* If the target list is a comma-separated list of targets: The object\n must be an iterable with the same number of items as there are\n targets in the target list, and the items are assigned, from left to\n right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n * If the name does not occur in a ``global`` statement in the\n current code block: the name is bound to the object in the current\n local namespace.\n\n * Otherwise: the name is bound to the object in the current global\n namespace.\n\n The name is rebound if it was already bound. This may cause the\n reference count for the object previously bound to the name to reach\n zero, causing the object to be deallocated and its destructor (if it\n has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n brackets: The object must be an iterable with the same number of\n items as there are targets in the target list, and its items are\n assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n the reference is evaluated. It should yield an object with\n assignable attributes; if this is not the case, ``TypeError`` is\n raised. That object is then asked to assign the assigned object to\n the given attribute; if it cannot perform the assignment, it raises\n an exception (usually but not necessarily ``AttributeError``).\n\n Note: If the object is a class instance and the attribute reference\n occurs on both sides of the assignment operator, the RHS expression,\n ``a.x`` can access either an instance attribute or (if no instance\n attribute exists) a class attribute. The LHS target ``a.x`` is\n always set as an instance attribute, creating it if necessary.\n Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n same attribute: if the RHS expression refers to a class attribute,\n the LHS creates a new instance attribute as the target of the\n assignment:\n\n class Cls:\n x = 3 # class variable\n inst = Cls()\n inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3\n\n This description does not necessarily apply to descriptor\n attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n reference is evaluated. It should yield either a mutable sequence\n object (such as a list) or a mapping object (such as a dictionary).\n Next, the subscript expression is evaluated.\n\n If the primary is a mutable sequence object (such as a list), the\n subscript must yield a plain integer. If it is negative, the\n sequence\'s length is added to it. The resulting value must be a\n nonnegative integer less than the sequence\'s length, and the\n sequence is asked to assign the assigned object to its item with\n that index. If the index is out of range, ``IndexError`` is raised\n (assignment to a subscripted sequence cannot add new items to a\n list).\n\n If the primary is a mapping object (such as a dictionary), the\n subscript must have a type compatible with the mapping\'s key type,\n and the mapping is then asked to create a key/datum pair which maps\n the subscript to the assigned object. This can either replace an\n existing key/value pair with the same key value, or insert a new\n key/value pair (if no key with the same value existed).\n\n* If the target is a slicing: The primary expression in the reference\n is evaluated. It should yield a mutable sequence object (such as a\n list). The assigned object should be a sequence object of the same\n type. Next, the lower and upper bound expressions are evaluated,\n insofar they are present; defaults are zero and the sequence\'s\n length. The bounds should evaluate to (small) integers. If either\n bound is negative, the sequence\'s length is added to it. The\n resulting bounds are clipped to lie between zero and the sequence\'s\n length, inclusive. Finally, the sequence object is asked to replace\n the slice with the items of the assigned sequence. The length of\n the slice may be different from the length of the assigned sequence,\n thus changing the length of the target sequence, if the object\n allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe! For instance, the\nfollowing program prints ``[0, 2]``:\n\n x = [0, 1]\n i = 0\n i, x[i] = 1, 2\n print x\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n augtarget ::= identifier | attributeref | subscription | slicing\n augop ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n', + 'atom-identifiers': '\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name. See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them. The transformation inserts the\nclass name, with leading underscores removed and a single underscore\ninserted, in front of the name. For example, the identifier\n``__spam`` occurring in a class named ``Ham`` will be transformed to\n``_Ham__spam``. This transformation is independent of the syntactical\ncontext in which the identifier is used. If the transformed name is\nextremely long (longer than 255 characters), implementation defined\ntruncation may happen. If the class name consists only of underscores,\nno transformation is done.\n', +@@ -29,11 +29,12 @@ + 'dynamic-features': '\nInteraction with dynamic features\n*********************************\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nIf ``exec`` is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n``SyntaxError`` unless the exec explicitly specifies the local\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, it is used for both.\n', + 'else': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n if_stmt ::= "if" expression ":" suite\n ( "elif" expression ":" suite )*\n ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n', + 'exceptions': '\nExceptions\n**********\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement. The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances. The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nExceptions can also be identified by strings, in which case the\n``except`` clause is selected by object identity. An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API. Their\n contents may change from one version of Python to the next without\n warning and should not be relied on by code which will run under\n multiple versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n operations is not available at the time the module is compiled.\n', ++ 'exec': '\nThe ``exec`` statement\n**********************\n\n exec_stmt ::= "exec" or_expr ["in" expression ["," expression]]\n\nThis statement supports dynamic execution of Python code. The first\nexpression should evaluate to either a Unicode string, a *Latin-1*\nencoded string, an open file object, a code object, or a tuple. If it\nis a string, the string is parsed as a suite of Python statements\nwhich is then executed (unless a syntax error occurs). [1] If it is an\nopen file, the file is parsed until EOF and executed. If it is a code\nobject, it is simply executed. For the interpretation of a tuple, see\nbelow. In all cases, the code that\'s executed is expected to be valid\nas file input (see section *File input*). Be aware that the\n``return`` and ``yield`` statements may not be used outside of\nfunction definitions even within the context of code passed to the\n``exec`` statement.\n\nIn all cases, if the optional parts are omitted, the code is executed\nin the current scope. If only the first expression after ``in`` is\nspecified, it should be a dictionary, which will be used for both the\nglobal and the local variables. If two expressions are given, they\nare used for the global and local variables, respectively. If\nprovided, *locals* can be any mapping object. Remember that at module\nlevel, globals and locals are the same dictionary. If two separate\nobjects are given as *globals* and *locals*, the code will be executed\nas if it were embedded in a class definition.\n\nThe first expression may also be a tuple of length 2 or 3. In this\ncase, the optional parts must be omitted. The form ``exec(expr,\nglobals)`` is equivalent to ``exec expr in globals``, while the form\n``exec(expr, globals, locals)`` is equivalent to ``exec expr in\nglobals, locals``. The tuple form of ``exec`` provides compatibility\nwith Python 3, where ``exec`` is a function rather than a statement.\n\nChanged in version 2.4: Formerly, *locals* was required to be a\ndictionary.\n\nAs a side effect, an implementation may insert additional keys into\nthe dictionaries given besides those corresponding to variable names\nset by the executed code. For example, the current implementation may\nadd a reference to the dictionary of the built-in module\n``__builtin__`` under the key ``__builtins__`` (!).\n\n**Programmer\'s hints:** dynamic evaluation of expressions is supported\nby the built-in function ``eval()``. The built-in functions\n``globals()`` and ``locals()`` return the current global and local\ndictionary, respectively, which may be useful to pass around for use\nby ``exec``.\n\n-[ Footnotes ]-\n\n[1] Note that the parser only accepts the Unix-style end of line\n convention. If you are reading the code from a file, make sure to\n use *universal newlines* mode to convert Windows or Mac-style\n newlines.\n', + 'execmodel': '\nExecution model\n***************\n\n\nNaming and binding\n==================\n\n*Names* refer to objects. Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block. A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the \'**-c**\' option) is a code block. The file read by the\nbuilt-in function ``execfile()`` is a code block. The string argument\npassed to the built-in function ``eval()`` and to the ``exec``\nstatement is a code block. The expression read and evaluated by the\nbuilt-in function ``input()`` is a code block.\n\nA code block is executed in an *execution frame*. A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block\'s execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block. If a local\nvariable is defined in a block, its scope includes that block. If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name. The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes generator expressions since\nthey are implemented using a function scope. This means that the\nfollowing will fail:\n\n class A:\n a = 42\n b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope. The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nIf a name is bound in a block, it is a local variable of that block.\nIf a name is bound at the module level, it is a global variable. (The\nvariables of the module code block are local and global.) If a\nvariable is used in a code block but not defined there, it is a *free\nvariable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised. ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, in the\nsecond position of an ``except`` clause header or after ``as`` in a\n``with`` statement. The ``import`` statement of the form ``from ...\nimport *`` binds all names defined in the imported module, except\nthose beginning with an underscore. This form may only be used at the\nmodule level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name). It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block. This can lead to errors when a name is used within a\nblock before it is bound. This rule is subtle. Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block. The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the global statement occurs within a block, all uses of the name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace. Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module ``__builtin__``. The global namespace is searched\nfirst. If the name is not found there, the builtins namespace is\nsearched. The global statement must precede all uses of the name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used). By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``__builtin__`` (note: no \'s\'); when in any other module,\n``__builtins__`` is an alias for the dictionary of the ``__builtin__``\nmodule itself. ``__builtins__`` can be set to a user-created\ndictionary to create a weak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail. Users\nwanting to override values in the builtins namespace should ``import``\nthe ``__builtin__`` (no \'s\') module and modify its attributes\nappropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported. The main module for a script is always called\n``__main__``.\n\nThe ``global`` statement has the same scope as a name binding\noperation in the same block. If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class. Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name. An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nIf ``exec`` is used in a function and the function contains or is a\nnested block with free variables, the compiler will raise a\n``SyntaxError`` unless the exec explicitly specifies the local\nnamespace for the ``exec``. (In other words, ``exec obj`` would be\nillegal, but ``exec obj in ns`` would be legal.)\n\nThe ``eval()``, ``execfile()``, and ``input()`` functions and the\n``exec`` statement do not have access to the full environment for\nresolving names. Names may be resolved in the local and global\nnamespaces of the caller. Free variables are not resolved in the\nnearest enclosing namespace, but in the global namespace. [1] The\n``exec`` statement and the ``eval()`` and ``execfile()`` functions\nhave optional arguments to override the global and local namespace.\nIf only one namespace is specified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions. An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero). A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement. The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop. In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances. The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof. The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nExceptions can also be identified by strings, in which case the\n``except`` clause is selected by object identity. An arbitrary value\ncan be raised along with the identifying string which can be passed to\nthe handler.\n\nNote: Messages to exceptions are not part of the Python API. Their\n contents may change from one version of Python to the next without\n warning and should not be relied on by code which will run under\n multiple versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n operations is not available at the time the module is compiled.\n', + 'exprlists': '\nExpression lists\n****************\n\n expression_list ::= expression ( "," expression )* [","]\n\nAn expression list containing at least one comma yields a tuple. The\nlength of the tuple is the number of expressions in the list. The\nexpressions are evaluated from left to right.\n\nThe trailing comma is required only to create a single tuple (a.k.a. a\n*singleton*); it is optional in all other cases. A single expression\nwithout a trailing comma doesn\'t create a tuple, but rather yields the\nvalue of that expression. (To create an empty tuple, use an empty pair\nof parentheses: ``()``.)\n', + 'floating': '\nFloating point literals\n***********************\n\nFloating point literals are described by the following lexical\ndefinitions:\n\n floatnumber ::= pointfloat | exponentfloat\n pointfloat ::= [intpart] fraction | intpart "."\n exponentfloat ::= (intpart | pointfloat) exponent\n intpart ::= digit+\n fraction ::= "." digit+\n exponent ::= ("e" | "E") ["+" | "-"] digit+\n\nNote that the integer and exponent parts of floating point numbers can\nlook like octal integers, but are interpreted using radix 10. For\nexample, ``077e010`` is legal, and denotes the same number as\n``77e10``. The allowed range of floating point literals is\nimplementation-dependent. Some examples of floating point literals:\n\n 3.14 10. .001 1e100 3.14e-10 0e0\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator ``-`` and the\nliteral ``1``.\n', + 'for': '\nThe ``for`` statement\n*********************\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n for_stmt ::= "for" target_list "in" expression_list ":" suite\n ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject. An iterator is created for the result of the\n``expression_list``. The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices. Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments, and then the suite is executed. When the items are\nexhausted (which is immediately when the sequence is empty), the suite\nin the ``else`` clause, if present, is executed, and the loop\nterminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nThe target list is not deleted when the loop is finished, but if the\nsequence is empty, it will not have been assigned to at all by the\nloop. Hint: the built-in function ``range()`` returns a sequence of\nintegers suitable to emulate the effect of Pascal\'s ``for i := a to b\ndo``; e.g., ``range(3)`` returns the list ``[0, 1, 2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n (this can only occur for mutable sequences, i.e. lists). An internal\n counter is used to keep track of which item is used next, and this\n is incremented on each iteration. When this counter has reached the\n length of the sequence the loop terminates. This means that if the\n suite deletes the current (or a previous) item from the sequence,\n the next item will be skipped (since it gets the index of the\n current item which has already been treated). Likewise, if the\n suite inserts an item in the sequence before the current item, the\n current item will be treated again the next time through the loop.\n This can lead to nasty bugs that can be avoided by making a\n temporary copy using a slice of the whole sequence, e.g.,\n\n for x in a[:]:\n if x < 0: a.remove(x)\n', +- 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output. If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe grammar for a replacement field is as follows:\n\n replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n field_name ::= arg_name ("." attribute_name | "[" element_index "]")*\n arg_name ::= [identifier | integer]\n attribute_name ::= identifier\n element_index ::= integer | index_string\n index_string ::= +\n conversion ::= "r" | "s"\n format_spec ::= \n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a *conversion* field, which is\npreceded by an exclamation point ``\'!\'``, and a *format_spec*, which\nis preceded by a colon ``\':\'``. These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword. If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument. If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings ``\'10\'`` or\n``\':-]\'``) within a format string. The *arg_name* can be followed by\nany number of index or attribute expressions. An expression of the\nform ``\'.name\'`` selects the named attribute using ``getattr()``,\nwhile an expression of the form ``\'[index]\'`` does an index lookup\nusing ``__getitem__()``.\n\nChanged in version 2.7: The positional argument specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to ``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n "First, thou shalt count to {0}" # References first positional argument\n "Bring me a {}" # Implicitly references the first positional argument\n "From {} to {}" # Same as "From {0} to {1}"\n "My quest is {name}" # References keyword argument \'name\'\n "Weight in tons {0.weight}" # \'weight\' attribute of first positional arg\n "Units destroyed: {players[0]}" # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself. However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting. By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nTwo conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, and ``\'!r\'`` which calls ``repr()``.\n\nSome examples:\n\n "Harold\'s a clever {0!s}" # Calls str() on the argument first\n "Bring out the holy {name!r}" # Calls repr() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on. Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed. The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*). They can also be passed directly to the\nbuilt-in ``format()`` function. Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value. A non-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n fill ::= \n align ::= "<" | ">" | "=" | "^"\n sign ::= "+" | "-" | " "\n width ::= integer\n precision ::= integer\n type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nIf a valid *align* value is specified, it can be preceeded by a *fill*\ncharacter that can be any character and defaults to a space if\nomitted. Note that it is not possible to use ``{`` and ``}`` as *fill*\nchar while using the ``str.format()`` method; this limitation however\ndoesn\'t affect the ``format()`` function.\n\nThe meaning of the various alignment options is as follows:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'<\'`` | Forces the field to be left-aligned within the available |\n | | space (this is the default for most objects). |\n +-----------+------------------------------------------------------------+\n | ``\'>\'`` | Forces the field to be right-aligned within the available |\n | | space (this is the default for numbers). |\n +-----------+------------------------------------------------------------+\n | ``\'=\'`` | Forces the padding to be placed after the sign (if any) |\n | | but before the digits. This is used for printing fields |\n | | in the form \'+000000120\'. This alignment option is only |\n | | valid for numeric types. |\n +-----------+------------------------------------------------------------+\n | ``\'^\'`` | Forces the field to be centered within the available |\n | | space. |\n +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'+\'`` | indicates that a sign should be used for both positive as |\n | | well as negative numbers. |\n +-----------+------------------------------------------------------------+\n | ``\'-\'`` | indicates that a sign should be used only for negative |\n | | numbers (this is the default behavior). |\n +-----------+------------------------------------------------------------+\n | space | indicates that a leading space should be used on positive |\n | | numbers, and a minus sign on negative numbers. |\n +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output. If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 2.7: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width. If not\nspecified, then the field width will be determined by the content.\n\nPreceding the *width* field by a zero (``\'0\'``) character enables\nsign-aware zero-padding for numeric types. This is equivalent to a\n*fill* character of ``\'0\'`` with an *alignment* type of ``\'=\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'s\'`` | String format. This is the default type for strings and |\n | | may be omitted. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'s\'``. |\n +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'b\'`` | Binary format. Outputs the number in base 2. |\n +-----------+------------------------------------------------------------+\n | ``\'c\'`` | Character. Converts the integer to the corresponding |\n | | unicode character before printing. |\n +-----------+------------------------------------------------------------+\n | ``\'d\'`` | Decimal Integer. Outputs the number in base 10. |\n +-----------+------------------------------------------------------------+\n | ``\'o\'`` | Octal format. Outputs the number in base 8. |\n +-----------+------------------------------------------------------------+\n | ``\'x\'`` | Hex format. Outputs the number in base 16, using lower- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'X\'`` | Hex format. Outputs the number in base 16, using upper- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'d\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'d\'``. |\n +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'e\'`` | Exponent notation. Prints the number in scientific |\n | | notation using the letter \'e\' to indicate the exponent. |\n | | The default precision is ``6``. |\n +-----------+------------------------------------------------------------+\n | ``\'E\'`` | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n | | case \'E\' as the separator character. |\n +-----------+------------------------------------------------------------+\n | ``\'f\'`` | Fixed point. Displays the number as a fixed-point number. |\n | | The default precision is ``6``. |\n +-----------+------------------------------------------------------------+\n | ``\'F\'`` | Fixed point. Same as ``\'f\'``. |\n +-----------+------------------------------------------------------------+\n | ``\'g\'`` | General format. For a given precision ``p >= 1``, this |\n | | rounds the number to ``p`` significant digits and then |\n | | formats the result in either fixed-point format or in |\n | | scientific notation, depending on its magnitude. The |\n | | precise rules are as follows: suppose that the result |\n | | formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp |\n | | < p``, the number is formatted with presentation type |\n | | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number |\n | | is formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1``. In both cases insignificant trailing zeros are |\n | | removed from the significand, and the decimal point is |\n | | also removed if there are no remaining digits following |\n | | it. Positive and negative infinity, positive and negative |\n | | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n | | ``-0`` and ``nan`` respectively, regardless of the |\n | | precision. A precision of ``0`` is treated as equivalent |\n | | to a precision of ``1``. The default precision is ``6``. |\n +-----------+------------------------------------------------------------+\n | ``\'G\'`` | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n | | if the number gets too large. The representations of |\n | | infinity and NaN are uppercased, too. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'g\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | ``\'%\'`` | Percentage. Multiplies the number by 100 and displays in |\n | | fixed (``\'f\'``) format, followed by a percent sign. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'g\'``. |\n +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the new format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of the cases the syntax is similar to the old\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n \'a, b, c\'\n >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\') # 2.7+ only\n \'a, b, c\'\n >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n \'c, b, a\'\n >>> \'{2}, {1}, {0}\'.format(*\'abc\') # unpacking argument sequence\n \'c, b, a\'\n >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\') # arguments\' indices can be repeated\n \'abracadabra\'\n\nAccessing arguments by name:\n\n >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n \'Coordinates: 37.24N, -115.81W\'\n >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n >>> c = 3-5j\n >>> (\'The complex number {0} is formed from the real part {0.real} \'\n ... \'and the imaginary part {0.imag}.\').format(c)\n \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n >>> class Point(object):\n ... def __init__(self, x, y):\n ... self.x, self.y = x, y\n ... def __str__(self):\n ... return \'Point({self.x}, {self.y})\'.format(self=self)\n ...\n >>> str(Point(4, 2))\n \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n >>> coord = (3, 5)\n >>> \'X: {0[0]}; Y: {0[1]}\'.format(coord)\n \'X: 3; Y: 5\'\n\nReplacing ``%s`` and ``%r``:\n\n >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n >>> \'{:<30}\'.format(\'left aligned\')\n \'left aligned \'\n >>> \'{:>30}\'.format(\'right aligned\')\n \' right aligned\'\n >>> \'{:^30}\'.format(\'centered\')\n \' centered \'\n >>> \'{:*^30}\'.format(\'centered\') # use \'*\' as a fill char\n \'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\n\n >>> \'{:+f}; {:+f}\'.format(3.14, -3.14) # show it always\n \'+3.140000; -3.140000\'\n >>> \'{: f}; {: f}\'.format(3.14, -3.14) # show a space for positive numbers\n \' 3.140000; -3.140000\'\n >>> \'{:-f}; {:-f}\'.format(3.14, -3.14) # show only the minus -- same as \'{:f}; {:f}\'\n \'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and converting the value to different\nbases:\n\n >>> # format also supports binary numbers\n >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)\n \'int: 42; hex: 2a; oct: 52; bin: 101010\'\n >>> # with 0x, 0o, or 0b as prefix:\n >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)\n \'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n >>> \'{:,}\'.format(1234567890)\n \'1,234,567,890\'\n\nExpressing a percentage:\n\n >>> points = 19.5\n >>> total = 22\n >>> \'Correct answers: {:.2%}\'.format(points/total)\n \'Correct answers: 88.64%\'\n\nUsing type-specific formatting:\n\n >>> import datetime\n >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n ... \'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n ...\n \'left<<<<<<<<<<<<\'\n \'^^^^^center^^^^^\'\n \'>>>>>>>>>>>right\'\n >>>\n >>> octets = [192, 168, 0, 1]\n >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n \'C0A80001\'\n >>> int(_, 16)\n 3232235521\n >>>\n >>> width = 5\n >>> for num in range(5,12):\n ... for base in \'dXob\':\n ... print \'{0:{width}{base}}\'.format(num, base=base, width=width),\n ... print\n ...\n 5 5 5 101\n 6 6 6 110\n 7 7 7 111\n 8 8 10 1000\n 9 9 11 1001\n 10 A 12 1010\n 11 B 13 1011\n', ++ 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output. If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe grammar for a replacement field is as follows:\n\n replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n field_name ::= arg_name ("." attribute_name | "[" element_index "]")*\n arg_name ::= [identifier | integer]\n attribute_name ::= identifier\n element_index ::= integer | index_string\n index_string ::= +\n conversion ::= "r" | "s"\n format_spec ::= \n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a *conversion* field, which is\npreceded by an exclamation point ``\'!\'``, and a *format_spec*, which\nis preceded by a colon ``\':\'``. These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword. If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument. If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings ``\'10\'`` or\n``\':-]\'``) within a format string. The *arg_name* can be followed by\nany number of index or attribute expressions. An expression of the\nform ``\'.name\'`` selects the named attribute using ``getattr()``,\nwhile an expression of the form ``\'[index]\'`` does an index lookup\nusing ``__getitem__()``.\n\nChanged in version 2.7: The positional argument specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to ``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n "First, thou shalt count to {0}" # References first positional argument\n "Bring me a {}" # Implicitly references the first positional argument\n "From {} to {}" # Same as "From {0} to {1}"\n "My quest is {name}" # References keyword argument \'name\'\n "Weight in tons {0.weight}" # \'weight\' attribute of first positional arg\n "Units destroyed: {players[0]}" # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself. However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting. By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nTwo conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, and ``\'!r\'`` which calls ``repr()``.\n\nSome examples:\n\n "Harold\'s a clever {0!s}" # Calls str() on the argument first\n "Bring out the holy {name!r}" # Calls repr() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on. Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed. The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*). They can also be passed directly to the\nbuilt-in ``format()`` function. Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value. A non-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n fill ::= \n align ::= "<" | ">" | "=" | "^"\n sign ::= "+" | "-" | " "\n width ::= integer\n precision ::= integer\n type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nIf a valid *align* value is specified, it can be preceded by a *fill*\ncharacter that can be any character and defaults to a space if\nomitted. Note that it is not possible to use ``{`` and ``}`` as *fill*\nchar while using the ``str.format()`` method; this limitation however\ndoesn\'t affect the ``format()`` function.\n\nThe meaning of the various alignment options is as follows:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'<\'`` | Forces the field to be left-aligned within the available |\n | | space (this is the default for most objects). |\n +-----------+------------------------------------------------------------+\n | ``\'>\'`` | Forces the field to be right-aligned within the available |\n | | space (this is the default for numbers). |\n +-----------+------------------------------------------------------------+\n | ``\'=\'`` | Forces the padding to be placed after the sign (if any) |\n | | but before the digits. This is used for printing fields |\n | | in the form \'+000000120\'. This alignment option is only |\n | | valid for numeric types. |\n +-----------+------------------------------------------------------------+\n | ``\'^\'`` | Forces the field to be centered within the available |\n | | space. |\n +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n +-----------+------------------------------------------------------------+\n | Option | Meaning |\n +===========+============================================================+\n | ``\'+\'`` | indicates that a sign should be used for both positive as |\n | | well as negative numbers. |\n +-----------+------------------------------------------------------------+\n | ``\'-\'`` | indicates that a sign should be used only for negative |\n | | numbers (this is the default behavior). |\n +-----------+------------------------------------------------------------+\n | space | indicates that a leading space should be used on positive |\n | | numbers, and a minus sign on negative numbers. |\n +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output. If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 2.7: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width. If not\nspecified, then the field width will be determined by the content.\n\nPreceding the *width* field by a zero (``\'0\'``) character enables\nsign-aware zero-padding for numeric types. This is equivalent to a\n*fill* character of ``\'0\'`` with an *alignment* type of ``\'=\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'s\'`` | String format. This is the default type for strings and |\n | | may be omitted. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'s\'``. |\n +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'b\'`` | Binary format. Outputs the number in base 2. |\n +-----------+------------------------------------------------------------+\n | ``\'c\'`` | Character. Converts the integer to the corresponding |\n | | unicode character before printing. |\n +-----------+------------------------------------------------------------+\n | ``\'d\'`` | Decimal Integer. Outputs the number in base 10. |\n +-----------+------------------------------------------------------------+\n | ``\'o\'`` | Octal format. Outputs the number in base 8. |\n +-----------+------------------------------------------------------------+\n | ``\'x\'`` | Hex format. Outputs the number in base 16, using lower- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'X\'`` | Hex format. Outputs the number in base 16, using upper- |\n | | case letters for the digits above 9. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'d\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'d\'``. |\n +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n +-----------+------------------------------------------------------------+\n | Type | Meaning |\n +===========+============================================================+\n | ``\'e\'`` | Exponent notation. Prints the number in scientific |\n | | notation using the letter \'e\' to indicate the exponent. |\n | | The default precision is ``6``. |\n +-----------+------------------------------------------------------------+\n | ``\'E\'`` | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n | | case \'E\' as the separator character. |\n +-----------+------------------------------------------------------------+\n | ``\'f\'`` | Fixed point. Displays the number as a fixed-point number. |\n | | The default precision is ``6``. |\n +-----------+------------------------------------------------------------+\n | ``\'F\'`` | Fixed point. Same as ``\'f\'``. |\n +-----------+------------------------------------------------------------+\n | ``\'g\'`` | General format. For a given precision ``p >= 1``, this |\n | | rounds the number to ``p`` significant digits and then |\n | | formats the result in either fixed-point format or in |\n | | scientific notation, depending on its magnitude. The |\n | | precise rules are as follows: suppose that the result |\n | | formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1`` would have exponent ``exp``. Then if ``-4 <= exp |\n | | < p``, the number is formatted with presentation type |\n | | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number |\n | | is formatted with presentation type ``\'e\'`` and precision |\n | | ``p-1``. In both cases insignificant trailing zeros are |\n | | removed from the significand, and the decimal point is |\n | | also removed if there are no remaining digits following |\n | | it. Positive and negative infinity, positive and negative |\n | | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n | | ``-0`` and ``nan`` respectively, regardless of the |\n | | precision. A precision of ``0`` is treated as equivalent |\n | | to a precision of ``1``. The default precision is ``6``. |\n +-----------+------------------------------------------------------------+\n | ``\'G\'`` | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n | | if the number gets too large. The representations of |\n | | infinity and NaN are uppercased, too. |\n +-----------+------------------------------------------------------------+\n | ``\'n\'`` | Number. This is the same as ``\'g\'``, except that it uses |\n | | the current locale setting to insert the appropriate |\n | | number separator characters. |\n +-----------+------------------------------------------------------------+\n | ``\'%\'`` | Percentage. Multiplies the number by 100 and displays in |\n | | fixed (``\'f\'``) format, followed by a percent sign. |\n +-----------+------------------------------------------------------------+\n | None | The same as ``\'g\'``. |\n +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the new format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of the cases the syntax is similar to the old\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n \'a, b, c\'\n >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\') # 2.7+ only\n \'a, b, c\'\n >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n \'c, b, a\'\n >>> \'{2}, {1}, {0}\'.format(*\'abc\') # unpacking argument sequence\n \'c, b, a\'\n >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\') # arguments\' indices can be repeated\n \'abracadabra\'\n\nAccessing arguments by name:\n\n >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n \'Coordinates: 37.24N, -115.81W\'\n >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n >>> c = 3-5j\n >>> (\'The complex number {0} is formed from the real part {0.real} \'\n ... \'and the imaginary part {0.imag}.\').format(c)\n \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n >>> class Point(object):\n ... def __init__(self, x, y):\n ... self.x, self.y = x, y\n ... def __str__(self):\n ... return \'Point({self.x}, {self.y})\'.format(self=self)\n ...\n >>> str(Point(4, 2))\n \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n >>> coord = (3, 5)\n >>> \'X: {0[0]}; Y: {0[1]}\'.format(coord)\n \'X: 3; Y: 5\'\n\nReplacing ``%s`` and ``%r``:\n\n >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n >>> \'{:<30}\'.format(\'left aligned\')\n \'left aligned \'\n >>> \'{:>30}\'.format(\'right aligned\')\n \' right aligned\'\n >>> \'{:^30}\'.format(\'centered\')\n \' centered \'\n >>> \'{:*^30}\'.format(\'centered\') # use \'*\' as a fill char\n \'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\n\n >>> \'{:+f}; {:+f}\'.format(3.14, -3.14) # show it always\n \'+3.140000; -3.140000\'\n >>> \'{: f}; {: f}\'.format(3.14, -3.14) # show a space for positive numbers\n \' 3.140000; -3.140000\'\n >>> \'{:-f}; {:-f}\'.format(3.14, -3.14) # show only the minus -- same as \'{:f}; {:f}\'\n \'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and converting the value to different\nbases:\n\n >>> # format also supports binary numbers\n >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)\n \'int: 42; hex: 2a; oct: 52; bin: 101010\'\n >>> # with 0x, 0o, or 0b as prefix:\n >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)\n \'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n >>> \'{:,}\'.format(1234567890)\n \'1,234,567,890\'\n\nExpressing a percentage:\n\n >>> points = 19.5\n >>> total = 22\n >>> \'Correct answers: {:.2%}\'.format(points/total)\n \'Correct answers: 88.64%\'\n\nUsing type-specific formatting:\n\n >>> import datetime\n >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n ... \'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n ...\n \'left<<<<<<<<<<<<\'\n \'^^^^^center^^^^^\'\n \'>>>>>>>>>>>right\'\n >>>\n >>> octets = [192, 168, 0, 1]\n >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n \'C0A80001\'\n >>> int(_, 16)\n 3232235521\n >>>\n >>> width = 5\n >>> for num in range(5,12):\n ... for base in \'dXob\':\n ... print \'{0:{width}{base}}\'.format(num, base=base, width=width),\n ... print\n ...\n 5 5 5 101\n 6 6 6 110\n 7 7 7 111\n 8 8 10 1000\n 9 9 11 1001\n 10 A 12 1010\n 11 B 13 1011\n', + 'function': '\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n decorated ::= decorators (classdef | funcdef)\n decorators ::= decorator+\n decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite\n dotted_name ::= identifier ("." identifier)*\n parameter_list ::= (defparameter ",")*\n ( "*" identifier ["," "**" identifier]\n | "**" identifier\n | defparameter [","] )\n defparameter ::= parameter ["=" expression]\n sublist ::= parameter ("," parameter)* [","]\n parameter ::= identifier | "(" sublist ")"\n funcname ::= identifier\n\nA function definition is an executable statement. Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function). This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition. The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object. Multiple decorators are applied in\nnested fashion. For example, the following code:\n\n @f1(arg)\n @f2\n def func(): pass\n\nis equivalent to:\n\n def func(): pass\n func = f1(arg)(f2(func))\n\nWhen one or more top-level *parameters* have the form *parameter*\n``=`` *expression*, the function is said to have "default parameter\nvalues." For a parameter with a default value, the corresponding\n*argument* may be omitted from a call, in which case the parameter\'s\ndefault value is substituted. If a parameter has a default value, all\nfollowing parameters must also have a default value --- this is a\nsyntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that the same "pre-computed" value is\nused for each call. This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended. A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n def whats_on_the_telly(penguin=None):\n if penguin is None:\n penguin = []\n penguin.append("property of the zoo")\n return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values. If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple. If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions. This uses lambda\nexpressions, described in section *Lambdas*. Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a "``def``" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression. The "``def``" form is actually more powerful since it\nallows the execution of multiple statements.\n\n**Programmer\'s note:** Functions are first-class objects. A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around. Free variables used in the\nnested function can access the local variables of the function\ncontaining the def. See section *Naming and binding* for details.\n', + 'global': '\nThe ``global`` statement\n************************\n\n global_stmt ::= "global" identifier ("," identifier)*\n\nThe ``global`` statement is a declaration which holds for the entire\ncurrent code block. It means that the listed identifiers are to be\ninterpreted as globals. It would be impossible to assign to a global\nvariable without ``global``, although free variables may refer to\nglobals without being declared global.\n\nNames listed in a ``global`` statement must not be used in the same\ncode block textually preceding that ``global`` statement.\n\nNames listed in a ``global`` statement must not be defined as formal\nparameters or in a ``for`` loop control target, ``class`` definition,\nfunction definition, or ``import`` statement.\n\n**CPython implementation detail:** The current implementation does not\nenforce the latter two restrictions, but programs should not abuse\nthis freedom, as future implementations may enforce them or silently\nchange the meaning of the program.\n\n**Programmer\'s note:** the ``global`` is a directive to the parser.\nIt applies only to code parsed at the same time as the ``global``\nstatement. In particular, a ``global`` statement contained in an\n``exec`` statement does not affect the code block *containing* the\n``exec`` statement, and code contained in an ``exec`` statement is\nunaffected by ``global`` statements in the code containing the\n``exec`` statement. The same applies to the ``eval()``,\n``execfile()`` and ``compile()`` functions.\n', + 'id-classes': '\nReserved classes of identifiers\n*******************************\n\nCertain classes of identifiers (besides keywords) have special\nmeanings. These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n Not imported by ``from module import *``. The special identifier\n ``_`` is used in the interactive interpreter to store the result of\n the last evaluation; it is stored in the ``__builtin__`` module.\n When not in interactive mode, ``_`` has no special meaning and is\n not defined. See section *The import statement*.\n\n Note: The name ``_`` is often used in conjunction with\n internationalization; refer to the documentation for the\n ``gettext`` module for more information on this convention.\n\n``__*__``\n System-defined names. These names are defined by the interpreter\n and its implementation (including the standard library). Current\n system names are discussed in the *Special method names* section\n and elsewhere. More will likely be defined in future versions of\n Python. *Any* use of ``__*__`` names, in any context, that does\n not follow explicitly documented use, is subject to breakage\n without warning.\n\n``__*``\n Class-private names. Names in this category, when used within the\n context of a class definition, are re-written to use a mangled form\n to help avoid name clashes between "private" attributes of base and\n derived classes. See section *Identifiers (Names)*.\n', +@@ -52,6 +53,7 @@ + 'operator-summary': '\nOperator precedence\n*******************\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding). Operators in the same box have the same precedence. Unless\nthe syntax is explicitly given, operators are binary. Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator | Description |\n+=================================================+=======================================+\n| ``lambda`` | Lambda expression |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else`` | Conditional expression |\n+-------------------------------------------------+---------------------------------------+\n| ``or`` | Boolean OR |\n+-------------------------------------------------+---------------------------------------+\n| ``and`` | Boolean AND |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` ``x`` | Boolean NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not in``, ``is``, ``is not``, ``<``, | Comparisons, including membership |\n| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | tests and identity tests |\n+-------------------------------------------------+---------------------------------------+\n| ``|`` | Bitwise OR |\n+-------------------------------------------------+---------------------------------------+\n| ``^`` | Bitwise XOR |\n+-------------------------------------------------+---------------------------------------+\n| ``&`` | Bitwise AND |\n+-------------------------------------------------+---------------------------------------+\n| ``<<``, ``>>`` | Shifts |\n+-------------------------------------------------+---------------------------------------+\n| ``+``, ``-`` | Addition and subtraction |\n+-------------------------------------------------+---------------------------------------+\n| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |\n| | [8] |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |\n+-------------------------------------------------+---------------------------------------+\n| ``**`` | Exponentiation [9] |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``, | Subscription, slicing, call, |\n| ``x(arguments...)``, ``x.attribute`` | attribute reference |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``, | Binding or tuple display, list |\n| ``{key: value...}``, ```expressions...``` | display, dictionary display, string |\n| | conversion |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] In Python 2.3 and later releases, a list comprehension "leaks" the\n control variables of each ``for`` it contains into the containing\n scope. However, this behavior is deprecated, and relying on it\n will not work in Python 3.\n\n[2] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n may not be true numerically due to roundoff. For example, and\n assuming a platform on which a Python float is an IEEE 754 double-\n precision number, in order that ``-1e-100 % 1e100`` have the same\n sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n which is numerically exactly equal to ``1e100``. The function\n ``math.fmod()`` returns a result whose sign matches the sign of\n the first argument instead, and so returns ``-1e-100`` in this\n case. Which approach is more appropriate depends on the\n application.\n\n[3] If x is very close to an exact integer multiple of y, it\'s\n possible for ``floor(x/y)`` to be one larger than ``(x-x%y)/y``\n due to rounding. In such cases, Python returns the latter result,\n in order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n close to ``x``.\n\n[4] While comparisons between unicode strings make sense at the byte\n level, they may be counter-intuitive to users. For example, the\n strings ``u"\\u00C7"`` and ``u"\\u0043\\u0327"`` compare differently,\n even though they both represent the same unicode character (LATIN\n CAPITAL LETTER C WITH CEDILLA). To compare strings in a human\n recognizable way, compare using ``unicodedata.normalize()``.\n\n[5] The implementation computes this efficiently, without constructing\n lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of the\n sorted (key, value) lists, but this was very expensive for the\n common case of comparing for equality. An even earlier version of\n Python compared dictionaries by identity only, but this caused\n surprises because people expected to be able to test a dictionary\n for emptiness by comparing it to ``{}``.\n\n[7] Due to automatic garbage-collection, free lists, and the dynamic\n nature of descriptors, you may notice seemingly unusual behaviour\n in certain uses of the ``is`` operator, like those involving\n comparisons between instance methods, or constants. Check their\n documentation for more info.\n\n[8] The ``%`` operator is also used for string formatting; the same\n precedence applies.\n\n[9] The power operator ``**`` binds less tightly than an arithmetic or\n bitwise unary operator on its right, that is, ``2**-1`` is\n ``0.5``.\n', + 'pass': '\nThe ``pass`` statement\n**********************\n\n pass_stmt ::= "pass"\n\n``pass`` is a null operation --- when it is executed, nothing happens.\nIt is useful as a placeholder when a statement is required\nsyntactically, but no code needs to be executed, for example:\n\n def f(arg): pass # a function that does nothing (yet)\n\n class C: pass # a class with no methods (yet)\n', + 'power': '\nThe power operator\n******************\n\nThe power operator binds more tightly than unary operators on its\nleft; it binds less tightly than unary operators on its right. The\nsyntax is:\n\n power ::= primary ["**" u_expr]\n\nThus, in an unparenthesized sequence of power and unary operators, the\noperators are evaluated from right to left (this does not constrain\nthe evaluation order for the operands): ``-1**2`` results in ``-1``.\n\nThe power operator has the same semantics as the built-in ``pow()``\nfunction, when called with two arguments: it yields its left argument\nraised to the power of its right argument. The numeric arguments are\nfirst converted to a common type. The result type is that of the\narguments after coercion.\n\nWith mixed operand types, the coercion rules for binary arithmetic\noperators apply. For int and long int operands, the result has the\nsame type as the operands (after coercion) unless the second argument\nis negative; in that case, all arguments are converted to float and a\nfloat result is delivered. For example, ``10**2`` returns ``100``, but\n``10**-2`` returns ``0.01``. (This last feature was added in Python\n2.2. In Python 2.1 and before, if both arguments were of integer types\nand the second argument was negative, an exception was raised).\n\nRaising ``0.0`` to a negative power results in a\n``ZeroDivisionError``. Raising a negative number to a fractional power\nresults in a ``ValueError``.\n', ++ 'print': '\nThe ``print`` statement\n***********************\n\n print_stmt ::= "print" ([expression ("," expression)* [","]]\n | ">>" expression [("," expression)+ [","]])\n\n``print`` evaluates each expression in turn and writes the resulting\nobject to standard output (see below). If an object is not a string,\nit is first converted to a string using the rules for string\nconversions. The (resulting or original) string is then written. A\nspace is written before each object is (converted and) written, unless\nthe output system believes it is positioned at the beginning of a\nline. This is the case (1) when no characters have yet been written\nto standard output, (2) when the last character written to standard\noutput is a whitespace character except ``\' \'``, or (3) when the last\nwrite operation on standard output was not a ``print`` statement. (In\nsome cases it may be functional to write an empty string to standard\noutput for this reason.)\n\nNote: Objects which act like file objects but which are not the built-in\n file objects often do not properly emulate this aspect of the file\n object\'s behavior, so it is best not to rely on this.\n\nA ``\'\\n\'`` character is written at the end, unless the ``print``\nstatement ends with a comma. This is the only action if the statement\ncontains just the keyword ``print``.\n\nStandard output is defined as the file object named ``stdout`` in the\nbuilt-in module ``sys``. If no such object exists, or if it does not\nhave a ``write()`` method, a ``RuntimeError`` exception is raised.\n\n``print`` also has an extended form, defined by the second portion of\nthe syntax described above. This form is sometimes referred to as\n"``print`` chevron." In this form, the first expression after the\n``>>`` must evaluate to a "file-like" object, specifically an object\nthat has a ``write()`` method as described above. With this extended\nform, the subsequent expressions are printed to this file object. If\nthe first expression evaluates to ``None``, then ``sys.stdout`` is\nused as the file for output.\n', + 'raise': '\nThe ``raise`` statement\n***********************\n\n raise_stmt ::= "raise" [expression ["," expression ["," expression]]]\n\nIf no expressions are present, ``raise`` re-raises the last exception\nthat was active in the current scope. If no exception is active in\nthe current scope, a ``TypeError`` exception is raised indicating that\nthis is an error (if running under IDLE, a ``Queue.Empty`` exception\nis raised instead).\n\nOtherwise, ``raise`` evaluates the expressions to get three objects,\nusing ``None`` as the value of omitted expressions. The first two\nobjects are used to determine the *type* and *value* of the exception.\n\nIf the first object is an instance, the type of the exception is the\nclass of the instance, the instance itself is the value, and the\nsecond object must be ``None``.\n\nIf the first object is a class, it becomes the type of the exception.\nThe second object is used to determine the exception value: If it is\nan instance of the class, the instance becomes the exception value. If\nthe second object is a tuple, it is used as the argument list for the\nclass constructor; if it is ``None``, an empty argument list is used,\nand any other object is treated as a single argument to the\nconstructor. The instance so created by calling the constructor is\nused as the exception value.\n\nIf a third object is present and not ``None``, it must be a traceback\nobject (see section *The standard type hierarchy*), and it is\nsubstituted instead of the current location as the place where the\nexception occurred. If the third object is present and not a\ntraceback object or ``None``, a ``TypeError`` exception is raised.\nThe three-expression form of ``raise`` is useful to re-raise an\nexception transparently in an except clause, but ``raise`` with no\nexpressions should be preferred if the exception to be re-raised was\nthe most recently active exception in the current scope.\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information about handling exceptions is in section\n*The try statement*.\n', + 'return': '\nThe ``return`` statement\n************************\n\n return_stmt ::= "return" [expression_list]\n\n``return`` may only occur syntactically nested in a function\ndefinition, not within a nested class definition.\n\nIf an expression list is present, it is evaluated, else ``None`` is\nsubstituted.\n\n``return`` leaves the current function call with the expression list\n(or ``None``) as return value.\n\nWhen ``return`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the function.\n\nIn a generator function, the ``return`` statement is not allowed to\ninclude an ``expression_list``. In that context, a bare ``return``\nindicates that the generator is done and will cause ``StopIteration``\nto be raised.\n', + 'sequence-types': "\nEmulating container types\n*************************\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well. The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items. (For backwards compatibility, the method\n``__getslice__()`` (see below) can also be defined to handle simple,\nbut not extended slices.) It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``has_key()``,\n``get()``, ``clear()``, ``setdefault()``, ``iterkeys()``,\n``itervalues()``, ``iteritems()``, ``pop()``, ``popitem()``,\n``copy()``, and ``update()`` behaving similar to those for Python's\nstandard dictionary objects. The ``UserDict`` module provides a\n``DictMixin`` class to help create those methods from a base set of\n``__getitem__()``, ``__setitem__()``, ``__delitem__()``, and\n``keys()``. Mutable sequences should provide methods ``append()``,\n``count()``, ``index()``, ``extend()``, ``insert()``, ``pop()``,\n``remove()``, ``reverse()`` and ``sort()``, like Python standard list\nobjects. Finally, sequence types should implement addition (meaning\nconcatenation) and multiplication (meaning repetition) by defining the\nmethods ``__add__()``, ``__radd__()``, ``__iadd__()``, ``__mul__()``,\n``__rmul__()`` and ``__imul__()`` described below; they should not\ndefine ``__coerce__()`` or other numerical operators. It is\nrecommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should be equivalent of ``has_key()``;\nfor sequences, it should search through the values. It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``iterkeys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n Called to implement the built-in function ``len()``. Should return\n the length of the object, an integer ``>=`` 0. Also, an object\n that doesn't define a ``__nonzero__()`` method and whose\n ``__len__()`` method returns zero is considered to be false in a\n Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of ``self[key]``. For sequence\n types, the accepted keys should be integers and slice objects.\n Note that the special interpretation of negative indexes (if the\n class wishes to emulate a sequence type) is up to the\n ``__getitem__()`` method. If *key* is of an inappropriate type,\n ``TypeError`` may be raised; if of a value outside the set of\n indexes for the sequence (after any special interpretation of\n negative values), ``IndexError`` should be raised. For mapping\n types, if *key* is missing (not in the container), ``KeyError``\n should be raised.\n\n Note: ``for`` loops expect that an ``IndexError`` will be raised for\n illegal indexes to allow proper detection of the end of the\n sequence.\n\nobject.__setitem__(self, key, value)\n\n Called to implement assignment to ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support changes to the values for keys, or if new keys\n can be added, or for sequences if elements can be replaced. The\n same exceptions should be raised for improper *key* values as for\n the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n Called to implement deletion of ``self[key]``. Same note as for\n ``__getitem__()``. This should only be implemented for mappings if\n the objects support removal of keys, or for sequences if elements\n can be removed from the sequence. The same exceptions should be\n raised for improper *key* values as for the ``__getitem__()``\n method.\n\nobject.__iter__(self)\n\n This method is called when an iterator is required for a container.\n This method should return a new iterator object that can iterate\n over all the objects in the container. For mappings, it should\n iterate over the keys of the container, and should also be made\n available as the method ``iterkeys()``.\n\n Iterator objects also need to implement this method; they are\n required to return themselves. For more information on iterator\n objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n Called (if present) by the ``reversed()`` built-in to implement\n reverse iteration. It should return a new iterator object that\n iterates over all the objects in the container in reverse order.\n\n If the ``__reversed__()`` method is not provided, the\n ``reversed()`` built-in will fall back to using the sequence\n protocol (``__len__()`` and ``__getitem__()``). Objects that\n support the sequence protocol should only provide\n ``__reversed__()`` if they can provide an implementation that is\n more efficient than the one provided by ``reversed()``.\n\n New in version 2.6.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence. However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n Called to implement membership test operators. Should return true\n if *item* is in *self*, false otherwise. For mapping objects, this\n should consider the keys of the mapping rather than the values or\n the key-item pairs.\n\n For objects that don't define ``__contains__()``, the membership\n test first tries iteration via ``__iter__()``, then the old\n sequence iteration protocol via ``__getitem__()``, see *this\n section in the language reference*.\n", +@@ -64,13 +66,13 @@ + 'subscriptions': '\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object of a sequence or mapping type.\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey. (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to a\nplain integer. If this value is negative, the length of the sequence\nis added to it (so that, e.g., ``x[-1]`` selects the last item of\n``x``.) The resulting value must be a nonnegative integer less than\nthe number of items in the sequence, and the subscription selects the\nitem whose index is that value (counting from zero).\n\nA string\'s items are characters. A character is not a separate data\ntype but a string of exactly one character.\n', + 'truth': "\nTruth Value Testing\n*******************\n\nAny object can be tested for truth value, for use in an ``if`` or\n``while`` condition or as operand of the Boolean operations below. The\nfollowing values are considered false:\n\n* ``None``\n\n* ``False``\n\n* zero of any numeric type, for example, ``0``, ``0L``, ``0.0``,\n ``0j``.\n\n* any empty sequence, for example, ``''``, ``()``, ``[]``.\n\n* any empty mapping, for example, ``{}``.\n\n* instances of user-defined classes, if the class defines a\n ``__nonzero__()`` or ``__len__()`` method, when that method returns\n the integer zero or ``bool`` value ``False``. [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\nunless otherwise stated. (Important exception: the Boolean operations\n``or`` and ``and`` always return one of their operands.)\n", + 'try': '\nThe ``try`` statement\n*********************\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n try_stmt ::= try1_stmt | try2_stmt\n try1_stmt ::= "try" ":" suite\n ("except" [expression [("as" | ",") target]] ":" suite)+\n ["else" ":" suite]\n ["finally" ":" suite]\n try2_stmt ::= "try" ":" suite\n "finally" ":" suite\n\nChanged in version 2.5: In previous versions of Python,\n``try``...``except``...``finally`` did not work. ``try``...``except``\nhad to be nested in ``try``...``finally``.\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started. This search inspects the except\nclauses in turn until one is found that matches the exception. An\nexpression-less except clause, if present, must be last; it matches\nany exception. For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception. An object is\ncompatible with an exception if it is the class or a base class of the\nexception object, or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified in that except clause, if present, and the except\nclause\'s suite is executed. All except clauses must have an\nexecutable block. When the end of this block is reached, execution\ncontinues normally after the entire try statement. (This means that\nif two nested handlers exist for the same exception, and the exception\noccurs in the try clause of the inner handler, the outer handler will\nnot handle the exception.)\n\nBefore an except clause\'s suite is executed, details about the\nexception are assigned to three variables in the ``sys`` module:\n``sys.exc_type`` receives the object identifying the exception;\n``sys.exc_value`` receives the exception\'s parameter;\n``sys.exc_traceback`` receives a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. These details are also available through the\n``sys.exc_info()`` function, which returns a tuple ``(exc_type,\nexc_value, exc_traceback)``. Use of the corresponding variables is\ndeprecated in favor of this function, since their use is unsafe in a\nthreaded program. As of Python 1.5, the variables are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler. The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses. If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted. If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is discarded:\n\n def f():\n try:\n 1/0\n finally:\n return 42\n\n >>> f()\n 42\n\nThe exception information is not available to the program during\nexecution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n', +- 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python. Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types. Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.).\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\' These are attributes that provide access to the\nimplementation and are not intended for general use. Their definition\nmay change in the future.\n\nNone\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name ``None``.\n It is used to signify the absence of a value in many situations,\n e.g., it is returned from functions that don\'t explicitly return\n anything. Its truth value is false.\n\nNotImplemented\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``NotImplemented``. Numeric methods and rich comparison methods may\n return this value if they do not implement the operation for the\n operands provided. (The interpreter will then try the reflected\n operation, or some other fallback, depending on the operator.) Its\n truth value is true.\n\nEllipsis\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``Ellipsis``. It is used to indicate the presence of the ``...``\n syntax in a slice. Its truth value is true.\n\n``numbers.Number``\n These are created by numeric literals and returned as results by\n arithmetic operators and arithmetic built-in functions. Numeric\n objects are immutable; once created their value never changes.\n Python numbers are of course strongly related to mathematical\n numbers, but subject to the limitations of numerical representation\n in computers.\n\n Python distinguishes between integers, floating point numbers, and\n complex numbers:\n\n ``numbers.Integral``\n These represent elements from the mathematical set of integers\n (positive and negative).\n\n There are three types of integers:\n\n Plain integers\n These represent numbers in the range -2147483648 through\n 2147483647. (The range may be larger on machines with a\n larger natural word size, but not smaller.) When the result\n of an operation would fall outside this range, the result is\n normally returned as a long integer (in some cases, the\n exception ``OverflowError`` is raised instead). For the\n purpose of shift and mask operations, integers are assumed to\n have a binary, 2\'s complement notation using 32 or more bits,\n and hiding no bits from the user (i.e., all 4294967296\n different bit patterns correspond to different values).\n\n Long integers\n These represent numbers in an unlimited range, subject to\n available (virtual) memory only. For the purpose of shift\n and mask operations, a binary representation is assumed, and\n negative numbers are represented in a variant of 2\'s\n complement which gives the illusion of an infinite string of\n sign bits extending to the left.\n\n Booleans\n These represent the truth values False and True. The two\n objects representing the values False and True are the only\n Boolean objects. The Boolean type is a subtype of plain\n integers, and Boolean values behave like the values 0 and 1,\n respectively, in almost all contexts, the exception being\n that when converted to a string, the strings ``"False"`` or\n ``"True"`` are returned, respectively.\n\n The rules for integer representation are intended to give the\n most meaningful interpretation of shift and mask operations\n involving negative integers and the least surprises when\n switching between the plain and long integer domains. Any\n operation, if it yields a result in the plain integer domain,\n will yield the same result in the long integer domain or when\n using mixed operands. The switch between domains is transparent\n to the programmer.\n\n ``numbers.Real`` (``float``)\n These represent machine-level double precision floating point\n numbers. You are at the mercy of the underlying machine\n architecture (and C or Java implementation) for the accepted\n range and handling of overflow. Python does not support single-\n precision floating point numbers; the savings in processor and\n memory usage that are usually the reason for using these is\n dwarfed by the overhead of using objects in Python, so there is\n no reason to complicate the language with two kinds of floating\n point numbers.\n\n ``numbers.Complex``\n These represent complex numbers as a pair of machine-level\n double precision floating point numbers. The same caveats apply\n as for floating point numbers. The real and imaginary parts of a\n complex number ``z`` can be retrieved through the read-only\n attributes ``z.real`` and ``z.imag``.\n\nSequences\n These represent finite ordered sets indexed by non-negative\n numbers. The built-in function ``len()`` returns the number of\n items of a sequence. When the length of a sequence is *n*, the\n index set contains the numbers 0, 1, ..., *n*-1. Item *i* of\n sequence *a* is selected by ``a[i]``.\n\n Sequences also support slicing: ``a[i:j]`` selects all items with\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When used as an\n expression, a slice is a sequence of the same type. This implies\n that the index set is renumbered so that it starts at 0.\n\n Some sequences also support "extended slicing" with a third "step"\n parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n *j*.\n\n Sequences are distinguished according to their mutability:\n\n Immutable sequences\n An object of an immutable sequence type cannot change once it is\n created. (If the object contains references to other objects,\n these other objects may be mutable and may be changed; however,\n the collection of objects directly referenced by an immutable\n object cannot change.)\n\n The following types are immutable sequences:\n\n Strings\n The items of a string are characters. There is no separate\n character type; a character is represented by a string of one\n item. Characters represent (at least) 8-bit bytes. The\n built-in functions ``chr()`` and ``ord()`` convert between\n characters and nonnegative integers representing the byte\n values. Bytes with the values 0-127 usually represent the\n corresponding ASCII values, but the interpretation of values\n is up to the program. The string data type is also used to\n represent arrays of bytes, e.g., to hold data read from a\n file.\n\n (On systems whose native character set is not ASCII, strings\n may use EBCDIC in their internal representation, provided the\n functions ``chr()`` and ``ord()`` implement a mapping between\n ASCII and EBCDIC, and string comparison preserves the ASCII\n order. Or perhaps someone can propose a better rule?)\n\n Unicode\n The items of a Unicode object are Unicode code units. A\n Unicode code unit is represented by a Unicode object of one\n item and can hold either a 16-bit or 32-bit value\n representing a Unicode ordinal (the maximum value for the\n ordinal is given in ``sys.maxunicode``, and depends on how\n Python is configured at compile time). Surrogate pairs may\n be present in the Unicode object, and will be reported as two\n separate items. The built-in functions ``unichr()`` and\n ``ord()`` convert between code units and nonnegative integers\n representing the Unicode ordinals as defined in the Unicode\n Standard 3.0. Conversion from and to other encodings are\n possible through the Unicode method ``encode()`` and the\n built-in function ``unicode()``.\n\n Tuples\n The items of a tuple are arbitrary Python objects. Tuples of\n two or more items are formed by comma-separated lists of\n expressions. A tuple of one item (a \'singleton\') can be\n formed by affixing a comma to an expression (an expression by\n itself does not create a tuple, since parentheses must be\n usable for grouping of expressions). An empty tuple can be\n formed by an empty pair of parentheses.\n\n Mutable sequences\n Mutable sequences can be changed after they are created. The\n subscription and slicing notations can be used as the target of\n assignment and ``del`` (delete) statements.\n\n There are currently two intrinsic mutable sequence types:\n\n Lists\n The items of a list are arbitrary Python objects. Lists are\n formed by placing a comma-separated list of expressions in\n square brackets. (Note that there are no special cases needed\n to form lists of length 0 or 1.)\n\n Byte Arrays\n A bytearray object is a mutable array. They are created by\n the built-in ``bytearray()`` constructor. Aside from being\n mutable (and hence unhashable), byte arrays otherwise provide\n the same interface and functionality as immutable bytes\n objects.\n\n The extension module ``array`` provides an additional example of\n a mutable sequence type.\n\nSet types\n These represent unordered, finite sets of unique, immutable\n objects. As such, they cannot be indexed by any subscript. However,\n they can be iterated over, and the built-in function ``len()``\n returns the number of items in a set. Common uses for sets are fast\n membership testing, removing duplicates from a sequence, and\n computing mathematical operations such as intersection, union,\n difference, and symmetric difference.\n\n For set elements, the same immutability rules apply as for\n dictionary keys. Note that numeric types obey the normal rules for\n numeric comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``), only one of them can be contained in a set.\n\n There are currently two intrinsic set types:\n\n Sets\n These represent a mutable set. They are created by the built-in\n ``set()`` constructor and can be modified afterwards by several\n methods, such as ``add()``.\n\n Frozen sets\n These represent an immutable set. They are created by the\n built-in ``frozenset()`` constructor. As a frozenset is\n immutable and *hashable*, it can be used again as an element of\n another set, or as a dictionary key.\n\nMappings\n These represent finite sets of objects indexed by arbitrary index\n sets. The subscript notation ``a[k]`` selects the item indexed by\n ``k`` from the mapping ``a``; this can be used in expressions and\n as the target of assignments or ``del`` statements. The built-in\n function ``len()`` returns the number of items in a mapping.\n\n There is currently a single intrinsic mapping type:\n\n Dictionaries\n These represent finite sets of objects indexed by nearly\n arbitrary values. The only types of values not acceptable as\n keys are values containing lists or dictionaries or other\n mutable types that are compared by value rather than by object\n identity, the reason being that the efficient implementation of\n dictionaries requires a key\'s hash value to remain constant.\n Numeric types used for keys obey the normal rules for numeric\n comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``) then they can be used interchangeably to index the same\n dictionary entry.\n\n Dictionaries are mutable; they can be created by the ``{...}``\n notation (see section *Dictionary displays*).\n\n The extension modules ``dbm``, ``gdbm``, and ``bsddb`` provide\n additional examples of mapping types.\n\nCallable types\n These are the types to which the function call operation (see\n section *Calls*) can be applied:\n\n User-defined functions\n A user-defined function object is created by a function\n definition (see section *Function definitions*). It should be\n called with an argument list containing the same number of items\n as the function\'s formal parameter list.\n\n Special attributes:\n\n +-------------------------+---------------------------------+-------------+\n | Attribute | Meaning | |\n +=========================+=================================+=============+\n | ``func_doc`` | The function\'s documentation | Writable |\n | | string, or ``None`` if | |\n | | unavailable | |\n +-------------------------+---------------------------------+-------------+\n | ``__doc__`` | Another way of spelling | Writable |\n | | ``func_doc`` | |\n +-------------------------+---------------------------------+-------------+\n | ``func_name`` | The function\'s name | Writable |\n +-------------------------+---------------------------------+-------------+\n | ``__name__`` | Another way of spelling | Writable |\n | | ``func_name`` | |\n +-------------------------+---------------------------------+-------------+\n | ``__module__`` | The name of the module the | Writable |\n | | function was defined in, or | |\n | | ``None`` if unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_defaults`` | A tuple containing default | Writable |\n | | argument values for those | |\n | | arguments that have defaults, | |\n | | or ``None`` if no arguments | |\n | | have a default value | |\n +-------------------------+---------------------------------+-------------+\n | ``func_code`` | The code object representing | Writable |\n | | the compiled function body. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_globals`` | A reference to the dictionary | Read-only |\n | | that holds the function\'s | |\n | | global variables --- the global | |\n | | namespace of the module in | |\n | | which the function was defined. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_dict`` | The namespace supporting | Writable |\n | | arbitrary function attributes. | |\n +-------------------------+---------------------------------+-------------+\n | ``func_closure`` | ``None`` or a tuple of cells | Read-only |\n | | that contain bindings for the | |\n | | function\'s free variables. | |\n +-------------------------+---------------------------------+-------------+\n\n Most of the attributes labelled "Writable" check the type of the\n assigned value.\n\n Changed in version 2.4: ``func_name`` is now writable.\n\n Function objects also support getting and setting arbitrary\n attributes, which can be used, for example, to attach metadata\n to functions. Regular attribute dot-notation is used to get and\n set such attributes. *Note that the current implementation only\n supports function attributes on user-defined functions. Function\n attributes on built-in functions may be supported in the\n future.*\n\n Additional information about a function\'s definition can be\n retrieved from its code object; see the description of internal\n types below.\n\n User-defined methods\n A user-defined method object combines a class, a class instance\n (or ``None``) and any callable object (normally a user-defined\n function).\n\n Special read-only attributes: ``im_self`` is the class instance\n object, ``im_func`` is the function object; ``im_class`` is the\n class of ``im_self`` for bound methods or the class that asked\n for the method for unbound methods; ``__doc__`` is the method\'s\n documentation (same as ``im_func.__doc__``); ``__name__`` is the\n method name (same as ``im_func.__name__``); ``__module__`` is\n the name of the module the method was defined in, or ``None`` if\n unavailable.\n\n Changed in version 2.2: ``im_self`` used to refer to the class\n that defined the method.\n\n Changed in version 2.6: For Python 3 forward-compatibility,\n ``im_func`` is also available as ``__func__``, and ``im_self``\n as ``__self__``.\n\n Methods also support accessing (but not setting) the arbitrary\n function attributes on the underlying function object.\n\n User-defined method objects may be created when getting an\n attribute of a class (perhaps via an instance of that class), if\n that attribute is a user-defined function object, an unbound\n user-defined method object, or a class method object. When the\n attribute is a user-defined method object, a new method object\n is only created if the class from which it is being retrieved is\n the same as, or a derived class of, the class stored in the\n original method object; otherwise, the original method object is\n used as it is.\n\n When a user-defined method object is created by retrieving a\n user-defined function object from a class, its ``im_self``\n attribute is ``None`` and the method object is said to be\n unbound. When one is created by retrieving a user-defined\n function object from a class via one of its instances, its\n ``im_self`` attribute is the instance, and the method object is\n said to be bound. In either case, the new method\'s ``im_class``\n attribute is the class from which the retrieval takes place, and\n its ``im_func`` attribute is the original function object.\n\n When a user-defined method object is created by retrieving\n another method object from a class or instance, the behaviour is\n the same as for a function object, except that the ``im_func``\n attribute of the new instance is not the original method object\n but its ``im_func`` attribute.\n\n When a user-defined method object is created by retrieving a\n class method object from a class or instance, its ``im_self``\n attribute is the class itself, and its ``im_func`` attribute is\n the function object underlying the class method.\n\n When an unbound user-defined method object is called, the\n underlying function (``im_func``) is called, with the\n restriction that the first argument must be an instance of the\n proper class (``im_class``) or of a derived class thereof.\n\n When a bound user-defined method object is called, the\n underlying function (``im_func``) is called, inserting the class\n instance (``im_self``) in front of the argument list. For\n instance, when ``C`` is a class which contains a definition for\n a function ``f()``, and ``x`` is an instance of ``C``, calling\n ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.\n\n When a user-defined method object is derived from a class method\n object, the "class instance" stored in ``im_self`` will actually\n be the class itself, so that calling either ``x.f(1)`` or\n ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n the underlying function.\n\n Note that the transformation from function object to (unbound or\n bound) method object happens each time the attribute is\n retrieved from the class or instance. In some cases, a fruitful\n optimization is to assign the attribute to a local variable and\n call that local variable. Also notice that this transformation\n only happens for user-defined functions; other callable objects\n (and all non-callable objects) are retrieved without\n transformation. It is also important to note that user-defined\n functions which are attributes of a class instance are not\n converted to bound methods; this *only* happens when the\n function is an attribute of the class.\n\n Generator functions\n A function or method which uses the ``yield`` statement (see\n section *The yield statement*) is called a *generator function*.\n Such a function, when called, always returns an iterator object\n which can be used to execute the body of the function: calling\n the iterator\'s ``next()`` method will cause the function to\n execute until it provides a value using the ``yield`` statement.\n When the function executes a ``return`` statement or falls off\n the end, a ``StopIteration`` exception is raised and the\n iterator will have reached the end of the set of values to be\n returned.\n\n Built-in functions\n A built-in function object is a wrapper around a C function.\n Examples of built-in functions are ``len()`` and ``math.sin()``\n (``math`` is a standard built-in module). The number and type of\n the arguments are determined by the C function. Special read-\n only attributes: ``__doc__`` is the function\'s documentation\n string, or ``None`` if unavailable; ``__name__`` is the\n function\'s name; ``__self__`` is set to ``None`` (but see the\n next item); ``__module__`` is the name of the module the\n function was defined in or ``None`` if unavailable.\n\n Built-in methods\n This is really a different disguise of a built-in function, this\n time containing an object passed to the C function as an\n implicit extra argument. An example of a built-in method is\n ``alist.append()``, assuming *alist* is a list object. In this\n case, the special read-only attribute ``__self__`` is set to the\n object denoted by *alist*.\n\n Class Types\n Class types, or "new-style classes," are callable. These\n objects normally act as factories for new instances of\n themselves, but variations are possible for class types that\n override ``__new__()``. The arguments of the call are passed to\n ``__new__()`` and, in the typical case, to ``__init__()`` to\n initialize the new instance.\n\n Classic Classes\n Class objects are described below. When a class object is\n called, a new class instance (also described below) is created\n and returned. This implies a call to the class\'s ``__init__()``\n method if it has one. Any arguments are passed on to the\n ``__init__()`` method. If there is no ``__init__()`` method,\n the class must be called without arguments.\n\n Class instances\n Class instances are described below. Class instances are\n callable only when the class has a ``__call__()`` method;\n ``x(arguments)`` is a shorthand for ``x.__call__(arguments)``.\n\nModules\n Modules are imported by the ``import`` statement (see section *The\n import statement*). A module object has a namespace implemented by\n a dictionary object (this is the dictionary referenced by the\n func_globals attribute of functions defined in the module).\n Attribute references are translated to lookups in this dictionary,\n e.g., ``m.x`` is equivalent to ``m.__dict__["x"]``. A module object\n does not contain the code object used to initialize the module\n (since it isn\'t needed once the initialization is done).\n\n Attribute assignment updates the module\'s namespace dictionary,\n e.g., ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.\n\n Special read-only attribute: ``__dict__`` is the module\'s namespace\n as a dictionary object.\n\n **CPython implementation detail:** Because of the way CPython\n clears module dictionaries, the module dictionary will be cleared\n when the module falls out of scope even if the dictionary still has\n live references. To avoid this, copy the dictionary or keep the\n module around while using its dictionary directly.\n\n Predefined (writable) attributes: ``__name__`` is the module\'s\n name; ``__doc__`` is the module\'s documentation string, or ``None``\n if unavailable; ``__file__`` is the pathname of the file from which\n the module was loaded, if it was loaded from a file. The\n ``__file__`` attribute is not present for C modules that are\n statically linked into the interpreter; for extension modules\n loaded dynamically from a shared library, it is the pathname of the\n shared library file.\n\nClasses\n Both class types (new-style classes) and class objects (old-\n style/classic classes) are typically created by class definitions\n (see section *Class definitions*). A class has a namespace\n implemented by a dictionary object. Class attribute references are\n translated to lookups in this dictionary, e.g., ``C.x`` is\n translated to ``C.__dict__["x"]`` (although for new-style classes\n in particular there are a number of hooks which allow for other\n means of locating attributes). When the attribute name is not found\n there, the attribute search continues in the base classes. For\n old-style classes, the search is depth-first, left-to-right in the\n order of occurrence in the base class list. New-style classes use\n the more complex C3 method resolution order which behaves correctly\n even in the presence of \'diamond\' inheritance structures where\n there are multiple inheritance paths leading back to a common\n ancestor. Additional details on the C3 MRO used by new-style\n classes can be found in the documentation accompanying the 2.3\n release at http://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class ``C``, say) would yield\n a user-defined function object or an unbound user-defined method\n object whose associated class is either ``C`` or one of its base\n classes, it is transformed into an unbound user-defined method\n object whose ``im_class`` attribute is ``C``. When it would yield a\n class method object, it is transformed into a bound user-defined\n method object whose ``im_self`` attribute is ``C``. When it would\n yield a static method object, it is transformed into the object\n wrapped by the static method object. See section *Implementing\n Descriptors* for another way in which attributes retrieved from a\n class may differ from those actually contained in its ``__dict__``\n (note that only new-style classes support descriptors).\n\n Class attribute assignments update the class\'s dictionary, never\n the dictionary of a base class.\n\n A class object can be called (see above) to yield a class instance\n (see below).\n\n Special attributes: ``__name__`` is the class name; ``__module__``\n is the module name in which the class was defined; ``__dict__`` is\n the dictionary containing the class\'s namespace; ``__bases__`` is a\n tuple (possibly empty or a singleton) containing the base classes,\n in the order of their occurrence in the base class list;\n ``__doc__`` is the class\'s documentation string, or None if\n undefined.\n\nClass instances\n A class instance is created by calling a class object (see above).\n A class instance has a namespace implemented as a dictionary which\n is the first place in which attribute references are searched.\n When an attribute is not found there, and the instance\'s class has\n an attribute by that name, the search continues with the class\n attributes. If a class attribute is found that is a user-defined\n function object or an unbound user-defined method object whose\n associated class is the class (call it ``C``) of the instance for\n which the attribute reference was initiated or one of its bases, it\n is transformed into a bound user-defined method object whose\n ``im_class`` attribute is ``C`` and whose ``im_self`` attribute is\n the instance. Static method and class method objects are also\n transformed, as if they had been retrieved from class ``C``; see\n above under "Classes". See section *Implementing Descriptors* for\n another way in which attributes of a class retrieved via its\n instances may differ from the objects actually stored in the\n class\'s ``__dict__``. If no class attribute is found, and the\n object\'s class has a ``__getattr__()`` method, that is called to\n satisfy the lookup.\n\n Attribute assignments and deletions update the instance\'s\n dictionary, never a class\'s dictionary. If the class has a\n ``__setattr__()`` or ``__delattr__()`` method, this is called\n instead of updating the instance dictionary directly.\n\n Class instances can pretend to be numbers, sequences, or mappings\n if they have methods with certain special names. See section\n *Special method names*.\n\n Special attributes: ``__dict__`` is the attribute dictionary;\n ``__class__`` is the instance\'s class.\n\nFiles\n A file object represents an open file. File objects are created by\n the ``open()`` built-in function, and also by ``os.popen()``,\n ``os.fdopen()``, and the ``makefile()`` method of socket objects\n (and perhaps by other functions or methods provided by extension\n modules). The objects ``sys.stdin``, ``sys.stdout`` and\n ``sys.stderr`` are initialized to file objects corresponding to the\n interpreter\'s standard input, output and error streams. See *File\n Objects* for complete documentation of file objects.\n\nInternal types\n A few types used internally by the interpreter are exposed to the\n user. Their definitions may change with future versions of the\n interpreter, but they are mentioned here for completeness.\n\n Code objects\n Code objects represent *byte-compiled* executable Python code,\n or *bytecode*. The difference between a code object and a\n function object is that the function object contains an explicit\n reference to the function\'s globals (the module in which it was\n defined), while a code object contains no context; also the\n default argument values are stored in the function object, not\n in the code object (because they represent values calculated at\n run-time). Unlike function objects, code objects are immutable\n and contain no references (directly or indirectly) to mutable\n objects.\n\n Special read-only attributes: ``co_name`` gives the function\n name; ``co_argcount`` is the number of positional arguments\n (including arguments with default values); ``co_nlocals`` is the\n number of local variables used by the function (including\n arguments); ``co_varnames`` is a tuple containing the names of\n the local variables (starting with the argument names);\n ``co_cellvars`` is a tuple containing the names of local\n variables that are referenced by nested functions;\n ``co_freevars`` is a tuple containing the names of free\n variables; ``co_code`` is a string representing the sequence of\n bytecode instructions; ``co_consts`` is a tuple containing the\n literals used by the bytecode; ``co_names`` is a tuple\n containing the names used by the bytecode; ``co_filename`` is\n the filename from which the code was compiled;\n ``co_firstlineno`` is the first line number of the function;\n ``co_lnotab`` is a string encoding the mapping from bytecode\n offsets to line numbers (for details see the source code of the\n interpreter); ``co_stacksize`` is the required stack size\n (including local variables); ``co_flags`` is an integer encoding\n a number of flags for the interpreter.\n\n The following flag bits are defined for ``co_flags``: bit\n ``0x04`` is set if the function uses the ``*arguments`` syntax\n to accept an arbitrary number of positional arguments; bit\n ``0x08`` is set if the function uses the ``**keywords`` syntax\n to accept arbitrary keyword arguments; bit ``0x20`` is set if\n the function is a generator.\n\n Future feature declarations (``from __future__ import\n division``) also use bits in ``co_flags`` to indicate whether a\n code object was compiled with a particular feature enabled: bit\n ``0x2000`` is set if the function was compiled with future\n division enabled; bits ``0x10`` and ``0x1000`` were used in\n earlier versions of Python.\n\n Other bits in ``co_flags`` are reserved for internal use.\n\n If a code object represents a function, the first item in\n ``co_consts`` is the documentation string of the function, or\n ``None`` if undefined.\n\n Frame objects\n Frame objects represent execution frames. They may occur in\n traceback objects (see below).\n\n Special read-only attributes: ``f_back`` is to the previous\n stack frame (towards the caller), or ``None`` if this is the\n bottom stack frame; ``f_code`` is the code object being executed\n in this frame; ``f_locals`` is the dictionary used to look up\n local variables; ``f_globals`` is used for global variables;\n ``f_builtins`` is used for built-in (intrinsic) names;\n ``f_restricted`` is a flag indicating whether the function is\n executing in restricted execution mode; ``f_lasti`` gives the\n precise instruction (this is an index into the bytecode string\n of the code object).\n\n Special writable attributes: ``f_trace``, if not ``None``, is a\n function called at the start of each source code line (this is\n used by the debugger); ``f_exc_type``, ``f_exc_value``,\n ``f_exc_traceback`` represent the last exception raised in the\n parent frame provided another exception was ever raised in the\n current frame (in all other cases they are None); ``f_lineno``\n is the current line number of the frame --- writing to this from\n within a trace function jumps to the given line (only for the\n bottom-most frame). A debugger can implement a Jump command\n (aka Set Next Statement) by writing to f_lineno.\n\n Traceback objects\n Traceback objects represent a stack trace of an exception. A\n traceback object is created when an exception occurs. When the\n search for an exception handler unwinds the execution stack, at\n each unwound level a traceback object is inserted in front of\n the current traceback. When an exception handler is entered,\n the stack trace is made available to the program. (See section\n *The try statement*.) It is accessible as ``sys.exc_traceback``,\n and also as the third item of the tuple returned by\n ``sys.exc_info()``. The latter is the preferred interface,\n since it works correctly when the program is using multiple\n threads. When the program contains no suitable handler, the\n stack trace is written (nicely formatted) to the standard error\n stream; if the interpreter is interactive, it is also made\n available to the user as ``sys.last_traceback``.\n\n Special read-only attributes: ``tb_next`` is the next level in\n the stack trace (towards the frame where the exception\n occurred), or ``None`` if there is no next level; ``tb_frame``\n points to the execution frame of the current level;\n ``tb_lineno`` gives the line number where the exception\n occurred; ``tb_lasti`` indicates the precise instruction. The\n line number and last instruction in the traceback may differ\n from the line number of its frame object if the exception\n occurred in a ``try`` statement with no matching except clause\n or with a finally clause.\n\n Slice objects\n Slice objects are used to represent slices when *extended slice\n syntax* is used. This is a slice using two colons, or multiple\n slices or ellipses separated by commas, e.g., ``a[i:j:step]``,\n ``a[i:j, k:l]``, or ``a[..., i:j]``. They are also created by\n the built-in ``slice()`` function.\n\n Special read-only attributes: ``start`` is the lower bound;\n ``stop`` is the upper bound; ``step`` is the step value; each is\n ``None`` if omitted. These attributes can have any type.\n\n Slice objects support one method:\n\n slice.indices(self, length)\n\n This method takes a single integer argument *length* and\n computes information about the extended slice that the slice\n object would describe if applied to a sequence of *length*\n items. It returns a tuple of three integers; respectively\n these are the *start* and *stop* indices and the *step* or\n stride length of the slice. Missing or out-of-bounds indices\n are handled in a manner consistent with regular slices.\n\n New in version 2.3.\n\n Static method objects\n Static method objects provide a way of defeating the\n transformation of function objects to method objects described\n above. A static method object is a wrapper around any other\n object, usually a user-defined method object. When a static\n method object is retrieved from a class or a class instance, the\n object actually returned is the wrapped object, which is not\n subject to any further transformation. Static method objects are\n not themselves callable, although the objects they wrap usually\n are. Static method objects are created by the built-in\n ``staticmethod()`` constructor.\n\n Class method objects\n A class method object, like a static method object, is a wrapper\n around another object that alters the way in which that object\n is retrieved from classes and class instances. The behaviour of\n class method objects upon such retrieval is described above,\n under "User-defined methods". Class method objects are created\n by the built-in ``classmethod()`` constructor.\n', ++ 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python. Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types. Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.).\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\' These are attributes that provide access to the\nimplementation and are not intended for general use. Their definition\nmay change in the future.\n\nNone\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name ``None``.\n It is used to signify the absence of a value in many situations,\n e.g., it is returned from functions that don\'t explicitly return\n anything. Its truth value is false.\n\nNotImplemented\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``NotImplemented``. Numeric methods and rich comparison methods may\n return this value if they do not implement the operation for the\n operands provided. (The interpreter will then try the reflected\n operation, or some other fallback, depending on the operator.) Its\n truth value is true.\n\nEllipsis\n This type has a single value. There is a single object with this\n value. This object is accessed through the built-in name\n ``Ellipsis``. It is used to indicate the presence of the ``...``\n syntax in a slice. Its truth value is true.\n\n``numbers.Number``\n These are created by numeric literals and returned as results by\n arithmetic operators and arithmetic built-in functions. Numeric\n objects are immutable; once created their value never changes.\n Python numbers are of course strongly related to mathematical\n numbers, but subject to the limitations of numerical representation\n in computers.\n\n Python distinguishes between integers, floating point numbers, and\n complex numbers:\n\n ``numbers.Integral``\n These represent elements from the mathematical set of integers\n (positive and negative).\n\n There are three types of integers:\n\n Plain integers\n These represent numbers in the range -2147483648 through\n 2147483647. (The range may be larger on machines with a\n larger natural word size, but not smaller.) When the result\n of an operation would fall outside this range, the result is\n normally returned as a long integer (in some cases, the\n exception ``OverflowError`` is raised instead). For the\n purpose of shift and mask operations, integers are assumed to\n have a binary, 2\'s complement notation using 32 or more bits,\n and hiding no bits from the user (i.e., all 4294967296\n different bit patterns correspond to different values).\n\n Long integers\n These represent numbers in an unlimited range, subject to\n available (virtual) memory only. For the purpose of shift\n and mask operations, a binary representation is assumed, and\n negative numbers are represented in a variant of 2\'s\n complement which gives the illusion of an infinite string of\n sign bits extending to the left.\n\n Booleans\n These represent the truth values False and True. The two\n objects representing the values ``False`` and ``True`` are\n the only Boolean objects. The Boolean type is a subtype of\n plain integers, and Boolean values behave like the values 0\n and 1, respectively, in almost all contexts, the exception\n being that when converted to a string, the strings\n ``"False"`` or ``"True"`` are returned, respectively.\n\n The rules for integer representation are intended to give the\n most meaningful interpretation of shift and mask operations\n involving negative integers and the least surprises when\n switching between the plain and long integer domains. Any\n operation, if it yields a result in the plain integer domain,\n will yield the same result in the long integer domain or when\n using mixed operands. The switch between domains is transparent\n to the programmer.\n\n ``numbers.Real`` (``float``)\n These represent machine-level double precision floating point\n numbers. You are at the mercy of the underlying machine\n architecture (and C or Java implementation) for the accepted\n range and handling of overflow. Python does not support single-\n precision floating point numbers; the savings in processor and\n memory usage that are usually the reason for using these is\n dwarfed by the overhead of using objects in Python, so there is\n no reason to complicate the language with two kinds of floating\n point numbers.\n\n ``numbers.Complex``\n These represent complex numbers as a pair of machine-level\n double precision floating point numbers. The same caveats apply\n as for floating point numbers. The real and imaginary parts of a\n complex number ``z`` can be retrieved through the read-only\n attributes ``z.real`` and ``z.imag``.\n\nSequences\n These represent finite ordered sets indexed by non-negative\n numbers. The built-in function ``len()`` returns the number of\n items of a sequence. When the length of a sequence is *n*, the\n index set contains the numbers 0, 1, ..., *n*-1. Item *i* of\n sequence *a* is selected by ``a[i]``.\n\n Sequences also support slicing: ``a[i:j]`` selects all items with\n index *k* such that *i* ``<=`` *k* ``<`` *j*. When used as an\n expression, a slice is a sequence of the same type. This implies\n that the index set is renumbered so that it starts at 0.\n\n Some sequences also support "extended slicing" with a third "step"\n parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n *j*.\n\n Sequences are distinguished according to their mutability:\n\n Immutable sequences\n An object of an immutable sequence type cannot change once it is\n created. (If the object contains references to other objects,\n these other objects may be mutable and may be changed; however,\n the collection of objects directly referenced by an immutable\n object cannot change.)\n\n The following types are immutable sequences:\n\n Strings\n The items of a string are characters. There is no separate\n character type; a character is represented by a string of one\n item. Characters represent (at least) 8-bit bytes. The\n built-in functions ``chr()`` and ``ord()`` convert between\n characters and nonnegative integers representing the byte\n values. Bytes with the values 0-127 usually represent the\n corresponding ASCII values, but the interpretation of values\n is up to the program. The string data type is also used to\n represent arrays of bytes, e.g., to hold data read from a\n file.\n\n (On systems whose native character set is not ASCII, strings\n may use EBCDIC in their internal representation, provided the\n functions ``chr()`` and ``ord()`` implement a mapping between\n ASCII and EBCDIC, and string comparison preserves the ASCII\n order. Or perhaps someone can propose a better rule?)\n\n Unicode\n The items of a Unicode object are Unicode code units. A\n Unicode code unit is represented by a Unicode object of one\n item and can hold either a 16-bit or 32-bit value\n representing a Unicode ordinal (the maximum value for the\n ordinal is given in ``sys.maxunicode``, and depends on how\n Python is configured at compile time). Surrogate pairs may\n be present in the Unicode object, and will be reported as two\n separate items. The built-in functions ``unichr()`` and\n ``ord()`` convert between code units and nonnegative integers\n representing the Unicode ordinals as defined in the Unicode\n Standard 3.0. Conversion from and to other encodings are\n possible through the Unicode method ``encode()`` and the\n built-in function ``unicode()``.\n\n Tuples\n The items of a tuple are arbitrary Python objects. Tuples of\n two or more items are formed by comma-separated lists of\n expressions. A tuple of one item (a \'singleton\') can be\n formed by affixing a comma to an expression (an expression by\n itself does not create a tuple, since parentheses must be\n usable for grouping of expressions). An empty tuple can be\n formed by an empty pair of parentheses.\n\n Mutable sequences\n Mutable sequences can be changed after they are created. The\n subscription and slicing notations can be used as the target of\n assignment and ``del`` (delete) statements.\n\n There are currently two intrinsic mutable sequence types:\n\n Lists\n The items of a list are arbitrary Python objects. Lists are\n formed by placing a comma-separated list of expressions in\n square brackets. (Note that there are no special cases needed\n to form lists of length 0 or 1.)\n\n Byte Arrays\n A bytearray object is a mutable array. They are created by\n the built-in ``bytearray()`` constructor. Aside from being\n mutable (and hence unhashable), byte arrays otherwise provide\n the same interface and functionality as immutable bytes\n objects.\n\n The extension module ``array`` provides an additional example of\n a mutable sequence type.\n\nSet types\n These represent unordered, finite sets of unique, immutable\n objects. As such, they cannot be indexed by any subscript. However,\n they can be iterated over, and the built-in function ``len()``\n returns the number of items in a set. Common uses for sets are fast\n membership testing, removing duplicates from a sequence, and\n computing mathematical operations such as intersection, union,\n difference, and symmetric difference.\n\n For set elements, the same immutability rules apply as for\n dictionary keys. Note that numeric types obey the normal rules for\n numeric comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``), only one of them can be contained in a set.\n\n There are currently two intrinsic set types:\n\n Sets\n These represent a mutable set. They are created by the built-in\n ``set()`` constructor and can be modified afterwards by several\n methods, such as ``add()``.\n\n Frozen sets\n These represent an immutable set. They are created by the\n built-in ``frozenset()`` constructor. As a frozenset is\n immutable and *hashable*, it can be used again as an element of\n another set, or as a dictionary key.\n\nMappings\n These represent finite sets of objects indexed by arbitrary index\n sets. The subscript notation ``a[k]`` selects the item indexed by\n ``k`` from the mapping ``a``; this can be used in expressions and\n as the target of assignments or ``del`` statements. The built-in\n function ``len()`` returns the number of items in a mapping.\n\n There is currently a single intrinsic mapping type:\n\n Dictionaries\n These represent finite sets of objects indexed by nearly\n arbitrary values. The only types of values not acceptable as\n keys are values containing lists or dictionaries or other\n mutable types that are compared by value rather than by object\n identity, the reason being that the efficient implementation of\n dictionaries requires a key\'s hash value to remain constant.\n Numeric types used for keys obey the normal rules for numeric\n comparison: if two numbers compare equal (e.g., ``1`` and\n ``1.0``) then they can be used interchangeably to index the same\n dictionary entry.\n\n Dictionaries are mutable; they can be created by the ``{...}``\n notation (see section *Dictionary displays*).\n\n The extension modules ``dbm``, ``gdbm``, and ``bsddb`` provide\n additional examples of mapping types.\n\nCallable types\n These are the types to which the function call operation (see\n section *Calls*) can be applied:\n\n User-defined functions\n A user-defined function object is created by a function\n definition (see section *Function definitions*). It should be\n called with an argument list containing the same number of items\n as the function\'s formal parameter list.\n\n Special attributes:\n\n +-------------------------+---------------------------------+-------------+\n | Attribute | Meaning | |\n +=========================+=================================+=============+\n | ``__doc__`` | The function\'s documentation | Writable |\n | ``func_doc`` | string, or ``None`` if | |\n | | unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | ``__name__`` | The function\'s name. | Writable |\n | ``func_name`` | | |\n +-------------------------+---------------------------------+-------------+\n | ``__module__`` | The name of the module the | Writable |\n | | function was defined in, or | |\n | | ``None`` if unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | ``__defaults__`` | A tuple containing default | Writable |\n | ``func_defaults`` | argument values for those | |\n | | arguments that have defaults, | |\n | | or ``None`` if no arguments | |\n | | have a default value. | |\n +-------------------------+---------------------------------+-------------+\n | ``__code__`` | The code object representing | Writable |\n | ``func_code`` | the compiled function body. | |\n +-------------------------+---------------------------------+-------------+\n | ``__globals__`` | A reference to the dictionary | Read-only |\n | ``func_globals`` | that holds the function\'s | |\n | | global variables --- the global | |\n | | namespace of the module in | |\n | | which the function was defined. | |\n +-------------------------+---------------------------------+-------------+\n | ``__dict__`` | The namespace supporting | Writable |\n | ``func_dict`` | arbitrary function attributes. | |\n +-------------------------+---------------------------------+-------------+\n | ``__closure__`` | ``None`` or a tuple of cells | Read-only |\n | ``func_closure`` | that contain bindings for the | |\n | | function\'s free variables. | |\n +-------------------------+---------------------------------+-------------+\n\n Most of the attributes labelled "Writable" check the type of the\n assigned value.\n\n Changed in version 2.4: ``func_name`` is now writable.\n\n Changed in version 2.6: The double-underscore attributes\n ``__closure__``, ``__code__``, ``__defaults__``, and\n ``__globals__`` were introduced as aliases for the corresponding\n ``func_*`` attributes for forwards compatibility with Python 3.\n\n Function objects also support getting and setting arbitrary\n attributes, which can be used, for example, to attach metadata\n to functions. Regular attribute dot-notation is used to get and\n set such attributes. *Note that the current implementation only\n supports function attributes on user-defined functions. Function\n attributes on built-in functions may be supported in the\n future.*\n\n Additional information about a function\'s definition can be\n retrieved from its code object; see the description of internal\n types below.\n\n User-defined methods\n A user-defined method object combines a class, a class instance\n (or ``None``) and any callable object (normally a user-defined\n function).\n\n Special read-only attributes: ``im_self`` is the class instance\n object, ``im_func`` is the function object; ``im_class`` is the\n class of ``im_self`` for bound methods or the class that asked\n for the method for unbound methods; ``__doc__`` is the method\'s\n documentation (same as ``im_func.__doc__``); ``__name__`` is the\n method name (same as ``im_func.__name__``); ``__module__`` is\n the name of the module the method was defined in, or ``None`` if\n unavailable.\n\n Changed in version 2.2: ``im_self`` used to refer to the class\n that defined the method.\n\n Changed in version 2.6: For Python 3 forward-compatibility,\n ``im_func`` is also available as ``__func__``, and ``im_self``\n as ``__self__``.\n\n Methods also support accessing (but not setting) the arbitrary\n function attributes on the underlying function object.\n\n User-defined method objects may be created when getting an\n attribute of a class (perhaps via an instance of that class), if\n that attribute is a user-defined function object, an unbound\n user-defined method object, or a class method object. When the\n attribute is a user-defined method object, a new method object\n is only created if the class from which it is being retrieved is\n the same as, or a derived class of, the class stored in the\n original method object; otherwise, the original method object is\n used as it is.\n\n When a user-defined method object is created by retrieving a\n user-defined function object from a class, its ``im_self``\n attribute is ``None`` and the method object is said to be\n unbound. When one is created by retrieving a user-defined\n function object from a class via one of its instances, its\n ``im_self`` attribute is the instance, and the method object is\n said to be bound. In either case, the new method\'s ``im_class``\n attribute is the class from which the retrieval takes place, and\n its ``im_func`` attribute is the original function object.\n\n When a user-defined method object is created by retrieving\n another method object from a class or instance, the behaviour is\n the same as for a function object, except that the ``im_func``\n attribute of the new instance is not the original method object\n but its ``im_func`` attribute.\n\n When a user-defined method object is created by retrieving a\n class method object from a class or instance, its ``im_self``\n attribute is the class itself, and its ``im_func`` attribute is\n the function object underlying the class method.\n\n When an unbound user-defined method object is called, the\n underlying function (``im_func``) is called, with the\n restriction that the first argument must be an instance of the\n proper class (``im_class``) or of a derived class thereof.\n\n When a bound user-defined method object is called, the\n underlying function (``im_func``) is called, inserting the class\n instance (``im_self``) in front of the argument list. For\n instance, when ``C`` is a class which contains a definition for\n a function ``f()``, and ``x`` is an instance of ``C``, calling\n ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.\n\n When a user-defined method object is derived from a class method\n object, the "class instance" stored in ``im_self`` will actually\n be the class itself, so that calling either ``x.f(1)`` or\n ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n the underlying function.\n\n Note that the transformation from function object to (unbound or\n bound) method object happens each time the attribute is\n retrieved from the class or instance. In some cases, a fruitful\n optimization is to assign the attribute to a local variable and\n call that local variable. Also notice that this transformation\n only happens for user-defined functions; other callable objects\n (and all non-callable objects) are retrieved without\n transformation. It is also important to note that user-defined\n functions which are attributes of a class instance are not\n converted to bound methods; this *only* happens when the\n function is an attribute of the class.\n\n Generator functions\n A function or method which uses the ``yield`` statement (see\n section *The yield statement*) is called a *generator function*.\n Such a function, when called, always returns an iterator object\n which can be used to execute the body of the function: calling\n the iterator\'s ``next()`` method will cause the function to\n execute until it provides a value using the ``yield`` statement.\n When the function executes a ``return`` statement or falls off\n the end, a ``StopIteration`` exception is raised and the\n iterator will have reached the end of the set of values to be\n returned.\n\n Built-in functions\n A built-in function object is a wrapper around a C function.\n Examples of built-in functions are ``len()`` and ``math.sin()``\n (``math`` is a standard built-in module). The number and type of\n the arguments are determined by the C function. Special read-\n only attributes: ``__doc__`` is the function\'s documentation\n string, or ``None`` if unavailable; ``__name__`` is the\n function\'s name; ``__self__`` is set to ``None`` (but see the\n next item); ``__module__`` is the name of the module the\n function was defined in or ``None`` if unavailable.\n\n Built-in methods\n This is really a different disguise of a built-in function, this\n time containing an object passed to the C function as an\n implicit extra argument. An example of a built-in method is\n ``alist.append()``, assuming *alist* is a list object. In this\n case, the special read-only attribute ``__self__`` is set to the\n object denoted by *alist*.\n\n Class Types\n Class types, or "new-style classes," are callable. These\n objects normally act as factories for new instances of\n themselves, but variations are possible for class types that\n override ``__new__()``. The arguments of the call are passed to\n ``__new__()`` and, in the typical case, to ``__init__()`` to\n initialize the new instance.\n\n Classic Classes\n Class objects are described below. When a class object is\n called, a new class instance (also described below) is created\n and returned. This implies a call to the class\'s ``__init__()``\n method if it has one. Any arguments are passed on to the\n ``__init__()`` method. If there is no ``__init__()`` method,\n the class must be called without arguments.\n\n Class instances\n Class instances are described below. Class instances are\n callable only when the class has a ``__call__()`` method;\n ``x(arguments)`` is a shorthand for ``x.__call__(arguments)``.\n\nModules\n Modules are imported by the ``import`` statement (see section *The\n import statement*). A module object has a namespace implemented by\n a dictionary object (this is the dictionary referenced by the\n func_globals attribute of functions defined in the module).\n Attribute references are translated to lookups in this dictionary,\n e.g., ``m.x`` is equivalent to ``m.__dict__["x"]``. A module object\n does not contain the code object used to initialize the module\n (since it isn\'t needed once the initialization is done).\n\n Attribute assignment updates the module\'s namespace dictionary,\n e.g., ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.\n\n Special read-only attribute: ``__dict__`` is the module\'s namespace\n as a dictionary object.\n\n **CPython implementation detail:** Because of the way CPython\n clears module dictionaries, the module dictionary will be cleared\n when the module falls out of scope even if the dictionary still has\n live references. To avoid this, copy the dictionary or keep the\n module around while using its dictionary directly.\n\n Predefined (writable) attributes: ``__name__`` is the module\'s\n name; ``__doc__`` is the module\'s documentation string, or ``None``\n if unavailable; ``__file__`` is the pathname of the file from which\n the module was loaded, if it was loaded from a file. The\n ``__file__`` attribute is not present for C modules that are\n statically linked into the interpreter; for extension modules\n loaded dynamically from a shared library, it is the pathname of the\n shared library file.\n\nClasses\n Both class types (new-style classes) and class objects (old-\n style/classic classes) are typically created by class definitions\n (see section *Class definitions*). A class has a namespace\n implemented by a dictionary object. Class attribute references are\n translated to lookups in this dictionary, e.g., ``C.x`` is\n translated to ``C.__dict__["x"]`` (although for new-style classes\n in particular there are a number of hooks which allow for other\n means of locating attributes). When the attribute name is not found\n there, the attribute search continues in the base classes. For\n old-style classes, the search is depth-first, left-to-right in the\n order of occurrence in the base class list. New-style classes use\n the more complex C3 method resolution order which behaves correctly\n even in the presence of \'diamond\' inheritance structures where\n there are multiple inheritance paths leading back to a common\n ancestor. Additional details on the C3 MRO used by new-style\n classes can be found in the documentation accompanying the 2.3\n release at http://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class ``C``, say) would yield\n a user-defined function object or an unbound user-defined method\n object whose associated class is either ``C`` or one of its base\n classes, it is transformed into an unbound user-defined method\n object whose ``im_class`` attribute is ``C``. When it would yield a\n class method object, it is transformed into a bound user-defined\n method object whose ``im_self`` attribute is ``C``. When it would\n yield a static method object, it is transformed into the object\n wrapped by the static method object. See section *Implementing\n Descriptors* for another way in which attributes retrieved from a\n class may differ from those actually contained in its ``__dict__``\n (note that only new-style classes support descriptors).\n\n Class attribute assignments update the class\'s dictionary, never\n the dictionary of a base class.\n\n A class object can be called (see above) to yield a class instance\n (see below).\n\n Special attributes: ``__name__`` is the class name; ``__module__``\n is the module name in which the class was defined; ``__dict__`` is\n the dictionary containing the class\'s namespace; ``__bases__`` is a\n tuple (possibly empty or a singleton) containing the base classes,\n in the order of their occurrence in the base class list;\n ``__doc__`` is the class\'s documentation string, or None if\n undefined.\n\nClass instances\n A class instance is created by calling a class object (see above).\n A class instance has a namespace implemented as a dictionary which\n is the first place in which attribute references are searched.\n When an attribute is not found there, and the instance\'s class has\n an attribute by that name, the search continues with the class\n attributes. If a class attribute is found that is a user-defined\n function object or an unbound user-defined method object whose\n associated class is the class (call it ``C``) of the instance for\n which the attribute reference was initiated or one of its bases, it\n is transformed into a bound user-defined method object whose\n ``im_class`` attribute is ``C`` and whose ``im_self`` attribute is\n the instance. Static method and class method objects are also\n transformed, as if they had been retrieved from class ``C``; see\n above under "Classes". See section *Implementing Descriptors* for\n another way in which attributes of a class retrieved via its\n instances may differ from the objects actually stored in the\n class\'s ``__dict__``. If no class attribute is found, and the\n object\'s class has a ``__getattr__()`` method, that is called to\n satisfy the lookup.\n\n Attribute assignments and deletions update the instance\'s\n dictionary, never a class\'s dictionary. If the class has a\n ``__setattr__()`` or ``__delattr__()`` method, this is called\n instead of updating the instance dictionary directly.\n\n Class instances can pretend to be numbers, sequences, or mappings\n if they have methods with certain special names. See section\n *Special method names*.\n\n Special attributes: ``__dict__`` is the attribute dictionary;\n ``__class__`` is the instance\'s class.\n\nFiles\n A file object represents an open file. File objects are created by\n the ``open()`` built-in function, and also by ``os.popen()``,\n ``os.fdopen()``, and the ``makefile()`` method of socket objects\n (and perhaps by other functions or methods provided by extension\n modules). The objects ``sys.stdin``, ``sys.stdout`` and\n ``sys.stderr`` are initialized to file objects corresponding to the\n interpreter\'s standard input, output and error streams. See *File\n Objects* for complete documentation of file objects.\n\nInternal types\n A few types used internally by the interpreter are exposed to the\n user. Their definitions may change with future versions of the\n interpreter, but they are mentioned here for completeness.\n\n Code objects\n Code objects represent *byte-compiled* executable Python code,\n or *bytecode*. The difference between a code object and a\n function object is that the function object contains an explicit\n reference to the function\'s globals (the module in which it was\n defined), while a code object contains no context; also the\n default argument values are stored in the function object, not\n in the code object (because they represent values calculated at\n run-time). Unlike function objects, code objects are immutable\n and contain no references (directly or indirectly) to mutable\n objects.\n\n Special read-only attributes: ``co_name`` gives the function\n name; ``co_argcount`` is the number of positional arguments\n (including arguments with default values); ``co_nlocals`` is the\n number of local variables used by the function (including\n arguments); ``co_varnames`` is a tuple containing the names of\n the local variables (starting with the argument names);\n ``co_cellvars`` is a tuple containing the names of local\n variables that are referenced by nested functions;\n ``co_freevars`` is a tuple containing the names of free\n variables; ``co_code`` is a string representing the sequence of\n bytecode instructions; ``co_consts`` is a tuple containing the\n literals used by the bytecode; ``co_names`` is a tuple\n containing the names used by the bytecode; ``co_filename`` is\n the filename from which the code was compiled;\n ``co_firstlineno`` is the first line number of the function;\n ``co_lnotab`` is a string encoding the mapping from bytecode\n offsets to line numbers (for details see the source code of the\n interpreter); ``co_stacksize`` is the required stack size\n (including local variables); ``co_flags`` is an integer encoding\n a number of flags for the interpreter.\n\n The following flag bits are defined for ``co_flags``: bit\n ``0x04`` is set if the function uses the ``*arguments`` syntax\n to accept an arbitrary number of positional arguments; bit\n ``0x08`` is set if the function uses the ``**keywords`` syntax\n to accept arbitrary keyword arguments; bit ``0x20`` is set if\n the function is a generator.\n\n Future feature declarations (``from __future__ import\n division``) also use bits in ``co_flags`` to indicate whether a\n code object was compiled with a particular feature enabled: bit\n ``0x2000`` is set if the function was compiled with future\n division enabled; bits ``0x10`` and ``0x1000`` were used in\n earlier versions of Python.\n\n Other bits in ``co_flags`` are reserved for internal use.\n\n If a code object represents a function, the first item in\n ``co_consts`` is the documentation string of the function, or\n ``None`` if undefined.\n\n Frame objects\n Frame objects represent execution frames. They may occur in\n traceback objects (see below).\n\n Special read-only attributes: ``f_back`` is to the previous\n stack frame (towards the caller), or ``None`` if this is the\n bottom stack frame; ``f_code`` is the code object being executed\n in this frame; ``f_locals`` is the dictionary used to look up\n local variables; ``f_globals`` is used for global variables;\n ``f_builtins`` is used for built-in (intrinsic) names;\n ``f_restricted`` is a flag indicating whether the function is\n executing in restricted execution mode; ``f_lasti`` gives the\n precise instruction (this is an index into the bytecode string\n of the code object).\n\n Special writable attributes: ``f_trace``, if not ``None``, is a\n function called at the start of each source code line (this is\n used by the debugger); ``f_exc_type``, ``f_exc_value``,\n ``f_exc_traceback`` represent the last exception raised in the\n parent frame provided another exception was ever raised in the\n current frame (in all other cases they are None); ``f_lineno``\n is the current line number of the frame --- writing to this from\n within a trace function jumps to the given line (only for the\n bottom-most frame). A debugger can implement a Jump command\n (aka Set Next Statement) by writing to f_lineno.\n\n Traceback objects\n Traceback objects represent a stack trace of an exception. A\n traceback object is created when an exception occurs. When the\n search for an exception handler unwinds the execution stack, at\n each unwound level a traceback object is inserted in front of\n the current traceback. When an exception handler is entered,\n the stack trace is made available to the program. (See section\n *The try statement*.) It is accessible as ``sys.exc_traceback``,\n and also as the third item of the tuple returned by\n ``sys.exc_info()``. The latter is the preferred interface,\n since it works correctly when the program is using multiple\n threads. When the program contains no suitable handler, the\n stack trace is written (nicely formatted) to the standard error\n stream; if the interpreter is interactive, it is also made\n available to the user as ``sys.last_traceback``.\n\n Special read-only attributes: ``tb_next`` is the next level in\n the stack trace (towards the frame where the exception\n occurred), or ``None`` if there is no next level; ``tb_frame``\n points to the execution frame of the current level;\n ``tb_lineno`` gives the line number where the exception\n occurred; ``tb_lasti`` indicates the precise instruction. The\n line number and last instruction in the traceback may differ\n from the line number of its frame object if the exception\n occurred in a ``try`` statement with no matching except clause\n or with a finally clause.\n\n Slice objects\n Slice objects are used to represent slices when *extended slice\n syntax* is used. This is a slice using two colons, or multiple\n slices or ellipses separated by commas, e.g., ``a[i:j:step]``,\n ``a[i:j, k:l]``, or ``a[..., i:j]``. They are also created by\n the built-in ``slice()`` function.\n\n Special read-only attributes: ``start`` is the lower bound;\n ``stop`` is the upper bound; ``step`` is the step value; each is\n ``None`` if omitted. These attributes can have any type.\n\n Slice objects support one method:\n\n slice.indices(self, length)\n\n This method takes a single integer argument *length* and\n computes information about the extended slice that the slice\n object would describe if applied to a sequence of *length*\n items. It returns a tuple of three integers; respectively\n these are the *start* and *stop* indices and the *step* or\n stride length of the slice. Missing or out-of-bounds indices\n are handled in a manner consistent with regular slices.\n\n New in version 2.3.\n\n Static method objects\n Static method objects provide a way of defeating the\n transformation of function objects to method objects described\n above. A static method object is a wrapper around any other\n object, usually a user-defined method object. When a static\n method object is retrieved from a class or a class instance, the\n object actually returned is the wrapped object, which is not\n subject to any further transformation. Static method objects are\n not themselves callable, although the objects they wrap usually\n are. Static method objects are created by the built-in\n ``staticmethod()`` constructor.\n\n Class method objects\n A class method object, like a static method object, is a wrapper\n around another object that alters the way in which that object\n is retrieved from classes and class instances. The behaviour of\n class method objects upon such retrieval is described above,\n under "User-defined methods". Class method objects are created\n by the built-in ``classmethod()`` constructor.\n', + 'typesfunctions': '\nFunctions\n*********\n\nFunction objects are created by function definitions. The only\noperation on a function object is to call it: ``func(argument-list)``.\n\nThere are really two flavors of function objects: built-in functions\nand user-defined functions. Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\n\nSee *Function definitions* for more information.\n', + 'typesmapping': '\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects. There is currently only one standard\nmapping type, the *dictionary*. (For other containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values. Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys. Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry. (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict(**kwarg)\nclass class dict(mapping, **kwarg)\nclass class dict(iterable, **kwarg)\n\n Return a new dictionary initialized from an optional positional\n argument and a possibly empty set of keyword arguments.\n\n If no positional argument is given, an empty dictionary is created.\n If a positional argument is given and it is a mapping object, a\n dictionary is created with the same key-value pairs as the mapping\n object. Otherwise, the positional argument must be an *iterator*\n object. Each item in the iterable must itself be an iterator with\n exactly two objects. The first object of each item becomes a key\n in the new dictionary, and the second object the corresponding\n value. If a key occurs more than once, the last value for that key\n becomes the corresponding value in the new dictionary.\n\n If keyword arguments are given, the keyword arguments and their\n values are added to the dictionary created from the positional\n argument. If a key being added is already present, the value from\n the keyword argument replaces the value from the positional\n argument.\n\n To illustrate, the following examples all return a dictionary equal\n to ``{"one": 1, "two": 2, "three": 3}``:\n\n >>> a = dict(one=1, two=2, three=3)\n >>> b = {\'one\': 1, \'two\': 2, \'three\': 3}\n >>> c = dict(zip([\'one\', \'two\', \'three\'], [1, 2, 3]))\n >>> d = dict([(\'two\', 2), (\'one\', 1), (\'three\', 3)])\n >>> e = dict({\'three\': 3, \'one\': 1, \'two\': 2})\n >>> a == b == c == d == e\n True\n\n Providing keyword arguments as in the first example only works for\n keys that are valid Python identifiers. Otherwise, any valid keys\n can be used.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for building a dictionary from\n keyword arguments added.\n\n These are the operations that dictionaries support (and therefore,\n custom mapping types should support too):\n\n len(d)\n\n Return the number of items in the dictionary *d*.\n\n d[key]\n\n Return the item of *d* with key *key*. Raises a ``KeyError`` if\n *key* is not in the map.\n\n New in version 2.5: If a subclass of dict defines a method\n ``__missing__()``, if the key *key* is not present, the\n ``d[key]`` operation calls that method with the key *key* as\n argument. The ``d[key]`` operation then returns or raises\n whatever is returned or raised by the ``__missing__(key)`` call\n if the key is not present. No other operations or methods invoke\n ``__missing__()``. If ``__missing__()`` is not defined,\n ``KeyError`` is raised. ``__missing__()`` must be a method; it\n cannot be an instance variable. For an example, see\n ``collections.defaultdict``.\n\n d[key] = value\n\n Set ``d[key]`` to *value*.\n\n del d[key]\n\n Remove ``d[key]`` from *d*. Raises a ``KeyError`` if *key* is\n not in the map.\n\n key in d\n\n Return ``True`` if *d* has a key *key*, else ``False``.\n\n New in version 2.2.\n\n key not in d\n\n Equivalent to ``not key in d``.\n\n New in version 2.2.\n\n iter(d)\n\n Return an iterator over the keys of the dictionary. This is a\n shortcut for ``iterkeys()``.\n\n clear()\n\n Remove all items from the dictionary.\n\n copy()\n\n Return a shallow copy of the dictionary.\n\n fromkeys(seq[, value])\n\n Create a new dictionary with keys from *seq* and values set to\n *value*.\n\n ``fromkeys()`` is a class method that returns a new dictionary.\n *value* defaults to ``None``.\n\n New in version 2.3.\n\n get(key[, default])\n\n Return the value for *key* if *key* is in the dictionary, else\n *default*. If *default* is not given, it defaults to ``None``,\n so that this method never raises a ``KeyError``.\n\n has_key(key)\n\n Test for the presence of *key* in the dictionary. ``has_key()``\n is deprecated in favor of ``key in d``.\n\n items()\n\n Return a copy of the dictionary\'s list of ``(key, value)``\n pairs.\n\n **CPython implementation detail:** Keys and values are listed in\n an arbitrary order which is non-random, varies across Python\n implementations, and depends on the dictionary\'s history of\n insertions and deletions.\n\n If ``items()``, ``keys()``, ``values()``, ``iteritems()``,\n ``iterkeys()``, and ``itervalues()`` are called with no\n intervening modifications to the dictionary, the lists will\n directly correspond. This allows the creation of ``(value,\n key)`` pairs using ``zip()``: ``pairs = zip(d.values(),\n d.keys())``. The same relationship holds for the ``iterkeys()``\n and ``itervalues()`` methods: ``pairs = zip(d.itervalues(),\n d.iterkeys())`` provides the same value for ``pairs``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.iteritems()]``.\n\n iteritems()\n\n Return an iterator over the dictionary\'s ``(key, value)`` pairs.\n See the note for ``dict.items()``.\n\n Using ``iteritems()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n iterkeys()\n\n Return an iterator over the dictionary\'s keys. See the note for\n ``dict.items()``.\n\n Using ``iterkeys()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n itervalues()\n\n Return an iterator over the dictionary\'s values. See the note\n for ``dict.items()``.\n\n Using ``itervalues()`` while adding or deleting entries in the\n dictionary may raise a ``RuntimeError`` or fail to iterate over\n all entries.\n\n New in version 2.2.\n\n keys()\n\n Return a copy of the dictionary\'s list of keys. See the note\n for ``dict.items()``.\n\n pop(key[, default])\n\n If *key* is in the dictionary, remove it and return its value,\n else return *default*. If *default* is not given and *key* is\n not in the dictionary, a ``KeyError`` is raised.\n\n New in version 2.3.\n\n popitem()\n\n Remove and return an arbitrary ``(key, value)`` pair from the\n dictionary.\n\n ``popitem()`` is useful to destructively iterate over a\n dictionary, as often used in set algorithms. If the dictionary\n is empty, calling ``popitem()`` raises a ``KeyError``.\n\n setdefault(key[, default])\n\n If *key* is in the dictionary, return its value. If not, insert\n *key* with a value of *default* and return *default*. *default*\n defaults to ``None``.\n\n update([other])\n\n Update the dictionary with the key/value pairs from *other*,\n overwriting existing keys. Return ``None``.\n\n ``update()`` accepts either another dictionary object or an\n iterable of key/value pairs (as tuples or other iterables of\n length two). If keyword arguments are specified, the dictionary\n is then updated with those key/value pairs: ``d.update(red=1,\n blue=2)``.\n\n Changed in version 2.4: Allowed the argument to be an iterable\n of key/value pairs and allowed keyword arguments.\n\n values()\n\n Return a copy of the dictionary\'s list of values. See the note\n for ``dict.items()``.\n\n viewitems()\n\n Return a new view of the dictionary\'s items (``(key, value)``\n pairs). See below for documentation of view objects.\n\n New in version 2.7.\n\n viewkeys()\n\n Return a new view of the dictionary\'s keys. See below for\n documentation of view objects.\n\n New in version 2.7.\n\n viewvalues()\n\n Return a new view of the dictionary\'s values. See below for\n documentation of view objects.\n\n New in version 2.7.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.viewkeys()``, ``dict.viewvalues()`` and\n``dict.viewitems()`` are *view objects*. They provide a dynamic view\non the dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n Return the number of entries in the dictionary.\n\niter(dictview)\n\n Return an iterator over the keys, values or items (represented as\n tuples of ``(key, value)``) in the dictionary.\n\n Keys and values are iterated over in an arbitrary order which is\n non-random, varies across Python implementations, and depends on\n the dictionary\'s history of insertions and deletions. If keys,\n values and items views are iterated over with no intervening\n modifications to the dictionary, the order of items will directly\n correspond. This allows the creation of ``(value, key)`` pairs\n using ``zip()``: ``pairs = zip(d.values(), d.keys())``. Another\n way to create the same list is ``pairs = [(v, k) for (k, v) in\n d.items()]``.\n\n Iterating views while adding or deleting entries in the dictionary\n may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n Return ``True`` if *x* is in the underlying dictionary\'s keys,\n values or items (in the latter case, *x* should be a ``(key,\n value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like. (Values views are not\ntreated as set-like since the entries are generally not unique.) Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n Return the intersection of the dictview and the other object as a\n new set.\n\ndictview | other\n\n Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n Return the difference between the dictview and the other object\n (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n Return the symmetric difference (all elements either in *dictview*\n or *other*, but not in both) of the dictview and the other object\n as a new set.\n\nAn example of dictionary view usage:\n\n >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n >>> keys = dishes.viewkeys()\n >>> values = dishes.viewvalues()\n\n >>> # iteration\n >>> n = 0\n >>> for val in values:\n ... n += val\n >>> print(n)\n 504\n\n >>> # keys and values are iterated over in the same order\n >>> list(keys)\n [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n >>> list(values)\n [2, 1, 1, 500]\n\n >>> # view objects are dynamic and reflect dict changes\n >>> del dishes[\'eggs\']\n >>> del dishes[\'sausage\']\n >>> list(keys)\n [\'spam\', \'bacon\']\n\n >>> # set operations\n >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n {\'bacon\'}\n', + 'typesmethods': '\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as ``append()`` on\nlists) and class instance methods. Built-in methods are described\nwith the types that support them.\n\nThe implementation adds two special read-only attributes to class\ninstance methods: ``m.im_self`` is the object on which the method\noperates, and ``m.im_func`` is the function implementing the method.\nCalling ``m(arg-1, arg-2, ..., arg-n)`` is completely equivalent to\ncalling ``m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)``.\n\nClass instance methods are either *bound* or *unbound*, referring to\nwhether the method was accessed through an instance or a class,\nrespectively. When a method is unbound, its ``im_self`` attribute\nwill be ``None`` and if called, an explicit ``self`` object must be\npassed as the first argument. In this case, ``self`` must be an\ninstance of the unbound method\'s class (or a subclass of that class),\notherwise a ``TypeError`` is raised.\n\nLike function objects, methods objects support getting arbitrary\nattributes. However, since method attributes are actually stored on\nthe underlying function object (``meth.im_func``), setting method\nattributes on either bound or unbound methods is disallowed.\nAttempting to set an attribute on a method results in an\n``AttributeError`` being raised. In order to set a method attribute,\nyou need to explicitly set it on the underlying function object:\n\n >>> class C:\n ... def method(self):\n ... pass\n ...\n >>> c = C()\n >>> c.method.whoami = \'my name is method\' # can\'t set on the method\n Traceback (most recent call last):\n File "", line 1, in \n AttributeError: \'instancemethod\' object has no attribute \'whoami\'\n >>> c.method.im_func.whoami = \'my name is method\'\n >>> c.method.whoami\n \'my name is method\'\n\nSee *The standard type hierarchy* for more information.\n', + 'typesmodules': "\nModules\n*******\n\nThe only special operation on a module is attribute access:\n``m.name``, where *m* is a module and *name* accesses a name defined\nin *m*'s symbol table. Module attributes can be assigned to. (Note\nthat the ``import`` statement is not, strictly speaking, an operation\non a module object; ``import foo`` does not require a module object\nnamed *foo* to exist, rather it requires an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA special attribute of every module is ``__dict__``. This is the\ndictionary containing the module's symbol table. Modifying this\ndictionary will actually change the module's symbol table, but direct\nassignment to the ``__dict__`` attribute is not possible (you can\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\nyou can't write ``m.__dict__ = {}``). Modifying ``__dict__`` directly\nis not recommended.\n\nModules built into the interpreter are written like this: ````. If loaded from a file, they are written as\n````.\n", +- 'typesseq': '\nSequence Types --- ``str``, ``unicode``, ``list``, ``tuple``, ``bytearray``, ``buffer``, ``xrange``\n***************************************************************************************************\n\nThere are seven sequence types: strings, Unicode strings, lists,\ntuples, bytearrays, buffers, and xrange objects.\n\nFor other containers see the built in ``dict`` and ``set`` classes,\nand the ``collections`` module.\n\nString literals are written in single or double quotes: ``\'xyzzy\'``,\n``"frobozz"``. See *String literals* for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding ``\'u\'`` character: ``u\'abc\'``, ``u"def"``. In\naddition to the functionality described here, there are also string-\nspecific methods described in the *String Methods* section. Lists are\nconstructed with square brackets, separating items with commas: ``[a,\nb, c]``. Tuples are constructed by the comma operator (not within\nsquare brackets), with or without enclosing parentheses, but an empty\ntuple must have the enclosing parentheses, such as ``a, b, c`` or\n``()``. A single item tuple must have a trailing comma, such as\n``(d,)``.\n\nBytearray objects are created with the built-in function\n``bytearray()``.\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function ``buffer()``. They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n``xrange()`` function. They don\'t support slicing, concatenation or\nrepetition, and using ``in``, ``not in``, ``min()`` or ``max()`` on\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+====================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+--------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+--------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n| | concatenated | |\n+--------------------+----------------------------------+------------+\n| ``s[i]`` | *i*th item of *s*, origin 0 | (3) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+--------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+--------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.index(i)`` | index of the first occurrence of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.count(i)`` | total number of occurrences of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the ``in`` and ``not\n in`` operations act like a substring test. In Python versions\n before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n beyond, *x* may be a string of any length.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n empty sequence of the same type as *s*). Note also that the copies\n are shallow; nested structures are not copied. This often haunts\n new Python programmers; consider:\n\n >>> lists = [[]] * 3\n >>> lists\n [[], [], []]\n >>> lists[0].append(3)\n >>> lists\n [[3], [3], [3]]\n\n What has happened is that ``[[]]`` is a one-element list containing\n an empty list, so all three elements of ``[[]] * 3`` are (pointers\n to) this single empty list. Modifying any of the elements of\n ``lists`` modifies this single list. You can create a list of\n different lists this way:\n\n >>> lists = [[] for i in range(3)]\n >>> lists[0].append(3)\n >>> lists[1].append(5)\n >>> lists[2].append(7)\n >>> lists\n [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n Changed in version 2.4: Formerly, string concatenation never\n occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support. Some of them are also available on\n``bytearray`` objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output formatted strings use\ntemplate strings or the ``%`` operator described in the *String\nFormatting Operations* section. Also, see the ``re`` module for string\nfunctions based on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with its first character capitalized\n and the rest lowercased.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. Tab positions occur every *tabsize* characters\n (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n To expand the string, the current column is set to zero and the\n string is examined character by character. If the character is a\n tab (``\\t``), one or more space characters are inserted in the\n result until the current column is equal to the next tab position.\n (The tab character itself is not copied.) If the character is a\n newline (``\\n``) or return (``\\r``), it is copied and the current\n column is reset to zero. Any other character is copied unchanged\n and the current column is incremented by one regardless of how the\n character is represented when printed.\n\n >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n \'01 012 0123 01234\'\n >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n \'01 012 0123 01234\'\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\n Note: The ``find()`` method should be used only if you need to know the\n position of *sub*. To check if *sub* is a substring or not, use\n the ``in`` operator:\n\n >>> \'Py\' in \'Python\'\n True\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n Return true if all cased characters [4] in the string are lowercase\n and there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return true if all cased characters [4] in the string are uppercase\n and there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string with all the cased characters [4]\n converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\n New in version 2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\n New in version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified or ``-1``, then there is\n no limit on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. This method uses the *universal newlines* approach to\n splitting lines. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\n For example, ``\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()`` returns\n ``[\'ab c\', \'\', \'de fg\', \'kl\']``, while the same call with\n ``splitlines(True)`` returns ``[\'ab c\\n\', \'\\n\', \'de fg\\r\',\n \'kl\\r\\n\']``.\n\n Unlike ``split()`` when a delimiter string *sep* is given, this\n method returns an empty list for the empty string, and a terminal\n line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\n Changed in version 2.5: Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n ... return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n ... lambda mo: mo.group(0)[0].upper() +\n ... mo.group(0)[1:].lower(),\n ... s)\n ...\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string with all the cased characters [4]\n converted to uppercase. Note that ``str.upper().isupper()`` might\n be ``False`` if ``s`` contains uncased characters or if the Unicode\n category of the resulting character(s) is not "Lu" (Letter,\n uppercase), but e.g. "Lt" (Letter, titlecase).\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than or equal to ``len(s)``.\n\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that can be used to form decimal-radix numbers,\n e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [5] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(number)03d quote types.\' % \\\n... {"language": "Python", "number": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using *repr()*). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (6) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'`` | No argument is converted, results in a ``\'%\'`` | |\n| | character in the result. | |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n point, even if no digits follow it.\n\n The precision determines the number of digits after the decimal\n point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n point, and trailing zeroes are not removed as they would otherwise\n be.\n\n The precision determines the number of significant digits before\n and after the decimal point and defaults to 6.\n\n5. The ``%r`` conversion was added in Python 2.0.\n\n The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a ``unicode`` string, the\n resulting string will also be ``unicode``.\n\n The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 2.7: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\n\nXRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable sequence types (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*\'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don\'t return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n', +- 'typesseq-mutable': "\nMutable Sequence Types\n**********************\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable sequence types (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn't have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method is only supported by the list and array types.\n The optional argument *i* defaults to ``-1``, so that by default\n the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don't return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n", ++ 'typesseq': '\nSequence Types --- ``str``, ``unicode``, ``list``, ``tuple``, ``bytearray``, ``buffer``, ``xrange``\n***************************************************************************************************\n\nThere are seven sequence types: strings, Unicode strings, lists,\ntuples, bytearrays, buffers, and xrange objects.\n\nFor other containers see the built in ``dict`` and ``set`` classes,\nand the ``collections`` module.\n\nString literals are written in single or double quotes: ``\'xyzzy\'``,\n``"frobozz"``. See *String literals* for more about string literals.\nUnicode strings are much like strings, but are specified in the syntax\nusing a preceding ``\'u\'`` character: ``u\'abc\'``, ``u"def"``. In\naddition to the functionality described here, there are also string-\nspecific methods described in the *String Methods* section. Lists are\nconstructed with square brackets, separating items with commas: ``[a,\nb, c]``. Tuples are constructed by the comma operator (not within\nsquare brackets), with or without enclosing parentheses, but an empty\ntuple must have the enclosing parentheses, such as ``a, b, c`` or\n``()``. A single item tuple must have a trailing comma, such as\n``(d,)``.\n\nBytearray objects are created with the built-in function\n``bytearray()``.\n\nBuffer objects are not directly supported by Python syntax, but can be\ncreated by calling the built-in function ``buffer()``. They don\'t\nsupport concatenation or repetition.\n\nObjects of type xrange are similar to buffers in that there is no\nspecific syntax to create them, but they are created using the\n``xrange()`` function. They don\'t support slicing, concatenation or\nrepetition, and using ``in``, ``not in``, ``min()`` or ``max()`` on\nthem is inefficient.\n\nMost sequence types support the following operations. The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations. The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority). In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation | Result | Notes |\n+====================+==================================+============+\n| ``x in s`` | ``True`` if an item of *s* is | (1) |\n| | equal to *x*, else ``False`` | |\n+--------------------+----------------------------------+------------+\n| ``x not in s`` | ``False`` if an item of *s* is | (1) |\n| | equal to *x*, else ``True`` | |\n+--------------------+----------------------------------+------------+\n| ``s + t`` | the concatenation of *s* and *t* | (6) |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s`` | *n* shallow copies of *s* | (2) |\n| | concatenated | |\n+--------------------+----------------------------------+------------+\n| ``s[i]`` | *i*th item of *s*, origin 0 | (3) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |\n| | with step *k* | |\n+--------------------+----------------------------------+------------+\n| ``len(s)`` | length of *s* | |\n+--------------------+----------------------------------+------------+\n| ``min(s)`` | smallest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``max(s)`` | largest item of *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.index(i)`` | index of the first occurrence of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n| ``s.count(i)`` | total number of occurrences of | |\n| | *i* in *s* | |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons. In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements. This means that to compare equal, every element must compare\nequal and the two sequences must be of the same type and have the same\nlength. (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string or Unicode string object the ``in`` and ``not\n in`` operations act like a substring test. In Python versions\n before 2.3, *x* had to be a string of length 1. In Python 2.3 and\n beyond, *x* may be a string of any length.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n empty sequence of the same type as *s*). Note also that the copies\n are shallow; nested structures are not copied. This often haunts\n new Python programmers; consider:\n\n >>> lists = [[]] * 3\n >>> lists\n [[], [], []]\n >>> lists[0].append(3)\n >>> lists\n [[3], [3], [3]]\n\n What has happened is that ``[[]]`` is a one-element list containing\n an empty list, so all three elements of ``[[]] * 3`` are (pointers\n to) this single empty list. Modifying any of the elements of\n ``lists`` modifies this single list. You can create a list of\n different lists this way:\n\n >>> lists = [[] for i in range(3)]\n >>> lists[0].append(3)\n >>> lists[1].append(5)\n >>> lists[2].append(7)\n >>> lists\n [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n string: ``len(s) + i`` or ``len(s) + j`` is substituted. But note\n that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n items with index *k* such that ``i <= k < j``. If *i* or *j* is\n greater than ``len(s)``, use ``len(s)``. If *i* is omitted or\n ``None``, use ``0``. If *j* is omitted or ``None``, use\n ``len(s)``. If *i* is greater than or equal to *j*, the slice is\n empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n sequence of items with index ``x = i + n*k`` such that ``0 <= n <\n (j-i)/k``. In other words, the indices are ``i``, ``i+k``,\n ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n never including *j*). If *i* or *j* is greater than ``len(s)``,\n use ``len(s)``. If *i* or *j* are omitted or ``None``, they become\n "end" values (which end depends on the sign of *k*). Note, *k*\n cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n some Python implementations such as CPython can usually perform an\n in-place optimization for assignments of the form ``s = s + t`` or\n ``s += t``. When applicable, this optimization makes quadratic\n run-time much less likely. This optimization is both version and\n implementation dependent. For performance sensitive code, it is\n preferable to use the ``str.join()`` method which assures\n consistent linear concatenation performance across versions and\n implementations.\n\n Changed in version 2.4: Formerly, string concatenation never\n occurred in-place.\n\n\nString Methods\n==============\n\nBelow are listed the string methods which both 8-bit strings and\nUnicode objects support. Some of them are also available on\n``bytearray`` objects.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, unicode, list, tuple,\nbytearray, buffer, xrange* section. To output formatted strings use\ntemplate strings or the ``%`` operator described in the *String\nFormatting Operations* section. Also, see the ``re`` module for string\nfunctions based on regular expressions.\n\nstr.capitalize()\n\n Return a copy of the string with its first character capitalized\n and the rest lowercased.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.center(width[, fillchar])\n\n Return centered in a string of length *width*. Padding is done\n using the specified *fillchar* (default is a space).\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.count(sub[, start[, end]])\n\n Return the number of non-overlapping occurrences of substring *sub*\n in the range [*start*, *end*]. Optional arguments *start* and\n *end* are interpreted as in slice notation.\n\nstr.decode([encoding[, errors]])\n\n Decodes the string using the codec registered for *encoding*.\n *encoding* defaults to the default string encoding. *errors* may\n be given to set a different error handling scheme. The default is\n ``\'strict\'``, meaning that encoding errors raise ``UnicodeError``.\n Other possible values are ``\'ignore\'``, ``\'replace\'`` and any other\n name registered via ``codecs.register_error()``, see section *Codec\n Base Classes*.\n\n New in version 2.2.\n\n Changed in version 2.3: Support for other error handling schemes\n added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.encode([encoding[, errors]])\n\n Return an encoded version of the string. Default encoding is the\n current default string encoding. *errors* may be given to set a\n different error handling scheme. The default for *errors* is\n ``\'strict\'``, meaning that encoding errors raise a\n ``UnicodeError``. Other possible values are ``\'ignore\'``,\n ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n any other name registered via ``codecs.register_error()``, see\n section *Codec Base Classes*. For a list of possible encodings, see\n section *Standard Encodings*.\n\n New in version 2.0.\n\n Changed in version 2.3: Support for ``\'xmlcharrefreplace\'`` and\n ``\'backslashreplace\'`` and other error handling schemes added.\n\n Changed in version 2.7: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n Return ``True`` if the string ends with the specified *suffix*,\n otherwise return ``False``. *suffix* can also be a tuple of\n suffixes to look for. With optional *start*, test beginning at\n that position. With optional *end*, stop comparing at that\n position.\n\n Changed in version 2.5: Accept tuples as *suffix*.\n\nstr.expandtabs([tabsize])\n\n Return a copy of the string where all tab characters are replaced\n by one or more spaces, depending on the current column and the\n given tab size. Tab positions occur every *tabsize* characters\n (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n To expand the string, the current column is set to zero and the\n string is examined character by character. If the character is a\n tab (``\\t``), one or more space characters are inserted in the\n result until the current column is equal to the next tab position.\n (The tab character itself is not copied.) If the character is a\n newline (``\\n``) or return (``\\r``), it is copied and the current\n column is reset to zero. Any other character is copied unchanged\n and the current column is incremented by one regardless of how the\n character is represented when printed.\n\n >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n \'01 012 0123 01234\'\n >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n \'01 012 0123 01234\'\n\nstr.find(sub[, start[, end]])\n\n Return the lowest index in the string where substring *sub* is\n found, such that *sub* is contained in the slice ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` if *sub* is not found.\n\n Note: The ``find()`` method should be used only if you need to know the\n position of *sub*. To check if *sub* is a substring or not, use\n the ``in`` operator:\n\n >>> \'Py\' in \'Python\'\n True\n\nstr.format(*args, **kwargs)\n\n Perform a string formatting operation. The string on which this\n method is called can contain literal text or replacement fields\n delimited by braces ``{}``. Each replacement field contains either\n the numeric index of a positional argument, or the name of a\n keyword argument. Returns a copy of the string where each\n replacement field is replaced with the string value of the\n corresponding argument.\n\n >>> "The sum of 1 + 2 is {0}".format(1+2)\n \'The sum of 1 + 2 is 3\'\n\n See *Format String Syntax* for a description of the various\n formatting options that can be specified in format strings.\n\n This method of string formatting is the new standard in Python 3,\n and should be preferred to the ``%`` formatting described in\n *String Formatting Operations* in new code.\n\n New in version 2.6.\n\nstr.index(sub[, start[, end]])\n\n Like ``find()``, but raise ``ValueError`` when the substring is not\n found.\n\nstr.isalnum()\n\n Return true if all characters in the string are alphanumeric and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isalpha()\n\n Return true if all characters in the string are alphabetic and\n there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isdigit()\n\n Return true if all characters in the string are digits and there is\n at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.islower()\n\n Return true if all cased characters [4] in the string are lowercase\n and there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isspace()\n\n Return true if there are only whitespace characters in the string\n and there is at least one character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.istitle()\n\n Return true if the string is a titlecased string and there is at\n least one character, for example uppercase characters may only\n follow uncased characters and lowercase characters only cased ones.\n Return false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.isupper()\n\n Return true if all cased characters [4] in the string are uppercase\n and there is at least one cased character, false otherwise.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.join(iterable)\n\n Return a string which is the concatenation of the strings in the\n *iterable* *iterable*. The separator between elements is the\n string providing this method.\n\nstr.ljust(width[, fillchar])\n\n Return the string left justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.lower()\n\n Return a copy of the string with all the cased characters [4]\n converted to lowercase.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.lstrip([chars])\n\n Return a copy of the string with leading characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a prefix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.lstrip()\n \'spacious \'\n >>> \'www.example.com\'.lstrip(\'cmowz.\')\n \'example.com\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.partition(sep)\n\n Split the string at the first occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing the string itself, followed by\n two empty strings.\n\n New in version 2.5.\n\nstr.replace(old, new[, count])\n\n Return a copy of the string with all occurrences of substring *old*\n replaced by *new*. If the optional argument *count* is given, only\n the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n Return the highest index in the string where substring *sub* is\n found, such that *sub* is contained within ``s[start:end]``.\n Optional arguments *start* and *end* are interpreted as in slice\n notation. Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n is not found.\n\nstr.rjust(width[, fillchar])\n\n Return the string right justified in a string of length *width*.\n Padding is done using the specified *fillchar* (default is a\n space). The original string is returned if *width* is less than or\n equal to ``len(s)``.\n\n Changed in version 2.4: Support for the *fillchar* argument.\n\nstr.rpartition(sep)\n\n Split the string at the last occurrence of *sep*, and return a\n 3-tuple containing the part before the separator, the separator\n itself, and the part after the separator. If the separator is not\n found, return a 3-tuple containing two empty strings, followed by\n the string itself.\n\n New in version 2.5.\n\nstr.rsplit([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n are done, the *rightmost* ones. If *sep* is not specified or\n ``None``, any whitespace string is a separator. Except for\n splitting from the right, ``rsplit()`` behaves like ``split()``\n which is described in detail below.\n\n New in version 2.4.\n\nstr.rstrip([chars])\n\n Return a copy of the string with trailing characters removed. The\n *chars* argument is a string specifying the set of characters to be\n removed. If omitted or ``None``, the *chars* argument defaults to\n removing whitespace. The *chars* argument is not a suffix; rather,\n all combinations of its values are stripped:\n\n >>> \' spacious \'.rstrip()\n \' spacious\'\n >>> \'mississippi\'.rstrip(\'ipz\')\n \'mississ\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.split([sep[, maxsplit]])\n\n Return a list of the words in the string, using *sep* as the\n delimiter string. If *maxsplit* is given, at most *maxsplit*\n splits are done (thus, the list will have at most ``maxsplit+1``\n elements). If *maxsplit* is not specified or ``-1``, then there is\n no limit on the number of splits (all possible splits are made).\n\n If *sep* is given, consecutive delimiters are not grouped together\n and are deemed to delimit empty strings (for example,\n ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``). The *sep*\n argument may consist of multiple characters (for example,\n ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n an empty string with a specified separator returns ``[\'\']``.\n\n If *sep* is not specified or is ``None``, a different splitting\n algorithm is applied: runs of consecutive whitespace are regarded\n as a single separator, and the result will contain no empty strings\n at the start or end if the string has leading or trailing\n whitespace. Consequently, splitting an empty string or a string\n consisting of just whitespace with a ``None`` separator returns\n ``[]``.\n\n For example, ``\' 1 2 3 \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n and ``\' 1 2 3 \'.split(None, 1)`` returns ``[\'1\', \'2 3 \']``.\n\nstr.splitlines([keepends])\n\n Return a list of the lines in the string, breaking at line\n boundaries. This method uses the *universal newlines* approach to\n splitting lines. Line breaks are not included in the resulting list\n unless *keepends* is given and true.\n\n For example, ``\'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()`` returns\n ``[\'ab c\', \'\', \'de fg\', \'kl\']``, while the same call with\n ``splitlines(True)`` returns ``[\'ab c\\n\', \'\\n\', \'de fg\\r\',\n \'kl\\r\\n\']``.\n\n Unlike ``split()`` when a delimiter string *sep* is given, this\n method returns an empty list for the empty string, and a terminal\n line break does not result in an extra line.\n\nstr.startswith(prefix[, start[, end]])\n\n Return ``True`` if string starts with the *prefix*, otherwise\n return ``False``. *prefix* can also be a tuple of prefixes to look\n for. With optional *start*, test string beginning at that\n position. With optional *end*, stop comparing string at that\n position.\n\n Changed in version 2.5: Accept tuples as *prefix*.\n\nstr.strip([chars])\n\n Return a copy of the string with the leading and trailing\n characters removed. The *chars* argument is a string specifying the\n set of characters to be removed. If omitted or ``None``, the\n *chars* argument defaults to removing whitespace. The *chars*\n argument is not a prefix or suffix; rather, all combinations of its\n values are stripped:\n\n >>> \' spacious \'.strip()\n \'spacious\'\n >>> \'www.example.com\'.strip(\'cmowz.\')\n \'example\'\n\n Changed in version 2.2.2: Support for the *chars* argument.\n\nstr.swapcase()\n\n Return a copy of the string with uppercase characters converted to\n lowercase and vice versa.\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.title()\n\n Return a titlecased version of the string where words start with an\n uppercase character and the remaining characters are lowercase.\n\n The algorithm uses a simple language-independent definition of a\n word as groups of consecutive letters. The definition works in\n many contexts but it means that apostrophes in contractions and\n possessives form word boundaries, which may not be the desired\n result:\n\n >>> "they\'re bill\'s friends from the UK".title()\n "They\'Re Bill\'S Friends From The Uk"\n\n A workaround for apostrophes can be constructed using regular\n expressions:\n\n >>> import re\n >>> def titlecase(s):\n ... return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n ... lambda mo: mo.group(0)[0].upper() +\n ... mo.group(0)[1:].lower(),\n ... s)\n ...\n >>> titlecase("they\'re bill\'s friends.")\n "They\'re Bill\'s Friends."\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.translate(table[, deletechars])\n\n Return a copy of the string where all characters occurring in the\n optional argument *deletechars* are removed, and the remaining\n characters have been mapped through the given translation table,\n which must be a string of length 256.\n\n You can use the ``maketrans()`` helper function in the ``string``\n module to create a translation table. For string objects, set the\n *table* argument to ``None`` for translations that only delete\n characters:\n\n >>> \'read this short text\'.translate(None, \'aeiou\')\n \'rd ths shrt txt\'\n\n New in version 2.6: Support for a ``None`` *table* argument.\n\n For Unicode objects, the ``translate()`` method does not accept the\n optional *deletechars* argument. Instead, it returns a copy of the\n *s* where all characters have been mapped through the given\n translation table which must be a mapping of Unicode ordinals to\n Unicode ordinals, Unicode strings or ``None``. Unmapped characters\n are left untouched. Characters mapped to ``None`` are deleted.\n Note, a more flexible approach is to create a custom character\n mapping codec using the ``codecs`` module (see ``encodings.cp1251``\n for an example).\n\nstr.upper()\n\n Return a copy of the string with all the cased characters [4]\n converted to uppercase. Note that ``str.upper().isupper()`` might\n be ``False`` if ``s`` contains uncased characters or if the Unicode\n category of the resulting character(s) is not "Lu" (Letter,\n uppercase), but e.g. "Lt" (Letter, titlecase).\n\n For 8-bit strings, this method is locale-dependent.\n\nstr.zfill(width)\n\n Return the numeric string left filled with zeros in a string of\n length *width*. A sign prefix is handled correctly. The original\n string is returned if *width* is less than or equal to ``len(s)``.\n\n New in version 2.2.2.\n\nThe following methods are present only on unicode objects:\n\nunicode.isnumeric()\n\n Return ``True`` if there are only numeric characters in S,\n ``False`` otherwise. Numeric characters include digit characters,\n and all characters that have the Unicode numeric value property,\n e.g. U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return ``True`` if there are only decimal characters in S,\n ``False`` otherwise. Decimal characters include digit characters,\n and all characters that can be used to form decimal-radix numbers,\n e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the\n``%`` operator (modulo). This is also known as the string\n*formatting* or *interpolation* operator. Given ``format % values``\n(where *format* is a string or Unicode object), ``%`` conversion\nspecifications in *format* are replaced with zero or more elements of\n*values*. The effect is similar to the using ``sprintf()`` in the C\nlanguage. If *format* is a Unicode object, or if any of the objects\nbeing converted using the ``%s`` conversion are Unicode objects, the\nresult will also be a Unicode object.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [5] Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n conversion types.\n\n4. Minimum field width (optional). If specified as an ``\'*\'``\n (asterisk), the actual width is read from the next element of the\n tuple in *values*, and the object to convert comes after the\n minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n precision. If specified as ``\'*\'`` (an asterisk), the actual width\n is read from the next element of the tuple in *values*, and the\n value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print \'%(language)s has %(number)03d quote types.\' % \\\n... {"language": "Python", "number": 2}\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag | Meaning |\n+===========+=======================================================================+\n| ``\'#\'`` | The value conversion will use the "alternate form" (where defined |\n| | below). |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'`` | The conversion will be zero padded for numeric values. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'`` | The converted value is left adjusted (overrides the ``\'0\'`` |\n| | conversion if both are given). |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'`` | (a space) A blank should be left before a positive number (or empty |\n| | string) produced by a signed conversion. |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'`` | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion |\n| | (overrides a "space" flag). |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion | Meaning | Notes |\n+==============+=======================================================+=========+\n| ``\'d\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'`` | Signed integer decimal. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'`` | Signed octal value. | (1) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'`` | Obsolete type -- it is identical to ``\'d\'``. | (7) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'`` | Signed hexadecimal (lowercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'`` | Signed hexadecimal (uppercase). | (2) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'`` | Floating point exponential format (lowercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'`` | Floating point exponential format (uppercase). | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'`` | Floating point decimal format. | (3) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'`` | Floating point format. Uses lowercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'`` | Floating point format. Uses uppercase exponential | (4) |\n| | format if exponent is less than -4 or not less than | |\n| | precision, decimal format otherwise. | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'`` | Single character (accepts integer or single character | |\n| | string). | |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'`` | String (converts any Python object using *repr()*). | (5) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'`` | String (converts any Python object using ``str()``). | (6) |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'`` | No argument is converted, results in a ``\'%\'`` | |\n| | character in the result. | |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n between left-hand padding and the formatting of the number if the\n leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n point, even if no digits follow it.\n\n The precision determines the number of digits after the decimal\n point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n point, and trailing zeroes are not removed as they would otherwise\n be.\n\n The precision determines the number of significant digits before\n and after the decimal point and defaults to 6.\n\n5. The ``%r`` conversion was added in Python 2.0.\n\n The precision determines the maximal number of characters used.\n\n6. If the object or format provided is a ``unicode`` string, the\n resulting string will also be ``unicode``.\n\n The precision determines the maximal number of characters used.\n\n7. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 2.7: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nXRange Type\n===========\n\nThe ``xrange`` type is an immutable sequence which is commonly used\nfor looping. The advantage of the ``xrange`` type is that an\n``xrange`` object will always take the same amount of memory, no\nmatter the size of the range it represents. There are no consistent\nperformance advantages.\n\nXRange objects have very little behavior: they only support indexing,\niteration, and the ``len()`` function.\n\n\nMutable Sequence Types\n======================\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable sequence types (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*\'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn\'t have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method\'s optional argument *i* defaults to ``-1``, so\n that by default the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don\'t return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n', ++ 'typesseq-mutable': "\nMutable Sequence Types\n**********************\n\nList and ``bytearray`` objects support additional operations that\nallow in-place modification of the object. Other mutable sequence\ntypes (when added to the language) should also support these\noperations. Strings and tuples are immutable sequence types: such\nobjects cannot be modified once created. The following operations are\ndefined on mutable sequence types (where *x* is an arbitrary object):\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation | Result | Notes |\n+================================+==================================+=======================+\n| ``s[i] = x`` | item *i* of *s* is replaced by | |\n| | *x* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t`` | slice of *s* from *i* to *j* is | |\n| | replaced by the contents of the | |\n| | iterable *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]`` | same as ``s[i:j] = []`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` are | (1) |\n| | replaced by those of *t* | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]`` | removes the elements of | |\n| | ``s[i:j:k]`` from the list | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)`` | same as ``s[len(s):len(s)] = | (2) |\n| | [x]`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)`` | same as ``s[len(s):len(s)] = x`` | (3) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)`` | return number of *i*'s for which | |\n| | ``s[i] == x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])`` | return smallest *k* such that | (4) |\n| | ``s[k] == x`` and ``i <= k < j`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | (5) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | (6) |\n| | return x`` | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | (4) |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()`` | reverses the items of *s* in | (7) |\n| | place | |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |\n| reverse]]])`` | | |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The C implementation of Python has historically accepted multiple\n parameters and implicitly joined them into a tuple; this no longer\n works in Python 2.0. Use of this misfeature has been deprecated\n since Python 1.4.\n\n3. *x* can be any iterable object.\n\n4. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n index is passed as the second or third parameter to the ``index()``\n method, the list length is added, as for slice indices. If it is\n still negative, it is truncated to zero, as for slice indices.\n\n Changed in version 2.3: Previously, ``index()`` didn't have\n arguments for specifying start and stop positions.\n\n5. When a negative index is passed as the first parameter to the\n ``insert()`` method, the list length is added, as for slice\n indices. If it is still negative, it is truncated to zero, as for\n slice indices.\n\n Changed in version 2.3: Previously, all negative indices were\n truncated to zero.\n\n6. The ``pop()`` method's optional argument *i* defaults to ``-1``, so\n that by default the last item is removed and returned.\n\n7. The ``sort()`` and ``reverse()`` methods modify the list in place\n for economy of space when sorting or reversing a large list. To\n remind you that they operate by side effect, they don't return the\n sorted or reversed list.\n\n8. The ``sort()`` method takes optional arguments for controlling the\n comparisons.\n\n *cmp* specifies a custom comparison function of two arguments (list\n items) which should return a negative, zero or positive number\n depending on whether the first argument is considered smaller than,\n equal to, or larger than the second argument: ``cmp=lambda x,y:\n cmp(x.lower(), y.lower())``. The default value is ``None``.\n\n *key* specifies a function of one argument that is used to extract\n a comparison key from each list element: ``key=str.lower``. The\n default value is ``None``.\n\n *reverse* is a boolean value. If set to ``True``, then the list\n elements are sorted as if each comparison were reversed.\n\n In general, the *key* and *reverse* conversion processes are much\n faster than specifying an equivalent *cmp* function. This is\n because *cmp* is called multiple times for each list element while\n *key* and *reverse* touch each element only once. Use\n ``functools.cmp_to_key()`` to convert an old-style *cmp* function\n to a *key* function.\n\n Changed in version 2.3: Support for ``None`` as an equivalent to\n omitting *cmp* was added.\n\n Changed in version 2.4: Support for *key* and *reverse* was added.\n\n9. Starting with Python 2.3, the ``sort()`` method is guaranteed to be\n stable. A sort is stable if it guarantees not to change the\n relative order of elements that compare equal --- this is helpful\n for sorting in multiple passes (for example, sort by department,\n then by salary grade).\n\n10. **CPython implementation detail:** While a list is being sorted,\n the effect of attempting to mutate, or even inspect, the list is\n undefined. The C implementation of Python 2.3 and newer makes the\n list appear empty for the duration, and raises ``ValueError`` if\n it can detect that the list has been mutated during a sort.\n", + 'unary': '\nUnary arithmetic and bitwise operations\n***************************************\n\nAll unary arithmetic and bitwise operations have the same priority:\n\n u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n\nThe unary ``-`` (minus) operator yields the negation of its numeric\nargument.\n\nThe unary ``+`` (plus) operator yields its numeric argument unchanged.\n\nThe unary ``~`` (invert) operator yields the bitwise inversion of its\nplain or long integer argument. The bitwise inversion of ``x`` is\ndefined as ``-(x+1)``. It only applies to integral numbers.\n\nIn all three cases, if the argument does not have the proper type, a\n``TypeError`` exception is raised.\n', + 'while': '\nThe ``while`` statement\n***********************\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n while_stmt ::= "while" expression ":" suite\n ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite. A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n', + 'with': '\nThe ``with`` statement\n**********************\n\nNew in version 2.5.\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n with_stmt ::= "with" with_item ("," with_item)* ":" suite\n with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the ``with_item``)\n is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n value from ``__enter__()`` is assigned to it.\n\n Note: The ``with`` statement guarantees that if the ``__enter__()``\n method returns without an error, then ``__exit__()`` will always\n be called. Thus, if an error occurs during the assignment to the\n target list, it will be treated the same as an error occurring\n within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked. If an\n exception caused the suite to be exited, its type, value, and\n traceback are passed as arguments to ``__exit__()``. Otherwise,\n three ``None`` arguments are supplied.\n\n If the suite was exited due to an exception, and the return value\n from the ``__exit__()`` method was false, the exception is\n reraised. If the return value was true, the exception is\n suppressed, and execution continues with the statement following\n the ``with`` statement.\n\n If the suite was exited for any reason other than an exception, the\n return value from ``__exit__()`` is ignored, and execution proceeds\n at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n with A() as a, B() as b:\n suite\n\nis equivalent to\n\n with A() as a:\n with B() as b:\n suite\n\nNote: In Python 2.5, the ``with`` statement is only allowed when the\n ``with_statement`` feature has been enabled. It is always enabled\n in Python 2.6.\n\nChanged in version 2.7: Support for multiple context expressions.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python\n ``with`` statement.\n', +diff -r 3a1db0d2747e Lib/random.py +--- a/Lib/random.py ++++ b/Lib/random.py +@@ -108,7 +108,7 @@ + + if a is None: + try: +- a = long(_hexlify(_urandom(16)), 16) ++ a = long(_hexlify(_urandom(32)), 16) + except NotImplementedError: + import time + a = long(time.time() * 256) # use fractional seconds +diff -r 3a1db0d2747e Lib/re.py +--- a/Lib/re.py ++++ b/Lib/re.py +@@ -225,11 +225,13 @@ + + def _compile(*key): + # internal: compile pattern +- cachekey = (type(key[0]),) + key +- p = _cache.get(cachekey) +- if p is not None: +- return p + pattern, flags = key ++ bypass_cache = flags & DEBUG ++ if not bypass_cache: ++ cachekey = (type(key[0]),) + key ++ p = _cache.get(cachekey) ++ if p is not None: ++ return p + if isinstance(pattern, _pattern_type): + if flags: + raise ValueError('Cannot process flags argument with a compiled pattern') +@@ -240,9 +242,10 @@ + p = sre_compile.compile(pattern, flags) + except error, v: + raise error, v # invalid expression +- if len(_cache) >= _MAXCACHE: +- _cache.clear() +- _cache[cachekey] = p ++ if not bypass_cache: ++ if len(_cache) >= _MAXCACHE: ++ _cache.clear() ++ _cache[cachekey] = p + return p + + def _compile_repl(*key): +diff -r 3a1db0d2747e Lib/shutil.py +--- a/Lib/shutil.py ++++ b/Lib/shutil.py +@@ -259,7 +259,8 @@ + def _basename(path): + # A basename() variant which first strips the trailing slash, if present. + # Thus we always get the last component of the path, even for directories. +- return os.path.basename(path.rstrip(os.path.sep)) ++ sep = os.path.sep + (os.path.altsep or '') ++ return os.path.basename(path.rstrip(sep)) + + def move(src, dst): + """Recursively move a file or directory to another location. This is +@@ -446,17 +447,15 @@ + zip_filename, base_dir) + + if not dry_run: +- zip = zipfile.ZipFile(zip_filename, "w", +- compression=zipfile.ZIP_DEFLATED) +- +- for dirpath, dirnames, filenames in os.walk(base_dir): +- for name in filenames: +- path = os.path.normpath(os.path.join(dirpath, name)) +- if os.path.isfile(path): +- zip.write(path, path) +- if logger is not None: +- logger.info("adding '%s'", path) +- zip.close() ++ with zipfile.ZipFile(zip_filename, "w", ++ compression=zipfile.ZIP_DEFLATED) as zf: ++ for dirpath, dirnames, filenames in os.walk(base_dir): ++ for name in filenames: ++ path = os.path.normpath(os.path.join(dirpath, name)) ++ if os.path.isfile(path): ++ zf.write(path, path) ++ if logger is not None: ++ logger.info("adding '%s'", path) + + return zip_filename + +diff -r 3a1db0d2747e Lib/sqlite3/test/factory.py +--- a/Lib/sqlite3/test/factory.py ++++ b/Lib/sqlite3/test/factory.py +@@ -47,9 +47,7 @@ + self.con.close() + + def CheckIsInstance(self): +- self.assertTrue(isinstance(self.con, +- MyConnection), +- "connection is not instance of MyConnection") ++ self.assertIsInstance(self.con, MyConnection) + + class CursorFactoryTests(unittest.TestCase): + def setUp(self): +@@ -60,9 +58,7 @@ + + def CheckIsInstance(self): + cur = self.con.cursor(factory=MyCursor) +- self.assertTrue(isinstance(cur, +- MyCursor), +- "cursor is not instance of MyCursor") ++ self.assertIsInstance(cur, MyCursor) + + class RowFactoryTestsBackwardsCompat(unittest.TestCase): + def setUp(self): +@@ -72,9 +68,7 @@ + cur = self.con.cursor(factory=MyCursor) + cur.execute("select 4+5 as foo") + row = cur.fetchone() +- self.assertTrue(isinstance(row, +- dict), +- "row is not instance of dict") ++ self.assertIsInstance(row, dict) + cur.close() + + def tearDown(self): +@@ -87,28 +81,24 @@ + def CheckCustomFactory(self): + self.con.row_factory = lambda cur, row: list(row) + row = self.con.execute("select 1, 2").fetchone() +- self.assertTrue(isinstance(row, +- list), +- "row is not instance of list") ++ self.assertIsInstance(row, list) + + def CheckSqliteRowIndex(self): + self.con.row_factory = sqlite.Row + row = self.con.execute("select 1 as a, 2 as b").fetchone() +- self.assertTrue(isinstance(row, +- sqlite.Row), +- "row is not instance of sqlite.Row") ++ self.assertIsInstance(row, sqlite.Row) + + col1, col2 = row["a"], row["b"] +- self.assertTrue(col1 == 1, "by name: wrong result for column 'a'") +- self.assertTrue(col2 == 2, "by name: wrong result for column 'a'") ++ self.assertEqual(col1, 1, "by name: wrong result for column 'a'") ++ self.assertEqual(col2, 2, "by name: wrong result for column 'a'") + + col1, col2 = row["A"], row["B"] +- self.assertTrue(col1 == 1, "by name: wrong result for column 'A'") +- self.assertTrue(col2 == 2, "by name: wrong result for column 'B'") ++ self.assertEqual(col1, 1, "by name: wrong result for column 'A'") ++ self.assertEqual(col2, 2, "by name: wrong result for column 'B'") + + col1, col2 = row[0], row[1] +- self.assertTrue(col1 == 1, "by index: wrong result for column 0") +- self.assertTrue(col2 == 2, "by index: wrong result for column 1") ++ self.assertEqual(col1, 1, "by index: wrong result for column 0") ++ self.assertEqual(col2, 2, "by index: wrong result for column 1") + + def CheckSqliteRowIter(self): + """Checks if the row object is iterable""" +@@ -122,6 +112,7 @@ + self.con.row_factory = sqlite.Row + row = self.con.execute("select 1 as a, 2 as b").fetchone() + t = tuple(row) ++ self.assertEqual(t, (row['a'], row['b'])) + + def CheckSqliteRowAsDict(self): + """Checks if the row object can be correctly converted to a dictionary""" +@@ -138,8 +129,8 @@ + row_2 = self.con.execute("select 1 as a, 2 as b").fetchone() + row_3 = self.con.execute("select 1 as a, 3 as b").fetchone() + +- self.assertTrue(row_1 == row_1) +- self.assertTrue(row_1 == row_2) ++ self.assertEqual(row_1, row_1) ++ self.assertEqual(row_1, row_2) + self.assertTrue(row_2 != row_3) + + self.assertFalse(row_1 != row_1) +@@ -161,20 +152,20 @@ + def CheckUnicode(self): + austria = unicode("Österreich", "latin1") + row = self.con.execute("select ?", (austria,)).fetchone() +- self.assertTrue(type(row[0]) == unicode, "type of row[0] must be unicode") ++ self.assertEqual(type(row[0]), unicode, "type of row[0] must be unicode") + + def CheckString(self): + self.con.text_factory = str + austria = unicode("Österreich", "latin1") + row = self.con.execute("select ?", (austria,)).fetchone() +- self.assertTrue(type(row[0]) == str, "type of row[0] must be str") +- self.assertTrue(row[0] == austria.encode("utf-8"), "column must equal original data in UTF-8") ++ self.assertEqual(type(row[0]), str, "type of row[0] must be str") ++ self.assertEqual(row[0], austria.encode("utf-8"), "column must equal original data in UTF-8") + + def CheckCustom(self): + self.con.text_factory = lambda x: unicode(x, "utf-8", "ignore") + austria = unicode("Österreich", "latin1") + row = self.con.execute("select ?", (austria.encode("latin1"),)).fetchone() +- self.assertTrue(type(row[0]) == unicode, "type of row[0] must be unicode") ++ self.assertEqual(type(row[0]), unicode, "type of row[0] must be unicode") + self.assertTrue(row[0].endswith(u"reich"), "column must contain original data") + + def CheckOptimizedUnicode(self): +@@ -183,8 +174,8 @@ + germany = unicode("Deutchland") + a_row = self.con.execute("select ?", (austria,)).fetchone() + d_row = self.con.execute("select ?", (germany,)).fetchone() +- self.assertTrue(type(a_row[0]) == unicode, "type of non-ASCII row must be unicode") +- self.assertTrue(type(d_row[0]) == str, "type of ASCII-only row must be str") ++ self.assertEqual(type(a_row[0]), unicode, "type of non-ASCII row must be unicode") ++ self.assertEqual(type(d_row[0]), str, "type of ASCII-only row must be str") + + def tearDown(self): + self.con.close() +diff -r 3a1db0d2747e Lib/sqlite3/test/hooks.py +--- a/Lib/sqlite3/test/hooks.py ++++ b/Lib/sqlite3/test/hooks.py +@@ -162,7 +162,7 @@ + create table bar (a, b) + """) + second_count = len(progress_calls) +- self.assertTrue(first_count > second_count) ++ self.assertGreaterEqual(first_count, second_count) + + def CheckCancelOperation(self): + """ +diff -r 3a1db0d2747e Lib/sqlite3/test/regression.py +--- a/Lib/sqlite3/test/regression.py ++++ b/Lib/sqlite3/test/regression.py +@@ -313,6 +313,11 @@ + datetime.datetime(2012, 4, 4, 15, 6, 0, 123456), + ]) + ++ def CheckInvalidIsolationLevelType(self): ++ # isolation level is a string, not an integer ++ self.assertRaises(TypeError, ++ sqlite.connect, ":memory:", isolation_level=123) ++ + + def suite(): + regression_suite = unittest.makeSuite(RegressionTests, "Check") +diff -r 3a1db0d2747e Lib/sre_compile.py +--- a/Lib/sre_compile.py ++++ b/Lib/sre_compile.py +@@ -276,10 +276,10 @@ + # set is constructed. Then, this bitmap is sliced into chunks of 256 + # characters, duplicate chunks are eliminated, and each chunk is + # given a number. In the compiled expression, the charset is +-# represented by a 16-bit word sequence, consisting of one word for +-# the number of different chunks, a sequence of 256 bytes (128 words) ++# represented by a 32-bit word sequence, consisting of one word for ++# the number of different chunks, a sequence of 256 bytes (64 words) + # of chunk numbers indexed by their original chunk position, and a +-# sequence of chunks (16 words each). ++# sequence of 256-bit chunks (8 words each). + + # Compression is normally good: in a typical charset, large ranges of + # Unicode will be either completely excluded (e.g. if only cyrillic +@@ -294,7 +294,7 @@ + + # In UCS-4 mode, the BIGCHARSET opcode still supports only subsets + # of the basic multilingual plane; an efficient representation +-# for all of UTF-16 has not yet been developed. This means, ++# for all of Unicode has not yet been developed. This means, + # in particular, that negated charsets cannot be represented as + # bigcharsets. + +diff -r 3a1db0d2747e Lib/ssl.py +--- a/Lib/ssl.py ++++ b/Lib/ssl.py +@@ -89,6 +89,7 @@ + + from socket import socket, _fileobject, _delegate_methods, error as socket_error + from socket import getnameinfo as _getnameinfo ++from socket import SOL_SOCKET, SO_TYPE, SOCK_STREAM + import base64 # for DER-to-PEM translation + import errno + +@@ -108,6 +109,10 @@ + ssl_version=PROTOCOL_SSLv23, ca_certs=None, + do_handshake_on_connect=True, + suppress_ragged_eofs=True, ciphers=None): ++ # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get ++ # mixed in. ++ if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: ++ raise NotImplementedError("only stream sockets are supported") + socket.__init__(self, _sock=sock._sock) + # The initializer for socket overrides the methods send(), recv(), etc. + # in the instancce, which we don't need -- but we want to provide the +diff -r 3a1db0d2747e Lib/subprocess.py +--- a/Lib/subprocess.py ++++ b/Lib/subprocess.py +@@ -11,7 +11,7 @@ + + This module allows you to spawn processes, connect to their + input/output/error pipes, and obtain their return codes. This module +-intends to replace several other, older modules and functions, like: ++intends to replace several older modules and functions: + + os.system + os.spawn* +@@ -645,6 +645,8 @@ + + + class Popen(object): ++ _child_created = False # Set here since __del__ checks it ++ + def __init__(self, args, bufsize=0, executable=None, + stdin=None, stdout=None, stderr=None, + preexec_fn=None, close_fds=False, shell=False, +@@ -653,7 +655,6 @@ + """Create new Popen instance.""" + _cleanup() + +- self._child_created = False + if not isinstance(bufsize, (int, long)): + raise TypeError("bufsize must be an integer") + +@@ -750,11 +751,11 @@ + return data + + +- def __del__(self, _maxint=sys.maxint, _active=_active): ++ def __del__(self, _maxint=sys.maxint): + # If __init__ hasn't had a chance to execute (e.g. if it + # was passed an undeclared keyword argument), we don't + # have a _child_created attribute at all. +- if not getattr(self, '_child_created', False): ++ if not self._child_created: + # We didn't get to successfully create a child process. + return + # In case the child hasn't been waited on, check if it's done. +@@ -1330,7 +1331,7 @@ + _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED, + _WEXITSTATUS=os.WEXITSTATUS): + # This method is called (indirectly) by __del__, so it cannot +- # refer to anything outside of its local scope.""" ++ # refer to anything outside of its local scope. + if _WIFSIGNALED(sts): + self.returncode = -_WTERMSIG(sts) + elif _WIFEXITED(sts): +diff -r 3a1db0d2747e Lib/sunau.py +--- a/Lib/sunau.py ++++ b/Lib/sunau.py +@@ -224,7 +224,7 @@ + if self._data_size == AUDIO_UNKNOWN_SIZE: + return AUDIO_UNKNOWN_SIZE + if self._encoding in _simple_encodings: +- return self._data_size / self._framesize ++ return self._data_size // self._framesize + return 0 # XXX--must do some arithmetic here + + def getcomptype(self): +diff -r 3a1db0d2747e Lib/tarfile.py +--- a/Lib/tarfile.py ++++ b/Lib/tarfile.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # -*- coding: iso-8859-1 -*- + #------------------------------------------------------------------- + # tarfile.py +@@ -1509,10 +1508,11 @@ + can be determined, `mode' is overridden by `fileobj's mode. + `fileobj' is not closed, when TarFile is closed. + """ +- if len(mode) > 1 or mode not in "raw": ++ modes = {"r": "rb", "a": "r+b", "w": "wb"} ++ if mode not in modes: + raise ValueError("mode must be 'r', 'a' or 'w'") + self.mode = mode +- self._mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] ++ self._mode = modes[mode] + + if not fileobj: + if self.mode == "a" and not os.path.exists(name): +@@ -1682,7 +1682,7 @@ + filemode = filemode or "r" + comptype = comptype or "tar" + +- if filemode not in "rw": ++ if filemode not in ("r", "w"): + raise ValueError("mode must be 'r' or 'w'") + + t = cls(name, filemode, +@@ -1691,7 +1691,7 @@ + t._extfileobj = False + return t + +- elif mode in "aw": ++ elif mode in ("a", "w"): + return cls.taropen(name, mode, fileobj, **kwargs) + + raise ValueError("undiscernible mode") +@@ -1700,7 +1700,7 @@ + def taropen(cls, name, mode="r", fileobj=None, **kwargs): + """Open uncompressed tar archive name for reading or writing. + """ +- if len(mode) > 1 or mode not in "raw": ++ if mode not in ("r", "a", "w"): + raise ValueError("mode must be 'r', 'a' or 'w'") + return cls(name, mode, fileobj, **kwargs) + +@@ -1709,7 +1709,7 @@ + """Open gzip compressed tar archive name for reading or writing. + Appending is not allowed. + """ +- if len(mode) > 1 or mode not in "rw": ++ if mode not in ("r", "w"): + raise ValueError("mode must be 'r' or 'w'") + + try: +@@ -1726,7 +1726,9 @@ + gzip.GzipFile(name, mode, compresslevel, fileobj), + **kwargs) + except IOError: +- raise ReadError("not a gzip file") ++ if mode == 'r': ++ raise ReadError("not a gzip file") ++ raise + t._extfileobj = False + return t + +@@ -1735,7 +1737,7 @@ + """Open bzip2 compressed tar archive name for reading or writing. + Appending is not allowed. + """ +- if len(mode) > 1 or mode not in "rw": ++ if mode not in ("r", "w"): + raise ValueError("mode must be 'r' or 'w'.") + + try: +@@ -1751,7 +1753,9 @@ + try: + t = cls.taropen(name, mode, fileobj, **kwargs) + except (IOError, EOFError): +- raise ReadError("not a bzip2 file") ++ if mode == 'r': ++ raise ReadError("not a bzip2 file") ++ raise + t._extfileobj = False + return t + +diff -r 3a1db0d2747e Lib/telnetlib.py +--- a/Lib/telnetlib.py ++++ b/Lib/telnetlib.py +@@ -312,7 +312,9 @@ + poller.register(self, poll_in_or_priority_flags) + while i < 0 and not self.eof: + try: +- ready = poller.poll(call_timeout) ++ # Poll takes its timeout in milliseconds. ++ ready = poller.poll(None if timeout is None ++ else 1000 * call_timeout) + except select.error as e: + if e.errno == errno.EINTR: + if timeout is not None: +@@ -682,7 +684,8 @@ + poller.register(self, poll_in_or_priority_flags) + while not m and not self.eof: + try: +- ready = poller.poll(call_timeout) ++ ready = poller.poll(None if timeout is None ++ else 1000 * call_timeout) + except select.error as e: + if e.errno == errno.EINTR: + if timeout is not None: +diff -r 3a1db0d2747e Lib/test/audiotests.py +--- a/Lib/test/audiotests.py ++++ b/Lib/test/audiotests.py +@@ -6,11 +6,19 @@ + import sys + import base64 + ++class UnseekableIO(file): ++ def tell(self): ++ raise io.UnsupportedOperation ++ ++ def seek(self, *args, **kwargs): ++ raise io.UnsupportedOperation ++ + def fromhex(s): + return base64.b16decode(s.replace(' ', '')) + + def byteswap2(data): +- a = array.array('h', data) ++ a = array.array('h') ++ a.fromstring(data) + a.byteswap() + return a.tostring() + +@@ -21,7 +29,8 @@ + return bytes(ba) + + def byteswap4(data): +- a = array.array('i', data) ++ a = array.array('i') ++ a.fromstring(data) + a.byteswap() + return a.tostring() + +@@ -131,6 +140,62 @@ + self.assertEqual(testfile.read(13), b'ababagalamaga') + self.check_file(testfile, self.nframes, self.frames) + ++ def test_unseekable_read(self): ++ f = self.create_file(TESTFN) ++ f.setnframes(self.nframes) ++ f.writeframes(self.frames) ++ f.close() ++ ++ with UnseekableIO(TESTFN, 'rb') as testfile: ++ self.check_file(testfile, self.nframes, self.frames) ++ ++ def test_unseekable_write(self): ++ with UnseekableIO(TESTFN, 'wb') as testfile: ++ f = self.create_file(testfile) ++ f.setnframes(self.nframes) ++ f.writeframes(self.frames) ++ f.close() ++ self.fout = None ++ ++ self.check_file(TESTFN, self.nframes, self.frames) ++ ++ def test_unseekable_incompleted_write(self): ++ with UnseekableIO(TESTFN, 'wb') as testfile: ++ testfile.write(b'ababagalamaga') ++ f = self.create_file(testfile) ++ f.setnframes(self.nframes + 1) ++ try: ++ f.writeframes(self.frames) ++ except IOError: ++ pass ++ try: ++ f.close() ++ except IOError: ++ pass ++ ++ with open(TESTFN, 'rb') as testfile: ++ self.assertEqual(testfile.read(13), b'ababagalamaga') ++ self.check_file(testfile, self.nframes + 1, self.frames) ++ ++ def test_unseekable_overflowed_write(self): ++ with UnseekableIO(TESTFN, 'wb') as testfile: ++ testfile.write(b'ababagalamaga') ++ f = self.create_file(testfile) ++ f.setnframes(self.nframes - 1) ++ try: ++ f.writeframes(self.frames) ++ except IOError: ++ pass ++ try: ++ f.close() ++ except IOError: ++ pass ++ ++ with open(TESTFN, 'rb') as testfile: ++ self.assertEqual(testfile.read(13), b'ababagalamaga') ++ framesize = self.nchannels * self.sampwidth ++ self.check_file(testfile, self.nframes - 1, self.frames[:-framesize]) ++ + + class AudioTestsWithSourceFile(AudioTests): + +diff -r 3a1db0d2747e Lib/test/bad_coding3.py +--- /dev/null ++++ b/Lib/test/bad_coding3.py +@@ -0,0 +1,2 @@ ++# coding: string-escape ++\x70\x72\x69\x6e\x74\x20\x32\x2b\x32\x0a +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.bmp +Binary file Lib/test/imghdrdata/python.bmp has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.gif +Binary file Lib/test/imghdrdata/python.gif has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.jpg +Binary file Lib/test/imghdrdata/python.jpg has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.pbm +--- /dev/null ++++ b/Lib/test/imghdrdata/python.pbm +@@ -0,0 +1,3 @@ ++P4 ++16 16 ++ûñ¿úßÕ­±[ñ¥a_ÁX°°ðððð?ÿÿ +\ No newline at end of file +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.pgm +Binary file Lib/test/imghdrdata/python.pgm has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.png +Binary file Lib/test/imghdrdata/python.png has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.ppm +Binary file Lib/test/imghdrdata/python.ppm has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.ras +Binary file Lib/test/imghdrdata/python.ras has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.sgi +Binary file Lib/test/imghdrdata/python.sgi has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.tiff +Binary file Lib/test/imghdrdata/python.tiff has changed +diff -r 3a1db0d2747e Lib/test/imghdrdata/python.xbm +--- /dev/null ++++ b/Lib/test/imghdrdata/python.xbm +@@ -0,0 +1,6 @@ ++#define python_width 16 ++#define python_height 16 ++static char python_bits[] = { ++ 0xDF, 0xFE, 0x8F, 0xFD, 0x5F, 0xFB, 0xAB, 0xFE, 0xB5, 0x8D, 0xDA, 0x8F, ++ 0xA5, 0x86, 0xFA, 0x83, 0x1A, 0x80, 0x0D, 0x80, 0x0D, 0x80, 0x0F, 0xE0, ++ 0x0F, 0xF8, 0x0F, 0xF8, 0x0F, 0xFC, 0xFF, 0xFF, }; +diff -r 3a1db0d2747e Lib/test/pickletester.py +--- a/Lib/test/pickletester.py ++++ b/Lib/test/pickletester.py +@@ -1152,30 +1152,34 @@ + if isinstance(object, int) and object % 2 == 0: + self.id_count += 1 + return str(object) ++ elif object == "test_false_value": ++ self.false_count += 1 ++ return "" + else: + return None + + def persistent_load(self, oid): +- self.load_count += 1 +- object = int(oid) +- assert object % 2 == 0 +- return object ++ if not oid: ++ self.load_false_count += 1 ++ return "test_false_value" ++ else: ++ self.load_count += 1 ++ object = int(oid) ++ assert object % 2 == 0 ++ return object + + def test_persistence(self): +- self.id_count = 0 +- self.load_count = 0 +- L = range(10) +- self.assertEqual(self.loads(self.dumps(L)), L) +- self.assertEqual(self.id_count, 5) +- self.assertEqual(self.load_count, 5) +- +- def test_bin_persistence(self): +- self.id_count = 0 +- self.load_count = 0 +- L = range(10) +- self.assertEqual(self.loads(self.dumps(L, 1)), L) +- self.assertEqual(self.id_count, 5) +- self.assertEqual(self.load_count, 5) ++ L = range(10) + ["test_false_value"] ++ for proto in protocols: ++ self.id_count = 0 ++ self.false_count = 0 ++ self.load_false_count = 0 ++ self.load_count = 0 ++ self.assertEqual(self.loads(self.dumps(L, proto)), L) ++ self.assertEqual(self.id_count, 5) ++ self.assertEqual(self.false_count, 1) ++ self.assertEqual(self.load_count, 5) ++ self.assertEqual(self.load_false_count, 1) + + class AbstractPicklerUnpicklerObjectTests(unittest.TestCase): + +diff -r 3a1db0d2747e Lib/test/string_tests.py +--- a/Lib/test/string_tests.py ++++ b/Lib/test/string_tests.py +@@ -5,7 +5,6 @@ + import unittest, string, sys, struct + from test import test_support + from UserList import UserList +-import _testcapi + + class Sequence: + def __init__(self, seq='wxyz'): self.seq = seq +@@ -750,10 +749,10 @@ + self.checkraises(TypeError, 'hello', 'replace', 42, 'h') + self.checkraises(TypeError, 'hello', 'replace', 'h', 42) + ++ @unittest.skipIf(sys.maxint > (1 << 32) or struct.calcsize('P') != 4, ++ 'only applies to 32-bit platforms') + def test_replace_overflow(self): + # Check for overflow checking on 32 bit machines +- if sys.maxint != 2147483647 or struct.calcsize("P") > 4: +- return + A2_16 = "A" * (2**16) + self.checkraises(OverflowError, A2_16, "replace", "", A2_16) + self.checkraises(OverflowError, A2_16, "replace", "A", A2_16) +@@ -1114,20 +1113,6 @@ + self.checkraises(TypeError, '%10.*f', '__mod__', ('foo', 42.)) + self.checkraises(ValueError, '%10', '__mod__', (42,)) + +- width = int(_testcapi.PY_SSIZE_T_MAX + 1) +- if width <= sys.maxint: +- self.checkraises(OverflowError, '%*s', '__mod__', (width, '')) +- prec = int(_testcapi.INT_MAX + 1) +- if prec <= sys.maxint: +- self.checkraises(OverflowError, '%.*f', '__mod__', (prec, 1. / 7)) +- # Issue 15989 +- width = int(1 << (_testcapi.PY_SSIZE_T_MAX.bit_length() + 1)) +- if width <= sys.maxint: +- self.checkraises(OverflowError, '%*s', '__mod__', (width, '')) +- prec = int(_testcapi.UINT_MAX + 1) +- if prec <= sys.maxint: +- self.checkraises(OverflowError, '%.*f', '__mod__', (prec, 1. / 7)) +- + class X(object): pass + self.checkraises(TypeError, 'abc', '__mod__', X()) + class X(Exception): +@@ -1135,6 +1120,24 @@ + return k + self.checkequal('melon apple', '%(melon)s %(apple)s', '__mod__', X()) + ++ @test_support.cpython_only ++ def test_formatting_c_limits(self): ++ from _testcapi import PY_SSIZE_T_MAX, INT_MAX, UINT_MAX ++ SIZE_MAX = (1 << (PY_SSIZE_T_MAX.bit_length() + 1)) - 1 ++ width = int(PY_SSIZE_T_MAX + 1) ++ if width <= sys.maxint: ++ self.checkraises(OverflowError, '%*s', '__mod__', (width, '')) ++ prec = int(INT_MAX + 1) ++ if prec <= sys.maxint: ++ self.checkraises(OverflowError, '%.*f', '__mod__', (prec, 1. / 7)) ++ # Issue 15989 ++ width = int(SIZE_MAX + 1) ++ if width <= sys.maxint: ++ self.checkraises(OverflowError, '%*s', '__mod__', (width, '')) ++ prec = int(UINT_MAX + 1) ++ if prec <= sys.maxint: ++ self.checkraises(OverflowError, '%.*f', '__mod__', (prec, 1. / 7)) ++ + def test_floatformatting(self): + # float formatting + for prec in xrange(100): +@@ -1286,27 +1289,27 @@ + # Additional tests that only work with + # 8bit compatible object, i.e. str and UserString + +- if test_support.have_unicode: +- def test_encoding_decoding(self): +- codecs = [('rot13', 'uryyb jbeyq'), +- ('base64', 'aGVsbG8gd29ybGQ=\n'), +- ('hex', '68656c6c6f20776f726c64'), +- ('uu', 'begin 666 \n+:&5L;&\\@=V]R;&0 \n \nend\n')] +- for encoding, data in codecs: +- self.checkequal(data, 'hello world', 'encode', encoding) +- self.checkequal('hello world', data, 'decode', encoding) +- # zlib is optional, so we make the test optional too... +- try: +- import zlib +- except ImportError: +- pass +- else: +- data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' +- self.checkequal(data, 'hello world', 'encode', 'zlib') +- self.checkequal('hello world', data, 'decode', 'zlib') ++ @unittest.skipUnless(test_support.have_unicode, 'no unicode support') ++ def test_encoding_decoding(self): ++ codecs = [('rot13', 'uryyb jbeyq'), ++ ('base64', 'aGVsbG8gd29ybGQ=\n'), ++ ('hex', '68656c6c6f20776f726c64'), ++ ('uu', 'begin 666 \n+:&5L;&\\@=V]R;&0 \n \nend\n')] ++ for encoding, data in codecs: ++ self.checkequal(data, 'hello world', 'encode', encoding) ++ self.checkequal('hello world', data, 'decode', encoding) ++ # zlib is optional, so we make the test optional too... ++ try: ++ import zlib ++ except ImportError: ++ pass ++ else: ++ data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' ++ self.checkequal(data, 'hello world', 'encode', 'zlib') ++ self.checkequal('hello world', data, 'decode', 'zlib') + +- self.checkraises(TypeError, 'xyz', 'decode', 42) +- self.checkraises(TypeError, 'xyz', 'encode', 42) ++ self.checkraises(TypeError, 'xyz', 'decode', 42) ++ self.checkraises(TypeError, 'xyz', 'encode', 42) + + + class MixinStrUnicodeTest: +diff -r 3a1db0d2747e Lib/test/test___future__.py +--- a/Lib/test/test___future__.py ++++ b/Lib/test/test___future__.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + import unittest + from test import test_support + import __future__ +diff -r 3a1db0d2747e Lib/test/test_aepack.py +--- a/Lib/test/test_aepack.py ++++ b/Lib/test/test_aepack.py +@@ -59,10 +59,10 @@ + try: + import Carbon.File + except: +- return ++ self.skipTest('Carbon.File not available') + + if not hasattr(Carbon.File, "FSSpec"): +- return ++ self.skipTest('Carbon.File.FSSpec not available') + o = Carbon.File.FSSpec(os.curdir) + packed = aepack.pack(o) + unpacked = aepack.unpack(packed) +@@ -72,9 +72,9 @@ + try: + import Carbon.File + except: +- return ++ self.skipTest('Carbon.File not available') + if not hasattr(Carbon.File, "FSSpec"): +- return ++ self.skipTest('Carbon.File.FSSpec not available') + o = Carbon.File.FSSpec(os.curdir).NewAliasMinimal() + packed = aepack.pack(o) + unpacked = aepack.unpack(packed) +diff -r 3a1db0d2747e Lib/test/test_aifc.py +--- a/Lib/test/test_aifc.py ++++ b/Lib/test/test_aifc.py +@@ -9,10 +9,14 @@ + import aifc + + +-class AifcPCM8Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): ++class AifcTest(audiotests.AudioWriteTests, ++ audiotests.AudioTestsWithSourceFile): + module = aifc ++ close_fd = True ++ test_unseekable_read = None ++ ++ ++class AifcPCM8Test(AifcTest, unittest.TestCase): + sndfilename = 'pluck-pcm8.aiff' + sndfilenframes = 3307 + nchannels = 2 +@@ -27,13 +31,9 @@ + 11FA 3EFB BCFC 66FF CF04 4309 C10E 5112 EE17 8216 7F14 8012 \ + 490E 520D EF0F CE0F E40C 630A 080A 2B0B 510E 8B11 B60E 440A \ + """) +- close_fd = True + + +-class AifcPCM16Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = aifc ++class AifcPCM16Test(AifcTest, unittest.TestCase): + sndfilename = 'pluck-pcm16.aiff' + sndfilenframes = 3307 + nchannels = 2 +@@ -50,13 +50,9 @@ + EEE21753 82071665 7FFF1443 8004128F 49A20EAF 52BB0DBA EFB40F60 CE3C0FBF \ + E4B30CEC 63430A5C 08C80A20 2BBB0B08 514A0E43 8BCF1139 B6F60EEB 44120A5E \ + """) +- close_fd = True + + +-class AifcPCM24Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = aifc ++class AifcPCM24Test(AifcTest, unittest.TestCase): + sndfilename = 'pluck-pcm24.aiff' + sndfilenframes = 3307 + nchannels = 2 +@@ -79,13 +75,9 @@ + E4B49C0CEA2D 6344A80A5A7C 08C8FE0A1FFE 2BB9860B0A0E \ + 51486F0E44E1 8BCC64113B05 B6F4EC0EEB36 4413170A5B48 \ + """) +- close_fd = True + + +-class AifcPCM32Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = aifc ++class AifcPCM32Test(AifcTest, unittest.TestCase): + sndfilename = 'pluck-pcm32.aiff' + sndfilenframes = 3307 + nchannels = 2 +@@ -108,13 +100,9 @@ + E4B49CC00CEA2D90 6344A8800A5A7CA0 08C8FE800A1FFEE0 2BB986C00B0A0E00 \ + 51486F800E44E190 8BCC6480113B0580 B6F4EC000EEB3630 441317800A5B48A0 \ + """) +- close_fd = True + + +-class AifcULAWTest(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = aifc ++class AifcULAWTest(AifcTest, unittest.TestCase): + sndfilename = 'pluck-ulaw.aifc' + sndfilenframes = 3307 + nchannels = 2 +@@ -133,7 +121,6 @@ + """) + if sys.byteorder != 'big': + frames = audiotests.byteswap2(frames) +- close_fd = True + + + class AifcMiscTest(audiotests.AudioTests, unittest.TestCase): +diff -r 3a1db0d2747e Lib/test/test_al.py +--- a/Lib/test/test_al.py ++++ b/Lib/test/test_al.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Whimpy test script for the al module + Roger E. Masse + """ +diff -r 3a1db0d2747e Lib/test/test_anydbm.py +--- a/Lib/test/test_anydbm.py ++++ b/Lib/test/test_anydbm.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for the anydbm module + based on testdumbdbm.py + """ +diff -r 3a1db0d2747e Lib/test/test_argparse.py +--- a/Lib/test/test_argparse.py ++++ b/Lib/test/test_argparse.py +@@ -2936,6 +2936,60 @@ + 0.1 + ''' + ++class TestShortColumns(HelpTestCase): ++ '''Test extremely small number of columns. ++ ++ TestCase prevents "COLUMNS" from being too small in the tests themselves, ++ but we don't want any exceptions thrown in such case. Only ugly representation. ++ ''' ++ def setUp(self): ++ env = test_support.EnvironmentVarGuard() ++ env.set("COLUMNS", '15') ++ self.addCleanup(env.__exit__) ++ ++ parser_signature = TestHelpBiggerOptionals.parser_signature ++ argument_signatures = TestHelpBiggerOptionals.argument_signatures ++ argument_group_signatures = TestHelpBiggerOptionals.argument_group_signatures ++ usage = '''\ ++ usage: PROG ++ [-h] ++ [-v] ++ [-x] ++ [--y Y] ++ foo ++ bar ++ ''' ++ help = usage + '''\ ++ ++ DESCRIPTION ++ ++ positional arguments: ++ foo ++ FOO HELP ++ bar ++ BAR HELP ++ ++ optional arguments: ++ -h, --help ++ show this ++ help ++ message and ++ exit ++ -v, --version ++ show ++ program's ++ version ++ number and ++ exit ++ -x ++ X HELP ++ --y Y ++ Y HELP ++ ++ EPILOG ++ ''' ++ version = TestHelpBiggerOptionals.version ++ + + class TestHelpBiggerOptionalGroups(HelpTestCase): + """Make sure that argument help aligns when options are longer""" +diff -r 3a1db0d2747e Lib/test/test_array.py +--- a/Lib/test/test_array.py ++++ b/Lib/test/test_array.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test the arraymodule. + Roger E. Masse + """ +@@ -9,6 +8,7 @@ + from weakref import proxy + import array, cStringIO + from cPickle import loads, dumps, HIGHEST_PROTOCOL ++import sys + + class ArraySubclass(array.array): + pass +@@ -49,7 +49,7 @@ + def test_constructor(self): + a = array.array(self.typecode) + self.assertEqual(a.typecode, self.typecode) +- self.assertTrue(a.itemsize>=self.minitemsize) ++ self.assertGreaterEqual(a.itemsize, self.minitemsize) + self.assertRaises(TypeError, array.array, self.typecode, None) + + def test_len(self): +@@ -253,39 +253,39 @@ + + def test_cmp(self): + a = array.array(self.typecode, self.example) +- self.assertTrue((a == 42) is False) +- self.assertTrue((a != 42) is True) ++ self.assertIs(a == 42, False) ++ self.assertIs(a != 42, True) + +- self.assertTrue((a == a) is True) +- self.assertTrue((a != a) is False) +- self.assertTrue((a < a) is False) +- self.assertTrue((a <= a) is True) +- self.assertTrue((a > a) is False) +- self.assertTrue((a >= a) is True) ++ self.assertIs(a == a, True) ++ self.assertIs(a != a, False) ++ self.assertIs(a < a, False) ++ self.assertIs(a <= a, True) ++ self.assertIs(a > a, False) ++ self.assertIs(a >= a, True) + + al = array.array(self.typecode, self.smallerexample) + ab = array.array(self.typecode, self.biggerexample) + +- self.assertTrue((a == 2*a) is False) +- self.assertTrue((a != 2*a) is True) +- self.assertTrue((a < 2*a) is True) +- self.assertTrue((a <= 2*a) is True) +- self.assertTrue((a > 2*a) is False) +- self.assertTrue((a >= 2*a) is False) ++ self.assertIs(a == 2*a, False) ++ self.assertIs(a != 2*a, True) ++ self.assertIs(a < 2*a, True) ++ self.assertIs(a <= 2*a, True) ++ self.assertIs(a > 2*a, False) ++ self.assertIs(a >= 2*a, False) + +- self.assertTrue((a == al) is False) +- self.assertTrue((a != al) is True) +- self.assertTrue((a < al) is False) +- self.assertTrue((a <= al) is False) +- self.assertTrue((a > al) is True) +- self.assertTrue((a >= al) is True) ++ self.assertIs(a == al, False) ++ self.assertIs(a != al, True) ++ self.assertIs(a < al, False) ++ self.assertIs(a <= al, False) ++ self.assertIs(a > al, True) ++ self.assertIs(a >= al, True) + +- self.assertTrue((a == ab) is False) +- self.assertTrue((a != ab) is True) +- self.assertTrue((a < ab) is True) +- self.assertTrue((a <= ab) is True) +- self.assertTrue((a > ab) is False) +- self.assertTrue((a >= ab) is False) ++ self.assertIs(a == ab, False) ++ self.assertIs(a != ab, True) ++ self.assertIs(a < ab, True) ++ self.assertIs(a <= ab, True) ++ self.assertIs(a > ab, False) ++ self.assertIs(a >= ab, False) + + def test_add(self): + a = array.array(self.typecode, self.example) \ +@@ -304,7 +304,7 @@ + a = array.array(self.typecode, self.example[::-1]) + b = a + a += array.array(self.typecode, 2*self.example) +- self.assertTrue(a is b) ++ self.assertIs(a, b) + self.assertEqual( + a, + array.array(self.typecode, self.example[::-1]+2*self.example) +@@ -353,22 +353,22 @@ + b = a + + a *= 5 +- self.assertTrue(a is b) ++ self.assertIs(a, b) + self.assertEqual( + a, + array.array(self.typecode, 5*self.example) + ) + + a *= 0 +- self.assertTrue(a is b) ++ self.assertIs(a, b) + self.assertEqual(a, array.array(self.typecode)) + + a *= 1000 +- self.assertTrue(a is b) ++ self.assertIs(a, b) + self.assertEqual(a, array.array(self.typecode)) + + a *= -1 +- self.assertTrue(a is b) ++ self.assertIs(a, b) + self.assertEqual(a, array.array(self.typecode)) + + a = array.array(self.typecode, self.example) +@@ -753,7 +753,7 @@ + try: + import gc + except ImportError: +- return ++ self.skipTest('gc module not available') + a = array.array(self.typecode) + l = [iter(a)] + l.append(l) +@@ -772,15 +772,15 @@ + s = None + self.assertRaises(ReferenceError, len, p) + ++ @unittest.skipUnless(hasattr(sys, 'getrefcount'), ++ 'test needs sys.getrefcount()') + def test_bug_782369(self): +- import sys +- if hasattr(sys, "getrefcount"): +- for i in range(10): +- b = array.array('B', range(64)) +- rc = sys.getrefcount(10) +- for i in range(10): +- b = array.array('B', range(64)) +- self.assertEqual(rc, sys.getrefcount(10)) ++ for i in range(10): ++ b = array.array('B', range(64)) ++ rc = sys.getrefcount(10) ++ for i in range(10): ++ 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 +diff -r 3a1db0d2747e Lib/test/test_binhex.py +--- a/Lib/test/test_binhex.py ++++ b/Lib/test/test_binhex.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for the binhex C module + + Uses the mechanism of the python binhex module +diff -r 3a1db0d2747e Lib/test/test_bsddb.py +--- a/Lib/test/test_bsddb.py ++++ b/Lib/test/test_bsddb.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for the bsddb C module by Roger E. Masse + Adapted to unittest format and expanded scope by Raymond Hettinger + """ +@@ -47,10 +46,7 @@ + self.assertIn('discovered', self.f.values()) + + def test_close_and_reopen(self): +- if self.fname is None: +- # if we're using an in-memory only db, we can't reopen it +- # so finish here. +- return ++ self.assertIsNotNone(self.fname) + self.f.close() + self.f = self.openmethod[0](self.fname, 'w') + for k, v in self.d.iteritems(): +@@ -309,8 +305,7 @@ + self.assertEqual(self.f[k], v) + + def test_keyordering(self): +- if self.openmethod[0] is not bsddb.btopen: +- return ++ self.assertIs(self.openmethod[0], bsddb.btopen) + keys = self.d.keys() + keys.sort() + self.assertEqual(self.f.first()[0], keys[0]) +@@ -327,19 +322,34 @@ + fname = None + openmethod = [bsddb.btopen] + ++ # if we're using an in-memory only db, we can't reopen it ++ test_close_and_reopen = None ++ + class TestBTree_InMemory_Truncate(TestBSDDB): + fname = None + openflag = 'n' + openmethod = [bsddb.btopen] + ++ # if we're using an in-memory only db, we can't reopen it ++ test_close_and_reopen = None ++ + class TestHashTable(TestBSDDB): + fname = test_support.TESTFN + openmethod = [bsddb.hashopen] + ++ # keyordering is specific to btopen method ++ test_keyordering = None ++ + class TestHashTable_InMemory(TestBSDDB): + fname = None + openmethod = [bsddb.hashopen] + ++ # if we're using an in-memory only db, we can't reopen it ++ test_close_and_reopen = None ++ ++ # keyordering is specific to btopen method ++ test_keyordering = None ++ + ## # (bsddb.rnopen,'Record Numbers'), 'put' for RECNO for bsddb 1.85 + ## # appears broken... at least on + ## # Solaris Intel - rmasse 1/97 +diff -r 3a1db0d2747e Lib/test/test_builtin.py +--- a/Lib/test/test_builtin.py ++++ b/Lib/test/test_builtin.py +@@ -447,59 +447,6 @@ + return 'a' + self.assertRaises(TypeError, eval, 'dir()', globals(), C()) + +- # Done outside of the method test_z to get the correct scope +- z = 0 +- f = open(TESTFN, 'w') +- f.write('z = z+1\n') +- f.write('z = z*2\n') +- f.close() +- with check_py3k_warnings(("execfile.. not supported in 3.x", +- DeprecationWarning)): +- execfile(TESTFN) +- +- def test_execfile(self): +- global numruns +- if numruns: +- return +- numruns += 1 +- +- globals = {'a': 1, 'b': 2} +- locals = {'b': 200, 'c': 300} +- +- self.assertEqual(self.__class__.z, 2) +- globals['z'] = 0 +- execfile(TESTFN, globals) +- self.assertEqual(globals['z'], 2) +- locals['z'] = 0 +- execfile(TESTFN, globals, locals) +- self.assertEqual(locals['z'], 2) +- +- class M: +- "Test mapping interface versus possible calls from execfile()." +- def __init__(self): +- self.z = 10 +- def __getitem__(self, key): +- if key == 'z': +- return self.z +- raise KeyError +- def __setitem__(self, key, value): +- if key == 'z': +- self.z = value +- return +- raise KeyError +- +- locals = M() +- locals['z'] = 0 +- execfile(TESTFN, globals, locals) +- self.assertEqual(locals['z'], 2) +- +- unlink(TESTFN) +- self.assertRaises(TypeError, execfile) +- self.assertRaises(TypeError, execfile, TESTFN, {}, ()) +- import os +- self.assertRaises(IOError, execfile, os.curdir) +- self.assertRaises(IOError, execfile, "I_dont_exist") +- + def test_filter(self): + self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld') + self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9]) +@@ -1646,6 +1593,56 @@ + self.assertRaises(ValueError, x.translate, "1", 1) + self.assertRaises(TypeError, x.translate, "1"*256, 1) + ++class TestExecFile(unittest.TestCase): ++ # Done outside of the method test_z to get the correct scope ++ z = 0 ++ f = open(TESTFN, 'w') ++ f.write('z = z+1\n') ++ f.write('z = z*2\n') ++ f.close() ++ with check_py3k_warnings(("execfile.. not supported in 3.x", ++ DeprecationWarning)): ++ execfile(TESTFN) ++ ++ def test_execfile(self): ++ globals = {'a': 1, 'b': 2} ++ locals = {'b': 200, 'c': 300} ++ ++ self.assertEqual(self.__class__.z, 2) ++ globals['z'] = 0 ++ execfile(TESTFN, globals) ++ self.assertEqual(globals['z'], 2) ++ locals['z'] = 0 ++ execfile(TESTFN, globals, locals) ++ self.assertEqual(locals['z'], 2) ++ ++ class M: ++ "Test mapping interface versus possible calls from execfile()." ++ def __init__(self): ++ self.z = 10 ++ def __getitem__(self, key): ++ if key == 'z': ++ return self.z ++ raise KeyError ++ def __setitem__(self, key, value): ++ if key == 'z': ++ self.z = value ++ return ++ raise KeyError ++ ++ locals = M() ++ locals['z'] = 0 ++ execfile(TESTFN, globals, locals) ++ self.assertEqual(locals['z'], 2) ++ ++ unlink(TESTFN) ++ self.assertRaises(TypeError, execfile) ++ self.assertRaises(TypeError, execfile, TESTFN, {}, ()) ++ import os ++ self.assertRaises(IOError, execfile, os.curdir) ++ self.assertRaises(IOError, execfile, "I_dont_exist") ++ ++ + class TestSorted(unittest.TestCase): + + def test_basic(self): +@@ -1693,6 +1690,12 @@ + run_unittest(*args) + + def test_main(verbose=None): ++ global numruns ++ if not numruns: ++ with check_py3k_warnings( ++ (".+ not supported in 3.x", DeprecationWarning)): ++ run_unittest(TestExecFile) ++ numruns += 1 + test_classes = (BuiltinTest, TestSorted) + + _run_unittest(*test_classes) +diff -r 3a1db0d2747e Lib/test/test_bz2.py +--- a/Lib/test/test_bz2.py ++++ b/Lib/test/test_bz2.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + from test import test_support + from test.test_support import TESTFN, _4G, bigmemtest, import_module, findfile + +@@ -325,6 +324,21 @@ + self.assertRaises(ValueError, f.readline) + self.assertRaises(ValueError, f.readlines) + ++ @unittest.skipIf(sys.platform == 'win32', ++ 'test depends on being able to delete a still-open file,' ++ ' which is not possible on Windows') ++ def testInitNonExistentFile(self): ++ # Issue #19878: Should not segfault when __init__ with non-existent ++ # file for the second time. ++ self.createTempFile() ++ # Test close(): ++ with BZ2File(self.filename, "wb") as f: ++ self.assertRaises(IOError, f.__init__, "non-existent-file") ++ # Test object deallocation without call to close(): ++ f = bz2.BZ2File(self.filename) ++ self.assertRaises(IOError, f.__init__, "non-existent-file") ++ del f ++ + class BZ2CompressorTest(BaseTest): + def testCompress(self): + # "Test BZ2Compressor.compress()/flush()" +diff -r 3a1db0d2747e Lib/test/test_capi.py +--- a/Lib/test/test_capi.py ++++ b/Lib/test/test_capi.py +@@ -13,7 +13,9 @@ + except ImportError: + thread = None + threading = None +-import _testcapi ++# Skip this test if the _testcapi module isn't available. ++_testcapi = test_support.import_module('_testcapi') ++ + + @unittest.skipUnless(threading, 'Threading required for this test.') + class TestPendingCalls(unittest.TestCase): +diff -r 3a1db0d2747e Lib/test/test_cd.py +--- a/Lib/test/test_cd.py ++++ b/Lib/test/test_cd.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Whimpy test script for the cd module + Roger E. Masse + """ +diff -r 3a1db0d2747e Lib/test/test_cfgparser.py +--- a/Lib/test/test_cfgparser.py ++++ b/Lib/test/test_cfgparser.py +@@ -284,13 +284,17 @@ + cf.set("sect", "option1", mystr("splat")) + cf.set("sect", "option2", "splat") + cf.set("sect", "option2", mystr("splat")) ++ ++ def test_set_unicode(self): + try: + unicode + except NameError: +- pass +- else: +- cf.set("sect", "option1", unicode("splat")) +- cf.set("sect", "option2", unicode("splat")) ++ self.skipTest('no unicode support') ++ ++ cf = self.fromstring("[sect]\n" ++ "option1=foo\n") ++ cf.set("sect", "option1", unicode("splat")) ++ cf.set("sect", "option2", unicode("splat")) + + def test_read_returns_file_list(self): + file1 = test_support.findfile("cfgparser.1") +diff -r 3a1db0d2747e Lib/test/test_cgi.py +--- a/Lib/test/test_cgi.py ++++ b/Lib/test/test_cgi.py +@@ -5,6 +5,8 @@ + import tempfile + import unittest + ++from collections import namedtuple ++ + class HackedSysModule: + # The regression test will have real values in sys.argv, which + # will completely confuse the test of the cgi module +@@ -230,7 +232,15 @@ + # if we're not chunking properly, readline is only called twice + # (by read_binary); if we are chunking properly, it will be called 5 times + # as long as the chunksize is 1 << 16. +- self.assertTrue(f.numcalls > 2) ++ self.assertGreater(f.numcalls, 2) ++ ++ def test_fieldstorage_invalid(self): ++ fs = cgi.FieldStorage() ++ self.assertFalse(fs) ++ self.assertRaises(TypeError, bool(fs)) ++ self.assertEqual(list(fs), list(fs.keys())) ++ fs.list.append(namedtuple('MockFieldStorage', 'name')('fieldvalue')) ++ self.assertTrue(fs) + + def test_fieldstorage_multipart(self): + #Test basic FieldStorage multipart parsing +diff -r 3a1db0d2747e Lib/test/test_cl.py +--- a/Lib/test/test_cl.py ++++ b/Lib/test/test_cl.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Whimpy test script for the cl module + Roger E. Masse + """ +diff -r 3a1db0d2747e Lib/test/test_cmath.py +--- a/Lib/test/test_cmath.py ++++ b/Lib/test/test_cmath.py +@@ -282,7 +282,7 @@ + + def test_specific_values(self): + if not float.__getformat__("double").startswith("IEEE"): +- return ++ self.skipTest('needs IEEE double') + + def rect_complex(z): + """Wrapped version of rect that accepts a complex number instead of +diff -r 3a1db0d2747e Lib/test/test_cmd.py +--- a/Lib/test/test_cmd.py ++++ b/Lib/test/test_cmd.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + """ + Test script for the 'cmd' module + Original by Michael Schneider +diff -r 3a1db0d2747e Lib/test/test_code.py +--- a/Lib/test/test_code.py ++++ b/Lib/test/test_code.py +@@ -82,7 +82,7 @@ + + import unittest + import weakref +-import _testcapi ++from test.test_support import run_doctest, run_unittest, cpython_only + + + def consts(t): +@@ -104,7 +104,9 @@ + + class CodeTest(unittest.TestCase): + ++ @cpython_only + def test_newempty(self): ++ import _testcapi + co = _testcapi.code_newempty("filename", "funcname", 15) + self.assertEqual(co.co_filename, "filename") + self.assertEqual(co.co_name, "funcname") +@@ -137,7 +139,6 @@ + + + def test_main(verbose=None): +- from test.test_support import run_doctest, run_unittest + from test import test_code + run_doctest(test_code, verbose) + run_unittest(CodeTest, CodeWeakRefTest) +diff -r 3a1db0d2747e Lib/test/test_codecencodings_cn.py +--- a/Lib/test/test_codecencodings_cn.py ++++ b/Lib/test/test_codecencodings_cn.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecencodings_cn.py + # Codec encoding tests for PRC encodings. +diff -r 3a1db0d2747e Lib/test/test_codecencodings_hk.py +--- a/Lib/test/test_codecencodings_hk.py ++++ b/Lib/test/test_codecencodings_hk.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecencodings_hk.py + # Codec encoding tests for HongKong encodings. +diff -r 3a1db0d2747e Lib/test/test_codecencodings_iso2022.py +--- a/Lib/test/test_codecencodings_iso2022.py ++++ b/Lib/test/test_codecencodings_iso2022.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +-# + # Codec encoding tests for ISO 2022 encodings. + + from test import test_support +@@ -36,6 +34,7 @@ + + # iso2022_kr.txt cannot be used to test "chunk coding": the escape + # sequence is only written on the first line ++ @unittest.skip('iso2022_kr.txt cannot be used to test "chunk coding"') + def test_chunkcoding(self): + pass + +diff -r 3a1db0d2747e Lib/test/test_codecencodings_jp.py +--- a/Lib/test/test_codecencodings_jp.py ++++ b/Lib/test/test_codecencodings_jp.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecencodings_jp.py + # Codec encoding tests for Japanese encodings. +diff -r 3a1db0d2747e Lib/test/test_codecencodings_kr.py +--- a/Lib/test/test_codecencodings_kr.py ++++ b/Lib/test/test_codecencodings_kr.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecencodings_kr.py + # Codec encoding tests for ROK encodings. +diff -r 3a1db0d2747e Lib/test/test_codecencodings_tw.py +--- a/Lib/test/test_codecencodings_tw.py ++++ b/Lib/test/test_codecencodings_tw.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecencodings_tw.py + # Codec encoding tests for ROC encodings. +diff -r 3a1db0d2747e Lib/test/test_codecmaps_cn.py +--- a/Lib/test/test_codecmaps_cn.py ++++ b/Lib/test/test_codecmaps_cn.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecmaps_cn.py + # Codec mapping tests for PRC encodings +diff -r 3a1db0d2747e Lib/test/test_codecmaps_hk.py +--- a/Lib/test/test_codecmaps_hk.py ++++ b/Lib/test/test_codecmaps_hk.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecmaps_hk.py + # Codec mapping tests for HongKong encodings +diff -r 3a1db0d2747e Lib/test/test_codecmaps_jp.py +--- a/Lib/test/test_codecmaps_jp.py ++++ b/Lib/test/test_codecmaps_jp.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecmaps_jp.py + # Codec mapping tests for Japanese encodings +diff -r 3a1db0d2747e Lib/test/test_codecmaps_kr.py +--- a/Lib/test/test_codecmaps_kr.py ++++ b/Lib/test/test_codecmaps_kr.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecmaps_kr.py + # Codec mapping tests for ROK encodings +diff -r 3a1db0d2747e Lib/test/test_codecmaps_tw.py +--- a/Lib/test/test_codecmaps_tw.py ++++ b/Lib/test/test_codecmaps_tw.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # + # test_codecmaps_tw.py + # Codec mapping tests for ROC encodings +diff -r 3a1db0d2747e Lib/test/test_codecs.py +--- a/Lib/test/test_codecs.py ++++ b/Lib/test/test_codecs.py +@@ -2,7 +2,7 @@ + import unittest + import codecs + import locale +-import sys, StringIO, _testcapi ++import sys, StringIO + + def coding_checker(self, coder): + def check(input, expect): +@@ -97,19 +97,20 @@ + self.assertEqual(readalllines(s, True, 10), sexpected) + self.assertEqual(readalllines(s, False, 10), sexpectednoends) + ++ lineends = ("\n", "\r\n", "\r", u"\u2028") + # Test long lines (multiple calls to read() in readline()) + vw = [] + vwo = [] +- for (i, lineend) in enumerate(u"\n \r\n \r \u2028".split()): +- vw.append((i*200)*u"\3042" + lineend) +- vwo.append((i*200)*u"\3042") +- self.assertEqual(readalllines("".join(vw), True), "".join(vw)) +- self.assertEqual(readalllines("".join(vw), False),"".join(vwo)) ++ for (i, lineend) in enumerate(lineends): ++ vw.append((i*200+200)*u"\u3042" + lineend) ++ vwo.append((i*200+200)*u"\u3042") ++ self.assertEqual(readalllines("".join(vw), True), "|".join(vw)) ++ self.assertEqual(readalllines("".join(vw), False), "|".join(vwo)) + + # Test lines where the first read might end with \r, so the + # reader has to look ahead whether this is a lone \r or a \r\n + for size in xrange(80): +- for lineend in u"\n \r\n \r \u2028".split(): ++ for lineend in lineends: + s = 10*(size*u"a" + lineend + u"xxx\n") + reader = getreader(s) + for i in xrange(10): +@@ -117,12 +118,54 @@ + reader.readline(keepends=True), + size*u"a" + lineend, + ) ++ self.assertEqual( ++ reader.readline(keepends=True), ++ "xxx\n", ++ ) + reader = getreader(s) + for i in xrange(10): + self.assertEqual( + reader.readline(keepends=False), + size*u"a", + ) ++ self.assertEqual( ++ reader.readline(keepends=False), ++ "xxx", ++ ) ++ ++ def test_mixed_readline_and_read(self): ++ lines = ["Humpty Dumpty sat on a wall,\n", ++ "Humpty Dumpty had a great fall.\r\n", ++ "All the king's horses and all the king's men\r", ++ "Couldn't put Humpty together again."] ++ data = ''.join(lines) ++ def getreader(): ++ stream = StringIO.StringIO(data.encode(self.encoding)) ++ return codecs.getreader(self.encoding)(stream) ++ ++ # Issue #8260: Test readline() followed by read() ++ f = getreader() ++ self.assertEqual(f.readline(), lines[0]) ++ self.assertEqual(f.read(), ''.join(lines[1:])) ++ self.assertEqual(f.read(), '') ++ ++ # Issue #16636: Test readline() followed by readlines() ++ f = getreader() ++ self.assertEqual(f.readline(), lines[0]) ++ self.assertEqual(f.readlines(), lines[1:]) ++ self.assertEqual(f.read(), '') ++ ++ # Test read() followed by read() ++ f = getreader() ++ self.assertEqual(f.read(size=40, chars=5), data[:5]) ++ self.assertEqual(f.read(), data[5:]) ++ self.assertEqual(f.read(), '') ++ ++ # Issue #12446: Test read() followed by readlines() ++ f = getreader() ++ self.assertEqual(f.read(size=40, chars=5), data[:5]) ++ self.assertEqual(f.readlines(), [lines[0][5:]] + lines[1:]) ++ self.assertEqual(f.read(), '') + + def test_bug1175396(self): + s = [ +@@ -1496,7 +1539,7 @@ + + class BasicUnicodeTest(unittest.TestCase): + def test_basics(self): +- s = u"abc123" # all codecs should be able to encode these ++ s = u"abc123" # all codecs should be able to encode these + for encoding in all_unicode_encodings: + name = codecs.lookup(encoding).name + if encoding.endswith("_codec"): +@@ -1505,9 +1548,9 @@ + name = "latin_1" + self.assertEqual(encoding.replace("_", "-"), name.replace("_", "-")) + (bytes, size) = codecs.getencoder(encoding)(s) +- self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding)) ++ self.assertEqual(size, len(s), "encoding=%r" % encoding) + (chars, size) = codecs.getdecoder(encoding)(bytes) +- self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding)) ++ self.assertEqual(chars, s, "encoding=%r" % encoding) + + if encoding not in broken_unicode_with_streams: + # check stream reader/writer +@@ -1523,15 +1566,13 @@ + for c in encodedresult: + q.write(c) + decodedresult += reader.read() +- self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) ++ self.assertEqual(decodedresult, s, "encoding=%r" % encoding) + + if encoding not in broken_incremental_coders: +- # check incremental decoder/encoder (fetched via the Python +- # and C API) and iterencode()/iterdecode() ++ # check incremental decoder/encoder and iterencode()/iterdecode() + try: + encoder = codecs.getincrementalencoder(encoding)() +- cencoder = _testcapi.codec_incrementalencoder(encoding) +- except LookupError: # no IncrementalEncoder ++ except LookupError: # no IncrementalEncoder + pass + else: + # check incremental decoder/encoder +@@ -1544,45 +1585,71 @@ + for c in encodedresult: + decodedresult += decoder.decode(c) + decodedresult += decoder.decode("", True) +- self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) +- +- # check C API +- encodedresult = "" +- for c in s: +- encodedresult += cencoder.encode(c) +- encodedresult += cencoder.encode(u"", True) +- cdecoder = _testcapi.codec_incrementaldecoder(encoding) +- decodedresult = u"" +- for c in encodedresult: +- decodedresult += cdecoder.decode(c) +- decodedresult += cdecoder.decode("", True) +- self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) ++ self.assertEqual(decodedresult, s, ++ "encoding=%r" % encoding) + + # check iterencode()/iterdecode() +- result = u"".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding)) +- self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding)) ++ result = u"".join(codecs.iterdecode( ++ codecs.iterencode(s, encoding), encoding)) ++ self.assertEqual(result, s, "encoding=%r" % encoding) + + # check iterencode()/iterdecode() with empty string +- result = u"".join(codecs.iterdecode(codecs.iterencode(u"", encoding), encoding)) ++ result = u"".join(codecs.iterdecode( ++ codecs.iterencode(u"", encoding), encoding)) + self.assertEqual(result, u"") + + if encoding not in only_strict_mode: + # check incremental decoder/encoder with errors argument + try: + encoder = codecs.getincrementalencoder(encoding)("ignore") +- cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore") +- except LookupError: # no IncrementalEncoder ++ except LookupError: # no IncrementalEncoder + pass + else: + encodedresult = "".join(encoder.encode(c) for c in s) + decoder = codecs.getincrementaldecoder(encoding)("ignore") +- decodedresult = u"".join(decoder.decode(c) for c in encodedresult) +- self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) ++ decodedresult = u"".join(decoder.decode(c) ++ for c in encodedresult) ++ self.assertEqual(decodedresult, s, ++ "encoding=%r" % encoding) + ++ @test_support.cpython_only ++ def test_basics_capi(self): ++ from _testcapi import codec_incrementalencoder, codec_incrementaldecoder ++ s = u"abc123" # all codecs should be able to encode these ++ for encoding in all_unicode_encodings: ++ if encoding not in broken_incremental_coders: ++ # check incremental decoder/encoder and iterencode()/iterdecode() ++ try: ++ cencoder = codec_incrementalencoder(encoding) ++ except LookupError: # no IncrementalEncoder ++ pass ++ else: ++ # check C API ++ encodedresult = "" ++ for c in s: ++ encodedresult += cencoder.encode(c) ++ encodedresult += cencoder.encode(u"", True) ++ cdecoder = codec_incrementaldecoder(encoding) ++ decodedresult = u"" ++ for c in encodedresult: ++ decodedresult += cdecoder.decode(c) ++ decodedresult += cdecoder.decode("", True) ++ self.assertEqual(decodedresult, s, ++ "encoding=%r" % encoding) ++ ++ if encoding not in only_strict_mode: ++ # check incremental decoder/encoder with errors argument ++ try: ++ cencoder = codec_incrementalencoder(encoding, "ignore") ++ except LookupError: # no IncrementalEncoder ++ pass ++ else: + encodedresult = "".join(cencoder.encode(c) for c in s) +- cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore") +- decodedresult = u"".join(cdecoder.decode(c) for c in encodedresult) +- self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) ++ cdecoder = codec_incrementaldecoder(encoding, "ignore") ++ decodedresult = u"".join(cdecoder.decode(c) ++ for c in encodedresult) ++ self.assertEqual(decodedresult, s, ++ "encoding=%r" % encoding) + + def test_seek(self): + # all codecs should be able to encode these +diff -r 3a1db0d2747e Lib/test/test_collections.py +--- a/Lib/test/test_collections.py ++++ b/Lib/test/test_collections.py +@@ -594,6 +594,35 @@ + s |= s + self.assertEqual(s, full) + ++ def test_issue16373(self): ++ # Recursion error comparing comparable and noncomparable ++ # Set instances ++ class MyComparableSet(Set): ++ def __contains__(self, x): ++ return False ++ def __len__(self): ++ return 0 ++ def __iter__(self): ++ return iter([]) ++ class MyNonComparableSet(Set): ++ def __contains__(self, x): ++ return False ++ def __len__(self): ++ return 0 ++ def __iter__(self): ++ return iter([]) ++ def __le__(self, x): ++ return NotImplemented ++ def __lt__(self, x): ++ return NotImplemented ++ ++ cs = MyComparableSet() ++ ncs = MyNonComparableSet() ++ self.assertFalse(ncs < cs) ++ self.assertFalse(ncs <= cs) ++ self.assertFalse(cs > ncs) ++ self.assertFalse(cs >= ncs) ++ + def test_Mapping(self): + for sample in [dict]: + self.assertIsInstance(sample(), Mapping) +diff -r 3a1db0d2747e Lib/test/test_compileall.py +--- a/Lib/test/test_compileall.py ++++ b/Lib/test/test_compileall.py +@@ -31,11 +31,10 @@ + compare = struct.pack('<4sl', imp.get_magic(), mtime) + return data, compare + ++ @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') + def recreation_check(self, metadata): + """Check that compileall recreates bytecode when the new metadata is + used.""" +- if not hasattr(os, 'stat'): +- return + py_compile.compile(self.source_path) + self.assertEqual(*self.data()) + with open(self.bc_path, 'rb') as file: +diff -r 3a1db0d2747e Lib/test/test_cookielib.py +--- a/Lib/test/test_cookielib.py ++++ b/Lib/test/test_cookielib.py +@@ -26,8 +26,9 @@ + az = time2isoz() + bz = time2isoz(500000) + for text in (az, bz): +- self.assertTrue(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text), +- "bad time2isoz format: %s %s" % (az, bz)) ++ self.assertRegexpMatches(text, ++ r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", ++ "bad time2isoz format: %s %s" % (az, bz)) + + def test_http2time(self): + from cookielib import http2time +@@ -75,12 +76,9 @@ + "%s => '%s' (%s)" % (test_t, result, expected)) + + for s in tests: +- t = http2time(s) +- t2 = http2time(s.lower()) +- t3 = http2time(s.upper()) +- +- self.assertTrue(t == t2 == t3 == test_t, +- "'%s' => %s, %s, %s (%s)" % (s, t, t2, t3, test_t)) ++ self.assertEqual(http2time(s), test_t, s) ++ self.assertEqual(http2time(s.lower()), test_t, s.lower()) ++ self.assertEqual(http2time(s.upper()), test_t, s.upper()) + + def test_http2time_garbage(self): + from cookielib import http2time +@@ -367,7 +365,7 @@ + request = urllib2.Request(url) + r = pol.domain_return_ok(domain, request) + if ok: self.assertTrue(r) +- else: self.assertTrue(not r) ++ else: self.assertFalse(r) + + def test_missing_value(self): + from cookielib import MozillaCookieJar, lwp_cookie_str +@@ -379,10 +377,10 @@ + interact_netscape(c, "http://www.acme.com/", 'eggs') + interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/') + cookie = c._cookies["www.acme.com"]["/"]["eggs"] +- self.assertTrue(cookie.value is None) ++ self.assertIsNone(cookie.value) + self.assertEqual(cookie.name, "eggs") + cookie = c._cookies["www.acme.com"]['/foo/']['"spam"'] +- self.assertTrue(cookie.value is None) ++ self.assertIsNone(cookie.value) + self.assertEqual(cookie.name, '"spam"') + self.assertEqual(lwp_cookie_str(cookie), ( + r'"spam"; path="/foo/"; domain="www.acme.com"; ' +@@ -426,7 +424,7 @@ + try: + cookie = c._cookies["www.example.com"]["/"]["ni"] + except KeyError: +- self.assertTrue(version is None) # didn't expect a stored cookie ++ self.assertIsNone(version) # didn't expect a stored cookie + else: + self.assertEqual(cookie.version, version) + # 2965 cookies are unaffected +@@ -452,26 +450,26 @@ + self.assertEqual(cookie.domain, ".acme.com") + self.assertTrue(cookie.domain_specified) + self.assertEqual(cookie.port, DEFAULT_HTTP_PORT) +- self.assertTrue(not cookie.port_specified) ++ self.assertFalse(cookie.port_specified) + # case is preserved +- self.assertTrue(cookie.has_nonstandard_attr("blArgh") and +- not cookie.has_nonstandard_attr("blargh")) ++ self.assertTrue(cookie.has_nonstandard_attr("blArgh")) ++ self.assertFalse(cookie.has_nonstandard_attr("blargh")) + + cookie = c._cookies["www.acme.com"]["/"]["ni"] + self.assertEqual(cookie.domain, "www.acme.com") +- self.assertTrue(not cookie.domain_specified) ++ self.assertFalse(cookie.domain_specified) + self.assertEqual(cookie.port, "80,8080") + self.assertTrue(cookie.port_specified) + + cookie = c._cookies["www.acme.com"]["/"]["nini"] +- self.assertTrue(cookie.port is None) +- self.assertTrue(not cookie.port_specified) ++ self.assertIsNone(cookie.port) ++ self.assertFalse(cookie.port_specified) + + # invalid expires should not cause cookie to be dropped + foo = c._cookies["www.acme.com"]["/"]["foo"] + spam = c._cookies["www.acme.com"]["/"]["foo"] +- self.assertTrue(foo.expires is None) +- self.assertTrue(spam.expires is None) ++ self.assertIsNone(foo.expires) ++ self.assertIsNone(spam.expires) + + def test_ns_parser_special_names(self): + # names such as 'expires' are not special in first name=value pair +@@ -655,12 +653,12 @@ + from cookielib import is_HDN + self.assertTrue(is_HDN("foo.bar.com")) + self.assertTrue(is_HDN("1foo2.3bar4.5com")) +- self.assertTrue(not is_HDN("192.168.1.1")) +- self.assertTrue(not is_HDN("")) +- self.assertTrue(not is_HDN(".")) +- self.assertTrue(not is_HDN(".foo.bar.com")) +- self.assertTrue(not is_HDN("..foo")) +- self.assertTrue(not is_HDN("foo.")) ++ self.assertFalse(is_HDN("192.168.1.1")) ++ self.assertFalse(is_HDN("")) ++ self.assertFalse(is_HDN(".")) ++ self.assertFalse(is_HDN(".foo.bar.com")) ++ self.assertFalse(is_HDN("..foo")) ++ self.assertFalse(is_HDN("foo.")) + + def test_reach(self): + from cookielib import reach +@@ -676,39 +674,39 @@ + def test_domain_match(self): + from cookielib import domain_match, user_domain_match + self.assertTrue(domain_match("192.168.1.1", "192.168.1.1")) +- self.assertTrue(not domain_match("192.168.1.1", ".168.1.1")) ++ self.assertFalse(domain_match("192.168.1.1", ".168.1.1")) + self.assertTrue(domain_match("x.y.com", "x.Y.com")) + self.assertTrue(domain_match("x.y.com", ".Y.com")) +- self.assertTrue(not domain_match("x.y.com", "Y.com")) ++ self.assertFalse(domain_match("x.y.com", "Y.com")) + self.assertTrue(domain_match("a.b.c.com", ".c.com")) +- self.assertTrue(not domain_match(".c.com", "a.b.c.com")) ++ self.assertFalse(domain_match(".c.com", "a.b.c.com")) + self.assertTrue(domain_match("example.local", ".local")) +- self.assertTrue(not domain_match("blah.blah", "")) +- self.assertTrue(not domain_match("", ".rhubarb.rhubarb")) ++ self.assertFalse(domain_match("blah.blah", "")) ++ self.assertFalse(domain_match("", ".rhubarb.rhubarb")) + self.assertTrue(domain_match("", "")) + + self.assertTrue(user_domain_match("acme.com", "acme.com")) +- self.assertTrue(not user_domain_match("acme.com", ".acme.com")) ++ self.assertFalse(user_domain_match("acme.com", ".acme.com")) + self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com")) + self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com")) + self.assertTrue(user_domain_match("x.y.com", "x.Y.com")) + self.assertTrue(user_domain_match("x.y.com", ".Y.com")) +- self.assertTrue(not user_domain_match("x.y.com", "Y.com")) ++ self.assertFalse(user_domain_match("x.y.com", "Y.com")) + self.assertTrue(user_domain_match("y.com", "Y.com")) +- self.assertTrue(not user_domain_match(".y.com", "Y.com")) ++ self.assertFalse(user_domain_match(".y.com", "Y.com")) + self.assertTrue(user_domain_match(".y.com", ".Y.com")) + self.assertTrue(user_domain_match("x.y.com", ".com")) +- self.assertTrue(not user_domain_match("x.y.com", "com")) +- self.assertTrue(not user_domain_match("x.y.com", "m")) +- self.assertTrue(not user_domain_match("x.y.com", ".m")) +- self.assertTrue(not user_domain_match("x.y.com", "")) +- self.assertTrue(not user_domain_match("x.y.com", ".")) ++ self.assertFalse(user_domain_match("x.y.com", "com")) ++ self.assertFalse(user_domain_match("x.y.com", "m")) ++ self.assertFalse(user_domain_match("x.y.com", ".m")) ++ self.assertFalse(user_domain_match("x.y.com", "")) ++ self.assertFalse(user_domain_match("x.y.com", ".")) + self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1")) + # not both HDNs, so must string-compare equal to match +- self.assertTrue(not user_domain_match("192.168.1.1", ".168.1.1")) +- self.assertTrue(not user_domain_match("192.168.1.1", ".")) ++ self.assertFalse(user_domain_match("192.168.1.1", ".168.1.1")) ++ self.assertFalse(user_domain_match("192.168.1.1", ".")) + # empty string is a special case +- self.assertTrue(not user_domain_match("192.168.1.1", "")) ++ self.assertFalse(user_domain_match("192.168.1.1", "")) + + def test_wrong_domain(self): + # Cookies whose effective request-host name does not domain-match the +@@ -865,7 +863,7 @@ + self.assertEqual(len(c), 2) + # ... and check is doesn't get returned + c.add_cookie_header(req) +- self.assertTrue(not req.has_header("Cookie")) ++ self.assertFalse(req.has_header("Cookie")) + + def test_domain_block(self): + from cookielib import CookieJar, DefaultCookiePolicy +@@ -892,8 +890,8 @@ + self.assertEqual(len(c), 1) + req = Request("http://www.roadrunner.net/") + c.add_cookie_header(req) +- self.assertTrue((req.has_header("Cookie") and +- req.has_header("Cookie2"))) ++ self.assertTrue(req.has_header("Cookie")) ++ self.assertTrue(req.has_header("Cookie2")) + + c.clear() + pol.set_blocked_domains([".acme.com"]) +@@ -908,7 +906,7 @@ + self.assertEqual(len(c), 2) + # ... and check is doesn't get returned + c.add_cookie_header(req) +- self.assertTrue(not req.has_header("Cookie")) ++ self.assertFalse(req.has_header("Cookie")) + + def test_secure(self): + from cookielib import CookieJar, DefaultCookiePolicy +@@ -928,8 +926,8 @@ + url = "http://www.acme.com/" + int(c, url, "foo1=bar%s%s" % (vs, whitespace)) + int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace)) +- self.assertTrue( +- not c._cookies["www.acme.com"]["/"]["foo1"].secure, ++ self.assertFalse( ++ c._cookies["www.acme.com"]["/"]["foo1"].secure, + "non-secure cookie registered secure") + self.assertTrue( + c._cookies["www.acme.com"]["/"]["foo2"].secure, +@@ -1011,8 +1009,8 @@ + url = "http://foo.bar.com/" + interact_2965(c, url, "spam=eggs; Version=1; Port") + h = interact_2965(c, url) +- self.assertTrue(re.search("\$Port([^=]|$)", h), +- "port with no value not returned with no value") ++ self.assertRegexpMatches(h, "\$Port([^=]|$)", ++ "port with no value not returned with no value") + + c = CookieJar(pol) + url = "http://foo.bar.com/" +@@ -1038,8 +1036,7 @@ + 'Comment="does anybody read these?"; ' + 'CommentURL="http://foo.bar.net/comment.html"') + h = interact_2965(c, url) +- self.assertTrue( +- "Comment" not in h, ++ self.assertNotIn("Comment", h, + "Comment or CommentURL cookie-attributes returned to server") + + def test_Cookie_iterator(self): +@@ -1128,7 +1125,7 @@ + headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"] + c = cookiejar_from_cookie_headers(headers) + cookie = c._cookies["www.example.com"]["/"]["c"] +- self.assertTrue(cookie.expires is None) ++ self.assertIsNone(cookie.expires) + + + class LWPCookieTests(TestCase): +@@ -1278,9 +1275,9 @@ + req = Request("http://www.acme.com/ammo") + c.add_cookie_header(req) + +- self.assertTrue(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*" +- "PART_NUMBER=ROCKET_LAUNCHER_0001", +- req.get_header("Cookie"))) ++ self.assertRegexpMatches(req.get_header("Cookie"), ++ r"PART_NUMBER=RIDING_ROCKET_0023;\s*" ++ "PART_NUMBER=ROCKET_LAUNCHER_0001") + + def test_ietf_example_1(self): + from cookielib import CookieJar, DefaultCookiePolicy +@@ -1314,7 +1311,7 @@ + cookie = interact_2965( + c, 'http://www.acme.com/acme/login', + 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"') +- self.assertTrue(not cookie) ++ self.assertFalse(cookie) + + # + # 3. User Agent -> Server +@@ -1336,9 +1333,8 @@ + cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem', + 'Part_Number="Rocket_Launcher_0001"; ' + 'Version="1"; Path="/acme"'); +- self.assertTrue(re.search( +- r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$', +- cookie)) ++ self.assertRegexpMatches(cookie, ++ r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$') + + # + # 5. User Agent -> Server +@@ -1361,11 +1357,11 @@ + cookie = interact_2965(c, "http://www.acme.com/acme/shipping", + 'Shipping="FedEx"; Version="1"; Path="/acme"') + +- self.assertTrue(re.search(r'^\$Version="?1"?;', cookie)) +- self.assertTrue(re.search(r'Part_Number="?Rocket_Launcher_0001"?;' +- '\s*\$Path="\/acme"', cookie)) +- self.assertTrue(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"', +- cookie)) ++ self.assertRegexpMatches(cookie, r'^\$Version="?1"?;') ++ self.assertRegexpMatches(cookie, ++ r'Part_Number="?Rocket_Launcher_0001"?;\s*\$Path="\/acme"') ++ self.assertRegexpMatches(cookie, ++ r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"') + + # + # 7. User Agent -> Server +@@ -1386,9 +1382,9 @@ + # Transaction is complete. + + cookie = interact_2965(c, "http://www.acme.com/acme/process") +- self.assertTrue( +- re.search(r'Shipping="?FedEx"?;\s*\$Path="\/acme"', cookie) and +- "WILE_E_COYOTE" in cookie) ++ self.assertRegexpMatches(cookie, ++ r'Shipping="?FedEx"?;\s*\$Path="\/acme"') ++ self.assertIn("WILE_E_COYOTE", cookie) + + # + # The user agent makes a series of requests on the origin server, after +@@ -1437,8 +1433,8 @@ + # than once. + + cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...") +- self.assertTrue( +- re.search(r"Riding_Rocket_0023.*Rocket_Launcher_0001", cookie)) ++ self.assertRegexpMatches(cookie, ++ r"Riding_Rocket_0023.*Rocket_Launcher_0001") + + # A subsequent request by the user agent to the (same) server for a URL of + # the form /acme/parts/ would include the following request header: +@@ -1466,7 +1462,7 @@ + # illegal domain (no embedded dots) + cookie = interact_2965(c, "http://www.acme.com", + 'foo=bar; domain=".com"; version=1') +- self.assertTrue(not c) ++ self.assertFalse(c) + + # legal domain + cookie = interact_2965(c, "http://www.acme.com", +@@ -1559,11 +1555,12 @@ + c, "http://www.acme.com/foo%2f%25/<<%0anewå/æøå", + 'bar=baz; path="/foo/"; version=1'); + version_re = re.compile(r'^\$version=\"?1\"?', re.I) +- self.assertTrue("foo=bar" in cookie and version_re.search(cookie)) ++ self.assertIn("foo=bar", cookie) ++ self.assertRegexpMatches(cookie, version_re) + + cookie = interact_2965( + c, "http://www.acme.com/foo/%25/<<%0anewå/æøå") +- self.assertTrue(not cookie) ++ self.assertFalse(cookie) + + # unicode URL doesn't raise exception + cookie = interact_2965(c, u"http://www.acme.com/\xfc") +@@ -1740,13 +1737,12 @@ + key = "%s_after" % cookie.value + counter[key] = counter[key] + 1 + +- self.assertTrue(not ( +- # a permanent cookie got lost accidentally +- counter["perm_after"] != counter["perm_before"] or ++ # a permanent cookie got lost accidently ++ self.assertEqual(counter["perm_after"], counter["perm_before"]) + # a session cookie hasn't been cleared +- counter["session_after"] != 0 or ++ self.assertEqual(counter["session_after"], 0) + # we didn't have session cookies in the first place +- counter["session_before"] == 0)) ++ self.assertNotEqual(counter["session_before"], 0) + + + def test_main(verbose=None): +diff -r 3a1db0d2747e Lib/test/test_csv.py +--- a/Lib/test/test_csv.py ++++ b/Lib/test/test_csv.py +@@ -630,6 +630,23 @@ + fileobj = StringIO() + self.assertRaises(TypeError, csv.DictWriter, fileobj) + ++ def test_write_fields_not_in_fieldnames(self): ++ fd, name = tempfile.mkstemp() ++ fileobj = os.fdopen(fd, "w+b") ++ try: ++ writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"]) ++ # Of special note is the non-string key (issue 19449) ++ with self.assertRaises(ValueError) as cx: ++ writer.writerow({"f4": 10, "f2": "spam", 1: "abc"}) ++ exception = str(cx.exception) ++ self.assertIn("fieldnames", exception) ++ self.assertIn("'f4'", exception) ++ self.assertNotIn("'f2'", exception) ++ self.assertIn("1", exception) ++ finally: ++ fileobj.close() ++ os.unlink(name) ++ + def test_read_dict_fields(self): + fd, name = tempfile.mkstemp() + fileobj = os.fdopen(fd, "w+b") +@@ -853,6 +870,7 @@ + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() ++ self.assertEqual(d.quoting, csv.QUOTE_NONE) + + mydialect.quoting = None + self.assertRaises(csv.Error, mydialect) +@@ -861,12 +879,21 @@ + mydialect.quoting = csv.QUOTE_ALL + mydialect.quotechar = '"' + d = mydialect() ++ self.assertEqual(d.quoting, csv.QUOTE_ALL) ++ self.assertEqual(d.quotechar, '"') ++ self.assertTrue(d.doublequote) + + mydialect.quotechar = "''" +- self.assertRaises(csv.Error, mydialect) ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"quotechar" must be an 1-character string') + + mydialect.quotechar = 4 +- self.assertRaises(csv.Error, mydialect) ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"quotechar" must be string, not int') + + def test_delimiter(self): + class mydialect(csv.Dialect): +@@ -877,12 +904,31 @@ + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() ++ self.assertEqual(d.delimiter, ";") + + mydialect.delimiter = ":::" +- self.assertRaises(csv.Error, mydialect) ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"delimiter" must be an 1-character string') ++ ++ mydialect.delimiter = "" ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"delimiter" must be an 1-character string') ++ ++ mydialect.delimiter = u"," ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"delimiter" must be string, not unicode') + + mydialect.delimiter = 4 +- self.assertRaises(csv.Error, mydialect) ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"delimiter" must be string, not int') + + def test_lineterminator(self): + class mydialect(csv.Dialect): +@@ -893,12 +939,17 @@ + lineterminator = '\r\n' + quoting = csv.QUOTE_NONE + d = mydialect() ++ self.assertEqual(d.lineterminator, '\r\n') + + mydialect.lineterminator = ":::" + d = mydialect() ++ self.assertEqual(d.lineterminator, ":::") + + mydialect.lineterminator = 4 +- self.assertRaises(csv.Error, mydialect) ++ with self.assertRaises(csv.Error) as cm: ++ mydialect() ++ self.assertEqual(str(cm.exception), ++ '"lineterminator" must be a string') + + + class TestSniffer(unittest.TestCase): +@@ -1014,78 +1065,77 @@ + dialect = sniffer.sniff(self.sample9) + self.assertTrue(dialect.doublequote) + +-if not hasattr(sys, "gettotalrefcount"): +- if test_support.verbose: print "*** skipping leakage tests ***" +-else: +- class NUL: +- def write(s, *args): +- pass +- writelines = write ++class NUL: ++ def write(s, *args): ++ pass ++ writelines = write + +- class TestLeaks(unittest.TestCase): +- def test_create_read(self): +- delta = 0 +- lastrc = sys.gettotalrefcount() +- for i in xrange(20): +- gc.collect() +- self.assertEqual(gc.garbage, []) +- rc = sys.gettotalrefcount() +- csv.reader(["a,b,c\r\n"]) +- csv.reader(["a,b,c\r\n"]) +- csv.reader(["a,b,c\r\n"]) +- delta = rc-lastrc +- lastrc = rc +- # if csv.reader() leaks, last delta should be 3 or more +- self.assertEqual(delta < 3, True) ++@unittest.skipUnless(hasattr(sys, "gettotalrefcount"), ++ 'requires sys.gettotalrefcount()') ++class TestLeaks(unittest.TestCase): ++ def test_create_read(self): ++ delta = 0 ++ lastrc = sys.gettotalrefcount() ++ for i in xrange(20): ++ gc.collect() ++ self.assertEqual(gc.garbage, []) ++ rc = sys.gettotalrefcount() ++ csv.reader(["a,b,c\r\n"]) ++ csv.reader(["a,b,c\r\n"]) ++ csv.reader(["a,b,c\r\n"]) ++ delta = rc-lastrc ++ lastrc = rc ++ # if csv.reader() leaks, last delta should be 3 or more ++ self.assertEqual(delta < 3, True) + +- def test_create_write(self): +- delta = 0 +- lastrc = sys.gettotalrefcount() +- s = NUL() +- for i in xrange(20): +- gc.collect() +- self.assertEqual(gc.garbage, []) +- rc = sys.gettotalrefcount() +- csv.writer(s) +- csv.writer(s) +- csv.writer(s) +- delta = rc-lastrc +- lastrc = rc +- # if csv.writer() leaks, last delta should be 3 or more +- self.assertEqual(delta < 3, True) ++ def test_create_write(self): ++ delta = 0 ++ lastrc = sys.gettotalrefcount() ++ s = NUL() ++ for i in xrange(20): ++ gc.collect() ++ self.assertEqual(gc.garbage, []) ++ rc = sys.gettotalrefcount() ++ csv.writer(s) ++ csv.writer(s) ++ csv.writer(s) ++ delta = rc-lastrc ++ lastrc = rc ++ # if csv.writer() leaks, last delta should be 3 or more ++ self.assertEqual(delta < 3, True) + +- def test_read(self): +- delta = 0 +- rows = ["a,b,c\r\n"]*5 +- lastrc = sys.gettotalrefcount() +- for i in xrange(20): +- gc.collect() +- self.assertEqual(gc.garbage, []) +- rc = sys.gettotalrefcount() +- rdr = csv.reader(rows) +- for row in rdr: +- pass +- delta = rc-lastrc +- lastrc = rc +- # if reader leaks during read, delta should be 5 or more +- self.assertEqual(delta < 5, True) ++ def test_read(self): ++ delta = 0 ++ rows = ["a,b,c\r\n"]*5 ++ lastrc = sys.gettotalrefcount() ++ for i in xrange(20): ++ gc.collect() ++ self.assertEqual(gc.garbage, []) ++ rc = sys.gettotalrefcount() ++ rdr = csv.reader(rows) ++ for row in rdr: ++ pass ++ delta = rc-lastrc ++ lastrc = rc ++ # if reader leaks during read, delta should be 5 or more ++ self.assertEqual(delta < 5, True) + +- def test_write(self): +- delta = 0 +- rows = [[1,2,3]]*5 +- s = NUL() +- lastrc = sys.gettotalrefcount() +- for i in xrange(20): +- gc.collect() +- self.assertEqual(gc.garbage, []) +- rc = sys.gettotalrefcount() +- writer = csv.writer(s) +- for row in rows: +- writer.writerow(row) +- delta = rc-lastrc +- lastrc = rc +- # if writer leaks during write, last delta should be 5 or more +- self.assertEqual(delta < 5, True) ++ def test_write(self): ++ delta = 0 ++ rows = [[1,2,3]]*5 ++ s = NUL() ++ lastrc = sys.gettotalrefcount() ++ for i in xrange(20): ++ gc.collect() ++ self.assertEqual(gc.garbage, []) ++ rc = sys.gettotalrefcount() ++ writer = csv.writer(s) ++ for row in rows: ++ writer.writerow(row) ++ delta = rc-lastrc ++ lastrc = rc ++ # if writer leaks during write, last delta should be 5 or more ++ self.assertEqual(delta < 5, True) + + # commented out for now - csv module doesn't yet support Unicode + ## class TestUnicode(unittest.TestCase): +diff -r 3a1db0d2747e Lib/test/test_datetime.py +--- a/Lib/test/test_datetime.py ++++ b/Lib/test/test_datetime.py +@@ -101,11 +101,11 @@ + # carry no data), but they need to be picklable anyway else + # concrete subclasses can't be pickled. + orig = tzinfo.__new__(tzinfo) +- self.assertTrue(type(orig) is tzinfo) ++ self.assertIs(type(orig), tzinfo) + for pickler, unpickler, proto in pickle_choices: + green = pickler.dumps(orig, proto) + derived = unpickler.loads(green) +- self.assertTrue(type(derived) is tzinfo) ++ self.assertIs(type(derived), tzinfo) + + def test_pickling_subclass(self): + # Make sure we can pickle/unpickle an instance of a subclass. +@@ -328,9 +328,9 @@ + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) +- self.assertTrue(not t1 != t2) +- self.assertTrue(not t1 < t2) +- self.assertTrue(not t1 > t2) ++ self.assertFalse(t1 != t2) ++ self.assertFalse(t1 < t2) ++ self.assertFalse(t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + +@@ -342,12 +342,12 @@ + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) +- self.assertTrue(not t1 == t2) +- self.assertTrue(not t2 == t1) +- self.assertTrue(not t1 > t2) +- self.assertTrue(not t2 < t1) +- self.assertTrue(not t1 >= t2) +- self.assertTrue(not t2 <= t1) ++ self.assertFalse(t1 == t2) ++ self.assertFalse(t2 == t1) ++ self.assertFalse(t1 > t2) ++ self.assertFalse(t2 < t1) ++ self.assertFalse(t1 >= t2) ++ self.assertFalse(t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + +@@ -459,7 +459,7 @@ + self.assertTrue(timedelta(0, 1)) + self.assertTrue(timedelta(0, 0, 1)) + self.assertTrue(timedelta(microseconds=1)) +- self.assertTrue(not timedelta(0)) ++ self.assertFalse(timedelta(0)) + + def test_subclass_timedelta(self): + +@@ -475,17 +475,17 @@ + return round(sum) + + t1 = T(days=1) +- self.assertTrue(type(t1) is T) ++ self.assertIs(type(t1), T) + self.assertEqual(t1.as_hours(), 24) + + t2 = T(days=-1, seconds=-3600) +- self.assertTrue(type(t2) is T) ++ self.assertIs(type(t2), T) + self.assertEqual(t2.as_hours(), -25) + + t3 = t1 + t2 +- self.assertTrue(type(t3) is timedelta) ++ self.assertIs(type(t3), timedelta) + t4 = T.from_td(t3) +- self.assertTrue(type(t4) is T) ++ self.assertIs(type(t4), T) + self.assertEqual(t3.days, t4.days) + self.assertEqual(t3.seconds, t4.seconds) + self.assertEqual(t3.microseconds, t4.microseconds) +@@ -783,8 +783,9 @@ + + # It worked or it didn't. If it didn't, assume it's reason #2, and + # let the test pass if they're within half a second of each other. +- self.assertTrue(today == todayagain or +- abs(todayagain - today) < timedelta(seconds=0.5)) ++ if today != todayagain: ++ self.assertAlmostEqual(todayagain, today, ++ delta=timedelta(seconds=0.5)) + + def test_weekday(self): + for i in range(7): +@@ -974,9 +975,9 @@ + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) +- self.assertTrue(not t1 != t2) +- self.assertTrue(not t1 < t2) +- self.assertTrue(not t1 > t2) ++ self.assertFalse(t1 != t2) ++ self.assertFalse(t1 < t2) ++ self.assertFalse(t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + +@@ -988,12 +989,12 @@ + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) +- self.assertTrue(not t1 == t2) +- self.assertTrue(not t2 == t1) +- self.assertTrue(not t1 > t2) +- self.assertTrue(not t2 < t1) +- self.assertTrue(not t1 >= t2) +- self.assertTrue(not t2 <= t1) ++ self.assertFalse(t1 == t2) ++ self.assertFalse(t2 == t1) ++ self.assertFalse(t1 > t2) ++ self.assertFalse(t2 < t1) ++ self.assertFalse(t1 >= t2) ++ self.assertFalse(t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + +@@ -1444,9 +1445,9 @@ + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) +- self.assertTrue(not t1 != t2) +- self.assertTrue(not t1 < t2) +- self.assertTrue(not t1 > t2) ++ self.assertFalse(t1 != t2) ++ self.assertFalse(t1 < t2) ++ self.assertFalse(t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + +@@ -1460,12 +1461,12 @@ + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) +- self.assertTrue(not t1 == t2) +- self.assertTrue(not t2 == t1) +- self.assertTrue(not t1 > t2) +- self.assertTrue(not t2 < t1) +- self.assertTrue(not t1 >= t2) +- self.assertTrue(not t2 <= t1) ++ self.assertFalse(t1 == t2) ++ self.assertFalse(t2 == t1) ++ self.assertFalse(t1 > t2) ++ self.assertFalse(t2 < t1) ++ self.assertFalse(t1 >= t2) ++ self.assertFalse(t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + +@@ -1541,7 +1542,7 @@ + if abs(from_timestamp - from_now) <= tolerance: + break + # Else try again a few times. +- self.assertTrue(abs(from_timestamp - from_now) <= tolerance) ++ self.assertLessEqual(abs(from_timestamp - from_now), tolerance) + + def test_strptime(self): + import _strptime +@@ -1727,9 +1728,9 @@ + self.assertTrue(t1 == t2) + self.assertTrue(t1 <= t2) + self.assertTrue(t1 >= t2) +- self.assertTrue(not t1 != t2) +- self.assertTrue(not t1 < t2) +- self.assertTrue(not t1 > t2) ++ self.assertFalse(t1 != t2) ++ self.assertFalse(t1 < t2) ++ self.assertFalse(t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + +@@ -1743,12 +1744,12 @@ + self.assertTrue(t2 >= t1) + self.assertTrue(t1 != t2) + self.assertTrue(t2 != t1) +- self.assertTrue(not t1 == t2) +- self.assertTrue(not t2 == t1) +- self.assertTrue(not t1 > t2) +- self.assertTrue(not t2 < t1) +- self.assertTrue(not t1 >= t2) +- self.assertTrue(not t2 <= t1) ++ self.assertFalse(t1 == t2) ++ self.assertFalse(t2 == t1) ++ self.assertFalse(t1 > t2) ++ self.assertFalse(t2 < t1) ++ self.assertFalse(t1 >= t2) ++ self.assertFalse(t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + +@@ -1928,8 +1929,8 @@ + self.assertTrue(cls(0, 1)) + self.assertTrue(cls(0, 0, 1)) + self.assertTrue(cls(0, 0, 0, 1)) +- self.assertTrue(not cls(0)) +- self.assertTrue(not cls()) ++ self.assertFalse(cls(0)) ++ self.assertFalse(cls()) + + def test_replace(self): + cls = self.theclass +@@ -2026,7 +2027,7 @@ + def utcoffset(self, dt): pass + b = BetterTry() + t = cls(1, 1, 1, tzinfo=b) +- self.assertTrue(t.tzinfo is b) ++ self.assertIs(t.tzinfo, b) + + def test_utc_offset_out_of_bounds(self): + class Edgy(tzinfo): +@@ -2065,9 +2066,9 @@ + for t in (cls(1, 1, 1), + cls(1, 1, 1, tzinfo=None), + cls(1, 1, 1, tzinfo=C1())): +- self.assertTrue(t.utcoffset() is None) +- self.assertTrue(t.dst() is None) +- self.assertTrue(t.tzname() is None) ++ self.assertIsNone(t.utcoffset()) ++ self.assertIsNone(t.dst()) ++ self.assertIsNone(t.tzname()) + + class C3(tzinfo): + def utcoffset(self, dt): return timedelta(minutes=-1439) +@@ -2161,7 +2162,7 @@ + self.assertEqual(t.minute, 0) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 0) +- self.assertTrue(t.tzinfo is None) ++ self.assertIsNone(t.tzinfo) + + def test_zones(self): + est = FixedOffset(-300, "EST", 1) +@@ -2176,25 +2177,25 @@ + self.assertEqual(t1.tzinfo, est) + self.assertEqual(t2.tzinfo, utc) + self.assertEqual(t3.tzinfo, met) +- self.assertTrue(t4.tzinfo is None) ++ self.assertIsNone(t4.tzinfo) + self.assertEqual(t5.tzinfo, utc) + + self.assertEqual(t1.utcoffset(), timedelta(minutes=-300)) + self.assertEqual(t2.utcoffset(), timedelta(minutes=0)) + self.assertEqual(t3.utcoffset(), timedelta(minutes=60)) +- self.assertTrue(t4.utcoffset() is None) ++ self.assertIsNone(t4.utcoffset()) + self.assertRaises(TypeError, t1.utcoffset, "no args") + + self.assertEqual(t1.tzname(), "EST") + self.assertEqual(t2.tzname(), "UTC") + self.assertEqual(t3.tzname(), "MET") +- self.assertTrue(t4.tzname() is None) ++ self.assertIsNone(t4.tzname()) + self.assertRaises(TypeError, t1.tzname, "no args") + + self.assertEqual(t1.dst(), timedelta(minutes=1)) + self.assertEqual(t2.dst(), timedelta(minutes=-2)) + self.assertEqual(t3.dst(), timedelta(minutes=3)) +- self.assertTrue(t4.dst() is None) ++ self.assertIsNone(t4.dst()) + self.assertRaises(TypeError, t1.dst, "no args") + + self.assertEqual(hash(t1), hash(t2)) +@@ -2285,10 +2286,10 @@ + self.assertTrue(t) + + t = cls(5, tzinfo=FixedOffset(300, "")) +- self.assertTrue(not t) ++ self.assertFalse(t) + + t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, "")) +- self.assertTrue(not t) ++ self.assertFalse(t) + + # Mostly ensuring this doesn't overflow internally. + t = cls(0, tzinfo=FixedOffset(23*60 + 59, "")) +@@ -2326,13 +2327,13 @@ + # Ensure we can get rid of a tzinfo. + self.assertEqual(base.tzname(), "+100") + base2 = base.replace(tzinfo=None) +- self.assertTrue(base2.tzinfo is None) +- self.assertTrue(base2.tzname() is None) ++ self.assertIsNone(base2.tzinfo) ++ self.assertIsNone(base2.tzname()) + + # Ensure we can add one. + base3 = base2.replace(tzinfo=z100) + self.assertEqual(base, base3) +- self.assertTrue(base.tzinfo is base3.tzinfo) ++ self.assertIs(base.tzinfo, base3.tzinfo) + + # Out of bounds. + base = cls(1) +@@ -2567,7 +2568,7 @@ + tz55 = FixedOffset(-330, "west 5:30") + timeaware = now.time().replace(tzinfo=tz55) + nowaware = self.theclass.combine(now.date(), timeaware) +- self.assertTrue(nowaware.tzinfo is tz55) ++ self.assertIs(nowaware.tzinfo, tz55) + self.assertEqual(nowaware.timetz(), timeaware) + + # Can't mix aware and non-aware. +@@ -2586,15 +2587,15 @@ + # Adding a delta should preserve tzinfo. + delta = timedelta(weeks=1, minutes=12, microseconds=5678) + nowawareplus = nowaware + delta +- self.assertTrue(nowaware.tzinfo is tz55) ++ self.assertIs(nowaware.tzinfo, tz55) + nowawareplus2 = delta + nowaware +- self.assertTrue(nowawareplus2.tzinfo is tz55) ++ self.assertIs(nowawareplus2.tzinfo, tz55) + self.assertEqual(nowawareplus, nowawareplus2) + + # that - delta should be what we started with, and that - what we + # started with should be delta. + diff = nowawareplus - delta +- self.assertTrue(diff.tzinfo is tz55) ++ self.assertIs(diff.tzinfo, tz55) + self.assertEqual(nowaware, diff) + self.assertRaises(TypeError, lambda: delta - nowawareplus) + self.assertEqual(nowawareplus - nowaware, delta) +@@ -2603,7 +2604,7 @@ + tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone") + # Attach it to nowawareplus. + nowawareplus = nowawareplus.replace(tzinfo=tzr) +- self.assertTrue(nowawareplus.tzinfo is tzr) ++ self.assertIs(nowawareplus.tzinfo, tzr) + # Make sure the difference takes the timezone adjustments into account. + got = nowaware - nowawareplus + # Expected: (nowaware base - nowaware offset) - +@@ -2630,7 +2631,7 @@ + off42 = FixedOffset(42, "42") + another = meth(off42) + again = meth(tz=off42) +- self.assertTrue(another.tzinfo is again.tzinfo) ++ self.assertIs(another.tzinfo, again.tzinfo) + self.assertEqual(another.utcoffset(), timedelta(minutes=42)) + # Bad argument with and w/o naming the keyword. + self.assertRaises(TypeError, meth, 16) +@@ -2647,7 +2648,7 @@ + utc = FixedOffset(0, "utc", 0) + for dummy in range(3): + now = datetime.now(weirdtz) +- self.assertTrue(now.tzinfo is weirdtz) ++ self.assertIs(now.tzinfo, weirdtz) + utcnow = datetime.utcnow().replace(tzinfo=utc) + now2 = utcnow.astimezone(weirdtz) + if abs(now - now2) < timedelta(seconds=30): +@@ -2668,7 +2669,7 @@ + off42 = FixedOffset(42, "42") + another = meth(ts, off42) + again = meth(ts, tz=off42) +- self.assertTrue(another.tzinfo is again.tzinfo) ++ self.assertIs(another.tzinfo, again.tzinfo) + self.assertEqual(another.utcoffset(), timedelta(minutes=42)) + # Bad argument with and w/o naming the keyword. + self.assertRaises(TypeError, meth, ts, 16) +@@ -2862,13 +2863,13 @@ + # Ensure we can get rid of a tzinfo. + self.assertEqual(base.tzname(), "+100") + base2 = base.replace(tzinfo=None) +- self.assertTrue(base2.tzinfo is None) +- self.assertTrue(base2.tzname() is None) ++ self.assertIsNone(base2.tzinfo) ++ self.assertIsNone(base2.tzname()) + + # Ensure we can add one. + base3 = base2.replace(tzinfo=z100) + self.assertEqual(base, base3) +- self.assertTrue(base.tzinfo is base3.tzinfo) ++ self.assertIs(base.tzinfo, base3.tzinfo) + + # Out of bounds. + base = cls(2000, 2, 29) +@@ -2881,20 +2882,20 @@ + fm5h = FixedOffset(-timedelta(hours=5), "m300") + + dt = self.theclass.now(tz=f44m) +- self.assertTrue(dt.tzinfo is f44m) ++ self.assertIs(dt.tzinfo, f44m) + # Replacing with degenerate tzinfo raises an exception. + self.assertRaises(ValueError, dt.astimezone, fnone) + # Ditto with None tz. + self.assertRaises(TypeError, dt.astimezone, None) + # Replacing with same tzinfo makes no change. + x = dt.astimezone(dt.tzinfo) +- self.assertTrue(x.tzinfo is f44m) ++ self.assertIs(x.tzinfo, f44m) + self.assertEqual(x.date(), dt.date()) + self.assertEqual(x.time(), dt.time()) + + # Replacing with different tzinfo does adjust. + got = dt.astimezone(fm5h) +- self.assertTrue(got.tzinfo is fm5h) ++ self.assertIs(got.tzinfo, fm5h) + self.assertEqual(got.utcoffset(), timedelta(hours=-5)) + expected = dt - dt.utcoffset() # in effect, convert to UTC + expected += fm5h.utcoffset(dt) # and from there to local time +@@ -2902,7 +2903,7 @@ + self.assertEqual(got.date(), expected.date()) + self.assertEqual(got.time(), expected.time()) + self.assertEqual(got.timetz(), expected.timetz()) +- self.assertTrue(got.tzinfo is expected.tzinfo) ++ self.assertIs(got.tzinfo, expected.tzinfo) + self.assertEqual(got, expected) + + def test_aware_subtract(self): +@@ -3330,8 +3331,8 @@ + as_datetime = datetime.combine(as_date, time()) + self.assertTrue(as_date != as_datetime) + self.assertTrue(as_datetime != as_date) +- self.assertTrue(not as_date == as_datetime) +- self.assertTrue(not as_datetime == as_date) ++ self.assertFalse(as_date == as_datetime) ++ self.assertFalse(as_datetime == as_date) + self.assertRaises(TypeError, lambda: as_date < as_datetime) + self.assertRaises(TypeError, lambda: as_datetime < as_date) + self.assertRaises(TypeError, lambda: as_date <= as_datetime) +@@ -3345,8 +3346,7 @@ + # projection if use of a date method is forced. + self.assertTrue(as_date.__eq__(as_datetime)) + different_day = (as_date.day + 1) % 20 + 1 +- self.assertTrue(not as_date.__eq__(as_datetime.replace(day= +- different_day))) ++ self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day))) + + # And date should compare with other subclasses of date. If a + # subclass wants to stop this, it's up to the subclass to do so. +diff -r 3a1db0d2747e Lib/test/test_decimal.py +--- a/Lib/test/test_decimal.py ++++ b/Lib/test/test_decimal.py +@@ -223,7 +223,6 @@ + global skip_expected + if skip_expected: + raise unittest.SkipTest +- return + with open(file) as f: + for line in f: + line = line.replace('\r\n', '').replace('\n', '') +@@ -234,7 +233,6 @@ + #Exception raised where there shouldn't have been one. + self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) + +- return + + def eval_line(self, s): + if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'): +@@ -391,7 +389,6 @@ + 'Incorrect answer for ' + s + ' -- got ' + result) + self.assertItemsEqual(myexceptions, theirexceptions, + 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) +- return + + def getexceptions(self): + return [e for e in Signals if self.context.flags[e]] +@@ -834,7 +831,7 @@ + try: + from locale import CHAR_MAX + except ImportError: +- return ++ self.skipTest('locale.CHAR_MAX not available') + + # Set up some localeconv-like dictionaries + en_US = { +@@ -1196,7 +1193,6 @@ + + cls.assertEqual(test1, Decimal('0.3333333333333333333333333333')) + cls.assertEqual(test2, Decimal('0.3333333333333333333333333333')) +- return + + def thfunc2(cls): + d1 = Decimal(1) +@@ -1210,17 +1206,12 @@ + + cls.assertEqual(test1, Decimal('0.3333333333333333333333333333')) + cls.assertEqual(test2, Decimal('0.333333333333333333')) +- return + + ++@unittest.skipUnless(threading, 'threading required') + class DecimalUseOfContextTest(unittest.TestCase): + '''Unit tests for Use of Context cases in Decimal.''' + +- try: +- import threading +- except ImportError: +- threading = None +- + # Take care executing this test from IDLE, there's an issue in threading + # that hangs IDLE and I couldn't find it + +@@ -1239,10 +1230,6 @@ + + self.finish1.wait() + self.finish2.wait() +- return +- +- if threading is None: +- del test_threading + + + class DecimalUsabilityTest(unittest.TestCase): +@@ -1540,7 +1527,6 @@ + self.assertEqual(d1._sign, b1._sign) + self.assertEqual(d1._int, b1._int) + self.assertEqual(d1._exp, b1._exp) +- return + + Decimal(d1) + self.assertEqual(d1._sign, b1._sign) +diff -r 3a1db0d2747e Lib/test/test_descr.py +--- a/Lib/test/test_descr.py ++++ b/Lib/test/test_descr.py +@@ -398,13 +398,21 @@ + + class ClassPropertiesAndMethods(unittest.TestCase): + ++ def assertHasAttr(self, obj, name): ++ self.assertTrue(hasattr(obj, name), ++ '%r has no attribute %r' % (obj, name)) ++ ++ def assertNotHasAttr(self, obj, name): ++ self.assertFalse(hasattr(obj, name), ++ '%r has unexpected attribute %r' % (obj, name)) ++ + def test_python_dicts(self): + # Testing Python subclass of dict... + self.assertTrue(issubclass(dict, dict)) + self.assertIsInstance({}, dict) + d = dict() + self.assertEqual(d, {}) +- self.assertTrue(d.__class__ is dict) ++ self.assertIs(d.__class__, dict) + self.assertIsInstance(d, dict) + class C(dict): + state = -1 +@@ -585,7 +593,7 @@ + def _set_x(self, x): + self.__x = -x + a = A() +- self.assertTrue(not hasattr(a, "x")) ++ self.assertNotHasAttr(a, "x") + a.x = 12 + self.assertEqual(a.x, 12) + self.assertEqual(a._A__x, -12) +@@ -934,14 +942,14 @@ + self.assertEqual(type(a), object) + b = object() + self.assertNotEqual(a, b) +- self.assertFalse(hasattr(a, "foo")) ++ self.assertNotHasAttr(a, "foo") + try: + a.foo = 12 + except (AttributeError, TypeError): + pass + else: + self.fail("object() should not allow setting a foo attribute") +- self.assertFalse(hasattr(object(), "__dict__")) ++ self.assertNotHasAttr(object(), "__dict__") + + class Cdict(object): + pass +@@ -956,28 +964,28 @@ + class C0(object): + __slots__ = [] + x = C0() +- self.assertFalse(hasattr(x, "__dict__")) +- self.assertFalse(hasattr(x, "foo")) ++ self.assertNotHasAttr(x, "__dict__") ++ self.assertNotHasAttr(x, "foo") + + class C1(object): + __slots__ = ['a'] + x = C1() +- self.assertFalse(hasattr(x, "__dict__")) +- self.assertFalse(hasattr(x, "a")) ++ self.assertNotHasAttr(x, "__dict__") ++ self.assertNotHasAttr(x, "a") + x.a = 1 + self.assertEqual(x.a, 1) + x.a = None + self.assertEqual(x.a, None) + del x.a +- self.assertFalse(hasattr(x, "a")) ++ self.assertNotHasAttr(x, "a") + + class C3(object): + __slots__ = ['a', 'b', 'c'] + x = C3() +- self.assertFalse(hasattr(x, "__dict__")) +- self.assertFalse(hasattr(x, 'a')) +- self.assertFalse(hasattr(x, 'b')) +- self.assertFalse(hasattr(x, 'c')) ++ self.assertNotHasAttr(x, "__dict__") ++ self.assertNotHasAttr(x, 'a') ++ self.assertNotHasAttr(x, 'b') ++ self.assertNotHasAttr(x, 'c') + x.a = 1 + x.b = 2 + x.c = 3 +@@ -993,8 +1001,8 @@ + def get(self): + return self.__a + x = C4(5) +- self.assertFalse(hasattr(x, '__dict__')) +- self.assertFalse(hasattr(x, '__a')) ++ self.assertNotHasAttr(x, '__dict__') ++ self.assertNotHasAttr(x, '__a') + self.assertEqual(x.get(), 5) + try: + x.__a = 6 +@@ -1051,11 +1059,12 @@ + c.abc = 5 + self.assertEqual(c.abc, 5) + ++ def test_unicode_slots(self): + # Test unicode slot names + try: + unicode + except NameError: +- pass ++ self.skipTest('no unicode support') + else: + # Test a single unicode string is not expanded as a sequence. + class C(object): +@@ -1164,16 +1173,16 @@ + class D(object): + __slots__ = ["__dict__"] + a = D() +- self.assertTrue(hasattr(a, "__dict__")) +- self.assertFalse(hasattr(a, "__weakref__")) ++ self.assertHasAttr(a, "__dict__") ++ self.assertNotHasAttr(a, "__weakref__") + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + + class W(object): + __slots__ = ["__weakref__"] + a = W() +- self.assertTrue(hasattr(a, "__weakref__")) +- self.assertFalse(hasattr(a, "__dict__")) ++ self.assertHasAttr(a, "__weakref__") ++ self.assertNotHasAttr(a, "__dict__") + try: + a.foo = 42 + except AttributeError: +@@ -1184,16 +1193,16 @@ + class C1(W, D): + __slots__ = [] + a = C1() +- self.assertTrue(hasattr(a, "__dict__")) +- self.assertTrue(hasattr(a, "__weakref__")) ++ self.assertHasAttr(a, "__dict__") ++ self.assertHasAttr(a, "__weakref__") + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + + class C2(D, W): + __slots__ = [] + a = C2() +- self.assertTrue(hasattr(a, "__dict__")) +- self.assertTrue(hasattr(a, "__weakref__")) ++ self.assertHasAttr(a, "__dict__") ++ self.assertHasAttr(a, "__weakref__") + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + +@@ -1241,7 +1250,7 @@ + class C(object): + pass + a = C() +- self.assertFalse(hasattr(a, "foobar")) ++ self.assertNotHasAttr(a, "foobar") + C.foobar = 2 + self.assertEqual(a.foobar, 2) + C.method = lambda self: 42 +@@ -1251,7 +1260,7 @@ + C.__int__ = lambda self: 100 + self.assertEqual(int(a), 100) + self.assertEqual(a.foobar, 2) +- self.assertFalse(hasattr(a, "spam")) ++ self.assertNotHasAttr(a, "spam") + def mygetattr(self, name): + if name == "spam": + return "spam" +@@ -1521,7 +1530,7 @@ + self.assertEqual(a.x, 10) + self.assertEqual(a.x, 11) + del a.x +- self.assertEqual(hasattr(a, 'x'), 0) ++ self.assertNotHasAttr(a, 'x') + + def test_newslots(self): + # Testing __new__ slot override... +@@ -1797,18 +1806,18 @@ + raise IndexError + c1 = C() + c2 = C() +- self.assertTrue(not not c1) # What? ++ self.assertFalse(not c1) + self.assertNotEqual(id(c1), id(c2)) + hash(c1) + hash(c2) + self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2))) + self.assertEqual(c1, c1) + self.assertTrue(c1 != c2) +- self.assertTrue(not c1 != c1) +- self.assertTrue(not c1 == c2) ++ self.assertFalse(c1 != c1) ++ self.assertFalse(c1 == c2) + # Note that the module name appears in str/repr, and that varies + # depending on whether this test is run standalone or from a framework. +- self.assertTrue(str(c1).find('C object at ') >= 0) ++ self.assertGreaterEqual(str(c1).find('C object at '), 0) + self.assertEqual(str(c1), repr(c1)) + self.assertNotIn(-1, c1) + for i in range(10): +@@ -1821,18 +1830,18 @@ + raise IndexError + d1 = D() + d2 = D() +- self.assertTrue(not not d1) ++ self.assertFalse(not d1) + self.assertNotEqual(id(d1), id(d2)) + hash(d1) + hash(d2) + self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2))) + self.assertEqual(d1, d1) + self.assertNotEqual(d1, d2) +- self.assertTrue(not d1 != d1) +- self.assertTrue(not d1 == d2) ++ self.assertFalse(d1 != d1) ++ self.assertFalse(d1 == d2) + # Note that the module name appears in str/repr, and that varies + # depending on whether this test is run standalone or from a framework. +- self.assertTrue(str(d1).find('D object at ') >= 0) ++ self.assertGreaterEqual(str(d1).find('D object at '), 0) + self.assertEqual(str(d1), repr(d1)) + self.assertNotIn(-1, d1) + for i in range(10): +@@ -1862,11 +1871,11 @@ + p1 = Proxy(1) + p_1 = Proxy(-1) + self.assertFalse(p0) +- self.assertTrue(not not p1) ++ self.assertFalse(not p1) + self.assertEqual(hash(p0), hash(0)) + self.assertEqual(p0, p0) + self.assertNotEqual(p0, p1) +- self.assertTrue(not p0 != p0) ++ self.assertFalse(p0 != p0) + self.assertEqual(not p0, p1) + self.assertEqual(cmp(p0, p1), -1) + self.assertEqual(cmp(p0, p0), 0) +@@ -1902,7 +1911,7 @@ + p1 = DProxy(1) + p_1 = DProxy(-1) + self.assertFalse(p0) +- self.assertTrue(not not p1) ++ self.assertFalse(not p1) + self.assertEqual(hash(p0), hash(0)) + self.assertEqual(p0, p0) + self.assertNotEqual(p0, p1) +@@ -1995,7 +2004,7 @@ + try: + weakref.ref(no) + except TypeError, msg: +- self.assertTrue(str(msg).find("weak reference") >= 0) ++ self.assertIn("weak reference", str(msg)) + else: + self.fail("weakref.ref(no) should be illegal") + class Weak(object): +@@ -2019,17 +2028,17 @@ + del self.__x + x = property(getx, setx, delx, doc="I'm the x property.") + a = C() +- self.assertFalse(hasattr(a, "x")) ++ self.assertNotHasAttr(a, "x") + a.x = 42 + self.assertEqual(a._C__x, 42) + self.assertEqual(a.x, 42) + del a.x +- self.assertFalse(hasattr(a, "x")) +- self.assertFalse(hasattr(a, "_C__x")) ++ self.assertNotHasAttr(a, "x") ++ self.assertNotHasAttr(a, "_C__x") + C.x.__set__(a, 100) + self.assertEqual(C.x.__get__(a), 100) + C.x.__delete__(a) +- self.assertFalse(hasattr(a, "x")) ++ self.assertNotHasAttr(a, "x") + + raw = C.__dict__['x'] + self.assertIsInstance(raw, property) +@@ -2041,9 +2050,9 @@ + self.assertIn("fdel", attrs) + + self.assertEqual(raw.__doc__, "I'm the x property.") +- self.assertTrue(raw.fget is C.__dict__['getx']) +- self.assertTrue(raw.fset is C.__dict__['setx']) +- self.assertTrue(raw.fdel is C.__dict__['delx']) ++ self.assertIs(raw.fget, C.__dict__['getx']) ++ self.assertIs(raw.fset, C.__dict__['setx']) ++ self.assertIs(raw.fdel, C.__dict__['delx']) + + for attr in "__doc__", "fget", "fset", "fdel": + try: +@@ -2083,6 +2092,7 @@ + prop2 = property(fset=setter) + self.assertEqual(prop2.__doc__, None) + ++ @test_support.cpython_only + def test_testcapi_no_segfault(self): + # this segfaulted in 2.5b2 + try: +@@ -2107,14 +2117,14 @@ + del self._foo + c = C() + self.assertEqual(C.foo.__doc__, "hello") +- self.assertFalse(hasattr(c, "foo")) ++ self.assertNotHasAttr(c, "foo") + c.foo = -42 +- self.assertTrue(hasattr(c, '_foo')) ++ self.assertHasAttr(c, '_foo') + self.assertEqual(c._foo, 42) + self.assertEqual(c.foo, 42) + del c.foo +- self.assertFalse(hasattr(c, '_foo')) +- self.assertFalse(hasattr(c, "foo")) ++ self.assertNotHasAttr(c, '_foo') ++ self.assertNotHasAttr(c, "foo") + + class D(C): + @C.foo.deleter +@@ -2500,13 +2510,13 @@ + a = hexint(12345) + self.assertEqual(a, 12345) + self.assertEqual(int(a), 12345) +- self.assertTrue(int(a).__class__ is int) ++ self.assertIs(int(a).__class__, int) + self.assertEqual(hash(a), hash(12345)) +- self.assertTrue((+a).__class__ is int) +- self.assertTrue((a >> 0).__class__ is int) +- self.assertTrue((a << 0).__class__ is int) +- self.assertTrue((hexint(0) << 12).__class__ is int) +- self.assertTrue((hexint(0) >> 12).__class__ is int) ++ self.assertIs((+a).__class__, int) ++ self.assertIs((a >> 0).__class__, int) ++ self.assertIs((a << 0).__class__, int) ++ self.assertIs((hexint(0) << 12).__class__, int) ++ self.assertIs((hexint(0) >> 12).__class__, int) + + class octlong(long): + __slots__ = [] +@@ -2526,31 +2536,31 @@ + self.assertEqual(a, 12345L) + self.assertEqual(long(a), 12345L) + self.assertEqual(hash(a), hash(12345L)) +- self.assertTrue(long(a).__class__ is long) +- self.assertTrue((+a).__class__ is long) +- self.assertTrue((-a).__class__ is long) +- self.assertTrue((-octlong(0)).__class__ is long) +- self.assertTrue((a >> 0).__class__ is long) +- self.assertTrue((a << 0).__class__ is long) +- self.assertTrue((a - 0).__class__ is long) +- self.assertTrue((a * 1).__class__ is long) +- self.assertTrue((a ** 1).__class__ is long) +- self.assertTrue((a // 1).__class__ is long) +- self.assertTrue((1 * a).__class__ is long) +- self.assertTrue((a | 0).__class__ is long) +- self.assertTrue((a ^ 0).__class__ is long) +- self.assertTrue((a & -1L).__class__ is long) +- self.assertTrue((octlong(0) << 12).__class__ is long) +- self.assertTrue((octlong(0) >> 12).__class__ is long) +- self.assertTrue(abs(octlong(0)).__class__ is long) ++ self.assertIs(long(a).__class__, long) ++ self.assertIs((+a).__class__, long) ++ self.assertIs((-a).__class__, long) ++ self.assertIs((-octlong(0)).__class__, long) ++ self.assertIs((a >> 0).__class__, long) ++ self.assertIs((a << 0).__class__, long) ++ self.assertIs((a - 0).__class__, long) ++ self.assertIs((a * 1).__class__, long) ++ self.assertIs((a ** 1).__class__, long) ++ self.assertIs((a // 1).__class__, long) ++ self.assertIs((1 * a).__class__, long) ++ self.assertIs((a | 0).__class__, long) ++ self.assertIs((a ^ 0).__class__, long) ++ self.assertIs((a & -1L).__class__, long) ++ self.assertIs((octlong(0) << 12).__class__, long) ++ self.assertIs((octlong(0) >> 12).__class__, long) ++ self.assertIs(abs(octlong(0)).__class__, long) + + # Because octlong overrides __add__, we can't check the absence of +0 + # optimizations using octlong. + class longclone(long): + pass + a = longclone(1) +- self.assertTrue((a + 0).__class__ is long) +- self.assertTrue((0 + a).__class__ is long) ++ self.assertIs((a + 0).__class__, long) ++ self.assertIs((0 + a).__class__, long) + + # Check that negative clones don't segfault + a = longclone(-1) +@@ -2567,9 +2577,9 @@ + a = precfloat(12345) + self.assertEqual(a, 12345.0) + self.assertEqual(float(a), 12345.0) +- self.assertTrue(float(a).__class__ is float) ++ self.assertIs(float(a).__class__, float) + self.assertEqual(hash(a), hash(12345.0)) +- self.assertTrue((+a).__class__ is float) ++ self.assertIs((+a).__class__, float) + + class madcomplex(complex): + def __repr__(self): +@@ -2617,20 +2627,20 @@ + self.assertEqual(v, t) + a = madtuple((1,2,3,4,5)) + self.assertEqual(tuple(a), (1,2,3,4,5)) +- self.assertTrue(tuple(a).__class__ is tuple) ++ self.assertIs(tuple(a).__class__, tuple) + self.assertEqual(hash(a), hash((1,2,3,4,5))) +- self.assertTrue(a[:].__class__ is tuple) +- self.assertTrue((a * 1).__class__ is tuple) +- self.assertTrue((a * 0).__class__ is tuple) +- self.assertTrue((a + ()).__class__ is tuple) ++ self.assertIs(a[:].__class__, tuple) ++ self.assertIs((a * 1).__class__, tuple) ++ self.assertIs((a * 0).__class__, tuple) ++ self.assertIs((a + ()).__class__, tuple) + a = madtuple(()) + self.assertEqual(tuple(a), ()) +- self.assertTrue(tuple(a).__class__ is tuple) +- self.assertTrue((a + a).__class__ is tuple) +- self.assertTrue((a * 0).__class__ is tuple) +- self.assertTrue((a * 1).__class__ is tuple) +- self.assertTrue((a * 2).__class__ is tuple) +- self.assertTrue(a[:].__class__ is tuple) ++ self.assertIs(tuple(a).__class__, tuple) ++ self.assertIs((a + a).__class__, tuple) ++ self.assertIs((a * 0).__class__, tuple) ++ self.assertIs((a * 1).__class__, tuple) ++ self.assertIs((a * 2).__class__, tuple) ++ self.assertIs(a[:].__class__, tuple) + + class madstring(str): + _rev = None +@@ -2652,51 +2662,51 @@ + self.assertEqual(u, s) + s = madstring("12345") + self.assertEqual(str(s), "12345") +- self.assertTrue(str(s).__class__ is str) ++ self.assertIs(str(s).__class__, str) + + base = "\x00" * 5 + s = madstring(base) + self.assertEqual(s, base) + self.assertEqual(str(s), base) +- self.assertTrue(str(s).__class__ is str) ++ self.assertIs(str(s).__class__, str) + self.assertEqual(hash(s), hash(base)) + self.assertEqual({s: 1}[base], 1) + self.assertEqual({base: 1}[s], 1) +- self.assertTrue((s + "").__class__ is str) ++ self.assertIs((s + "").__class__, str) + self.assertEqual(s + "", base) +- self.assertTrue(("" + s).__class__ is str) ++ self.assertIs(("" + s).__class__, str) + self.assertEqual("" + s, base) +- self.assertTrue((s * 0).__class__ is str) ++ self.assertIs((s * 0).__class__, str) + self.assertEqual(s * 0, "") +- self.assertTrue((s * 1).__class__ is str) ++ self.assertIs((s * 1).__class__, str) + self.assertEqual(s * 1, base) +- self.assertTrue((s * 2).__class__ is str) ++ self.assertIs((s * 2).__class__, str) + self.assertEqual(s * 2, base + base) +- self.assertTrue(s[:].__class__ is str) ++ self.assertIs(s[:].__class__, str) + self.assertEqual(s[:], base) +- self.assertTrue(s[0:0].__class__ is str) ++ self.assertIs(s[0:0].__class__, str) + self.assertEqual(s[0:0], "") +- self.assertTrue(s.strip().__class__ is str) ++ self.assertIs(s.strip().__class__, str) + self.assertEqual(s.strip(), base) +- self.assertTrue(s.lstrip().__class__ is str) ++ self.assertIs(s.lstrip().__class__, str) + self.assertEqual(s.lstrip(), base) +- self.assertTrue(s.rstrip().__class__ is str) ++ self.assertIs(s.rstrip().__class__, str) + self.assertEqual(s.rstrip(), base) + identitytab = ''.join([chr(i) for i in range(256)]) +- self.assertTrue(s.translate(identitytab).__class__ is str) ++ self.assertIs(s.translate(identitytab).__class__, str) + self.assertEqual(s.translate(identitytab), base) +- self.assertTrue(s.translate(identitytab, "x").__class__ is str) ++ self.assertIs(s.translate(identitytab, "x").__class__, str) + self.assertEqual(s.translate(identitytab, "x"), base) + self.assertEqual(s.translate(identitytab, "\x00"), "") +- self.assertTrue(s.replace("x", "x").__class__ is str) ++ self.assertIs(s.replace("x", "x").__class__, str) + self.assertEqual(s.replace("x", "x"), base) +- self.assertTrue(s.ljust(len(s)).__class__ is str) ++ self.assertIs(s.ljust(len(s)).__class__, str) + self.assertEqual(s.ljust(len(s)), base) +- self.assertTrue(s.rjust(len(s)).__class__ is str) ++ self.assertIs(s.rjust(len(s)).__class__, str) + self.assertEqual(s.rjust(len(s)), base) +- self.assertTrue(s.center(len(s)).__class__ is str) ++ self.assertIs(s.center(len(s)).__class__, str) + self.assertEqual(s.center(len(s)), base) +- self.assertTrue(s.lower().__class__ is str) ++ self.assertIs(s.lower().__class__, str) + self.assertEqual(s.lower(), base) + + class madunicode(unicode): +@@ -2715,47 +2725,47 @@ + base = u"12345" + u = madunicode(base) + self.assertEqual(unicode(u), base) +- self.assertTrue(unicode(u).__class__ is unicode) ++ self.assertIs(unicode(u).__class__, unicode) + self.assertEqual(hash(u), hash(base)) + self.assertEqual({u: 1}[base], 1) + self.assertEqual({base: 1}[u], 1) +- self.assertTrue(u.strip().__class__ is unicode) ++ self.assertIs(u.strip().__class__, unicode) + self.assertEqual(u.strip(), base) +- self.assertTrue(u.lstrip().__class__ is unicode) ++ self.assertIs(u.lstrip().__class__, unicode) + self.assertEqual(u.lstrip(), base) +- self.assertTrue(u.rstrip().__class__ is unicode) ++ self.assertIs(u.rstrip().__class__, unicode) + self.assertEqual(u.rstrip(), base) +- self.assertTrue(u.replace(u"x", u"x").__class__ is unicode) ++ self.assertIs(u.replace(u"x", u"x").__class__, unicode) + self.assertEqual(u.replace(u"x", u"x"), base) +- self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode) ++ self.assertIs(u.replace(u"xy", u"xy").__class__, unicode) + self.assertEqual(u.replace(u"xy", u"xy"), base) +- self.assertTrue(u.center(len(u)).__class__ is unicode) ++ self.assertIs(u.center(len(u)).__class__, unicode) + self.assertEqual(u.center(len(u)), base) +- self.assertTrue(u.ljust(len(u)).__class__ is unicode) ++ self.assertIs(u.ljust(len(u)).__class__, unicode) + self.assertEqual(u.ljust(len(u)), base) +- self.assertTrue(u.rjust(len(u)).__class__ is unicode) ++ self.assertIs(u.rjust(len(u)).__class__, unicode) + self.assertEqual(u.rjust(len(u)), base) +- self.assertTrue(u.lower().__class__ is unicode) ++ self.assertIs(u.lower().__class__, unicode) + self.assertEqual(u.lower(), base) +- self.assertTrue(u.upper().__class__ is unicode) ++ self.assertIs(u.upper().__class__, unicode) + self.assertEqual(u.upper(), base) +- self.assertTrue(u.capitalize().__class__ is unicode) ++ self.assertIs(u.capitalize().__class__, unicode) + self.assertEqual(u.capitalize(), base) +- self.assertTrue(u.title().__class__ is unicode) ++ self.assertIs(u.title().__class__, unicode) + self.assertEqual(u.title(), base) +- self.assertTrue((u + u"").__class__ is unicode) ++ self.assertIs((u + u"").__class__, unicode) + self.assertEqual(u + u"", base) +- self.assertTrue((u"" + u).__class__ is unicode) ++ self.assertIs((u"" + u).__class__, unicode) + self.assertEqual(u"" + u, base) +- self.assertTrue((u * 0).__class__ is unicode) ++ self.assertIs((u * 0).__class__, unicode) + self.assertEqual(u * 0, u"") +- self.assertTrue((u * 1).__class__ is unicode) ++ self.assertIs((u * 1).__class__, unicode) + self.assertEqual(u * 1, base) +- self.assertTrue((u * 2).__class__ is unicode) ++ self.assertIs((u * 2).__class__, unicode) + self.assertEqual(u * 2, base + base) +- self.assertTrue(u[:].__class__ is unicode) ++ self.assertIs(u[:].__class__, unicode) + self.assertEqual(u[:], base) +- self.assertTrue(u[0:0].__class__ is unicode) ++ self.assertIs(u[0:0].__class__, unicode) + self.assertEqual(u[0:0], u"") + + class sublist(list): +@@ -2901,12 +2911,16 @@ + c = {1: c1, 2: c2, 3: c3} + for x in 1, 2, 3: + for y in 1, 2, 3: +- self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) ++ self.assertEqual(cmp(c[x], c[y]), cmp(x, y), ++ "x=%d, y=%d" % (x, y)) + for op in "<", "<=", "==", "!=", ">", ">=": +- self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), +- "x=%d, y=%d" % (x, y)) +- self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) +- self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) ++ self.assertEqual(eval("c[x] %s c[y]" % op), ++ eval("x %s y" % op), ++ "x=%d, y=%d" % (x, y)) ++ self.assertEqual(cmp(c[x], y), cmp(x, y), ++ "x=%d, y=%d" % (x, y)) ++ self.assertEqual(cmp(x, c[y]), cmp(x, y), ++ "x=%d, y=%d" % (x, y)) + + def test_rich_comparisons(self): + # Testing rich comparisons... +@@ -2979,12 +2993,15 @@ + for x in 1, 2, 3: + for y in 1, 2, 3: + for op in "<", "<=", "==", "!=", ">", ">=": +- self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), +- "x=%d, y=%d" % (x, y)) +- self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op), +- "x=%d, y=%d" % (x, y)) +- self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op), +- "x=%d, y=%d" % (x, y)) ++ self.assertEqual(eval("c[x] %s c[y]" % op), ++ eval("x %s y" % op), ++ "x=%d, y=%d" % (x, y)) ++ self.assertEqual(eval("c[x] %s y" % op), ++ eval("x %s y" % op), ++ "x=%d, y=%d" % (x, y)) ++ self.assertEqual(eval("x %s c[y]" % op), ++ eval("x %s y" % op), ++ "x=%d, y=%d" % (x, y)) + + def test_coercions(self): + # Testing coercions... +@@ -3049,9 +3066,9 @@ + for cls2 in C, D, E, F: + x = cls() + x.__class__ = cls2 +- self.assertTrue(x.__class__ is cls2) ++ self.assertIs(x.__class__, cls2) + x.__class__ = cls +- self.assertTrue(x.__class__ is cls) ++ self.assertIs(x.__class__, cls) + def cant(x, C): + try: + x.__class__ = C +@@ -3113,11 +3130,11 @@ + x = cls() + x.a = 1 + x.__class__ = cls2 +- self.assertTrue(x.__class__ is cls2, ++ self.assertIs(x.__class__, cls2, + "assigning %r as __class__ for %r silently failed" % (cls2, x)) + self.assertEqual(x.a, 1) + x.__class__ = cls +- self.assertTrue(x.__class__ is cls, ++ self.assertIs(x.__class__, cls, + "assigning %r as __class__ for %r silently failed" % (cls, x)) + self.assertEqual(x.a, 1) + for cls in G, J, K, L, M, N, P, R, list, Int: +@@ -3287,7 +3304,7 @@ + for cls in C, C1, C2: + s = p.dumps(cls, bin) + cls2 = p.loads(s) +- self.assertTrue(cls2 is cls) ++ self.assertIs(cls2, cls) + + a = C1(1, 2); a.append(42); a.append(24) + b = C2("hello", "world", 42) +@@ -3317,7 +3334,7 @@ + import copy + for cls in C, C1, C2: + cls2 = copy.deepcopy(cls) +- self.assertTrue(cls2 is cls) ++ self.assertIs(cls2, cls) + + a = C1(1, 2); a.append(42); a.append(24) + b = C2("hello", "world", 42) +@@ -3388,9 +3405,9 @@ + # Now it should work + x = C() + y = pickle.loads(pickle.dumps(x)) +- self.assertEqual(hasattr(y, 'a'), 0) ++ self.assertNotHasAttr(y, 'a') + y = cPickle.loads(cPickle.dumps(x)) +- self.assertEqual(hasattr(y, 'a'), 0) ++ self.assertNotHasAttr(y, 'a') + x.a = 42 + y = pickle.loads(pickle.dumps(x)) + self.assertEqual(y.a, 42) +@@ -3706,9 +3723,9 @@ + from types import ModuleType as M + m = M.__new__(M) + str(m) +- self.assertEqual(hasattr(m, "__name__"), 0) +- self.assertEqual(hasattr(m, "__file__"), 0) +- self.assertEqual(hasattr(m, "foo"), 0) ++ self.assertNotHasAttr(m, "__name__") ++ self.assertNotHasAttr(m, "__file__") ++ self.assertNotHasAttr(m, "foo") + self.assertFalse(m.__dict__) # None or {} are both reasonable answers + m.foo = 1 + self.assertEqual(m.__dict__, {"foo": 1}) +@@ -3888,8 +3905,8 @@ + __slots__=() + if test_support.check_impl_detail(): + self.assertEqual(C.__basicsize__, B.__basicsize__) +- self.assertTrue(hasattr(C, '__dict__')) +- self.assertTrue(hasattr(C, '__weakref__')) ++ self.assertHasAttr(C, '__dict__') ++ self.assertHasAttr(C, '__weakref__') + C().x = 2 + + def test_rmul(self): +@@ -4390,7 +4407,7 @@ + self.assertEqual(c.attr, 1) + # this makes a crash more likely: + test_support.gc_collect() +- self.assertEqual(hasattr(c, 'attr'), False) ++ self.assertNotHasAttr(c, 'attr') + + def test_init(self): + # SF 1155938 +@@ -4411,17 +4428,17 @@ + l = [] + self.assertEqual(l.__add__, l.__add__) + self.assertEqual(l.__add__, [].__add__) +- self.assertTrue(l.__add__ != [5].__add__) +- self.assertTrue(l.__add__ != l.__mul__) +- self.assertTrue(l.__add__.__name__ == '__add__') ++ self.assertNotEqual(l.__add__, [5].__add__) ++ self.assertNotEqual(l.__add__, l.__mul__) ++ self.assertEqual(l.__add__.__name__, '__add__') + if hasattr(l.__add__, '__self__'): + # CPython +- self.assertTrue(l.__add__.__self__ is l) +- self.assertTrue(l.__add__.__objclass__ is list) ++ self.assertIs(l.__add__.__self__, l) ++ self.assertIs(l.__add__.__objclass__, list) + else: + # Python implementations where [].__add__ is a normal bound method +- self.assertTrue(l.__add__.im_self is l) +- self.assertTrue(l.__add__.im_class is list) ++ self.assertIs(l.__add__.im_self, l) ++ self.assertIs(l.__add__.im_class, list) + self.assertEqual(l.__add__.__doc__, list.__add__.__doc__) + try: + hash(l.__add__) +@@ -4604,7 +4621,7 @@ + + fake_str = FakeStr() + # isinstance() reads __class__ on new style classes +- self.assertTrue(isinstance(fake_str, str)) ++ self.assertIsInstance(fake_str, str) + + # call a method descriptor + with self.assertRaises(TypeError): +diff -r 3a1db0d2747e Lib/test/test_dis.py +--- a/Lib/test/test_dis.py ++++ b/Lib/test/test_dis.py +@@ -125,6 +125,8 @@ + # so fails if the tests are run with -O. Skip this test then. + if __debug__: + self.do_disassembly_test(bug1333982, dis_bug1333982) ++ else: ++ self.skipTest('need asserts, run without -O') + + def test_big_linenos(self): + def func(count): +diff -r 3a1db0d2747e Lib/test/test_dl.py +--- a/Lib/test/test_dl.py ++++ b/Lib/test/test_dl.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test dlmodule.c + Roger E. Masse revised strategy by Barry Warsaw + """ +diff -r 3a1db0d2747e Lib/test/test_doctest.py +--- a/Lib/test/test_doctest.py ++++ b/Lib/test/test_doctest.py +@@ -1019,6 +1019,33 @@ + ValueError: message + TestResults(failed=1, attempted=1) + ++If the exception does not have a message, you can still use ++IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3: ++ ++ >>> def f(x): ++ ... r''' ++ ... >>> from Queue import Empty ++ ... >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL ++ ... Traceback (most recent call last): ++ ... foo.bar.Empty ++ ... ''' ++ >>> test = doctest.DocTestFinder().find(f)[0] ++ >>> doctest.DocTestRunner(verbose=False).run(test) ++ TestResults(failed=0, attempted=2) ++ ++Note that a trailing colon doesn't matter either: ++ ++ >>> def f(x): ++ ... r''' ++ ... >>> from Queue import Empty ++ ... >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL ++ ... Traceback (most recent call last): ++ ... foo.bar.Empty: ++ ... ''' ++ >>> test = doctest.DocTestFinder().find(f)[0] ++ >>> doctest.DocTestRunner(verbose=False).run(test) ++ TestResults(failed=0, attempted=2) ++ + If an exception is raised but not expected, then it is reported as an + unexpected exception: + +diff -r 3a1db0d2747e Lib/test/test_dumbdbm.py +--- a/Lib/test/test_dumbdbm.py ++++ b/Lib/test/test_dumbdbm.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for the dumbdbm module + Original by Roger E. Masse + """ +@@ -38,11 +37,9 @@ + self.read_helper(f) + f.close() + ++ @unittest.skipUnless(hasattr(os, 'chmod'), 'os.chmod not available') ++ @unittest.skipUnless(hasattr(os, 'umask'), 'os.umask not available') + def test_dumbdbm_creation_mode(self): +- # On platforms without chmod, don't do anything. +- if not (hasattr(os, 'chmod') and hasattr(os, 'umask')): +- return +- + try: + old_umask = os.umask(0002) + f = dumbdbm.open(_fname, 'c', 0637) +diff -r 3a1db0d2747e Lib/test/test_enumerate.py +--- a/Lib/test/test_enumerate.py ++++ b/Lib/test/test_enumerate.py +@@ -188,11 +188,10 @@ + self.assertRaises(TypeError, reversed) + self.assertRaises(TypeError, reversed, [], 'extra') + ++ @unittest.skipUnless(hasattr(sys, 'getrefcount'), 'test needs sys.getrefcount()') + def test_bug1229429(self): + # this bug was never in reversed, it was in + # PyObject_CallMethod, and reversed_new calls that sometimes. +- if not hasattr(sys, "getrefcount"): +- return + def f(): + pass + r = f.__reversed__ = object() +diff -r 3a1db0d2747e Lib/test/test_eof.py +--- a/Lib/test/test_eof.py ++++ b/Lib/test/test_eof.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """test script for a few new invalid token catches""" + + import unittest +diff -r 3a1db0d2747e Lib/test/test_errno.py +--- a/Lib/test/test_errno.py ++++ b/Lib/test/test_errno.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test the errno module + Roger E. Masse + """ +diff -r 3a1db0d2747e Lib/test/test_fcntl.py +--- a/Lib/test/test_fcntl.py ++++ b/Lib/test/test_fcntl.py +@@ -6,10 +6,9 @@ + import os + import struct + import sys +-import _testcapi + import unittest + from test.test_support import (verbose, TESTFN, unlink, run_unittest, +- import_module) ++ import_module, cpython_only) + + # Skip test if no fcntl module. + fcntl = import_module('fcntl') +@@ -52,6 +51,12 @@ + lockdata = get_lockdata() + + ++class BadFile: ++ def __init__(self, fn): ++ self.fn = fn ++ def fileno(self): ++ return self.fn ++ + class TestFcntl(unittest.TestCase): + + def setUp(self): +@@ -83,24 +88,27 @@ + self.f.close() + + def test_fcntl_bad_file(self): +- class F: +- def __init__(self, fn): +- self.fn = fn +- def fileno(self): +- return self.fn +- self.assertRaises(ValueError, fcntl.fcntl, -1, fcntl.F_SETFL, os.O_NONBLOCK) +- self.assertRaises(ValueError, fcntl.fcntl, F(-1), fcntl.F_SETFL, os.O_NONBLOCK) +- self.assertRaises(TypeError, fcntl.fcntl, 'spam', fcntl.F_SETFL, os.O_NONBLOCK) +- self.assertRaises(TypeError, fcntl.fcntl, F('spam'), fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(ValueError): ++ fcntl.fcntl(-1, fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(ValueError): ++ fcntl.fcntl(BadFile(-1), fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(TypeError): ++ fcntl.fcntl('spam', fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(TypeError): ++ fcntl.fcntl(BadFile('spam'), fcntl.F_SETFL, os.O_NONBLOCK) ++ ++ @cpython_only ++ def test_fcntl_bad_file_overflow(self): ++ from _testcapi import INT_MAX, INT_MIN + # Issue 15989 +- self.assertRaises(ValueError, fcntl.fcntl, _testcapi.INT_MAX + 1, +- fcntl.F_SETFL, os.O_NONBLOCK) +- self.assertRaises(ValueError, fcntl.fcntl, F(_testcapi.INT_MAX + 1), +- fcntl.F_SETFL, os.O_NONBLOCK) +- self.assertRaises(ValueError, fcntl.fcntl, _testcapi.INT_MIN - 1, +- fcntl.F_SETFL, os.O_NONBLOCK) +- self.assertRaises(ValueError, fcntl.fcntl, F(_testcapi.INT_MIN - 1), +- fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(ValueError): ++ fcntl.fcntl(INT_MAX + 1, fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(ValueError): ++ fcntl.fcntl(BadFile(INT_MAX + 1), fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(ValueError): ++ fcntl.fcntl(INT_MIN - 1, fcntl.F_SETFL, os.O_NONBLOCK) ++ with self.assertRaises(ValueError): ++ fcntl.fcntl(BadFile(INT_MIN - 1), fcntl.F_SETFL, os.O_NONBLOCK) + + def test_fcntl_64_bit(self): + # Issue #1309352: fcntl shouldn't fail when the third arg fits in a +@@ -113,7 +121,10 @@ + self.skipTest("F_NOTIFY or DN_MULTISHOT unavailable") + fd = os.open(os.path.dirname(os.path.abspath(TESTFN)), os.O_RDONLY) + try: ++ # This will raise OverflowError if issue1309352 is present. + fcntl.fcntl(fd, cmd, flags) ++ except IOError: ++ pass # Running on a system that doesn't support these flags. + finally: + os.close(fd) + +diff -r 3a1db0d2747e Lib/test/test_file2k.py +--- a/Lib/test/test_file2k.py ++++ b/Lib/test/test_file2k.py +@@ -415,6 +415,20 @@ + finally: + os.unlink(TESTFN) + ++ @unittest.skipUnless(os.name == 'posix', 'test requires a posix system.') ++ def test_write_full(self): ++ # Issue #17976 ++ try: ++ f = open('/dev/full', 'w', 1) ++ except IOError: ++ self.skipTest("requires '/dev/full'") ++ try: ++ with self.assertRaises(IOError): ++ f.write('hello') ++ f.write('\n') ++ finally: ++ f.close() ++ + class FileSubclassTests(unittest.TestCase): + + def testExit(self): +diff -r 3a1db0d2747e Lib/test/test_fileinput.py +--- a/Lib/test/test_fileinput.py ++++ b/Lib/test/test_fileinput.py +@@ -218,8 +218,49 @@ + finally: + remove_tempfiles(t1) + ++ def test_readline(self): ++ with open(TESTFN, 'wb') as f: ++ f.write('A\nB\r\nC\r') ++ # Fill TextIOWrapper buffer. ++ f.write('123456789\n' * 1000) ++ # Issue #20501: readline() shouldn't read whole file. ++ f.write('\x80') ++ self.addCleanup(safe_unlink, TESTFN) ++ ++ fi = FileInput(files=TESTFN, openhook=hook_encoded('ascii'), bufsize=8) ++ # The most likely failure is a UnicodeDecodeError due to the entire ++ # file being read when it shouldn't have been. ++ self.assertEqual(fi.readline(), u'A\n') ++ self.assertEqual(fi.readline(), u'B\r\n') ++ self.assertEqual(fi.readline(), u'C\r') ++ with self.assertRaises(UnicodeDecodeError): ++ # Read to the end of file. ++ list(fi) ++ fi.close() ++ ++class Test_hook_encoded(unittest.TestCase): ++ """Unit tests for fileinput.hook_encoded()""" ++ ++ def test_modes(self): ++ with open(TESTFN, 'wb') as f: ++ # UTF-7 is a convenient, seldom used encoding ++ f.write('A\nB\r\nC\rD+IKw-') ++ self.addCleanup(safe_unlink, TESTFN) ++ ++ def check(mode, expected_lines): ++ fi = FileInput(files=TESTFN, mode=mode, ++ openhook=hook_encoded('utf-7')) ++ lines = list(fi) ++ fi.close() ++ self.assertEqual(lines, expected_lines) ++ ++ check('r', [u'A\n', u'B\r\n', u'C\r', u'D\u20ac']) ++ check('rU', [u'A\n', u'B\r\n', u'C\r', u'D\u20ac']) ++ check('U', [u'A\n', u'B\r\n', u'C\r', u'D\u20ac']) ++ check('rb', [u'A\n', u'B\r\n', u'C\r', u'D\u20ac']) ++ + def test_main(): +- run_unittest(BufferSizesTests, FileInputTests) ++ run_unittest(BufferSizesTests, FileInputTests, Test_hook_encoded) + + if __name__ == "__main__": + test_main() +diff -r 3a1db0d2747e Lib/test/test_fileio.py +--- a/Lib/test/test_fileio.py ++++ b/Lib/test/test_fileio.py +@@ -10,10 +10,9 @@ + from weakref import proxy + from functools import wraps + from UserList import UserList +-import _testcapi + + from test.test_support import TESTFN, check_warnings, run_unittest, make_bad_fd +-from test.test_support import py3k_bytes as bytes ++from test.test_support import py3k_bytes as bytes, cpython_only + from test.script_helper import run_python + + from _io import FileIO as _FileIO +@@ -283,28 +282,29 @@ + self.assertEqual(f.seekable(), True) + self.assertEqual(f.isatty(), False) + f.close() +- +- if sys.platform != "win32": +- try: +- f = _FileIO("/dev/tty", "a") +- except EnvironmentError: +- # When run in a cron job there just aren't any +- # ttys, so skip the test. This also handles other +- # OS'es that don't support /dev/tty. +- pass +- else: +- self.assertEqual(f.readable(), False) +- self.assertEqual(f.writable(), True) +- if sys.platform != "darwin" and \ +- 'bsd' not in sys.platform and \ +- not sys.platform.startswith('sunos'): +- # Somehow /dev/tty appears seekable on some BSDs +- self.assertEqual(f.seekable(), False) +- self.assertEqual(f.isatty(), True) +- f.close() + finally: + os.unlink(TESTFN) + ++ @unittest.skipIf(sys.platform == 'win32', 'no ttys on Windows') ++ def testAblesOnTTY(self): ++ try: ++ f = _FileIO("/dev/tty", "a") ++ except EnvironmentError: ++ # When run in a cron job there just aren't any ++ # ttys, so skip the test. This also handles other ++ # OS'es that don't support /dev/tty. ++ self.skipTest('need /dev/tty') ++ else: ++ self.assertEqual(f.readable(), False) ++ self.assertEqual(f.writable(), True) ++ if sys.platform != "darwin" and \ ++ 'bsd' not in sys.platform and \ ++ not sys.platform.startswith('sunos'): ++ # Somehow /dev/tty appears seekable on some BSDs ++ self.assertEqual(f.seekable(), False) ++ self.assertEqual(f.isatty(), True) ++ f.close() ++ + def testInvalidModeStrings(self): + # check invalid mode strings + for mode in ("", "aU", "wU+", "rw", "rt"): +@@ -342,8 +342,7 @@ + try: + fn = TESTFN.encode("ascii") + except UnicodeEncodeError: +- # Skip test +- return ++ self.skipTest('could not encode %r to ascii' % TESTFN) + f = _FileIO(fn, "w") + try: + f.write(b"abc") +@@ -359,7 +358,11 @@ + if sys.platform == 'win32': + import msvcrt + self.assertRaises(IOError, msvcrt.get_osfhandle, make_bad_fd()) ++ ++ @cpython_only ++ def testInvalidFd_overflow(self): + # Issue 15989 ++ import _testcapi + self.assertRaises(TypeError, _FileIO, _testcapi.INT_MAX + 1) + self.assertRaises(TypeError, _FileIO, _testcapi.INT_MIN - 1) + +diff -r 3a1db0d2747e Lib/test/test_float.py +--- a/Lib/test/test_float.py ++++ b/Lib/test/test_float.py +@@ -101,7 +101,7 @@ + # it still has to accept the normal python syntax + import locale + if not locale.localeconv()['decimal_point'] == ',': +- return ++ self.skipTest('decimal_point is not ","') + + self.assertEqual(float(" 3.14 "), 3.14) + self.assertEqual(float("+3.14 "), 3.14) +diff -r 3a1db0d2747e Lib/test/test_format.py +--- a/Lib/test/test_format.py ++++ b/Lib/test/test_format.py +@@ -303,21 +303,31 @@ + test_support.run_unittest(FormatTest) + + def test_precision(self): +- INT_MAX = 2147483647 +- + f = 1.2 + self.assertEqual(format(f, ".0f"), "1") + self.assertEqual(format(f, ".3f"), "1.200") + with self.assertRaises(ValueError) as cm: +- format(f, ".%sf" % (INT_MAX + 1)) ++ format(f, ".%sf" % (sys.maxsize + 1)) + self.assertEqual(str(cm.exception), "precision too big") + + c = complex(f) +- self.assertEqual(format(f, ".0f"), "1") +- self.assertEqual(format(f, ".3f"), "1.200") ++ self.assertEqual(format(c, ".0f"), "1+0j") ++ self.assertEqual(format(c, ".3f"), "1.200+0.000j") ++ with self.assertRaises(ValueError) as cm: ++ format(c, ".%sf" % (sys.maxsize + 1)) ++ self.assertEqual(str(cm.exception), "precision too big") ++ ++ @test_support.cpython_only ++ def test_precision_c_limits(self): ++ from _testcapi import INT_MAX ++ ++ f = 1.2 + with self.assertRaises(ValueError) as cm: + format(f, ".%sf" % (INT_MAX + 1)) +- self.assertEqual(str(cm.exception), "precision too big") ++ ++ c = complex(f) ++ with self.assertRaises(ValueError) as cm: ++ format(c, ".%sf" % (INT_MAX + 1)) + + + if __name__ == "__main__": +diff -r 3a1db0d2747e Lib/test/test_ftplib.py +--- a/Lib/test/test_ftplib.py ++++ b/Lib/test/test_ftplib.py +@@ -15,7 +15,7 @@ + except ImportError: + ssl = None + +-from unittest import TestCase ++from unittest import TestCase, SkipTest, skipUnless + from test import test_support + from test.test_support import HOST, HOSTv6 + threading = test_support.import_module('threading') +@@ -579,8 +579,16 @@ + self.assertRaises(ftplib.Error, self.client.storlines, 'stor', f) + + ++@skipUnless(socket.has_ipv6, "IPv6 not enabled") + class TestIPv6Environment(TestCase): + ++ @classmethod ++ def setUpClass(cls): ++ try: ++ DummyFTPServer((HOST, 0), af=socket.AF_INET6) ++ except socket.error: ++ raise SkipTest("IPv6 not enabled") ++ + def setUp(self): + self.server = DummyFTPServer((HOSTv6, 0), af=socket.AF_INET6) + self.server.start() +@@ -615,6 +623,7 @@ + retr() + + ++@skipUnless(ssl, "SSL not available") + class TestTLS_FTPClassMixin(TestFTPClass): + """Repeat TestFTPClass tests starting the TLS layer for both control + and data connections first. +@@ -630,6 +639,7 @@ + self.client.prot_p() + + ++@skipUnless(ssl, "SSL not available") + class TestTLS_FTPClass(TestCase): + """Specific TLS_FTP class tests.""" + +@@ -730,7 +740,7 @@ + + def testTimeoutDefault(self): + # default -- use global socket timeout +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + socket.setdefaulttimeout(30) + try: + ftp = ftplib.FTP(HOST) +@@ -742,13 +752,13 @@ + + def testTimeoutNone(self): + # no timeout -- do not use global socket timeout +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + socket.setdefaulttimeout(30) + try: + ftp = ftplib.FTP(HOST, timeout=None) + finally: + socket.setdefaulttimeout(None) +- self.assertTrue(ftp.sock.gettimeout() is None) ++ self.assertIsNone(ftp.sock.gettimeout()) + self.evt.wait() + ftp.close() + +@@ -783,17 +793,9 @@ + + + def test_main(): +- tests = [TestFTPClass, TestTimeouts] +- if socket.has_ipv6: +- try: +- DummyFTPServer((HOST, 0), af=socket.AF_INET6) +- except socket.error: +- pass +- else: +- tests.append(TestIPv6Environment) +- +- if ssl is not None: +- tests.extend([TestTLS_FTPClassMixin, TestTLS_FTPClass]) ++ tests = [TestFTPClass, TestTimeouts, ++ TestIPv6Environment, ++ TestTLS_FTPClassMixin, TestTLS_FTPClass] + + thread_info = test_support.threading_setup() + try: +diff -r 3a1db0d2747e Lib/test/test_functools.py +--- a/Lib/test/test_functools.py ++++ b/Lib/test/test_functools.py +@@ -43,8 +43,6 @@ + self.assertEqual(p.args, (1, 2)) + self.assertEqual(p.keywords, dict(a=10, b=20)) + # attributes should not be writable +- if not isinstance(self.thetype, type): +- return + self.assertRaises(TypeError, setattr, p, 'func', map) + self.assertRaises(TypeError, setattr, p, 'args', (1, 2)) + self.assertRaises(TypeError, setattr, p, 'keywords', dict(a=1, b=2)) +@@ -180,8 +178,10 @@ + thetype = PythonPartial + + # the python version isn't picklable +- def test_pickle(self): pass +- def test_setstate_refcount(self): pass ++ test_pickle = test_setstate_refcount = None ++ ++ # the python version isn't a type ++ test_attributes = None + + class TestUpdateWrapper(unittest.TestCase): + +diff -r 3a1db0d2747e Lib/test/test_gdb.py +--- a/Lib/test/test_gdb.py ++++ b/Lib/test/test_gdb.py +@@ -49,7 +49,7 @@ + return out, err + + # Verify that "gdb" was built with the embedded python support enabled: +-gdbpy_version, _ = run_gdb("--eval-command=python import sys; print sys.version_info") ++gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)") + if not gdbpy_version: + raise unittest.SkipTest("gdb not built with embedded python support") + +@@ -214,7 +214,7 @@ + # matches repr(value) in this process: + gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val), + cmds_after_breakpoint) +- self.assertEqual(gdb_repr, repr(val), gdb_output) ++ self.assertEqual(gdb_repr, repr(val)) + + def test_int(self): + 'Verify the pretty-printing of various "int" values' +diff -r 3a1db0d2747e Lib/test/test_genericpath.py +--- a/Lib/test/test_genericpath.py ++++ b/Lib/test/test_genericpath.py +@@ -199,13 +199,40 @@ + self.assertEqual(expandvars("$[foo]bar"), "$[foo]bar") + self.assertEqual(expandvars("$bar bar"), "$bar bar") + self.assertEqual(expandvars("$?bar"), "$?bar") +- self.assertEqual(expandvars("${foo}bar"), "barbar") + self.assertEqual(expandvars("$foo}bar"), "bar}bar") + self.assertEqual(expandvars("${foo"), "${foo") + self.assertEqual(expandvars("${{foo}}"), "baz1}") + self.assertEqual(expandvars("$foo$foo"), "barbar") + self.assertEqual(expandvars("$bar$bar"), "$bar$bar") + ++ @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII') ++ def test_expandvars_nonascii(self): ++ if self.pathmodule.__name__ == 'macpath': ++ self.skipTest('macpath.expandvars is a stub') ++ expandvars = self.pathmodule.expandvars ++ def check(value, expected): ++ self.assertEqual(expandvars(value), expected) ++ encoding = sys.getfilesystemencoding() ++ with test_support.EnvironmentVarGuard() as env: ++ env.clear() ++ unonascii = test_support.FS_NONASCII ++ snonascii = unonascii.encode(encoding) ++ env['spam'] = snonascii ++ env[snonascii] = 'ham' + snonascii ++ check(snonascii, snonascii) ++ check('$spam bar', '%s bar' % snonascii) ++ check('${spam}bar', '%sbar' % snonascii) ++ check('${%s}bar' % snonascii, 'ham%sbar' % snonascii) ++ check('$bar%s bar' % snonascii, '$bar%s bar' % snonascii) ++ check('$spam}bar', '%s}bar' % snonascii) ++ ++ check(unonascii, unonascii) ++ check(u'$spam bar', u'%s bar' % unonascii) ++ check(u'${spam}bar', u'%sbar' % unonascii) ++ check(u'${%s}bar' % unonascii, u'ham%sbar' % unonascii) ++ check(u'$bar%s bar' % unonascii, u'$bar%s bar' % unonascii) ++ check(u'$spam}bar', u'%s}bar' % unonascii) ++ + def test_abspath(self): + self.assertIn("foo", self.pathmodule.abspath("foo")) + +diff -r 3a1db0d2747e Lib/test/test_getargs2.py +--- a/Lib/test/test_getargs2.py ++++ b/Lib/test/test_getargs2.py +@@ -1,5 +1,7 @@ + import unittest + from test import test_support ++# Skip this test if the _testcapi module isn't available. ++test_support.import_module('_testcapi') + from _testcapi import getargs_keywords + import warnings + +@@ -42,6 +44,13 @@ + INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, \ + SHRT_MIN, SHRT_MAX + ++try: ++ from _testcapi import getargs_L, getargs_K ++except ImportError: ++ _PY_LONG_LONG_available = False ++else: ++ _PY_LONG_LONG_available = True ++ + # fake, they are not defined in Python's header files + LLONG_MAX = 2**63-1 + LLONG_MIN = -2**63 +@@ -208,6 +217,7 @@ + self.assertRaises(OverflowError, getargs_n, VERY_LARGE) + + ++@unittest.skipUnless(_PY_LONG_LONG_available, 'PY_LONG_LONG not available') + class LongLong_TestCase(unittest.TestCase): + def test_L(self): + from _testcapi import getargs_L +@@ -322,13 +332,8 @@ + self.fail('TypeError should have been raised') + + def test_main(): +- tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase, Keywords_TestCase] +- try: +- from _testcapi import getargs_L, getargs_K +- except ImportError: +- pass # PY_LONG_LONG not available +- else: +- tests.append(LongLong_TestCase) ++ tests = [Signed_TestCase, Unsigned_TestCase, LongLong_TestCase, ++ Tuple_TestCase, Keywords_TestCase] + test_support.run_unittest(*tests) + + if __name__ == "__main__": +diff -r 3a1db0d2747e Lib/test/test_gl.py +--- a/Lib/test/test_gl.py ++++ b/Lib/test/test_gl.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Very simple test script for the SGI gl library extension module + taken mostly from the documentation. + Roger E. Masse +diff -r 3a1db0d2747e Lib/test/test_grp.py +--- a/Lib/test/test_grp.py ++++ b/Lib/test/test_grp.py +@@ -26,8 +26,10 @@ + for e in entries: + self.check_value(e) + ++ def test_values_extended(self): ++ entries = grp.getgrall() + if len(entries) > 1000: # Huge group file (NIS?) -- skip the rest +- return ++ self.skipTest('huge group file, extended test skipped') + + for e in entries: + e2 = grp.getgrgid(e.gr_gid) +diff -r 3a1db0d2747e Lib/test/test_gzip.py +--- a/Lib/test/test_gzip.py ++++ b/Lib/test/test_gzip.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for the gzip module. + """ + +diff -r 3a1db0d2747e Lib/test/test_hashlib.py +--- a/Lib/test/test_hashlib.py ++++ b/Lib/test/test_hashlib.py +@@ -207,30 +207,20 @@ + self.check('md5', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', + 'd174ab98d277d9f5a5611c2c9f419d9f') + +- @precisionbigmemtest(size=_4G + 5, memuse=1) ++ @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems') ++ @precisionbigmemtest(size=_4G + 5, memuse=1, dry_run=False) + def test_case_md5_huge(self, size): +- if size == _4G + 5: +- try: +- self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d') +- except OverflowError: +- pass # 32-bit arch ++ self.check('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d') + +- @precisionbigmemtest(size=_4G + 5, memuse=1) ++ @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems') ++ @precisionbigmemtest(size=_4G + 5, memuse=1, dry_run=False) + def test_case_md5_huge_update(self, size): +- if size == _4G + 5: +- try: +- self.check_update('md5', 'A'*size, +- 'c9af2dff37468ce5dfee8f2cfc0a9c6d') +- except OverflowError: +- pass # 32-bit arch ++ self.check_update('md5', 'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d') + +- @precisionbigmemtest(size=_4G - 1, memuse=1) ++ @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems') ++ @precisionbigmemtest(size=_4G - 1, memuse=1, dry_run=False) + def test_case_md5_uintmax(self, size): +- if size == _4G - 1: +- try: +- self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3') +- except OverflowError: +- pass # 32-bit arch ++ self.check('md5', 'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3') + + # use the three examples from Federal Information Processing Standards + # Publication 180-1, Secure Hash Standard, 1995 April 17 +diff -r 3a1db0d2747e Lib/test/test_htmlparser.py +--- a/Lib/test/test_htmlparser.py ++++ b/Lib/test/test_htmlparser.py +@@ -206,8 +206,7 @@ + self._run_check("", [('comment', '$')]) + self._run_check("", [('data', '", [('starttag', 'a", [('endtag', 'a'", [('data', "", [('starttag', 'a$b', [])]) ++ self._run_check("", [('startendtag', 'a$b', [])]) ++ self._run_check("", [('starttag', 'a$b', [])]) ++ self._run_check("", [('startendtag', 'a$b', [])]) + + def test_valid_doctypes(self): + # from http://www.w3.org/QA/2002/04/valid-dtd-list.html +@@ -390,6 +394,12 @@ + ("data", "&#bad;"), + ("endtag", "p"), + ]) ++ # add the [] as a workaround to avoid buffering (see #20288) ++ self._run_check(["

&#bad;
"], [ ++ ("starttag", "div", []), ++ ("data", "&#bad;"), ++ ("endtag", "div"), ++ ]) + + def test_unescape_function(self): + parser = HTMLParser.HTMLParser() +diff -r 3a1db0d2747e Lib/test/test_httplib.py +--- a/Lib/test/test_httplib.py ++++ b/Lib/test/test_httplib.py +@@ -123,7 +123,7 @@ + conn.sock = FakeSocket(None) + conn.putrequest('GET','/') + conn.putheader('Content-length',42) +- self.assertTrue('Content-length: 42' in conn._buffer) ++ self.assertIn('Content-length: 42', conn._buffer) + + def test_ipv6host_header(self): + # Default host header on IPv6 transaction should wrapped by [] if +@@ -153,6 +153,8 @@ + sock = FakeSocket(body) + resp = httplib.HTTPResponse(sock) + resp.begin() ++ self.assertEqual(resp.read(0), '') # Issue #20007 ++ self.assertFalse(resp.isclosed()) + self.assertEqual(resp.read(), 'Text') + self.assertTrue(resp.isclosed()) + +@@ -464,7 +466,7 @@ + HTTPConnection and into the socket. + ''' + # default -- use global socket timeout +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + socket.setdefaulttimeout(30) + try: + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT) +@@ -475,7 +477,7 @@ + httpConn.close() + + # no timeout -- do not use global socket default +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + socket.setdefaulttimeout(30) + try: + httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, +diff -r 3a1db0d2747e Lib/test/test_httpservers.py +--- a/Lib/test/test_httpservers.py ++++ b/Lib/test/test_httpservers.py +@@ -114,7 +114,7 @@ + + def verify_http_server_response(self, response): + match = self.HTTPResponseMatch.search(response) +- self.assertTrue(match is not None) ++ self.assertIsNotNone(match) + + def test_http_1_1(self): + result = self.send_typical_request('GET / HTTP/1.1\r\n\r\n') +diff -r 3a1db0d2747e Lib/test/test_idle.py +--- a/Lib/test/test_idle.py ++++ b/Lib/test/test_idle.py +@@ -14,6 +14,7 @@ + try: + root = tk.Tk() + root.destroy() ++ del root + except tk.TclError: + while 'gui' in use_resources: + use_resources.remove('gui') +@@ -23,6 +24,10 @@ + # load_tests() if it finds it. (Unittest.main does the same.) + load_tests = idletest.load_tests + ++# pre-3.3 regrtest does not support the load_tests protocol. use test_main ++def test_main(): ++ support.run_unittest(unittest.TestLoader().loadTestsFromModule(idletest)) ++ + if __name__ == '__main__': + # Until unittest supports resources, we emulate regrtest's -ugui + # so loaded tests run the same as if textually present here. +diff -r 3a1db0d2747e Lib/test/test_imageop.py +--- a/Lib/test/test_imageop.py ++++ b/Lib/test/test_imageop.py +@@ -1,5 +1,3 @@ +-#! /usr/bin/env python +- + """Test script for the imageop module. This has the side + effect of partially testing the imgfile module as well. + Roger E. Masse +diff -r 3a1db0d2747e Lib/test/test_imaplib.py +--- a/Lib/test/test_imaplib.py ++++ b/Lib/test/test_imaplib.py +@@ -165,6 +165,16 @@ + self.imap_class, *server.server_address) + + ++ def test_linetoolong(self): ++ class TooLongHandler(SimpleIMAPHandler): ++ def handle(self): ++ # Send a very long response line ++ self.wfile.write('* OK ' + imaplib._MAXLINE*'x' + '\r\n') ++ ++ with self.reaped_server(TooLongHandler) as server: ++ self.assertRaises(imaplib.IMAP4.error, ++ self.imap_class, *server.server_address) ++ + class ThreadedNetworkedTests(BaseThreadedNetworkedTests): + + server_class = SocketServer.TCPServer +@@ -177,6 +187,9 @@ + server_class = SecureTCPServer + imap_class = IMAP4_SSL + ++ def test_linetoolong(self): ++ raise unittest.SkipTest("test is not reliable on 2.7; see issue 20118") ++ + + class RemoteIMAPTest(unittest.TestCase): + host = 'cyrus.andrew.cmu.edu' +diff -r 3a1db0d2747e Lib/test/test_imgfile.py +--- a/Lib/test/test_imgfile.py ++++ b/Lib/test/test_imgfile.py +@@ -1,5 +1,3 @@ +-#! /usr/bin/env python +- + """Simple test script for imgfile.c + Roger E. Masse + """ +diff -r 3a1db0d2747e Lib/test/test_imghdr.py +--- /dev/null ++++ b/Lib/test/test_imghdr.py +@@ -0,0 +1,120 @@ ++import imghdr ++import io ++import sys ++import unittest ++from test.test_support import findfile, TESTFN, unlink, run_unittest ++ ++TEST_FILES = ( ++ ('python.png', 'png'), ++ ('python.gif', 'gif'), ++ ('python.bmp', 'bmp'), ++ ('python.ppm', 'ppm'), ++ ('python.pgm', 'pgm'), ++ ('python.pbm', 'pbm'), ++ ('python.jpg', 'jpeg'), ++ ('python.ras', 'rast'), ++ ('python.sgi', 'rgb'), ++ ('python.tiff', 'tiff'), ++ ('python.xbm', 'xbm') ++) ++ ++class UnseekableIO(io.FileIO): ++ def tell(self): ++ raise io.UnsupportedOperation ++ ++ def seek(self, *args, **kwargs): ++ raise io.UnsupportedOperation ++ ++class TestImghdr(unittest.TestCase): ++ @classmethod ++ def setUpClass(cls): ++ cls.testfile = findfile('python.png', subdir='imghdrdata') ++ with open(cls.testfile, 'rb') as stream: ++ cls.testdata = stream.read() ++ ++ def tearDown(self): ++ unlink(TESTFN) ++ ++ def test_data(self): ++ for filename, expected in TEST_FILES: ++ filename = findfile(filename, subdir='imghdrdata') ++ self.assertEqual(imghdr.what(filename), expected) ++ ufilename = filename.decode(sys.getfilesystemencoding()) ++ self.assertEqual(imghdr.what(ufilename), expected) ++ with open(filename, 'rb') as stream: ++ self.assertEqual(imghdr.what(stream), expected) ++ with open(filename, 'rb') as stream: ++ data = stream.read() ++ self.assertEqual(imghdr.what(None, data), expected) ++ ++ def test_register_test(self): ++ def test_jumbo(h, file): ++ if h.startswith(b'eggs'): ++ return 'ham' ++ imghdr.tests.append(test_jumbo) ++ self.addCleanup(imghdr.tests.pop) ++ self.assertEqual(imghdr.what(None, b'eggs'), 'ham') ++ ++ def test_file_pos(self): ++ with open(TESTFN, 'wb') as stream: ++ stream.write(b'ababagalamaga') ++ pos = stream.tell() ++ stream.write(self.testdata) ++ with open(TESTFN, 'rb') as stream: ++ stream.seek(pos) ++ self.assertEqual(imghdr.what(stream), 'png') ++ self.assertEqual(stream.tell(), pos) ++ ++ def test_bad_args(self): ++ with self.assertRaises(TypeError): ++ imghdr.what() ++ with self.assertRaises(AttributeError): ++ imghdr.what(None) ++ with self.assertRaises(TypeError): ++ imghdr.what(self.testfile, 1) ++ with open(self.testfile, 'rb') as f: ++ with self.assertRaises(AttributeError): ++ imghdr.what(f.fileno()) ++ ++ def test_invalid_headers(self): ++ for header in (b'\211PN\r\n', ++ b'\001\331', ++ b'\x59\xA6', ++ b'cutecat', ++ b'000000JFI', ++ b'GIF80'): ++ self.assertIsNone(imghdr.what(None, header)) ++ ++ def test_missing_file(self): ++ with self.assertRaises(IOError): ++ imghdr.what('missing') ++ ++ def test_closed_file(self): ++ stream = open(self.testfile, 'rb') ++ stream.close() ++ with self.assertRaises(ValueError) as cm: ++ imghdr.what(stream) ++ stream = io.BytesIO(self.testdata) ++ stream.close() ++ with self.assertRaises(ValueError) as cm: ++ imghdr.what(stream) ++ ++ def test_unseekable(self): ++ with open(TESTFN, 'wb') as stream: ++ stream.write(self.testdata) ++ with UnseekableIO(TESTFN, 'rb') as stream: ++ with self.assertRaises(io.UnsupportedOperation): ++ imghdr.what(stream) ++ ++ def test_output_stream(self): ++ with open(TESTFN, 'wb') as stream: ++ stream.write(self.testdata) ++ stream.seek(0) ++ with self.assertRaises(IOError) as cm: ++ imghdr.what(stream) ++ ++def test_main(): ++ run_unittest(TestImghdr) ++ ++if __name__ == '__main__': ++ test_main() +diff -r 3a1db0d2747e Lib/test/test_imp.py +--- a/Lib/test/test_imp.py ++++ b/Lib/test/test_imp.py +@@ -2,7 +2,12 @@ + import unittest + from test import test_support + ++try: ++ import thread ++except ImportError: ++ thread = None + ++@unittest.skipUnless(thread, 'threading not available') + class LockTests(unittest.TestCase): + + """Very basic test of import lock functions.""" +@@ -68,13 +73,8 @@ + def test_main(): + tests = [ + ReloadTests, ++ LockTests, + ] +- try: +- import thread +- except ImportError: +- pass +- else: +- tests.append(LockTests) + test_support.run_unittest(*tests) + + if __name__ == "__main__": +diff -r 3a1db0d2747e Lib/test/test_index.py +--- a/Lib/test/test_index.py ++++ b/Lib/test/test_index.py +@@ -91,7 +91,7 @@ + self.assertEqual(self.seq[self.o:self.o2], self.seq[1:3]) + self.assertEqual(self.seq[self.n:self.n2], self.seq[2:4]) + +- def test_slice_bug7532(self): ++ def test_slice_bug7532a(self): + seqlen = len(self.seq) + self.o.ind = int(seqlen * 1.5) + self.n.ind = seqlen + 2 +@@ -99,9 +99,12 @@ + self.assertEqual(self.seq[:self.o], self.seq) + self.assertEqual(self.seq[self.n:], self.seq[0:0]) + self.assertEqual(self.seq[:self.n], self.seq) ++ ++ def test_slice_bug7532b(self): + if isinstance(self.seq, ClassicSeq): +- return ++ self.skipTest('test fails for ClassicSeq') + # These tests fail for ClassicSeq (see bug #7532) ++ seqlen = len(self.seq) + self.o2.ind = -seqlen - 2 + self.n2.ind = -int(seqlen * 1.5) + self.assertEqual(self.seq[self.o2:], self.seq) +diff -r 3a1db0d2747e Lib/test/test_io.py +--- a/Lib/test/test_io.py ++++ b/Lib/test/test_io.py +@@ -393,14 +393,9 @@ + # a long time to build the >2GB file and takes >2GB of disk space + # therefore the resource must be enabled to run this test. + if sys.platform[:3] == 'win' or sys.platform == 'darwin': +- if not support.is_resource_enabled("largefile"): +- print("\nTesting large file ops skipped on %s." % sys.platform, +- file=sys.stderr) +- print("It requires %d bytes and a long time." % self.LARGE, +- file=sys.stderr) +- print("Use 'regrtest.py -u largefile test_io' to run it.", +- file=sys.stderr) +- return ++ support.requires( ++ 'largefile', ++ 'test requires %s bytes and a long time to run' % self.LARGE) + with self.open(support.TESTFN, "w+b", 0) as f: + self.large_file_ops(f) + with self.open(support.TESTFN, "w+b") as f: +@@ -650,6 +645,7 @@ + + self.assertEqual(42, bufio.fileno()) + ++ @unittest.skip('test having existential crisis') + def test_no_fileno(self): + # XXX will we always have fileno() function? If so, kill + # this test. Else, write it. +@@ -797,6 +793,16 @@ + bufio.__init__(rawio) + self.assertEqual(b"abc", bufio.read()) + ++ def test_uninitialized(self): ++ bufio = self.tp.__new__(self.tp) ++ del bufio ++ bufio = self.tp.__new__(self.tp) ++ self.assertRaisesRegexp((ValueError, AttributeError), ++ 'uninitialized|has no attribute', ++ bufio.read, 0) ++ bufio.__init__(self.MockRawIO()) ++ self.assertEqual(bufio.read(0), b'') ++ + def test_read(self): + for arg in (None, 7): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) +@@ -1033,6 +1039,16 @@ + bufio.flush() + self.assertEqual(b"".join(rawio._write_stack), b"abcghi") + ++ def test_uninitialized(self): ++ bufio = self.tp.__new__(self.tp) ++ del bufio ++ bufio = self.tp.__new__(self.tp) ++ self.assertRaisesRegexp((ValueError, AttributeError), ++ 'uninitialized|has no attribute', ++ bufio.write, b'') ++ bufio.__init__(self.MockRawIO()) ++ self.assertEqual(bufio.write(b''), 0) ++ + def test_detach_flush(self): + raw = self.MockRawIO() + buf = self.tp(raw) +@@ -1317,6 +1333,20 @@ + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertFalse(pair.closed) + ++ def test_uninitialized(self): ++ pair = self.tp.__new__(self.tp) ++ del pair ++ pair = self.tp.__new__(self.tp) ++ self.assertRaisesRegexp((ValueError, AttributeError), ++ 'uninitialized|has no attribute', ++ pair.read, 0) ++ self.assertRaisesRegexp((ValueError, AttributeError), ++ 'uninitialized|has no attribute', ++ pair.write, b'') ++ pair.__init__(self.MockRawIO(), self.MockRawIO()) ++ self.assertEqual(pair.read(0), b'') ++ self.assertEqual(pair.write(b''), 0) ++ + def test_detach(self): + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertRaises(self.UnsupportedOperation, pair.detach) +@@ -1444,6 +1474,10 @@ + BufferedReaderTest.test_constructor(self) + BufferedWriterTest.test_constructor(self) + ++ def test_uninitialized(self): ++ BufferedReaderTest.test_uninitialized(self) ++ BufferedWriterTest.test_uninitialized(self) ++ + def test_read_and_write(self): + raw = self.MockRawIO((b"asdf", b"ghjk")) + rw = self.tp(raw, 8) +diff -r 3a1db0d2747e Lib/test/test_iter.py +--- a/Lib/test/test_iter.py ++++ b/Lib/test/test_iter.py +@@ -526,7 +526,7 @@ + d = {"one": 1, "two": 2, "three": 3} + self.assertEqual(reduce(add, d), "".join(d.keys())) + +- # This test case will be removed if we don't have Unicode ++ @unittest.skipUnless(have_unicode, 'needs unicode support') + def test_unicode_join_endcase(self): + + # This class inserts a Unicode object into its argument's natural +@@ -567,8 +567,6 @@ + unlink(TESTFN) + except OSError: + pass +- if not have_unicode: +- def test_unicode_join_endcase(self): pass + + # Test iterators with 'x in y' and 'x not in y'. + def test_in_and_not_in(self): +diff -r 3a1db0d2747e Lib/test/test_locale.py +--- a/Lib/test/test_locale.py ++++ b/Lib/test/test_locale.py +@@ -372,6 +372,77 @@ + self.assertEqual('\xec\xa0\xbc'.split(), ['\xec\xa0\xbc']) + + ++class NormalizeTest(unittest.TestCase): ++ def check(self, localename, expected): ++ self.assertEqual(locale.normalize(localename), expected, msg=localename) ++ ++ def test_locale_alias(self): ++ for localename, alias in locale.locale_alias.items(): ++ self.check(localename, alias) ++ ++ def test_empty(self): ++ self.check('', '') ++ ++ def test_c(self): ++ self.check('c', 'C') ++ self.check('posix', 'C') ++ ++ def test_english(self): ++ self.check('en', 'en_US.ISO8859-1') ++ self.check('EN', 'en_US.ISO8859-1') ++ self.check('en_US', 'en_US.ISO8859-1') ++ self.check('en_us', 'en_US.ISO8859-1') ++ self.check('en_GB', 'en_GB.ISO8859-1') ++ self.check('en_US.UTF-8', 'en_US.UTF-8') ++ self.check('en_US.utf8', 'en_US.UTF-8') ++ self.check('en_US:UTF-8', 'en_US.UTF-8') ++ self.check('en_US.ISO8859-1', 'en_US.ISO8859-1') ++ self.check('en_US.US-ASCII', 'en_US.ISO8859-1') ++ self.check('english', 'en_EN.ISO8859-1') ++ ++ def test_hyphenated_encoding(self): ++ self.check('az_AZ.iso88599e', 'az_AZ.ISO8859-9E') ++ self.check('az_AZ.ISO8859-9E', 'az_AZ.ISO8859-9E') ++ self.check('tt_RU.koi8c', 'tt_RU.KOI8-C') ++ self.check('tt_RU.KOI8-C', 'tt_RU.KOI8-C') ++ self.check('lo_LA.cp1133', 'lo_LA.IBM-CP1133') ++ self.check('lo_LA.ibmcp1133', 'lo_LA.IBM-CP1133') ++ self.check('lo_LA.IBM-CP1133', 'lo_LA.IBM-CP1133') ++ self.check('uk_ua.microsoftcp1251', 'uk_UA.CP1251') ++ self.check('uk_ua.microsoft-cp1251', 'uk_UA.CP1251') ++ self.check('ka_ge.georgianacademy', 'ka_GE.GEORGIAN-ACADEMY') ++ self.check('ka_GE.GEORGIAN-ACADEMY', 'ka_GE.GEORGIAN-ACADEMY') ++ self.check('cs_CZ.iso88592', 'cs_CZ.ISO8859-2') ++ self.check('cs_CZ.ISO8859-2', 'cs_CZ.ISO8859-2') ++ ++ def test_euro_modifier(self): ++ self.check('de_DE@euro', 'de_DE.ISO8859-15') ++ self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15') ++ ++ def test_latin_modifier(self): ++ self.check('be_BY.UTF-8@latin', 'be_BY.UTF-8@latin') ++ self.check('sr_RS.UTF-8@latin', 'sr_RS.UTF-8@latin') ++ ++ def test_valencia_modifier(self): ++ self.check('ca_ES.UTF-8@valencia', 'ca_ES.UTF-8@valencia') ++ self.check('ca_ES@valencia', 'ca_ES.ISO8859-1@valencia') ++ self.check('ca@valencia', 'ca_ES.ISO8859-1@valencia') ++ ++ def test_devanagari_modifier(self): ++ self.check('ks_IN.UTF-8@devanagari', 'ks_IN.UTF-8@devanagari') ++ self.check('ks_IN@devanagari', 'ks_IN.UTF-8@devanagari') ++ self.check('ks@devanagari', 'ks_IN.UTF-8@devanagari') ++ self.check('ks_IN.UTF-8', 'ks_IN.UTF-8') ++ self.check('ks_IN', 'ks_IN.UTF-8') ++ self.check('ks', 'ks_IN.UTF-8') ++ self.check('sd_IN.UTF-8@devanagari', 'sd_IN.UTF-8@devanagari') ++ self.check('sd_IN@devanagari', 'sd_IN.UTF-8@devanagari') ++ self.check('sd@devanagari', 'sd_IN.UTF-8@devanagari') ++ self.check('sd_IN.UTF-8', 'sd_IN.UTF-8') ++ self.check('sd_IN', 'sd_IN.UTF-8') ++ self.check('sd', 'sd_IN.UTF-8') ++ ++ + class TestMiscellaneous(unittest.TestCase): + def test_getpreferredencoding(self): + # Invoke getpreferredencoding to make sure it does not cause exceptions. +@@ -400,13 +471,21 @@ + # Issue #1813: setting and getting the locale under a Turkish locale + oldlocale = locale.getlocale() + self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) +- try: +- locale.setlocale(locale.LC_CTYPE, 'tr_TR') +- except locale.Error: ++ for loc in ('tr_TR', 'tr_TR.UTF-8', 'tr_TR.ISO8859-9'): ++ try: ++ locale.setlocale(locale.LC_CTYPE, loc) ++ break ++ except locale.Error: ++ continue ++ else: + # Unsupported locale on this system + self.skipTest('test needs Turkish locale') + loc = locale.getlocale() +- locale.setlocale(locale.LC_CTYPE, loc) ++ try: ++ locale.setlocale(locale.LC_CTYPE, loc) ++ except Exception as e: ++ self.fail("Failed to set locale %r (default locale is %r): %r" % ++ (loc, oldlocale, e)) + self.assertEqual(loc, locale.getlocale()) + + def test_normalize_issue12752(self): +diff -r 3a1db0d2747e Lib/test/test_logging.py +--- a/Lib/test/test_logging.py ++++ b/Lib/test/test_logging.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +-# + # Copyright 2001-2013 by Vinay Sajip. All Rights Reserved. + # + # Permission to use, copy, modify, and distribute this software and its +diff -r 3a1db0d2747e Lib/test/test_long.py +--- a/Lib/test/test_long.py ++++ b/Lib/test/test_long.py +@@ -90,7 +90,7 @@ + # The sign of the number is also random. + + def getran(self, ndigits): +- self.assertTrue(ndigits > 0) ++ self.assertGreater(ndigits, 0) + nbits_hi = ndigits * SHIFT + nbits_lo = nbits_hi - SHIFT + 1 + answer = 0L +@@ -588,7 +588,7 @@ + pass + x = long2(1L<<100) + y = int(x) +- self.assertTrue(type(y) is long, ++ self.assertIs(type(y), long, + "overflowing int conversion must return long not long subtype") + + # long -> Py_ssize_t conversion +diff -r 3a1db0d2747e Lib/test/test_macos.py +--- a/Lib/test/test_macos.py ++++ b/Lib/test/test_macos.py +@@ -8,11 +8,9 @@ + TESTFN2 = test_support.TESTFN + '2' + + class TestMacOS(unittest.TestCase): +- ++ @unittest.skipUnless(os.path.exists('/Developer/Tools/SetFile'), ++ '/Developer/Tools/SetFile does not exist') + def testGetCreatorAndType(self): +- if not os.path.exists('/Developer/Tools/SetFile'): +- return +- + try: + fp = open(test_support.TESTFN, 'w') + fp.write('\n') +@@ -29,10 +27,9 @@ + finally: + os.unlink(test_support.TESTFN) + ++ @unittest.skipUnless(os.path.exists('/Developer/Tools/GetFileInfo'), ++ '/Developer/Tools/GetFileInfo does not exist') + def testSetCreatorAndType(self): +- if not os.path.exists('/Developer/Tools/GetFileInfo'): +- return +- + try: + fp = open(test_support.TESTFN, 'w') + fp.write('\n') +diff -r 3a1db0d2747e Lib/test/test_macostools.py +--- a/Lib/test/test_macostools.py ++++ b/Lib/test/test_macostools.py +@@ -12,6 +12,8 @@ + + TESTFN2 = test_support.TESTFN + '2' + ++requires_32bit = unittest.skipUnless(sys.maxint < 2**32, '32-bit only test') ++ + class TestMacostools(unittest.TestCase): + + def setUp(self): +@@ -51,30 +53,32 @@ + DeprecationWarning), quiet=True): + macostools.touched(test_support.TESTFN) + +- if sys.maxint < 2**32: +- def test_copy(self): +- test_support.unlink(TESTFN2) +- macostools.copy(test_support.TESTFN, TESTFN2) +- self.assertEqual(self.compareData(), '') ++ @requires_32bit ++ def test_copy(self): ++ test_support.unlink(TESTFN2) ++ macostools.copy(test_support.TESTFN, TESTFN2) ++ self.assertEqual(self.compareData(), '') + +- if sys.maxint < 2**32: +- def test_mkalias(self): +- test_support.unlink(TESTFN2) +- macostools.mkalias(test_support.TESTFN, TESTFN2) +- fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) +- self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) ++ @requires_32bit ++ def test_mkalias(self): ++ test_support.unlink(TESTFN2) ++ macostools.mkalias(test_support.TESTFN, TESTFN2) ++ fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) ++ self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) + +- def test_mkalias_relative(self): +- test_support.unlink(TESTFN2) +- # If the directory doesn't exist, then chances are this is a new +- # install of Python so don't create it since the user might end up +- # running ``sudo make install`` and creating the directory here won't +- # leave it with the proper permissions. +- if not os.path.exists(sys.prefix): +- return +- macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) +- fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) +- self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) ++ @requires_32bit ++ # If the directory doesn't exist, then chances are this is a new ++ # install of Python so don't create it since the user might end up ++ # running ``sudo make install`` and creating the directory here won't ++ # leave it with the proper permissions. ++ @unittest.skipUnless(os.path.exists(sys.prefix), ++ "%r doesn't exist" % sys.prefix) ++ def test_mkalias_relative(self): ++ test_support.unlink(TESTFN2) ++ ++ macostools.mkalias(test_support.TESTFN, TESTFN2, sys.prefix) ++ fss, _, _ = Carbon.File.ResolveAliasFile(TESTFN2, 0) ++ self.assertEqual(fss.as_pathname(), os.path.realpath(test_support.TESTFN)) + + + def test_main(): +diff -r 3a1db0d2747e Lib/test/test_mailbox.py +--- a/Lib/test/test_mailbox.py ++++ b/Lib/test/test_mailbox.py +@@ -138,7 +138,7 @@ + msg = self._box.get(key0) + self.assertEqual(msg['from'], 'foo') + self.assertEqual(msg.get_payload(), '0\n') +- self.assertIs(self._box.get('foo'), None) ++ self.assertIsNone(self._box.get('foo')) + self.assertFalse(self._box.get('foo', False)) + self._box.close() + self._box = self._factory(self._path, factory=rfc822.Message) +@@ -249,8 +249,7 @@ + count = 0 + for value in returned_values: + self.assertEqual(value['from'], 'foo') +- self.assertTrue(int(value.get_payload()) < repetitions, +- (value.get_payload(), repetitions)) ++ self.assertLess(int(value.get_payload()), repetitions) + count += 1 + self.assertEqual(len(values), count) + +@@ -664,7 +663,7 @@ + "tmp")), + "File in wrong location: '%s'" % head) + match = pattern.match(tail) +- self.assertTrue(match is not None, "Invalid file name: '%s'" % tail) ++ self.assertIsNotNone(match, "Invalid file name: '%s'" % tail) + groups = match.groups() + if previous_groups is not None: + self.assertGreaterEqual(int(groups[0]), int(previous_groups[0]), +@@ -674,22 +673,22 @@ + self.assertGreaterEqual(int(groups[1]), int(previous_groups[1]), + "Non-monotonic milliseconds: '%s' before '%s'" % + (previous_groups[1], groups[1])) +- self.assertTrue(int(groups[2]) == pid, ++ self.assertEqual(int(groups[2]), pid, + "Process ID mismatch: '%s' should be '%s'" % + (groups[2], pid)) +- self.assertTrue(int(groups[3]) == int(previous_groups[3]) + 1, ++ self.assertEqual(int(groups[3]), int(previous_groups[3]) + 1, + "Non-sequential counter: '%s' before '%s'" % + (previous_groups[3], groups[3])) +- self.assertTrue(groups[4] == hostname, ++ self.assertEqual(groups[4], hostname, + "Host name mismatch: '%s' should be '%s'" % + (groups[4], hostname)) + previous_groups = groups + tmp_file.write(_sample_message) + tmp_file.seek(0) +- self.assertTrue(tmp_file.read() == _sample_message) ++ self.assertEqual(tmp_file.read(), _sample_message) + tmp_file.close() + file_count = len(os.listdir(os.path.join(self._path, "tmp"))) +- self.assertTrue(file_count == repetitions, ++ self.assertEqual(file_count, repetitions, + "Wrong file count: '%s' should be '%s'" % + (file_count, repetitions)) + +@@ -772,10 +771,10 @@ + for msg in self._box: + pass + ++ @unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()') ++ @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') + def test_file_permissions(self): + # Verify that message files are created without execute permissions +- if not hasattr(os, "stat") or not hasattr(os, "umask"): +- return + msg = mailbox.MaildirMessage(self._template % 0) + orig_umask = os.umask(0) + try: +@@ -786,12 +785,11 @@ + mode = os.stat(path).st_mode + self.assertEqual(mode & 0111, 0) + ++ @unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()') ++ @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') + def test_folder_file_perms(self): + # From bug #3228, we want to verify that the file created inside a Maildir + # subfolder isn't marked as executable. +- if not hasattr(os, "stat") or not hasattr(os, "umask"): +- return +- + orig_umask = os.umask(0) + try: + subfolder = self._box.add_folder('subfolder') +@@ -991,24 +989,25 @@ + + _factory = lambda self, path, factory=None: mailbox.mbox(path, factory) + ++ @unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()') ++ @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') + def test_file_perms(self): + # From bug #3228, we want to verify that the mailbox file isn't executable, + # even if the umask is set to something that would leave executable bits set. + # We only run this test on platforms that support umask. +- if hasattr(os, 'umask') and hasattr(os, 'stat'): +- try: +- old_umask = os.umask(0077) +- self._box.close() +- os.unlink(self._path) +- self._box = mailbox.mbox(self._path, create=True) +- self._box.add('') +- self._box.close() +- finally: +- os.umask(old_umask) ++ try: ++ old_umask = os.umask(0077) ++ self._box.close() ++ os.unlink(self._path) ++ self._box = mailbox.mbox(self._path, create=True) ++ self._box.add('') ++ self._box.close() ++ finally: ++ os.umask(old_umask) + +- st = os.stat(self._path) +- perms = st.st_mode +- self.assertFalse((perms & 0111)) # Execute bits should all be off. ++ st = os.stat(self._path) ++ perms = st.st_mode ++ self.assertFalse((perms & 0111)) # Execute bits should all be off. + + def test_terminating_newline(self): + message = email.message.Message() +@@ -1240,7 +1239,7 @@ + self.assertIsInstance(msg, self._factory) + self.assertEqual(msg.keys(), []) + self.assertFalse(msg.is_multipart()) +- self.assertEqual(msg.get_payload(), None) ++ self.assertIsNone(msg.get_payload()) + + def test_initialize_incorrectly(self): + # Initialize with invalid argument +@@ -1313,7 +1312,7 @@ + # Use get_date() and set_date() + msg = mailbox.MaildirMessage(_sample_message) + diff = msg.get_date() - time.time() +- self.assertTrue(abs(diff) < 60, diff) ++ self.assertLess(abs(diff), 60, diff) + msg.set_date(0.0) + self.assertEqual(msg.get_date(), 0.0) + +@@ -1388,8 +1387,9 @@ + # Check contents of "From " line + if sender is None: + sender = "MAILER-DAEMON" +- self.assertTrue(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:" +- r"\d{2} \d{4}", msg.get_from())) ++ self.assertIsNotNone(re.match( ++ sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:\d{2} \d{4}", ++ msg.get_from())) + + + class TestMboxMessage(_TestMboxMMDFMessage, TestMessage): +@@ -1463,7 +1463,7 @@ + msg = mailbox.BabylMessage(_sample_message) + visible = msg.get_visible() + self.assertEqual(visible.keys(), []) +- self.assertIs(visible.get_payload(), None) ++ self.assertIsNone(visible.get_payload()) + visible['User-Agent'] = 'FooBar 1.0' + visible['X-Whatever'] = 'Blah' + self.assertEqual(msg.get_visible().keys(), []) +@@ -1472,10 +1472,10 @@ + self.assertEqual(visible.keys(), ['User-Agent', 'X-Whatever']) + self.assertEqual(visible['User-Agent'], 'FooBar 1.0') + self.assertEqual(visible['X-Whatever'], 'Blah') +- self.assertIs(visible.get_payload(), None) ++ self.assertIsNone(visible.get_payload()) + msg.update_visible() + self.assertEqual(visible.keys(), ['User-Agent', 'X-Whatever']) +- self.assertIs(visible.get_payload(), None) ++ self.assertIsNone(visible.get_payload()) + visible = msg.get_visible() + self.assertEqual(visible.keys(), ['User-Agent', 'Date', 'From', 'To', + 'Subject']) +@@ -1971,43 +1971,43 @@ + # Make sure the boxes attribute actually gets set. + self.mbox = mailbox.Maildir(test_support.TESTFN) + #self.assertTrue(hasattr(self.mbox, "boxes")) +- #self.assertTrue(len(self.mbox.boxes) == 0) +- self.assertIs(self.mbox.next(), None) +- self.assertIs(self.mbox.next(), None) ++ #self.assertEqual(len(self.mbox.boxes), 0) ++ self.assertIsNone(self.mbox.next()) ++ self.assertIsNone(self.mbox.next()) + + def test_nonempty_maildir_cur(self): + self.createMessage("cur") + self.mbox = mailbox.Maildir(test_support.TESTFN) +- #self.assertTrue(len(self.mbox.boxes) == 1) ++ #self.assertEqual(len(self.mbox.boxes), 1) + msg = self.mbox.next() +- self.assertIsNot(msg, None) ++ self.assertIsNotNone(msg) + msg.fp.close() +- self.assertIs(self.mbox.next(), None) +- self.assertIs(self.mbox.next(), None) ++ self.assertIsNone(self.mbox.next()) ++ self.assertIsNone(self.mbox.next()) + + def test_nonempty_maildir_new(self): + self.createMessage("new") + self.mbox = mailbox.Maildir(test_support.TESTFN) +- #self.assertTrue(len(self.mbox.boxes) == 1) ++ #self.assertEqual(len(self.mbox.boxes), 1) + msg = self.mbox.next() +- self.assertIsNot(msg, None) ++ self.assertIsNotNone(msg) + msg.fp.close() +- self.assertIs(self.mbox.next(), None) +- self.assertIs(self.mbox.next(), None) ++ self.assertIsNone(self.mbox.next()) ++ self.assertIsNone(self.mbox.next()) + + def test_nonempty_maildir_both(self): + self.createMessage("cur") + self.createMessage("new") + self.mbox = mailbox.Maildir(test_support.TESTFN) +- #self.assertTrue(len(self.mbox.boxes) == 2) ++ #self.assertEqual(len(self.mbox.boxes), 2) + msg = self.mbox.next() +- self.assertIsNot(msg, None) ++ self.assertIsNotNone(msg) + msg.fp.close() + msg = self.mbox.next() +- self.assertIsNot(msg, None) ++ self.assertIsNotNone(msg) + msg.fp.close() +- self.assertIs(self.mbox.next(), None) +- self.assertIs(self.mbox.next(), None) ++ self.assertIsNone(self.mbox.next()) ++ self.assertIsNone(self.mbox.next()) + + def test_unix_mbox(self): + ### should be better! +diff -r 3a1db0d2747e Lib/test/test_marshal.py +--- a/Lib/test/test_marshal.py ++++ b/Lib/test/test_marshal.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # -*- coding: iso-8859-1 -*- + + from test import test_support +@@ -286,7 +285,7 @@ + self.check_unmarshallable('x' * size) + + @test_support.precisionbigmemtest(size=LARGE_SIZE, +- memuse=character_size, dry_run=False) ++ memuse=character_size + 2, dry_run=False) + def test_unicode(self, size): + self.check_unmarshallable(u'x' * size) + +diff -r 3a1db0d2747e Lib/test/test_math.py +--- a/Lib/test/test_math.py ++++ b/Lib/test/test_math.py +@@ -906,38 +906,37 @@ + # still fails this part of the test on some platforms. For now, we only + # *run* test_exceptions() in verbose mode, so that this isn't normally + # tested. ++ @unittest.skipUnless(verbose, 'requires verbose mode') ++ def test_exceptions(self): ++ try: ++ x = math.exp(-1000000000) ++ except: ++ # mathmodule.c is failing to weed out underflows from libm, or ++ # we've got an fp format with huge dynamic range ++ self.fail("underflowing exp() should not have raised " ++ "an exception") ++ if x != 0: ++ self.fail("underflowing exp() should have returned 0") + +- if verbose: +- def test_exceptions(self): +- try: +- x = math.exp(-1000000000) +- except: +- # mathmodule.c is failing to weed out underflows from libm, or +- # we've got an fp format with huge dynamic range +- self.fail("underflowing exp() should not have raised " +- "an exception") +- if x != 0: +- self.fail("underflowing exp() should have returned 0") ++ # If this fails, probably using a strict IEEE-754 conforming libm, and x ++ # is +Inf afterwards. But Python wants overflows detected by default. ++ try: ++ x = math.exp(1000000000) ++ except OverflowError: ++ pass ++ else: ++ self.fail("overflowing exp() didn't trigger OverflowError") + +- # If this fails, probably using a strict IEEE-754 conforming libm, and x +- # is +Inf afterwards. But Python wants overflows detected by default. +- try: +- x = math.exp(1000000000) +- except OverflowError: +- pass +- else: +- self.fail("overflowing exp() didn't trigger OverflowError") +- +- # If this fails, it could be a puzzle. One odd possibility is that +- # mathmodule.c's macros are getting confused while comparing +- # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE +- # as a result (and so raising OverflowError instead). +- try: +- x = math.sqrt(-1.0) +- except ValueError: +- pass +- else: +- self.fail("sqrt(-1) didn't raise ValueError") ++ # If this fails, it could be a puzzle. One odd possibility is that ++ # mathmodule.c's macros are getting confused while comparing ++ # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE ++ # as a result (and so raising OverflowError instead). ++ try: ++ x = math.sqrt(-1.0) ++ except ValueError: ++ pass ++ else: ++ self.fail("sqrt(-1) didn't raise ValueError") + + @requires_IEEE_754 + def test_testfile(self): +diff -r 3a1db0d2747e Lib/test/test_memoryio.py +--- a/Lib/test/test_memoryio.py ++++ b/Lib/test/test_memoryio.py +@@ -522,6 +522,17 @@ + self.assertIsNone(memio.errors) + self.assertFalse(memio.line_buffering) + ++ def test_newline_default(self): ++ memio = self.ioclass("a\nb\r\nc\rd") ++ self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) ++ self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") ++ ++ memio = self.ioclass() ++ self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) ++ memio.seek(0) ++ self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) ++ self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") ++ + def test_newline_none(self): + # newline=None + memio = self.ioclass("a\nb\r\nc\rd", newline=None) +@@ -531,12 +542,16 @@ + self.assertEqual(memio.read(2), "\nb") + self.assertEqual(memio.read(2), "\nc") + self.assertEqual(memio.read(1), "\n") ++ self.assertEqual(memio.getvalue(), "a\nb\nc\nd") ++ + memio = self.ioclass(newline=None) + self.assertEqual(2, memio.write("a\n")) + self.assertEqual(3, memio.write("b\r\n")) + self.assertEqual(3, memio.write("c\rd")) + memio.seek(0) + self.assertEqual(memio.read(), "a\nb\nc\nd") ++ self.assertEqual(memio.getvalue(), "a\nb\nc\nd") ++ + memio = self.ioclass("a\r\nb", newline=None) + self.assertEqual(memio.read(3), "a\nb") + +@@ -548,6 +563,8 @@ + self.assertEqual(memio.read(4), "a\nb\r") + self.assertEqual(memio.read(2), "\nc") + self.assertEqual(memio.read(1), "\r") ++ self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") ++ + memio = self.ioclass(newline="") + self.assertEqual(2, memio.write("a\n")) + self.assertEqual(2, memio.write("b\r")) +@@ -555,11 +572,19 @@ + self.assertEqual(2, memio.write("\rd")) + memio.seek(0) + self.assertEqual(list(memio), ["a\n", "b\r\n", "c\r", "d"]) ++ self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") + + def test_newline_lf(self): + # newline="\n" +- memio = self.ioclass("a\nb\r\nc\rd") ++ memio = self.ioclass("a\nb\r\nc\rd", newline="\n") + self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) ++ self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") ++ ++ memio = self.ioclass(newline="\n") ++ self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) ++ memio.seek(0) ++ self.assertEqual(list(memio), ["a\n", "b\r\n", "c\rd"]) ++ self.assertEqual(memio.getvalue(), "a\nb\r\nc\rd") + + def test_newline_cr(self): + # newline="\r" +@@ -567,6 +592,15 @@ + self.assertEqual(memio.read(), "a\rb\r\rc\rd") + memio.seek(0) + self.assertEqual(list(memio), ["a\r", "b\r", "\r", "c\r", "d"]) ++ self.assertEqual(memio.getvalue(), "a\rb\r\rc\rd") ++ ++ memio = self.ioclass(newline="\r") ++ self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) ++ memio.seek(0) ++ self.assertEqual(list(memio), ["a\r", "b\r", "\r", "c\r", "d"]) ++ memio.seek(0) ++ self.assertEqual(memio.readlines(), ["a\r", "b\r", "\r", "c\r", "d"]) ++ self.assertEqual(memio.getvalue(), "a\rb\r\rc\rd") + + def test_newline_crlf(self): + # newline="\r\n" +@@ -574,11 +608,21 @@ + self.assertEqual(memio.read(), "a\r\nb\r\r\nc\rd") + memio.seek(0) + self.assertEqual(list(memio), ["a\r\n", "b\r\r\n", "c\rd"]) ++ memio.seek(0) ++ self.assertEqual(memio.readlines(), ["a\r\n", "b\r\r\n", "c\rd"]) ++ self.assertEqual(memio.getvalue(), "a\r\nb\r\r\nc\rd") ++ ++ memio = self.ioclass(newline="\r\n") ++ self.assertEqual(memio.write("a\nb\r\nc\rd"), 8) ++ memio.seek(0) ++ self.assertEqual(list(memio), ["a\r\n", "b\r\r\n", "c\rd"]) ++ self.assertEqual(memio.getvalue(), "a\r\nb\r\r\nc\rd") + + def test_issue5265(self): + # StringIO can duplicate newlines in universal newlines mode + memio = self.ioclass("a\r\nb\r\n", newline=None) + self.assertEqual(memio.read(5), "a\nb\n") ++ self.assertEqual(memio.getvalue(), "a\nb\n") + + + class PyStringIOTest(MemoryTestMixin, MemorySeekTestMixin, +@@ -588,6 +632,16 @@ + UnsupportedOperation = pyio.UnsupportedOperation + EOF = "" + ++ def test_lone_surrogates(self): ++ # Issue #20424 ++ surrogate = unichr(0xd800) ++ memio = self.ioclass(surrogate) ++ self.assertEqual(memio.read(), surrogate) ++ ++ memio = self.ioclass() ++ memio.write(surrogate) ++ self.assertEqual(memio.getvalue(), surrogate) ++ + + class PyStringIOPickleTest(TextIOTestMixin, unittest.TestCase): + """Test if pickle restores properly the internal state of StringIO. +diff -r 3a1db0d2747e Lib/test/test_memoryview.py +--- a/Lib/test/test_memoryview.py ++++ b/Lib/test/test_memoryview.py +@@ -63,7 +63,7 @@ + + def test_setitem_readonly(self): + if not self.ro_type: +- return ++ self.skipTest("no read-only type to test") + b = self.ro_type(self._source) + oldrefcount = sys.getrefcount(b) + m = self._view(b) +@@ -77,7 +77,7 @@ + + def test_setitem_writable(self): + if not self.rw_type: +- return ++ self.skipTest("no writable type to test") + tp = self.rw_type + b = self.rw_type(self._source) + oldrefcount = sys.getrefcount(b) +@@ -183,13 +183,13 @@ + + def test_attributes_readonly(self): + if not self.ro_type: +- return ++ self.skipTest("no read-only type to test") + m = self.check_attributes_with_type(self.ro_type) + self.assertEqual(m.readonly, True) + + def test_attributes_writable(self): + if not self.rw_type: +- return ++ self.skipTest("no writable type to test") + m = self.check_attributes_with_type(self.rw_type) + self.assertEqual(m.readonly, False) + +@@ -236,7 +236,7 @@ + # buffer as writable causing a segfault if using mmap + tp = self.ro_type + if tp is None: +- return ++ self.skipTest("no read-only type to test") + b = tp(self._source) + m = self._view(b) + i = io.BytesIO(b'ZZZZ') +diff -r 3a1db0d2747e Lib/test/test_minidom.py +--- a/Lib/test/test_minidom.py ++++ b/Lib/test/test_minidom.py +@@ -340,19 +340,6 @@ + and el.getAttribute("spam2") == "bam2") + dom.unlink() + +- def testGetAttrList(self): +- pass +- +- def testGetAttrValues(self): pass +- +- def testGetAttrLength(self): pass +- +- def testGetAttribute(self): pass +- +- def testGetAttributeNS(self): pass +- +- def testGetAttributeNode(self): pass +- + def testGetElementsByTagNameNS(self): + d=""" + +@@ -423,8 +410,6 @@ + self.confirm(str(node) == repr(node)) + dom.unlink() + +- def testTextNodeRepr(self): pass +- + def testWriteXML(self): + str = '' + dom = parseString(str) +@@ -488,14 +473,6 @@ + and pi.localName is None + and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE) + +- def testProcessingInstructionRepr(self): pass +- +- def testTextRepr(self): pass +- +- def testWriteText(self): pass +- +- def testDocumentElement(self): pass +- + def testTooManyDocumentElements(self): + doc = parseString("") + elem = doc.createElement("extra") +@@ -504,26 +481,6 @@ + elem.unlink() + doc.unlink() + +- def testCreateElementNS(self): pass +- +- def testCreateAttributeNS(self): pass +- +- def testParse(self): pass +- +- def testParseString(self): pass +- +- def testComment(self): pass +- +- def testAttrListItem(self): pass +- +- def testAttrListItems(self): pass +- +- def testAttrListItemNS(self): pass +- +- def testAttrListKeys(self): pass +- +- def testAttrListKeysNS(self): pass +- + def testRemoveNamedItem(self): + doc = parseString("") + e = doc.documentElement +@@ -543,32 +500,6 @@ + self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS, + "http://xml.python.org/", "b") + +- def testAttrListValues(self): pass +- +- def testAttrListLength(self): pass +- +- def testAttrList__getitem__(self): pass +- +- def testAttrList__setitem__(self): pass +- +- def testSetAttrValueandNodeValue(self): pass +- +- def testParseElement(self): pass +- +- def testParseAttributes(self): pass +- +- def testParseElementNamespaces(self): pass +- +- def testParseAttributeNamespaces(self): pass +- +- def testParseProcessingInstructions(self): pass +- +- def testChildNodes(self): pass +- +- def testFirstChild(self): pass +- +- def testHasChildNodes(self): pass +- + def _testCloneElementCopiesAttributes(self, e1, e2, test): + attrs1 = e1.attributes + attrs2 = e2.attributes +diff -r 3a1db0d2747e Lib/test/test_mmap.py +--- a/Lib/test/test_mmap.py ++++ b/Lib/test/test_mmap.py +@@ -320,26 +320,25 @@ + mf.close() + f.close() + ++ @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") + def test_entire_file(self): + # test mapping of entire file by passing 0 for map length +- if hasattr(os, "stat"): +- f = open(TESTFN, "w+") ++ f = open(TESTFN, "w+") + +- f.write(2**16 * 'm') # Arbitrary character +- f.close() ++ f.write(2**16 * 'm') # Arbitrary character ++ f.close() + +- f = open(TESTFN, "rb+") +- mf = mmap.mmap(f.fileno(), 0) +- self.assertEqual(len(mf), 2**16, "Map size should equal file size.") +- self.assertEqual(mf.read(2**16), 2**16 * "m") +- mf.close() +- f.close() ++ f = open(TESTFN, "rb+") ++ mf = mmap.mmap(f.fileno(), 0) ++ self.assertEqual(len(mf), 2**16, "Map size should equal file size.") ++ self.assertEqual(mf.read(2**16), 2**16 * "m") ++ mf.close() ++ f.close() + ++ @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") + def test_length_0_offset(self): + # Issue #10916: test mapping of remainder of file by passing 0 for + # map length with an offset doesn't cause a segfault. +- if not hasattr(os, "stat"): +- self.skipTest("needs os.stat") + # NOTE: allocation granularity is currently 65536 under Win64, + # and therefore the minimum offset alignment. + with open(TESTFN, "wb") as f: +@@ -352,12 +351,10 @@ + finally: + mf.close() + ++ @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()") + def test_length_0_large_offset(self): + # Issue #10959: test mapping of a file by passing 0 for + # map length with a large offset doesn't cause a segfault. +- if not hasattr(os, "stat"): +- self.skipTest("needs os.stat") +- + with open(TESTFN, "wb") as f: + f.write(115699 * b'm') # Arbitrary character + +@@ -538,9 +535,8 @@ + return mmap.mmap.__new__(klass, -1, *args, **kwargs) + anon_mmap(PAGESIZE) + ++ @unittest.skipUnless(hasattr(mmap, 'PROT_READ'), "needs mmap.PROT_READ") + def test_prot_readonly(self): +- if not hasattr(mmap, 'PROT_READ'): +- return + mapsize = 10 + open(TESTFN, "wb").write("a"*mapsize) + f = open(TESTFN, "rb") +@@ -584,66 +580,68 @@ + m.seek(8) + self.assertRaises(ValueError, m.write, "bar") + +- if os.name == 'nt': +- def test_tagname(self): +- data1 = "0123456789" +- data2 = "abcdefghij" +- assert len(data1) == len(data2) ++ @unittest.skipUnless(os.name == 'nt', 'requires Windows') ++ def test_tagname(self): ++ data1 = "0123456789" ++ data2 = "abcdefghij" ++ assert len(data1) == len(data2) + +- # Test same tag +- m1 = mmap.mmap(-1, len(data1), tagname="foo") +- m1[:] = data1 +- m2 = mmap.mmap(-1, len(data2), tagname="foo") +- m2[:] = data2 +- self.assertEqual(m1[:], data2) +- self.assertEqual(m2[:], data2) +- m2.close() +- m1.close() ++ # Test same tag ++ m1 = mmap.mmap(-1, len(data1), tagname="foo") ++ m1[:] = data1 ++ m2 = mmap.mmap(-1, len(data2), tagname="foo") ++ m2[:] = data2 ++ self.assertEqual(m1[:], data2) ++ self.assertEqual(m2[:], data2) ++ m2.close() ++ m1.close() + +- # Test different tag +- m1 = mmap.mmap(-1, len(data1), tagname="foo") +- m1[:] = data1 +- m2 = mmap.mmap(-1, len(data2), tagname="boo") +- m2[:] = data2 +- self.assertEqual(m1[:], data1) +- self.assertEqual(m2[:], data2) +- m2.close() +- m1.close() ++ # Test different tag ++ m1 = mmap.mmap(-1, len(data1), tagname="foo") ++ m1[:] = data1 ++ m2 = mmap.mmap(-1, len(data2), tagname="boo") ++ m2[:] = data2 ++ self.assertEqual(m1[:], data1) ++ self.assertEqual(m2[:], data2) ++ m2.close() ++ m1.close() + +- def test_crasher_on_windows(self): +- # Should not crash (Issue 1733986) +- m = mmap.mmap(-1, 1000, tagname="foo") +- try: +- mmap.mmap(-1, 5000, tagname="foo")[:] # same tagname, but larger size +- except: +- pass +- m.close() ++ @unittest.skipUnless(os.name == 'nt', 'requires Windows') ++ def test_crasher_on_windows(self): ++ # Should not crash (Issue 1733986) ++ m = mmap.mmap(-1, 1000, tagname="foo") ++ try: ++ mmap.mmap(-1, 5000, tagname="foo")[:] # same tagname, but larger size ++ except: ++ pass ++ m.close() + +- # Should not crash (Issue 5385) +- open(TESTFN, "wb").write("x"*10) +- f = open(TESTFN, "r+b") +- m = mmap.mmap(f.fileno(), 0) +- f.close() +- try: +- m.resize(0) # will raise WindowsError +- except: +- pass +- try: +- m[:] +- except: +- pass +- m.close() ++ # Should not crash (Issue 5385) ++ open(TESTFN, "wb").write("x"*10) ++ f = open(TESTFN, "r+b") ++ m = mmap.mmap(f.fileno(), 0) ++ f.close() ++ try: ++ m.resize(0) # will raise WindowsError ++ except: ++ pass ++ try: ++ m[:] ++ except: ++ pass ++ m.close() + +- def test_invalid_descriptor(self): +- # socket file descriptors are valid, but out of range +- # for _get_osfhandle, causing a crash when validating the +- # parameters to _get_osfhandle. +- s = socket.socket() +- try: +- with self.assertRaises(mmap.error): +- m = mmap.mmap(s.fileno(), 10) +- finally: +- s.close() ++ @unittest.skipUnless(os.name == 'nt', 'requires Windows') ++ def test_invalid_descriptor(self): ++ # socket file descriptors are valid, but out of range ++ # for _get_osfhandle, causing a crash when validating the ++ # parameters to _get_osfhandle. ++ s = socket.socket() ++ try: ++ with self.assertRaises(mmap.error): ++ m = mmap.mmap(s.fileno(), 10) ++ finally: ++ s.close() + + + class LargeMmapTests(unittest.TestCase): +diff -r 3a1db0d2747e Lib/test/test_multibytecodec.py +--- a/Lib/test/test_multibytecodec.py ++++ b/Lib/test/test_multibytecodec.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +-# + # test_multibytecodec.py + # Unit test for multibytecodec itself + # +@@ -157,57 +155,55 @@ + os.unlink(TESTFN) + + class Test_StreamWriter(unittest.TestCase): +- if len(u'\U00012345') == 2: # UCS2 +- def test_gb18030(self): +- s = StringIO.StringIO() +- c = codecs.getwriter('gb18030')(s) +- c.write(u'123') +- self.assertEqual(s.getvalue(), '123') +- c.write(u'\U00012345') +- self.assertEqual(s.getvalue(), '123\x907\x959') ++ @unittest.skipUnless(len(u'\U00012345') == 2, 'need a narrow build') ++ def test_gb18030(self): ++ s = StringIO.StringIO() ++ c = codecs.getwriter('gb18030')(s) ++ c.write(u'123') ++ self.assertEqual(s.getvalue(), '123') ++ c.write(u'\U00012345') ++ self.assertEqual(s.getvalue(), '123\x907\x959') ++ c.write(u'\U00012345'[0]) ++ self.assertEqual(s.getvalue(), '123\x907\x959') ++ c.write(u'\U00012345'[1] + u'\U00012345' + u'\uac00\u00ac') ++ self.assertEqual(s.getvalue(), ++ '123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851') ++ c.write(u'\U00012345'[0]) ++ self.assertEqual(s.getvalue(), ++ '123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851') ++ self.assertRaises(UnicodeError, c.reset) ++ self.assertEqual(s.getvalue(), ++ '123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851') ++ ++ @unittest.skipUnless(len(u'\U00012345') == 2, 'need a narrow build') ++ def test_utf_8(self): ++ s= StringIO.StringIO() ++ c = codecs.getwriter('utf-8')(s) ++ c.write(u'123') ++ self.assertEqual(s.getvalue(), '123') ++ c.write(u'\U00012345') ++ self.assertEqual(s.getvalue(), '123\xf0\x92\x8d\x85') ++ ++ # Python utf-8 codec can't buffer surrogate pairs yet. ++ if 0: + c.write(u'\U00012345'[0]) +- self.assertEqual(s.getvalue(), '123\x907\x959') ++ self.assertEqual(s.getvalue(), '123\xf0\x92\x8d\x85') + c.write(u'\U00012345'[1] + u'\U00012345' + u'\uac00\u00ac') + self.assertEqual(s.getvalue(), +- '123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851') ++ '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' ++ '\xea\xb0\x80\xc2\xac') + c.write(u'\U00012345'[0]) + self.assertEqual(s.getvalue(), +- '123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851') +- self.assertRaises(UnicodeError, c.reset) ++ '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' ++ '\xea\xb0\x80\xc2\xac') ++ c.reset() + self.assertEqual(s.getvalue(), +- '123\x907\x959\x907\x959\x907\x959\x827\xcf5\x810\x851') +- +- def test_utf_8(self): +- s= StringIO.StringIO() +- c = codecs.getwriter('utf-8')(s) +- c.write(u'123') +- self.assertEqual(s.getvalue(), '123') +- c.write(u'\U00012345') +- self.assertEqual(s.getvalue(), '123\xf0\x92\x8d\x85') +- +- # Python utf-8 codec can't buffer surrogate pairs yet. +- if 0: +- c.write(u'\U00012345'[0]) +- self.assertEqual(s.getvalue(), '123\xf0\x92\x8d\x85') +- c.write(u'\U00012345'[1] + u'\U00012345' + u'\uac00\u00ac') +- self.assertEqual(s.getvalue(), +- '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' +- '\xea\xb0\x80\xc2\xac') +- c.write(u'\U00012345'[0]) +- self.assertEqual(s.getvalue(), +- '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' +- '\xea\xb0\x80\xc2\xac') +- c.reset() +- self.assertEqual(s.getvalue(), +- '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' +- '\xea\xb0\x80\xc2\xac\xed\xa0\x88') +- c.write(u'\U00012345'[1]) +- self.assertEqual(s.getvalue(), +- '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' +- '\xea\xb0\x80\xc2\xac\xed\xa0\x88\xed\xbd\x85') +- +- else: # UCS4 +- pass ++ '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' ++ '\xea\xb0\x80\xc2\xac\xed\xa0\x88') ++ c.write(u'\U00012345'[1]) ++ self.assertEqual(s.getvalue(), ++ '123\xf0\x92\x8d\x85\xf0\x92\x8d\x85\xf0\x92\x8d\x85' ++ '\xea\xb0\x80\xc2\xac\xed\xa0\x88\xed\xbd\x85') + + def test_streamwriter_strwrite(self): + s = StringIO.StringIO() +diff -r 3a1db0d2747e Lib/test/test_multibytecodec_support.py +--- a/Lib/test/test_multibytecodec_support.py ++++ b/Lib/test/test_multibytecodec_support.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +-# + # test_multibytecodec_support.py + # Common Unittest Routines for CJK codecs + # +@@ -67,7 +65,7 @@ + + def test_xmlcharrefreplace(self): + if self.has_iso10646: +- return ++ self.skipTest('encoding contains full ISO 10646 map') + + s = u"\u0b13\u0b23\u0b60 nd eggs" + self.assertEqual( +@@ -77,7 +75,7 @@ + + def test_customreplace_encode(self): + if self.has_iso10646: +- return ++ self.skipTest('encoding contains full ISO 10646 map') + + from htmlentitydefs import codepoint2name + +diff -r 3a1db0d2747e Lib/test/test_multiprocessing.py +--- a/Lib/test/test_multiprocessing.py ++++ b/Lib/test/test_multiprocessing.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +- + # + # Unit tests for the multiprocessing package + # +@@ -182,7 +180,7 @@ + + def test_current(self): + if self.TYPE == 'threads': +- return ++ self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + current = self.current_process() + authkey = current.authkey +@@ -249,7 +247,7 @@ + + def test_terminate(self): + if self.TYPE == 'threads': +- return ++ self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + p = self.Process(target=self._test_terminate) + p.daemon = True +@@ -334,12 +332,12 @@ + def test_sys_exit(self): + # See Issue 13854 + if self.TYPE == 'threads': +- return ++ self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + testfn = test_support.TESTFN + self.addCleanup(test_support.unlink, testfn) + +- for reason, code in (([1, 2, 3], 1), ('ignore this', 0)): ++ for reason, code in (([1, 2, 3], 1), ('ignore this', 1)): + p = self.Process(target=self._test_sys_exit, args=(reason, testfn)) + p.daemon = True + p.start() +@@ -582,7 +580,7 @@ + try: + self.assertEqual(q.qsize(), 0) + except NotImplementedError: +- return ++ self.skipTest('qsize method not implemented') + q.put(1) + self.assertEqual(q.qsize(), 1) + q.put(5) +@@ -683,7 +681,7 @@ + + def test_timeout(self): + if self.TYPE != 'processes': +- return ++ self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + sem = self.Semaphore(0) + acquire = TimingWrapper(sem.acquire) +@@ -1117,6 +1115,16 @@ + self.assertEqual(pmap(sqr, range(100), chunksize=20), + map(sqr, range(100))) + ++ def test_map_unplicklable(self): ++ # Issue #19425 -- failure to pickle should not cause a hang ++ if self.TYPE == 'threads': ++ self.skipTest('test not appropriate for {}'.format(self.TYPE)) ++ class A(object): ++ def __reduce__(self): ++ raise RuntimeError('cannot pickle') ++ with self.assertRaises(RuntimeError): ++ self.pool.map(sqr, [A()]*10) ++ + def test_map_chunksize(self): + try: + self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1) +@@ -1130,7 +1138,7 @@ + self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) + + def test_async_timeout(self): +- res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 0.2)) ++ res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 1.0)) + get = TimingWrapper(res.get) + self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2) + self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2) +@@ -1166,20 +1174,12 @@ + p.join() + + def test_terminate(self): +- if self.TYPE == 'manager': +- # On Unix a forked process increfs each shared object to +- # which its parent process held a reference. If the +- # forked process gets terminated then there is likely to +- # be a reference leak. So to prevent +- # _TestZZZNumberOfObjects from failing we skip this test +- # when using a manager. +- return +- +- result = self.pool.map_async( ++ p = self.Pool(4) ++ result = p.map_async( + time.sleep, [0.1 for i in range(10000)], chunksize=1 + ) +- self.pool.terminate() +- join = TimingWrapper(self.pool.join) ++ p.terminate() ++ join = TimingWrapper(p.join) + join() + self.assertTrue(join.elapsed < 0.2) + +@@ -1571,7 +1571,7 @@ + + def test_sendbytes(self): + if self.TYPE != 'processes': +- return ++ self.skipTest('test not appropriate for {}'.format(self.TYPE)) + + msg = latin('abcdefghijklmnopqrstuvwxyz') + a, b = self.Pipe() +diff -r 3a1db0d2747e Lib/test/test_nis.py +--- a/Lib/test/test_nis.py ++++ b/Lib/test/test_nis.py +@@ -9,11 +9,7 @@ + maps = nis.maps() + except nis.error, msg: + # NIS is probably not active, so this test isn't useful +- if test_support.verbose: +- print "Test Skipped:", msg +- # Can't raise SkipTest as regrtest only recognizes the exception +- # import time. +- return ++ self.skipTest(str(msg)) + try: + # On some systems, this map is only accessible to the + # super user +diff -r 3a1db0d2747e Lib/test/test_nntplib.py +--- a/Lib/test/test_nntplib.py ++++ b/Lib/test/test_nntplib.py +@@ -1,7 +1,13 @@ + import socket +-import threading + import nntplib + import time ++import unittest ++ ++try: ++ import threading ++except ImportError: ++ threading = None ++ + + from unittest import TestCase + from test import test_support +@@ -41,6 +47,7 @@ + self.evt.wait() + + ++@unittest.skipUnless(threading, 'threading required') + class ServerTests(BaseServerTest): + evil = False + +@@ -49,6 +56,7 @@ + nntp.sock.close() + + ++@unittest.skipUnless(threading, 'threading required') + class EvilServerTests(BaseServerTest): + evil = True + +diff -r 3a1db0d2747e Lib/test/test_ntpath.py +--- a/Lib/test/test_ntpath.py ++++ b/Lib/test/test_ntpath.py +@@ -1,16 +1,19 @@ + import ntpath + import os ++import sys + from test.test_support import TestFailed + from test import test_support, test_genericpath + import unittest + ++def tester0(fn, wantResult): ++ gotResult = eval(fn) ++ if wantResult != gotResult: ++ raise TestFailed, "%s should return: %r but returned: %r" \ ++ %(fn, wantResult, gotResult) + + def tester(fn, wantResult): + fn = fn.replace("\\", "\\\\") +- gotResult = eval(fn) +- if wantResult != gotResult: +- raise TestFailed, "%s should return: %s but returned: %s" \ +- %(str(fn), str(wantResult), str(gotResult)) ++ tester0(fn, wantResult) + + + class TestNtpath(unittest.TestCase): +@@ -33,10 +36,24 @@ + ('c:', '/foo/bar')) + + def test_splitunc(self): ++ tester('ntpath.splitunc("c:\\foo\\bar")', ++ ('', 'c:\\foo\\bar')) ++ tester('ntpath.splitunc("c:/foo/bar")', ++ ('', 'c:/foo/bar')) + tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', + ('\\\\conky\\mountpoint', '\\foo\\bar')) + tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', + ('//conky/mountpoint', '/foo/bar')) ++ tester('ntpath.splitunc("\\\\\\conky\\mountpoint\\foo\\bar")', ++ ('', '\\\\\\conky\\mountpoint\\foo\\bar')) ++ tester('ntpath.splitunc("///conky/mountpoint/foo/bar")', ++ ('', '///conky/mountpoint/foo/bar')) ++ tester('ntpath.splitunc("\\\\conky\\\\mountpoint\\foo\\bar")', ++ ('', '\\\\conky\\\\mountpoint\\foo\\bar')) ++ tester('ntpath.splitunc("//conky//mountpoint/foo/bar")', ++ ('', '//conky//mountpoint/foo/bar')) ++ self.assertEqual(ntpath.splitunc(u'//conky/MOUNTPO\u0130NT/foo/bar'), ++ (u'//conky/MOUNTPO\u0130NT', u'/foo/bar')) + + def test_split(self): + tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar')) +@@ -71,10 +88,7 @@ + tester('ntpath.join("/a")', '/a') + tester('ntpath.join("\\a")', '\\a') + tester('ntpath.join("a:")', 'a:') +- tester('ntpath.join("a:", "b")', 'a:b') +- tester('ntpath.join("a:", "/b")', 'a:/b') + tester('ntpath.join("a:", "\\b")', 'a:\\b') +- tester('ntpath.join("a", "/b")', '/b') + tester('ntpath.join("a", "\\b")', '\\b') + tester('ntpath.join("a", "b", "c")', 'a\\b\\c') + tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c') +@@ -82,22 +96,46 @@ + tester('ntpath.join("a", "b", "\\c")', '\\c') + tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep') + tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b') +- tester("ntpath.join('c:', '/a')", 'c:/a') +- tester("ntpath.join('c:/', '/a')", 'c:/a') +- tester("ntpath.join('c:/a', '/b')", '/b') +- tester("ntpath.join('c:', 'd:/')", 'd:/') +- tester("ntpath.join('c:/', 'd:/')", 'd:/') +- tester("ntpath.join('c:/', 'd:/a/b')", 'd:/a/b') + +- tester("ntpath.join('')", '') +- tester("ntpath.join('', '', '', '', '')", '') +- tester("ntpath.join('a')", 'a') + tester("ntpath.join('', 'a')", 'a') + tester("ntpath.join('', '', '', '', 'a')", 'a') + tester("ntpath.join('a', '')", 'a\\') + tester("ntpath.join('a', '', '', '', '')", 'a\\') + tester("ntpath.join('a\\', '')", 'a\\') + tester("ntpath.join('a\\', '', '', '', '')", 'a\\') ++ tester("ntpath.join('a/', '')", 'a/') ++ ++ tester("ntpath.join('a/b', 'x/y')", 'a/b\\x/y') ++ tester("ntpath.join('/a/b', 'x/y')", '/a/b\\x/y') ++ tester("ntpath.join('/a/b/', 'x/y')", '/a/b/x/y') ++ tester("ntpath.join('c:', 'x/y')", 'c:x/y') ++ tester("ntpath.join('c:a/b', 'x/y')", 'c:a/b\\x/y') ++ tester("ntpath.join('c:a/b/', 'x/y')", 'c:a/b/x/y') ++ tester("ntpath.join('c:/', 'x/y')", 'c:/x/y') ++ tester("ntpath.join('c:/a/b', 'x/y')", 'c:/a/b\\x/y') ++ tester("ntpath.join('c:/a/b/', 'x/y')", 'c:/a/b/x/y') ++ #tester("ntpath.join('//computer/share', 'x/y')", '//computer/share\\x/y') ++ #tester("ntpath.join('//computer/share/', 'x/y')", '//computer/share/x/y') ++ #tester("ntpath.join('//computer/share/a/b', 'x/y')", '//computer/share/a/b\\x/y') ++ ++ tester("ntpath.join('a/b', '/x/y')", '/x/y') ++ tester("ntpath.join('/a/b', '/x/y')", '/x/y') ++ tester("ntpath.join('c:', '/x/y')", 'c:/x/y') ++ tester("ntpath.join('c:a/b', '/x/y')", 'c:/x/y') ++ tester("ntpath.join('c:/', '/x/y')", 'c:/x/y') ++ tester("ntpath.join('c:/a/b', '/x/y')", 'c:/x/y') ++ #tester("ntpath.join('//computer/share', '/x/y')", '//computer/share/x/y') ++ #tester("ntpath.join('//computer/share/', '/x/y')", '//computer/share/x/y') ++ #tester("ntpath.join('//computer/share/a', '/x/y')", '//computer/share/x/y') ++ ++ tester("ntpath.join('c:', 'C:x/y')", 'C:x/y') ++ tester("ntpath.join('c:a/b', 'C:x/y')", 'C:a/b\\x/y') ++ tester("ntpath.join('c:/', 'C:x/y')", 'C:/x/y') ++ tester("ntpath.join('c:/a/b', 'C:x/y')", 'C:/a/b\\x/y') ++ ++ for x in ('', 'a/b', '/a/b', 'c:', 'c:a/b', 'c:/', 'c:/a/b'): ++ for y in ('d:', 'd:x/y', 'd:/', 'd:/x/y'): ++ tester("ntpath.join(%r, %r)" % (x, y), y) + + def test_normpath(self): + tester("ntpath.normpath('A//////././//.//B')", r'A\B') +@@ -138,7 +176,6 @@ + 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}") +@@ -152,6 +189,30 @@ + tester('ntpath.expandvars("%foo%%bar")', "bar%bar") + tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar") + ++ @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII') ++ def test_expandvars_nonascii(self): ++ encoding = sys.getfilesystemencoding() ++ def check(value, expected): ++ tester0("ntpath.expandvars(%r)" % value, expected) ++ tester0("ntpath.expandvars(%r)" % value.decode(encoding), ++ expected.decode(encoding)) ++ with test_support.EnvironmentVarGuard() as env: ++ env.clear() ++ unonascii = test_support.FS_NONASCII ++ snonascii = unonascii.encode(encoding) ++ env['spam'] = snonascii ++ env[snonascii] = 'ham' + snonascii ++ check('$spam bar', '%s bar' % snonascii) ++ check('$%s bar' % snonascii, '$%s bar' % snonascii) ++ check('${spam}bar', '%sbar' % snonascii) ++ check('${%s}bar' % snonascii, 'ham%sbar' % snonascii) ++ check('$spam}bar', '%s}bar' % snonascii) ++ check('$%s}bar' % snonascii, '$%s}bar' % snonascii) ++ check('%spam% bar', '%s bar' % snonascii) ++ check('%{}% bar'.format(snonascii), 'ham%s bar' % snonascii) ++ check('%spam%bar', '%sbar' % snonascii) ++ check('%{}%bar'.format(snonascii), 'ham%sbar' % snonascii) ++ + def test_abspath(self): + # ntpath.abspath() can only be used on a system with the "nt" module + # (reasonably), so we protect this test with "import nt". This allows +diff -r 3a1db0d2747e Lib/test/test_optparse.py +--- a/Lib/test/test_optparse.py ++++ b/Lib/test/test_optparse.py +@@ -1444,6 +1444,39 @@ + -h, --help show this help message and exit + """ + ++_expected_very_help_short_lines = """\ ++Usage: bar.py [options] ++ ++Options: ++ -a APPLE ++ throw ++ APPLEs at ++ basket ++ -b NUM, --boo=NUM ++ shout ++ "boo!" NUM ++ times (in ++ order to ++ frighten ++ away all ++ the evil ++ spirits ++ that cause ++ trouble and ++ mayhem) ++ --foo=FOO ++ store FOO ++ in the foo ++ list for ++ later ++ fooing ++ -h, --help ++ show this ++ help ++ message and ++ exit ++""" ++ + class TestHelp(BaseTest): + def setUp(self): + self.parser = self.make_parser(80) +@@ -1505,6 +1538,8 @@ + # we look at $COLUMNS. + self.parser = self.make_parser(60) + self.assertHelpEquals(_expected_help_short_lines) ++ self.parser = self.make_parser(0) ++ self.assertHelpEquals(_expected_very_help_short_lines) + + def test_help_unicode(self): + self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) +diff -r 3a1db0d2747e Lib/test/test_os.py +--- a/Lib/test/test_os.py ++++ b/Lib/test/test_os.py +@@ -83,9 +83,8 @@ + open(name, "w") + self.files.append(name) + ++ @unittest.skipUnless(hasattr(os, 'tempnam'), 'test needs os.tempnam()') + def test_tempnam(self): +- if not hasattr(os, "tempnam"): +- return + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "tempnam", RuntimeWarning, + r"test_os$") +@@ -99,9 +98,8 @@ + self.assertTrue(os.path.basename(name)[:3] == "pfx") + self.check_tempfile(name) + ++ @unittest.skipUnless(hasattr(os, 'tmpfile'), 'test needs os.tmpfile()') + def test_tmpfile(self): +- if not hasattr(os, "tmpfile"): +- return + # As with test_tmpnam() below, the Windows implementation of tmpfile() + # attempts to create a file in the root directory of the current drive. + # On Vista and Server 2008, this test will always fail for normal users +@@ -150,9 +148,8 @@ + fp.close() + self.assertTrue(s == "foobar") + ++ @unittest.skipUnless(hasattr(os, 'tmpnam'), 'test needs os.tmpnam()') + def test_tmpnam(self): +- if not hasattr(os, "tmpnam"): +- return + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "tmpnam", RuntimeWarning, + r"test_os$") +@@ -193,10 +190,8 @@ + os.unlink(self.fname) + os.rmdir(test_support.TESTFN) + ++ @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()') + def test_stat_attributes(self): +- if not hasattr(os, "stat"): +- return +- + import stat + result = os.stat(self.fname) + +@@ -256,16 +251,14 @@ + pass + + ++ @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()') + def test_statvfs_attributes(self): +- if not hasattr(os, "statvfs"): +- return +- + try: + result = os.statvfs(self.fname) + except OSError, e: + # On AtheOS, glibc always returns ENOSYS + if e.errno == errno.ENOSYS: +- return ++ self.skipTest('glibc always returns ENOSYS on AtheOS') + + # Make sure direct access works + self.assertEqual(result.f_bfree, result[3]) +@@ -311,10 +304,10 @@ + st2 = os.stat(test_support.TESTFN) + self.assertEqual(st2.st_mtime, int(st.st_mtime-delta)) + +- # Restrict test to Win32, since there is no guarantee other ++ # Restrict tests to Win32, since there is no guarantee other + # systems support centiseconds +- if sys.platform == 'win32': +- def get_file_system(path): ++ def get_file_system(path): ++ if sys.platform == 'win32': + root = os.path.splitdrive(os.path.abspath(path))[0] + '\\' + import ctypes + kernel32 = ctypes.windll.kernel32 +@@ -322,25 +315,31 @@ + if kernel32.GetVolumeInformationA(root, None, 0, None, None, None, buf, len(buf)): + return buf.value + +- if get_file_system(test_support.TESTFN) == "NTFS": +- def test_1565150(self): +- t1 = 1159195039.25 +- os.utime(self.fname, (t1, t1)) +- self.assertEqual(os.stat(self.fname).st_mtime, t1) ++ @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") ++ @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS", ++ "requires NTFS") ++ def test_1565150(self): ++ t1 = 1159195039.25 ++ os.utime(self.fname, (t1, t1)) ++ self.assertEqual(os.stat(self.fname).st_mtime, t1) + +- def test_large_time(self): +- t1 = 5000000000 # some day in 2128 +- os.utime(self.fname, (t1, t1)) +- self.assertEqual(os.stat(self.fname).st_mtime, t1) ++ @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") ++ @unittest.skipUnless(get_file_system(test_support.TESTFN) == "NTFS", ++ "requires NTFS") ++ def test_large_time(self): ++ t1 = 5000000000 # some day in 2128 ++ os.utime(self.fname, (t1, t1)) ++ self.assertEqual(os.stat(self.fname).st_mtime, t1) + +- def test_1686475(self): +- # Verify that an open file can be stat'ed +- try: +- os.stat(r"c:\pagefile.sys") +- except WindowsError, e: +- if e.errno == 2: # file does not exist; cannot run test +- return +- self.fail("Could not stat pagefile.sys") ++ @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") ++ def test_1686475(self): ++ # Verify that an open file can be stat'ed ++ try: ++ os.stat(r"c:\pagefile.sys") ++ except WindowsError, e: ++ if e.errno == 2: # file does not exist; cannot run test ++ self.skipTest(r'c:\pagefile.sys does not exist') ++ self.fail("Could not stat pagefile.sys") + + from test import mapping_tests + +@@ -598,6 +597,7 @@ + self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) + + ++@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") + class Win32ErrorTests(unittest.TestCase): + def test_rename(self): + self.assertRaises(WindowsError, os.rename, test_support.TESTFN, test_support.TESTFN+".bak") +@@ -644,121 +644,118 @@ + self.fail("%r didn't raise a OSError with a bad file descriptor" + % f) + ++ @unittest.skipUnless(hasattr(os, 'isatty'), 'test needs os.isatty()') + def test_isatty(self): +- if hasattr(os, "isatty"): +- self.assertEqual(os.isatty(test_support.make_bad_fd()), False) ++ self.assertEqual(os.isatty(test_support.make_bad_fd()), False) + ++ @unittest.skipUnless(hasattr(os, 'closerange'), 'test needs os.closerange()') + def test_closerange(self): +- if hasattr(os, "closerange"): +- fd = test_support.make_bad_fd() +- # Make sure none of the descriptors we are about to close are +- # currently valid (issue 6542). +- for i in range(10): +- try: os.fstat(fd+i) +- except OSError: +- pass +- else: +- break +- if i < 2: +- raise unittest.SkipTest( +- "Unable to acquire a range of invalid file descriptors") +- self.assertEqual(os.closerange(fd, fd + i-1), None) ++ fd = test_support.make_bad_fd() ++ # Make sure none of the descriptors we are about to close are ++ # currently valid (issue 6542). ++ for i in range(10): ++ try: os.fstat(fd+i) ++ except OSError: ++ pass ++ else: ++ break ++ if i < 2: ++ raise unittest.SkipTest( ++ "Unable to acquire a range of invalid file descriptors") ++ self.assertEqual(os.closerange(fd, fd + i-1), None) + ++ @unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()') + def test_dup2(self): +- if hasattr(os, "dup2"): +- self.check(os.dup2, 20) ++ self.check(os.dup2, 20) + ++ @unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()') + def test_fchmod(self): +- if hasattr(os, "fchmod"): +- self.check(os.fchmod, 0) ++ self.check(os.fchmod, 0) + ++ @unittest.skipUnless(hasattr(os, 'fchown'), 'test needs os.fchown()') + def test_fchown(self): +- if hasattr(os, "fchown"): +- self.check(os.fchown, -1, -1) ++ self.check(os.fchown, -1, -1) + ++ @unittest.skipUnless(hasattr(os, 'fpathconf'), 'test needs os.fpathconf()') + def test_fpathconf(self): +- if hasattr(os, "fpathconf"): +- self.check(os.fpathconf, "PC_NAME_MAX") ++ self.check(os.fpathconf, "PC_NAME_MAX") + ++ @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()') + def test_ftruncate(self): +- if hasattr(os, "ftruncate"): +- self.check(os.ftruncate, 0) ++ self.check(os.ftruncate, 0) + ++ @unittest.skipUnless(hasattr(os, 'lseek'), 'test needs os.lseek()') + def test_lseek(self): +- if hasattr(os, "lseek"): +- self.check(os.lseek, 0, 0) ++ self.check(os.lseek, 0, 0) + ++ @unittest.skipUnless(hasattr(os, 'read'), 'test needs os.read()') + def test_read(self): +- if hasattr(os, "read"): +- self.check(os.read, 1) ++ self.check(os.read, 1) + ++ @unittest.skipUnless(hasattr(os, 'tcsetpgrp'), 'test needs os.tcsetpgrp()') + def test_tcsetpgrpt(self): +- if hasattr(os, "tcsetpgrp"): +- self.check(os.tcsetpgrp, 0) ++ self.check(os.tcsetpgrp, 0) + ++ @unittest.skipUnless(hasattr(os, 'write'), 'test needs os.write()') + def test_write(self): +- if hasattr(os, "write"): +- self.check(os.write, " ") ++ self.check(os.write, " ") + +-if sys.platform != 'win32': +- class Win32ErrorTests(unittest.TestCase): +- pass ++@unittest.skipIf(sys.platform == "win32", "Posix specific tests") ++class PosixUidGidTests(unittest.TestCase): ++ @unittest.skipUnless(hasattr(os, 'setuid'), 'test needs os.setuid()') ++ def test_setuid(self): ++ if os.getuid() != 0: ++ self.assertRaises(os.error, os.setuid, 0) ++ self.assertRaises(OverflowError, os.setuid, 1<<32) + +- class PosixUidGidTests(unittest.TestCase): +- if hasattr(os, 'setuid'): +- def test_setuid(self): +- if os.getuid() != 0: +- self.assertRaises(os.error, os.setuid, 0) +- self.assertRaises(OverflowError, os.setuid, 1<<32) ++ @unittest.skipUnless(hasattr(os, 'setgid'), 'test needs os.setgid()') ++ def test_setgid(self): ++ if os.getuid() != 0: ++ self.assertRaises(os.error, os.setgid, 0) ++ self.assertRaises(OverflowError, os.setgid, 1<<32) + +- if hasattr(os, 'setgid'): +- def test_setgid(self): +- if os.getuid() != 0: +- self.assertRaises(os.error, os.setgid, 0) +- self.assertRaises(OverflowError, os.setgid, 1<<32) ++ @unittest.skipUnless(hasattr(os, 'seteuid'), 'test needs os.seteuid()') ++ def test_seteuid(self): ++ if os.getuid() != 0: ++ self.assertRaises(os.error, os.seteuid, 0) ++ self.assertRaises(OverflowError, os.seteuid, 1<<32) + +- if hasattr(os, 'seteuid'): +- def test_seteuid(self): +- if os.getuid() != 0: +- self.assertRaises(os.error, os.seteuid, 0) +- self.assertRaises(OverflowError, os.seteuid, 1<<32) ++ @unittest.skipUnless(hasattr(os, 'setegid'), 'test needs os.setegid()') ++ def test_setegid(self): ++ if os.getuid() != 0: ++ self.assertRaises(os.error, os.setegid, 0) ++ self.assertRaises(OverflowError, os.setegid, 1<<32) + +- if hasattr(os, 'setegid'): +- def test_setegid(self): +- if os.getuid() != 0: +- self.assertRaises(os.error, os.setegid, 0) +- self.assertRaises(OverflowError, os.setegid, 1<<32) ++ @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()') ++ def test_setreuid(self): ++ if os.getuid() != 0: ++ self.assertRaises(os.error, os.setreuid, 0, 0) ++ self.assertRaises(OverflowError, os.setreuid, 1<<32, 0) ++ self.assertRaises(OverflowError, os.setreuid, 0, 1<<32) + +- if hasattr(os, 'setreuid'): +- def test_setreuid(self): +- if os.getuid() != 0: +- self.assertRaises(os.error, os.setreuid, 0, 0) +- self.assertRaises(OverflowError, os.setreuid, 1<<32, 0) +- self.assertRaises(OverflowError, os.setreuid, 0, 1<<32) ++ @unittest.skipUnless(hasattr(os, 'setreuid'), 'test needs os.setreuid()') ++ def test_setreuid_neg1(self): ++ # Needs to accept -1. We run this in a subprocess to avoid ++ # altering the test runner's process state (issue8045). ++ subprocess.check_call([ ++ sys.executable, '-c', ++ 'import os,sys;os.setreuid(-1,-1);sys.exit(0)']) + +- def test_setreuid_neg1(self): +- # Needs to accept -1. We run this in a subprocess to avoid +- # altering the test runner's process state (issue8045). +- subprocess.check_call([ +- sys.executable, '-c', +- 'import os,sys;os.setreuid(-1,-1);sys.exit(0)']) ++ @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()') ++ def test_setregid(self): ++ if os.getuid() != 0: ++ self.assertRaises(os.error, os.setregid, 0, 0) ++ self.assertRaises(OverflowError, os.setregid, 1<<32, 0) ++ self.assertRaises(OverflowError, os.setregid, 0, 1<<32) + +- if hasattr(os, 'setregid'): +- def test_setregid(self): +- if os.getuid() != 0: +- self.assertRaises(os.error, os.setregid, 0, 0) +- self.assertRaises(OverflowError, os.setregid, 1<<32, 0) +- self.assertRaises(OverflowError, os.setregid, 0, 1<<32) ++ @unittest.skipUnless(hasattr(os, 'setregid'), 'test needs os.setregid()') ++ def test_setregid_neg1(self): ++ # Needs to accept -1. We run this in a subprocess to avoid ++ # altering the test runner's process state (issue8045). ++ subprocess.check_call([ ++ sys.executable, '-c', ++ 'import os,sys;os.setregid(-1,-1);sys.exit(0)']) + +- def test_setregid_neg1(self): +- # Needs to accept -1. We run this in a subprocess to avoid +- # altering the test runner's process state (issue8045). +- subprocess.check_call([ +- sys.executable, '-c', +- 'import os,sys;os.setregid(-1,-1);sys.exit(0)']) +-else: +- class PosixUidGidTests(unittest.TestCase): +- pass + + @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") + class Win32KillTests(unittest.TestCase): +diff -r 3a1db0d2747e Lib/test/test_pep263.py +--- a/Lib/test/test_pep263.py ++++ b/Lib/test/test_pep263.py +@@ -58,6 +58,11 @@ + with self.assertRaisesRegexp(SyntaxError, 'BOM'): + compile('\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec') + ++ def test_non_unicode_codec(self): ++ with self.assertRaisesRegexp(SyntaxError, ++ 'codec did not return a unicode'): ++ from test import bad_coding3 ++ + + def test_main(): + test_support.run_unittest(PEP263Test) +diff -r 3a1db0d2747e Lib/test/test_poll.py +--- a/Lib/test/test_poll.py ++++ b/Lib/test/test_poll.py +@@ -3,14 +3,13 @@ + import os + import random + import select +-import _testcapi + try: + import threading + except ImportError: + threading = None + import time + import unittest +-from test.test_support import TESTFN, run_unittest, reap_threads ++from test.test_support import TESTFN, run_unittest, reap_threads, cpython_only + + try: + select.poll +@@ -159,14 +158,23 @@ + if x != 5: + self.fail('Overflow must have occurred') + ++ # Issues #15989, #17919 ++ self.assertRaises(OverflowError, pollster.register, 0, -1) ++ self.assertRaises(OverflowError, pollster.register, 0, 1 << 64) ++ self.assertRaises(OverflowError, pollster.modify, 1, -1) ++ self.assertRaises(OverflowError, pollster.modify, 1, 1 << 64) ++ ++ @cpython_only ++ def test_poll_c_limits(self): ++ from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX + pollster = select.poll() +- # Issue 15989 +- self.assertRaises(OverflowError, pollster.register, 0, +- _testcapi.SHRT_MAX + 1) +- self.assertRaises(OverflowError, pollster.register, 0, +- _testcapi.USHRT_MAX + 1) +- self.assertRaises(OverflowError, pollster.poll, _testcapi.INT_MAX + 1) +- self.assertRaises(OverflowError, pollster.poll, _testcapi.UINT_MAX + 1) ++ pollster.register(1) ++ ++ # Issues #15989, #17919 ++ self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1) ++ self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1) ++ self.assertRaises(OverflowError, pollster.poll, INT_MAX + 1) ++ self.assertRaises(OverflowError, pollster.poll, UINT_MAX + 1) + + @unittest.skipUnless(threading, 'Threading required for this test.') + @reap_threads +diff -r 3a1db0d2747e Lib/test/test_popen.py +--- a/Lib/test/test_popen.py ++++ b/Lib/test/test_popen.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Basic tests for os.popen() + + Particularly useful for platforms that fake popen. +diff -r 3a1db0d2747e Lib/test/test_popen2.py +--- a/Lib/test/test_popen2.py ++++ b/Lib/test/test_popen2.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for popen2.py""" + + import warnings +diff -r 3a1db0d2747e Lib/test/test_poplib.py +--- a/Lib/test/test_poplib.py ++++ b/Lib/test/test_poplib.py +@@ -11,7 +11,7 @@ + import time + import errno + +-from unittest import TestCase ++from unittest import TestCase, skipUnless + from test import test_support + from test.test_support import HOST + threading = test_support.import_module('threading') +@@ -263,17 +263,20 @@ + else: + DummyPOP3Handler.handle_read(self) + +- class TestPOP3_SSLClass(TestPOP3Class): +- # repeat previous tests by using poplib.POP3_SSL ++requires_ssl = skipUnless(SUPPORTS_SSL, 'SSL not supported') + +- def setUp(self): +- self.server = DummyPOP3Server((HOST, 0)) +- self.server.handler = DummyPOP3_SSLHandler +- self.server.start() +- self.client = poplib.POP3_SSL(self.server.host, self.server.port) ++@requires_ssl ++class TestPOP3_SSLClass(TestPOP3Class): ++ # repeat previous tests by using poplib.POP3_SSL + +- def test__all__(self): +- self.assertIn('POP3_SSL', poplib.__all__) ++ def setUp(self): ++ self.server = DummyPOP3Server((HOST, 0)) ++ self.server.handler = DummyPOP3_SSLHandler ++ self.server.start() ++ self.client = poplib.POP3_SSL(self.server.host, self.server.port) ++ ++ def test__all__(self): ++ self.assertIn('POP3_SSL', poplib.__all__) + + + class TestTimeouts(TestCase): +@@ -305,7 +308,7 @@ + serv.close() + + def testTimeoutDefault(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + socket.setdefaulttimeout(30) + try: + pop = poplib.POP3(HOST, self.port) +@@ -315,13 +318,13 @@ + pop.sock.close() + + def testTimeoutNone(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + socket.setdefaulttimeout(30) + try: + pop = poplib.POP3(HOST, self.port, timeout=None) + finally: + socket.setdefaulttimeout(None) +- self.assertTrue(pop.sock.gettimeout() is None) ++ self.assertIsNone(pop.sock.gettimeout()) + pop.sock.close() + + def testTimeoutValue(self): +@@ -331,9 +334,8 @@ + + + def test_main(): +- tests = [TestPOP3Class, TestTimeouts] +- if SUPPORTS_SSL: +- tests.append(TestPOP3_SSLClass) ++ tests = [TestPOP3Class, TestTimeouts, ++ TestPOP3_SSLClass] + thread_info = test_support.threading_setup() + try: + test_support.run_unittest(*tests) +diff -r 3a1db0d2747e Lib/test/test_posix.py +--- a/Lib/test/test_posix.py ++++ b/Lib/test/test_posix.py +@@ -53,47 +53,55 @@ + posix_func() + self.assertRaises(TypeError, posix_func, 1) + +- if hasattr(posix, 'getresuid'): +- def test_getresuid(self): +- user_ids = posix.getresuid() +- self.assertEqual(len(user_ids), 3) +- for val in user_ids: +- self.assertGreaterEqual(val, 0) ++ @unittest.skipUnless(hasattr(posix, 'getresuid'), ++ 'test needs posix.getresuid()') ++ def test_getresuid(self): ++ user_ids = posix.getresuid() ++ self.assertEqual(len(user_ids), 3) ++ for val in user_ids: ++ self.assertGreaterEqual(val, 0) + +- if hasattr(posix, 'getresgid'): +- def test_getresgid(self): +- group_ids = posix.getresgid() +- self.assertEqual(len(group_ids), 3) +- for val in group_ids: +- self.assertGreaterEqual(val, 0) ++ @unittest.skipUnless(hasattr(posix, 'getresgid'), ++ 'test needs posix.getresgid()') ++ def test_getresgid(self): ++ group_ids = posix.getresgid() ++ self.assertEqual(len(group_ids), 3) ++ for val in group_ids: ++ self.assertGreaterEqual(val, 0) + +- if hasattr(posix, 'setresuid'): +- def test_setresuid(self): +- current_user_ids = posix.getresuid() +- self.assertIsNone(posix.setresuid(*current_user_ids)) +- # -1 means don't change that value. +- self.assertIsNone(posix.setresuid(-1, -1, -1)) ++ @unittest.skipUnless(hasattr(posix, 'setresuid'), ++ 'test needs posix.setresuid()') ++ def test_setresuid(self): ++ current_user_ids = posix.getresuid() ++ self.assertIsNone(posix.setresuid(*current_user_ids)) ++ # -1 means don't change that value. ++ self.assertIsNone(posix.setresuid(-1, -1, -1)) + +- def test_setresuid_exception(self): +- # Don't do this test if someone is silly enough to run us as root. +- current_user_ids = posix.getresuid() +- if 0 not in current_user_ids: +- new_user_ids = (current_user_ids[0]+1, -1, -1) +- self.assertRaises(OSError, posix.setresuid, *new_user_ids) ++ @unittest.skipUnless(hasattr(posix, 'setresuid'), ++ 'test needs posix.setresuid()') ++ def test_setresuid_exception(self): ++ # Don't do this test if someone is silly enough to run us as root. ++ current_user_ids = posix.getresuid() ++ if 0 not in current_user_ids: ++ new_user_ids = (current_user_ids[0]+1, -1, -1) ++ self.assertRaises(OSError, posix.setresuid, *new_user_ids) + +- if hasattr(posix, 'setresgid'): +- def test_setresgid(self): +- current_group_ids = posix.getresgid() +- self.assertIsNone(posix.setresgid(*current_group_ids)) +- # -1 means don't change that value. +- self.assertIsNone(posix.setresgid(-1, -1, -1)) ++ @unittest.skipUnless(hasattr(posix, 'setresgid'), ++ 'test needs posix.setresgid()') ++ def test_setresgid(self): ++ current_group_ids = posix.getresgid() ++ self.assertIsNone(posix.setresgid(*current_group_ids)) ++ # -1 means don't change that value. ++ self.assertIsNone(posix.setresgid(-1, -1, -1)) + +- def test_setresgid_exception(self): +- # Don't do this test if someone is silly enough to run us as root. +- current_group_ids = posix.getresgid() +- if 0 not in current_group_ids: +- new_group_ids = (current_group_ids[0]+1, -1, -1) +- self.assertRaises(OSError, posix.setresgid, *new_group_ids) ++ @unittest.skipUnless(hasattr(posix, 'setresgid'), ++ 'test needs posix.setresgid()') ++ def test_setresgid_exception(self): ++ # Don't do this test if someone is silly enough to run us as root. ++ current_group_ids = posix.getresgid() ++ if 0 not in current_group_ids: ++ new_group_ids = (current_group_ids[0]+1, -1, -1) ++ self.assertRaises(OSError, posix.setresgid, *new_group_ids) + + @unittest.skipUnless(hasattr(posix, 'initgroups'), + "test needs os.initgroups()") +@@ -120,107 +128,118 @@ + else: + self.fail("Expected OSError to be raised by initgroups") + ++ @unittest.skipUnless(hasattr(posix, 'statvfs'), ++ 'test needs posix.statvfs()') + def test_statvfs(self): +- if hasattr(posix, 'statvfs'): +- self.assertTrue(posix.statvfs(os.curdir)) ++ self.assertTrue(posix.statvfs(os.curdir)) + ++ @unittest.skipUnless(hasattr(posix, 'fstatvfs'), ++ 'test needs posix.fstatvfs()') + def test_fstatvfs(self): +- if hasattr(posix, 'fstatvfs'): +- fp = open(test_support.TESTFN) +- try: +- self.assertTrue(posix.fstatvfs(fp.fileno())) +- finally: +- fp.close() ++ fp = open(test_support.TESTFN) ++ try: ++ self.assertTrue(posix.fstatvfs(fp.fileno())) ++ finally: ++ fp.close() + ++ @unittest.skipUnless(hasattr(posix, 'ftruncate'), ++ 'test needs posix.ftruncate()') + def test_ftruncate(self): +- if hasattr(posix, 'ftruncate'): +- fp = open(test_support.TESTFN, 'w+') +- try: +- # we need to have some data to truncate +- fp.write('test') +- fp.flush() +- posix.ftruncate(fp.fileno(), 0) +- finally: +- fp.close() ++ fp = open(test_support.TESTFN, 'w+') ++ try: ++ # we need to have some data to truncate ++ fp.write('test') ++ fp.flush() ++ posix.ftruncate(fp.fileno(), 0) ++ finally: ++ fp.close() + ++ @unittest.skipUnless(hasattr(posix, 'dup'), ++ 'test needs posix.dup()') + def test_dup(self): +- if hasattr(posix, 'dup'): +- fp = open(test_support.TESTFN) +- try: +- fd = posix.dup(fp.fileno()) +- self.assertIsInstance(fd, int) +- os.close(fd) +- finally: +- fp.close() ++ fp = open(test_support.TESTFN) ++ try: ++ fd = posix.dup(fp.fileno()) ++ self.assertIsInstance(fd, int) ++ os.close(fd) ++ finally: ++ fp.close() + ++ @unittest.skipUnless(hasattr(posix, 'confstr'), ++ 'test needs posix.confstr()') + def test_confstr(self): +- if hasattr(posix, 'confstr'): +- self.assertRaises(ValueError, posix.confstr, "CS_garbage") +- self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True) ++ self.assertRaises(ValueError, posix.confstr, "CS_garbage") ++ self.assertEqual(len(posix.confstr("CS_PATH")) > 0, True) + ++ @unittest.skipUnless(hasattr(posix, 'dup2'), ++ 'test needs posix.dup2()') + def test_dup2(self): +- if hasattr(posix, 'dup2'): +- fp1 = open(test_support.TESTFN) +- fp2 = open(test_support.TESTFN) +- try: +- posix.dup2(fp1.fileno(), fp2.fileno()) +- finally: +- fp1.close() +- fp2.close() ++ fp1 = open(test_support.TESTFN) ++ fp2 = open(test_support.TESTFN) ++ try: ++ posix.dup2(fp1.fileno(), fp2.fileno()) ++ finally: ++ fp1.close() ++ fp2.close() + + def fdopen_helper(self, *args): + fd = os.open(test_support.TESTFN, os.O_RDONLY) + fp2 = posix.fdopen(fd, *args) + fp2.close() + ++ @unittest.skipUnless(hasattr(posix, 'fdopen'), ++ 'test needs posix.fdopen()') + def test_fdopen(self): +- if hasattr(posix, 'fdopen'): +- self.fdopen_helper() +- self.fdopen_helper('r') +- self.fdopen_helper('r', 100) ++ self.fdopen_helper() ++ self.fdopen_helper('r') ++ self.fdopen_helper('r', 100) + ++ @unittest.skipUnless(hasattr(posix, 'O_EXLOCK'), ++ 'test needs posix.O_EXLOCK') + def test_osexlock(self): +- if hasattr(posix, "O_EXLOCK"): ++ fd = os.open(test_support.TESTFN, ++ os.O_WRONLY|os.O_EXLOCK|os.O_CREAT) ++ self.assertRaises(OSError, os.open, test_support.TESTFN, ++ os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK) ++ os.close(fd) ++ ++ if hasattr(posix, "O_SHLOCK"): + fd = os.open(test_support.TESTFN, +- os.O_WRONLY|os.O_EXLOCK|os.O_CREAT) ++ os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) + self.assertRaises(OSError, os.open, test_support.TESTFN, + os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK) + os.close(fd) + +- if hasattr(posix, "O_SHLOCK"): +- fd = os.open(test_support.TESTFN, +- os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) +- self.assertRaises(OSError, os.open, test_support.TESTFN, +- os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK) +- os.close(fd) ++ @unittest.skipUnless(hasattr(posix, 'O_SHLOCK'), ++ 'test needs posix.O_SHLOCK') ++ def test_osshlock(self): ++ fd1 = os.open(test_support.TESTFN, ++ os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) ++ fd2 = os.open(test_support.TESTFN, ++ os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) ++ os.close(fd2) ++ os.close(fd1) + +- def test_osshlock(self): +- if hasattr(posix, "O_SHLOCK"): +- fd1 = os.open(test_support.TESTFN, ++ if hasattr(posix, "O_EXLOCK"): ++ fd = os.open(test_support.TESTFN, + os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) +- fd2 = os.open(test_support.TESTFN, +- os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) +- os.close(fd2) +- os.close(fd1) ++ self.assertRaises(OSError, os.open, test_support.TESTFN, ++ os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK) ++ os.close(fd) + +- if hasattr(posix, "O_EXLOCK"): +- fd = os.open(test_support.TESTFN, +- os.O_WRONLY|os.O_SHLOCK|os.O_CREAT) +- self.assertRaises(OSError, os.open, test_support.TESTFN, +- os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK) +- os.close(fd) ++ @unittest.skipUnless(hasattr(posix, 'fstat'), ++ 'test needs posix.fstat()') ++ def test_fstat(self): ++ fp = open(test_support.TESTFN) ++ try: ++ self.assertTrue(posix.fstat(fp.fileno())) ++ finally: ++ fp.close() + +- def test_fstat(self): +- if hasattr(posix, 'fstat'): +- fp = open(test_support.TESTFN) +- try: +- self.assertTrue(posix.fstat(fp.fileno())) +- finally: +- fp.close() +- ++ @unittest.skipUnless(hasattr(posix, 'stat'), ++ 'test needs posix.stat()') + def test_stat(self): +- if hasattr(posix, 'stat'): +- self.assertTrue(posix.stat(test_support.TESTFN)) ++ self.assertTrue(posix.stat(test_support.TESTFN)) + + def _test_all_chown_common(self, chown_func, first_param, stat_func): + """Common code for chown, fchown and lchown tests.""" +@@ -313,59 +332,62 @@ + self._test_all_chown_common(posix.lchown, test_support.TESTFN, + getattr(posix, 'lstat', None)) + ++ @unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()') + def test_chdir(self): +- if hasattr(posix, 'chdir'): +- posix.chdir(os.curdir) +- self.assertRaises(OSError, posix.chdir, test_support.TESTFN) ++ posix.chdir(os.curdir) ++ self.assertRaises(OSError, posix.chdir, test_support.TESTFN) + ++ @unittest.skipUnless(hasattr(posix, 'lsdir'), 'test needs posix.lsdir()') + def test_lsdir(self): +- if hasattr(posix, 'lsdir'): +- self.assertIn(test_support.TESTFN, posix.lsdir(os.curdir)) ++ self.assertIn(test_support.TESTFN, posix.lsdir(os.curdir)) + ++ @unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()') + def test_access(self): +- if hasattr(posix, 'access'): +- self.assertTrue(posix.access(test_support.TESTFN, os.R_OK)) ++ self.assertTrue(posix.access(test_support.TESTFN, os.R_OK)) + ++ @unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()') + def test_umask(self): +- if hasattr(posix, 'umask'): +- old_mask = posix.umask(0) +- self.assertIsInstance(old_mask, int) +- posix.umask(old_mask) ++ old_mask = posix.umask(0) ++ self.assertIsInstance(old_mask, int) ++ posix.umask(old_mask) + ++ @unittest.skipUnless(hasattr(posix, 'strerror'), ++ 'test needs posix.strerror()') + def test_strerror(self): +- if hasattr(posix, 'strerror'): +- self.assertTrue(posix.strerror(0)) ++ self.assertTrue(posix.strerror(0)) + ++ @unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()') + def test_pipe(self): +- if hasattr(posix, 'pipe'): +- reader, writer = posix.pipe() +- os.close(reader) +- os.close(writer) ++ reader, writer = posix.pipe() ++ os.close(reader) ++ os.close(writer) + ++ @unittest.skipUnless(hasattr(posix, 'tempnam'), ++ 'test needs posix.tempnam()') + def test_tempnam(self): +- if hasattr(posix, 'tempnam'): +- with warnings.catch_warnings(): +- warnings.filterwarnings("ignore", "tempnam", DeprecationWarning) +- self.assertTrue(posix.tempnam()) +- self.assertTrue(posix.tempnam(os.curdir)) +- self.assertTrue(posix.tempnam(os.curdir, 'blah')) ++ with warnings.catch_warnings(): ++ warnings.filterwarnings("ignore", "tempnam", DeprecationWarning) ++ self.assertTrue(posix.tempnam()) ++ self.assertTrue(posix.tempnam(os.curdir)) ++ self.assertTrue(posix.tempnam(os.curdir, 'blah')) + ++ @unittest.skipUnless(hasattr(posix, 'tmpfile'), ++ 'test needs posix.tmpfile()') + def test_tmpfile(self): +- if hasattr(posix, 'tmpfile'): +- with warnings.catch_warnings(): +- warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning) +- fp = posix.tmpfile() +- fp.close() ++ with warnings.catch_warnings(): ++ warnings.filterwarnings("ignore", "tmpfile", DeprecationWarning) ++ fp = posix.tmpfile() ++ fp.close() + ++ @unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()') + def test_utime(self): +- if hasattr(posix, 'utime'): +- now = time.time() +- posix.utime(test_support.TESTFN, None) +- self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (None, None)) +- self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (now, None)) +- self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (None, now)) +- posix.utime(test_support.TESTFN, (int(now), int(now))) +- posix.utime(test_support.TESTFN, (now, now)) ++ now = time.time() ++ posix.utime(test_support.TESTFN, None) ++ self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (None, None)) ++ self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (now, None)) ++ self.assertRaises(TypeError, posix.utime, test_support.TESTFN, (None, now)) ++ posix.utime(test_support.TESTFN, (int(now), int(now))) ++ posix.utime(test_support.TESTFN, (now, now)) + + def _test_chflags_regular_file(self, chflags_func, target_file): + st = os.stat(target_file) +@@ -428,56 +450,54 @@ + finally: + posix.lchflags(_DUMMY_SYMLINK, dummy_symlink_st.st_flags) + ++ @unittest.skipUnless(hasattr(posix, 'getcwd'), ++ 'test needs posix.getcwd()') + def test_getcwd_long_pathnames(self): +- if hasattr(posix, 'getcwd'): +- dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef' +- curdir = os.getcwd() +- base_path = os.path.abspath(test_support.TESTFN) + '.getcwd' ++ dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef' ++ curdir = os.getcwd() ++ base_path = os.path.abspath(test_support.TESTFN) + '.getcwd' + +- try: +- os.mkdir(base_path) +- os.chdir(base_path) +- except: +-# Just returning nothing instead of the SkipTest exception, +-# because the test results in Error in that case. +-# Is that ok? +-# raise unittest.SkipTest, "cannot create directory for testing" +- return ++ try: ++ os.mkdir(base_path) ++ os.chdir(base_path) ++ except: ++ self.skipTest("cannot create directory for testing") + +- try: +- def _create_and_do_getcwd(dirname, current_path_length = 0): +- try: +- os.mkdir(dirname) +- except: +- raise unittest.SkipTest, "mkdir cannot create directory sufficiently deep for getcwd test" ++ try: ++ def _create_and_do_getcwd(dirname, current_path_length = 0): ++ try: ++ os.mkdir(dirname) ++ except: ++ self.skipTest("mkdir cannot create directory sufficiently " ++ "deep for getcwd test") + +- os.chdir(dirname) +- try: +- os.getcwd() +- if current_path_length < 4099: +- _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1) +- except OSError as e: +- expected_errno = errno.ENAMETOOLONG +- # The following platforms have quirky getcwd() +- # behaviour -- see issue 9185 and 15765 for +- # more information. +- quirky_platform = ( +- 'sunos' in sys.platform or +- 'netbsd' in sys.platform or +- 'openbsd' in sys.platform +- ) +- if quirky_platform: +- expected_errno = errno.ERANGE +- self.assertEqual(e.errno, expected_errno) +- finally: +- os.chdir('..') +- os.rmdir(dirname) ++ os.chdir(dirname) ++ try: ++ os.getcwd() ++ if current_path_length < 4099: ++ _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1) ++ except OSError as e: ++ expected_errno = errno.ENAMETOOLONG ++ # The following platforms have quirky getcwd() ++ # behaviour -- see issue 9185 and 15765 for ++ # more information. ++ quirky_platform = ( ++ 'sunos' in sys.platform or ++ 'netbsd' in sys.platform or ++ 'openbsd' in sys.platform ++ ) ++ if quirky_platform: ++ expected_errno = errno.ERANGE ++ self.assertEqual(e.errno, expected_errno) ++ finally: ++ os.chdir('..') ++ os.rmdir(dirname) + +- _create_and_do_getcwd(dirname) ++ _create_and_do_getcwd(dirname) + +- finally: +- os.chdir(curdir) +- shutil.rmtree(base_path) ++ finally: ++ os.chdir(curdir) ++ shutil.rmtree(base_path) + + @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()") + def test_getgroups(self): +@@ -522,17 +542,17 @@ + posix.initgroups(name, self.saved_groups[0]) + + @unittest.skipUnless(hasattr(posix, 'initgroups'), +- "test needs posix.initgroups()") ++ 'test needs posix.initgroups()') + def test_initgroups(self): + # find missing group + +- g = max(self.saved_groups) + 1 ++ g = max(self.saved_groups or [0]) + 1 + name = pwd.getpwuid(posix.getuid()).pw_name + posix.initgroups(name, g) + self.assertIn(g, posix.getgroups()) + + @unittest.skipUnless(hasattr(posix, 'setgroups'), +- "test needs posix.setgroups()") ++ 'test needs posix.setgroups()') + def test_setgroups(self): + for groups in [[0], range(16)]: + posix.setgroups(groups) +diff -r 3a1db0d2747e Lib/test/test_pwd.py +--- a/Lib/test/test_pwd.py ++++ b/Lib/test/test_pwd.py +@@ -8,8 +8,6 @@ + + def test_values(self): + entries = pwd.getpwall() +- entriesbyname = {} +- entriesbyuid = {} + + for e in entries: + self.assertEqual(len(e), 7) +@@ -32,13 +30,20 @@ + # for one uid + # self.assertEqual(pwd.getpwuid(e.pw_uid), e) + # instead of this collect all entries for one uid +- # and check afterwards ++ # and check afterwards (done in test_values_extended) ++ ++ def test_values_extended(self): ++ entries = pwd.getpwall() ++ entriesbyname = {} ++ entriesbyuid = {} ++ ++ if len(entries) > 1000: # Huge passwd file (NIS?) -- skip this test ++ self.skipTest('passwd file is huge; extended test skipped') ++ ++ for e in entries: + entriesbyname.setdefault(e.pw_name, []).append(e) + entriesbyuid.setdefault(e.pw_uid, []).append(e) + +- if len(entries) > 1000: # Huge passwd file (NIS?) -- skip the rest +- return +- + # check whether the entry returned by getpwuid() + # for each uid is among those from getpwall() for this uid + for e in entries: +diff -r 3a1db0d2747e Lib/test/test_pydoc.py +--- a/Lib/test/test_pydoc.py ++++ b/Lib/test/test_pydoc.py +@@ -10,6 +10,7 @@ + import pkgutil + import unittest + import xml.etree ++import types + import test.test_support + from collections import namedtuple + from test.script_helper import assert_python_ok +@@ -421,13 +422,103 @@ + def test_namedtuple_public_underscore(self): + NT = namedtuple('NT', ['abc', 'def'], rename=True) + with captured_stdout() as help_io: +- help(NT) ++ pydoc.help(NT) + helptext = help_io.getvalue() + self.assertIn('_1', helptext) + self.assertIn('_replace', helptext) + self.assertIn('_asdict', helptext) + + ++@unittest.skipUnless(test.test_support.have_unicode, ++ "test requires unicode support") ++class TestUnicode(unittest.TestCase): ++ ++ def setUp(self): ++ # Better not to use unicode escapes in literals, lest the ++ # parser choke on it if Python has been built without ++ # unicode support. ++ self.Q = types.ModuleType( ++ 'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8')) ++ self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8') ++ self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8') ++ self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8') ++ self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8') ++ ++ self.assertIsInstance(self.Q.__doc__, unicode) ++ ++ def test_render_doc(self): ++ # render_doc is robust against unicode in docstrings ++ doc = pydoc.render_doc(self.Q) ++ self.assertIsInstance(doc, str) ++ ++ def test_encode(self): ++ # _encode is robust against characters out the specified encoding ++ self.assertEqual(pydoc._encode(self.Q.__doc__, 'ascii'), 'Rational numbers: ℚ') ++ ++ def test_pipepager(self): ++ # pipepager does not choke on unicode ++ doc = pydoc.render_doc(self.Q) ++ ++ saved, os.popen = os.popen, open ++ try: ++ with test.test_support.temp_cwd(): ++ pydoc.pipepager(doc, 'pipe') ++ self.assertEqual(open('pipe').read(), pydoc._encode(doc)) ++ finally: ++ os.popen = saved ++ ++ def test_tempfilepager(self): ++ # tempfilepager does not choke on unicode ++ doc = pydoc.render_doc(self.Q) ++ ++ output = {} ++ def mock_system(cmd): ++ filename = cmd.strip()[1:-1] ++ self.assertEqual('"' + filename + '"', cmd.strip()) ++ output['content'] = open(filename).read() ++ saved, os.system = os.system, mock_system ++ try: ++ pydoc.tempfilepager(doc, '') ++ self.assertEqual(output['content'], pydoc._encode(doc)) ++ finally: ++ os.system = saved ++ ++ def test_plainpager(self): ++ # plainpager does not choke on unicode ++ doc = pydoc.render_doc(self.Q) ++ ++ # Note: captured_stdout is too permissive when it comes to ++ # unicode, and using it here would make the test always ++ # pass. ++ with test.test_support.temp_cwd(): ++ with open('output', 'w') as f: ++ saved, sys.stdout = sys.stdout, f ++ try: ++ pydoc.plainpager(doc) ++ finally: ++ sys.stdout = saved ++ self.assertIn('Rational numbers:', open('output').read()) ++ ++ def test_ttypager(self): ++ # ttypager does not choke on unicode ++ doc = pydoc.render_doc(self.Q) ++ # Test ttypager ++ with test.test_support.temp_cwd(), test.test_support.captured_stdin(): ++ with open('output', 'w') as f: ++ saved, sys.stdout = sys.stdout, f ++ try: ++ pydoc.ttypager(doc) ++ finally: ++ sys.stdout = saved ++ self.assertIn('Rational numbers:', open('output').read()) ++ ++ def test_htmlpage(self): ++ # html.page does not choke on unicode ++ with test.test_support.temp_cwd(): ++ with captured_stdout() as output: ++ pydoc.writedoc(self.Q) ++ self.assertEqual(output.getvalue(), 'wrote Q.html\n') ++ + class TestHelper(unittest.TestCase): + def test_keywords(self): + self.assertEqual(sorted(pydoc.Helper.keywords), +@@ -456,6 +547,7 @@ + test.test_support.run_unittest(PydocDocTest, + PydocImportTest, + TestDescriptions, ++ TestUnicode, + TestHelper) + finally: + reap_children() +diff -r 3a1db0d2747e Lib/test/test_random.py +--- a/Lib/test/test_random.py ++++ b/Lib/test/test_random.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +- + import unittest + import random + import time +@@ -251,10 +249,10 @@ + + def test_bigrand_ranges(self): + for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: +- start = self.gen.randrange(2 ** i) +- stop = self.gen.randrange(2 ** (i-2)) ++ start = self.gen.randrange(2 ** (i-2)) ++ stop = self.gen.randrange(2 ** i) + if stop <= start: +- return ++ continue + self.assertTrue(start <= self.gen.randrange(start, stop) < stop) + + def test_rangelimits(self): +@@ -403,10 +401,10 @@ + + def test_bigrand_ranges(self): + for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: +- start = self.gen.randrange(2 ** i) +- stop = self.gen.randrange(2 ** (i-2)) ++ start = self.gen.randrange(2 ** (i-2)) ++ stop = self.gen.randrange(2 ** i) + if stop <= start: +- return ++ continue + self.assertTrue(start <= self.gen.randrange(start, stop) < stop) + + def test_rangelimits(self): +diff -r 3a1db0d2747e Lib/test/test_re.py +--- a/Lib/test/test_re.py ++++ b/Lib/test/test_re.py +@@ -1,5 +1,6 @@ + from test.test_support import verbose, run_unittest, import_module + from test.test_support import precisionbigmemtest, _2G, cpython_only ++from test.test_support import captured_stdout + import re + from re import Scanner + import sre_constants +@@ -700,7 +701,7 @@ + try: + unicode + except NameError: +- return # no problem if we have no unicode ++ self.skipTest('no problem if we have no unicode') + class my_unicode(unicode): pass + pat = re.compile(my_unicode("abc")) + self.assertEqual(pat.match("xyz"), None) +@@ -714,7 +715,7 @@ + try: + unicode + except NameError: +- return # no problem if we have no unicode ++ self.skipTest('no problem if we have no unicode') + self.assertTrue(re.compile('bug_926075') is not + re.compile(eval("u'bug_926075'"))) + +@@ -722,7 +723,7 @@ + try: + unicode + except NameError: +- pass ++ self.skipTest('no problem if we have no unicode') + pattern = eval('u"[\u002E\u3002\uFF0E\uFF61]"') + self.assertEqual(re.compile(pattern).split("a.b.c"), + ['a','b','c']) +@@ -920,6 +921,32 @@ + self.assertEqual(m.group(1), "") + self.assertEqual(m.group(2), "y") + ++ def test_debug_flag(self): ++ with captured_stdout() as out: ++ re.compile('foo', re.DEBUG) ++ self.assertEqual(out.getvalue().splitlines(), ++ ['literal 102', 'literal 111', 'literal 111']) ++ # Debug output is output again even a second time (bypassing ++ # the cache -- issue #20426). ++ with captured_stdout() as out: ++ re.compile('foo', re.DEBUG) ++ self.assertEqual(out.getvalue().splitlines(), ++ ['literal 102', 'literal 111', 'literal 111']) ++ ++ def test_keyword_parameters(self): ++ # Issue #20283: Accepting the string keyword parameter. ++ pat = re.compile(r'(ab)') ++ self.assertEqual( ++ pat.match(string='abracadabra', pos=7, endpos=10).span(), (7, 9)) ++ self.assertEqual( ++ pat.search(string='abracadabra', pos=3, endpos=10).span(), (7, 9)) ++ self.assertEqual( ++ pat.findall(string='abracadabra', pos=3, endpos=10), ['ab']) ++ self.assertEqual( ++ pat.split(string='abracadabra', maxsplit=1), ++ ['', 'ab', 'racadabra']) ++ ++ + def run_re_tests(): + from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR + if verbose: +diff -r 3a1db0d2747e Lib/test/test_repr.py +--- a/Lib/test/test_repr.py ++++ b/Lib/test/test_repr.py +@@ -179,8 +179,15 @@ + self.assertTrue(repr(x).startswith('') ++ self.assertRegexpMatches(r(x), r'') + + def test_descriptors(self): + eq = self.assertEqual +@@ -261,6 +268,7 @@ + eq(repr(foo.foo), + "" % foo.__name__) + ++ @unittest.skip('need a suitable object') + def test_object(self): + # XXX Test the repr of a type with a really long tp_name but with no + # tp_repr. WIBNI we had ::Inline? :) +@@ -302,6 +310,7 @@ + '= 0, "Error resolving host to ip.") + try: + hname, aliases, ipaddrs = socket.gethostbyaddr(ip) + except socket.error: + # Probably a similar problem as above; skip this test +- return ++ self.skipTest('address lookup failure') + all_host_names = [hostname, hname] + aliases + fqhn = socket.getfqdn(ip) + if not fqhn in all_host_names: + self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) + ++ @unittest.skipUnless(hasattr(sys, 'getrefcount'), ++ 'test needs sys.getrefcount()') + def testRefCountGetNameInfo(self): + # Testing reference count for getnameinfo +- if hasattr(sys, "getrefcount"): +- try: +- # On some versions, this loses a reference +- orig = sys.getrefcount(__name__) +- socket.getnameinfo(__name__,0) +- except TypeError: +- self.assertEqual(sys.getrefcount(__name__), orig, +- "socket.getnameinfo loses a reference") ++ try: ++ # On some versions, this loses a reference ++ orig = sys.getrefcount(__name__) ++ socket.getnameinfo(__name__,0) ++ except TypeError: ++ self.assertEqual(sys.getrefcount(__name__), orig, ++ "socket.getnameinfo loses a reference") + + def testInterpreterCrash(self): + # Making sure getnameinfo doesn't crash the interpreter +@@ -459,17 +457,17 @@ + # Check that setting it to an invalid type raises TypeError + self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") + ++ @unittest.skipUnless(hasattr(socket, 'inet_aton'), ++ 'test needs socket.inet_aton()') + def testIPv4_inet_aton_fourbytes(self): +- if not hasattr(socket, 'inet_aton'): +- return # No inet_aton, nothing to check + # Test that issue1008086 and issue767150 are fixed. + # It must return 4 bytes. + self.assertEqual('\x00'*4, socket.inet_aton('0.0.0.0')) + self.assertEqual('\xff'*4, socket.inet_aton('255.255.255.255')) + ++ @unittest.skipUnless(hasattr(socket, 'inet_pton'), ++ 'test needs socket.inet_pton()') + def testIPv4toString(self): +- if not hasattr(socket, 'inet_pton'): +- return # No inet_pton() on this platform + from socket import inet_aton as f, inet_pton, AF_INET + g = lambda a: inet_pton(AF_INET, a) + +@@ -484,15 +482,15 @@ + self.assertEqual('\xaa\xaa\xaa\xaa', g('170.170.170.170')) + self.assertEqual('\xff\xff\xff\xff', g('255.255.255.255')) + ++ @unittest.skipUnless(hasattr(socket, 'inet_pton'), ++ 'test needs socket.inet_pton()') + def testIPv6toString(self): +- if not hasattr(socket, 'inet_pton'): +- return # No inet_pton() on this platform + try: + from socket import inet_pton, AF_INET6, has_ipv6 + if not has_ipv6: +- return ++ self.skipTest('IPv6 not available') + except ImportError: +- return ++ self.skipTest('could not import needed symbols from socket') + f = lambda a: inet_pton(AF_INET6, a) + + self.assertEqual('\x00' * 16, f('::')) +@@ -503,9 +501,9 @@ + f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') + ) + ++ @unittest.skipUnless(hasattr(socket, 'inet_ntop'), ++ 'test needs socket.inet_ntop()') + def testStringToIPv4(self): +- if not hasattr(socket, 'inet_ntop'): +- return # No inet_ntop() on this platform + from socket import inet_ntoa as f, inet_ntop, AF_INET + g = lambda a: inet_ntop(AF_INET, a) + +@@ -518,15 +516,15 @@ + self.assertEqual('170.85.170.85', g('\xaa\x55\xaa\x55')) + self.assertEqual('255.255.255.255', g('\xff\xff\xff\xff')) + ++ @unittest.skipUnless(hasattr(socket, 'inet_ntop'), ++ 'test needs socket.inet_ntop()') + def testStringToIPv6(self): +- if not hasattr(socket, 'inet_ntop'): +- return # No inet_ntop() on this platform + try: + from socket import inet_ntop, AF_INET6, has_ipv6 + if not has_ipv6: +- return ++ self.skipTest('IPv6 not available') + except ImportError: +- return ++ self.skipTest('could not import needed symbols from socket') + f = lambda a: inet_ntop(AF_INET6, a) + + self.assertEqual('::', f('\x00' * 16)) +@@ -566,7 +564,7 @@ + my_ip_addr = socket.gethostbyname(socket.gethostname()) + except socket.error: + # Probably name lookup wasn't set up right; skip this test +- return ++ self.skipTest('name lookup failure') + self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) + self.assertEqual(name[1], port) + +@@ -665,9 +663,15 @@ + socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, + socket.AI_PASSIVE) + +- # Issue 17269 ++ # Issue 17269: test workaround for OS X platform bug segfault + if hasattr(socket, 'AI_NUMERICSERV'): +- socket.getaddrinfo("localhost", None, 0, 0, 0, socket.AI_NUMERICSERV) ++ try: ++ # The arguments here are undefined and the call may succeed ++ # or fail. All we care here is that it doesn't segfault. ++ socket.getaddrinfo("localhost", None, 0, 0, 0, ++ socket.AI_NUMERICSERV) ++ except socket.gaierror: ++ pass + + def check_sendall_interrupted(self, with_timeout): + # socketpair() is not stricly required, but it makes things easier. +@@ -712,7 +716,10 @@ + srv.listen(backlog) + srv.close() + ++ @test_support.cpython_only ++ def test_listen_backlog_overflow(self): + # Issue 15989 ++ import _testcapi + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.bind((HOST, 0)) + self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1) +@@ -785,10 +792,10 @@ + big_chunk = 'f' * 2048 + self.serv_conn.sendall(big_chunk) + ++ @unittest.skipUnless(hasattr(socket, 'fromfd'), ++ 'socket.fromfd not availble') + def testFromFd(self): + # Testing fromfd() +- if not hasattr(socket, "fromfd"): +- return # On Windows, this doesn't exist + fd = self.cli_conn.fileno() + sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) + self.addCleanup(sock.close) +@@ -819,6 +826,14 @@ + + def _testShutdown(self): + self.serv_conn.send(MSG) ++ self.serv_conn.shutdown(2) ++ ++ testShutdown_overflow = test_support.cpython_only(testShutdown) ++ ++ @test_support.cpython_only ++ def _testShutdown_overflow(self): ++ import _testcapi ++ self.serv_conn.send(MSG) + # Issue 15989 + self.assertRaises(OverflowError, self.serv_conn.shutdown, + _testcapi.INT_MAX + 1) +@@ -871,6 +886,8 @@ + self.cli.connect((HOST, self.port)) + time.sleep(1.0) + ++@unittest.skipUnless(hasattr(socket, 'socketpair'), ++ 'test needs socket.socketpair()') + @unittest.skipUnless(thread, 'Threading required for this test.') + class BasicSocketPairTest(SocketPairTest): + +@@ -910,14 +927,23 @@ + pass + end = time.time() + self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.") +- # Issue 15989 +- if _testcapi.UINT_MAX < _testcapi.ULONG_MAX: +- self.serv.setblocking(_testcapi.UINT_MAX + 1) +- self.assertIsNone(self.serv.gettimeout()) + + def _testSetBlocking(self): + pass + ++ @test_support.cpython_only ++ def testSetBlocking_overflow(self): ++ # Issue 15989 ++ import _testcapi ++ if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX: ++ self.skipTest('needs UINT_MAX < ULONG_MAX') ++ self.serv.setblocking(False) ++ self.assertEqual(self.serv.gettimeout(), 0.0) ++ self.serv.setblocking(_testcapi.UINT_MAX + 1) ++ self.assertIsNone(self.serv.gettimeout()) ++ ++ _testSetBlocking_overflow = test_support.cpython_only(_testSetBlocking) ++ + def testAccept(self): + # Testing non-blocking accept + self.serv.setblocking(0) +@@ -1456,12 +1482,12 @@ + if not ok: + self.fail("accept() returned success when we did not expect it") + ++ @unittest.skipUnless(hasattr(signal, 'alarm'), ++ 'test needs signal.alarm()') + def testInterruptedTimeout(self): + # XXX I don't know how to do this test on MSWindows or any other + # plaform that doesn't support signal.alarm() or os.kill(), though + # the bug should have existed on all platforms. +- if not hasattr(signal, "alarm"): +- return # can only test on *nix + self.serv.settimeout(5.0) # must be longer than alarm + class Alarm(Exception): + pass +@@ -1521,6 +1547,7 @@ + self.assertTrue(issubclass(socket.gaierror, socket.error)) + self.assertTrue(issubclass(socket.timeout, socket.error)) + ++@unittest.skipUnless(sys.platform == 'linux', 'Linux specific test') + class TestLinuxAbstractNamespace(unittest.TestCase): + + UNIX_PATH_MAX = 108 +@@ -1616,6 +1643,23 @@ + + _testRecvFromIntoMemoryview = _testRecvFromIntoArray + ++ def testRecvFromIntoSmallBuffer(self): ++ # See issue #20246. ++ buf = bytearray(8) ++ self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024) ++ ++ def _testRecvFromIntoSmallBuffer(self): ++ with test_support.check_py3k_warnings(): ++ buf = buffer(MSG) ++ self.serv_conn.send(buf) ++ ++ def testRecvFromIntoEmptyBuffer(self): ++ buf = bytearray() ++ self.cli_conn.recvfrom_into(buf) ++ self.cli_conn.recvfrom_into(buf, 0) ++ ++ _testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray ++ + + TIPC_STYPE = 2000 + TIPC_LOWER = 200 +@@ -1635,11 +1679,11 @@ + for line in f: + if line.startswith("tipc "): + return True +- if test_support.verbose: +- print "TIPC module is not loaded, please 'sudo modprobe tipc'" + return False + +-class TIPCTest (unittest.TestCase): ++@unittest.skipUnless(isTipcAvailable(), ++ "TIPC module is not loaded, please 'sudo modprobe tipc'") ++class TIPCTest(unittest.TestCase): + def testRDM(self): + srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) + cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) +@@ -1659,7 +1703,9 @@ + self.assertEqual(msg, MSG) + + +-class TIPCThreadableTest (unittest.TestCase, ThreadableTest): ++@unittest.skipUnless(isTipcAvailable(), ++ "TIPC module is not loaded, please 'sudo modprobe tipc'") ++class TIPCThreadableTest(unittest.TestCase, ThreadableTest): + def __init__(self, methodName = 'runTest'): + unittest.TestCase.__init__(self, methodName = methodName) + ThreadableTest.__init__(self) +@@ -1712,13 +1758,9 @@ + NetworkConnectionAttributesTest, + NetworkConnectionBehaviourTest, + ]) +- if hasattr(socket, "socketpair"): +- tests.append(BasicSocketPairTest) +- if sys.platform == 'linux2': +- tests.append(TestLinuxAbstractNamespace) +- if isTipcAvailable(): +- tests.append(TIPCTest) +- tests.append(TIPCThreadableTest) ++ tests.append(BasicSocketPairTest) ++ tests.append(TestLinuxAbstractNamespace) ++ tests.extend([TIPCTest, TIPCThreadableTest]) + + thread_info = test_support.threading_setup() + test_support.run_unittest(*tests) +diff -r 3a1db0d2747e Lib/test/test_socketserver.py +--- a/Lib/test/test_socketserver.py ++++ b/Lib/test/test_socketserver.py +@@ -27,7 +27,10 @@ + HOST = test.test_support.HOST + + HAVE_UNIX_SOCKETS = hasattr(socket, "AF_UNIX") ++requires_unix_sockets = unittest.skipUnless(HAVE_UNIX_SOCKETS, ++ 'requires Unix sockets') + HAVE_FORKING = hasattr(os, "fork") and os.name != "os2" ++requires_forking = unittest.skipUnless(HAVE_FORKING, 'requires forking') + + def signal_alarm(n): + """Call signal.alarm when it exists (i.e. not on Windows).""" +@@ -188,31 +191,33 @@ + SocketServer.StreamRequestHandler, + self.stream_examine) + +- if HAVE_FORKING: +- def test_ForkingTCPServer(self): +- with simple_subprocess(self): +- self.run_server(SocketServer.ForkingTCPServer, +- SocketServer.StreamRequestHandler, +- self.stream_examine) +- +- if HAVE_UNIX_SOCKETS: +- def test_UnixStreamServer(self): +- self.run_server(SocketServer.UnixStreamServer, ++ @requires_forking ++ def test_ForkingTCPServer(self): ++ with simple_subprocess(self): ++ self.run_server(SocketServer.ForkingTCPServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + +- def test_ThreadingUnixStreamServer(self): +- self.run_server(SocketServer.ThreadingUnixStreamServer, ++ @requires_unix_sockets ++ def test_UnixStreamServer(self): ++ self.run_server(SocketServer.UnixStreamServer, ++ SocketServer.StreamRequestHandler, ++ self.stream_examine) ++ ++ @requires_unix_sockets ++ def test_ThreadingUnixStreamServer(self): ++ self.run_server(SocketServer.ThreadingUnixStreamServer, ++ SocketServer.StreamRequestHandler, ++ self.stream_examine) ++ ++ @requires_unix_sockets ++ @requires_forking ++ def test_ForkingUnixStreamServer(self): ++ with simple_subprocess(self): ++ self.run_server(ForkingUnixStreamServer, + SocketServer.StreamRequestHandler, + self.stream_examine) + +- if HAVE_FORKING: +- def test_ForkingUnixStreamServer(self): +- with simple_subprocess(self): +- self.run_server(ForkingUnixStreamServer, +- SocketServer.StreamRequestHandler, +- self.stream_examine) +- + def test_UDPServer(self): + self.run_server(SocketServer.UDPServer, + SocketServer.DatagramRequestHandler, +@@ -223,12 +228,12 @@ + SocketServer.DatagramRequestHandler, + self.dgram_examine) + +- if HAVE_FORKING: +- def test_ForkingUDPServer(self): +- with simple_subprocess(self): +- self.run_server(SocketServer.ForkingUDPServer, +- SocketServer.DatagramRequestHandler, +- self.dgram_examine) ++ @requires_forking ++ def test_ForkingUDPServer(self): ++ with simple_subprocess(self): ++ self.run_server(SocketServer.ForkingUDPServer, ++ SocketServer.DatagramRequestHandler, ++ self.dgram_examine) + + @contextlib.contextmanager + def mocked_select_module(self): +@@ -265,22 +270,24 @@ + # Alas, on Linux (at least) recvfrom() doesn't return a meaningful + # client address so this cannot work: + +- # if HAVE_UNIX_SOCKETS: +- # def test_UnixDatagramServer(self): +- # self.run_server(SocketServer.UnixDatagramServer, +- # SocketServer.DatagramRequestHandler, +- # self.dgram_examine) ++ # @requires_unix_sockets ++ # def test_UnixDatagramServer(self): ++ # self.run_server(SocketServer.UnixDatagramServer, ++ # SocketServer.DatagramRequestHandler, ++ # self.dgram_examine) + # +- # def test_ThreadingUnixDatagramServer(self): +- # self.run_server(SocketServer.ThreadingUnixDatagramServer, +- # SocketServer.DatagramRequestHandler, +- # self.dgram_examine) ++ # @requires_unix_sockets ++ # def test_ThreadingUnixDatagramServer(self): ++ # self.run_server(SocketServer.ThreadingUnixDatagramServer, ++ # SocketServer.DatagramRequestHandler, ++ # self.dgram_examine) + # +- # if HAVE_FORKING: +- # def test_ForkingUnixDatagramServer(self): +- # self.run_server(SocketServer.ForkingUnixDatagramServer, +- # SocketServer.DatagramRequestHandler, +- # self.dgram_examine) ++ # @requires_unix_sockets ++ # @requires_forking ++ # def test_ForkingUnixDatagramServer(self): ++ # self.run_server(SocketServer.ForkingUnixDatagramServer, ++ # SocketServer.DatagramRequestHandler, ++ # self.dgram_examine) + + @reap_threads + def test_shutdown(self): +diff -r 3a1db0d2747e Lib/test/test_ssl.py +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -192,9 +192,8 @@ + self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)), + (s, t)) + ++ @test_support.requires_resource('network') + def test_ciphers(self): +- if not test_support.is_resource_enabled('network'): +- return + remote = ("svn.python.org", 443) + with test_support.transient_internet(remote[0]): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), +@@ -233,6 +232,13 @@ + self.assertRaises(socket.error, ss.send, b'x') + self.assertRaises(socket.error, ss.sendto, b'x', ('0.0.0.0', 0)) + ++ def test_unsupported_dtls(self): ++ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ++ self.addCleanup(s.close) ++ with self.assertRaises(NotImplementedError) as cx: ++ ssl.wrap_socket(s, cert_reqs=ssl.CERT_NONE) ++ self.assertEqual(str(cx.exception), "only stream sockets are supported") ++ + + class NetworkedTests(unittest.TestCase): + +@@ -384,19 +390,24 @@ + + def test_get_server_certificate(self): + with test_support.transient_internet("svn.python.org"): +- pem = ssl.get_server_certificate(("svn.python.org", 443)) ++ pem = ssl.get_server_certificate(("svn.python.org", 443), ++ ssl.PROTOCOL_SSLv23) + if not pem: + self.fail("No server certificate on svn.python.org:443!") + + try: +- pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=CERTFILE) ++ pem = ssl.get_server_certificate(("svn.python.org", 443), ++ ssl.PROTOCOL_SSLv23, ++ ca_certs=CERTFILE) + except ssl.SSLError: + #should fail + pass + else: + self.fail("Got server certificate %s for svn.python.org!" % pem) + +- pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT) ++ pem = ssl.get_server_certificate(("svn.python.org", 443), ++ ssl.PROTOCOL_SSLv23, ++ ca_certs=SVN_PYTHON_ORG_ROOT_CERT) + if not pem: + self.fail("No server certificate on svn.python.org:443!") + if test_support.verbose: +@@ -1046,7 +1057,7 @@ + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) +- try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) ++ try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, False) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) + try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + +diff -r 3a1db0d2747e Lib/test/test_str.py +--- a/Lib/test/test_str.py ++++ b/Lib/test/test_str.py +@@ -1,4 +1,4 @@ +- ++import unittest + import struct + import sys + from test import test_support, string_tests +@@ -110,12 +110,12 @@ + self.assertEqual(str(Foo9("foo")), "string") + self.assertEqual(unicode(Foo9("foo")), u"not unicode") + ++ # This test only affects 32-bit platforms because expandtabs can only take ++ # an int as the max value, not a 64-bit C long. If expandtabs is changed ++ # to take a 64-bit long, this test should apply to all platforms. ++ @unittest.skipIf(sys.maxint > (1 << 32) or struct.calcsize('P') != 4, ++ 'only applies to 32-bit platforms') + def test_expandtabs_overflows_gracefully(self): +- # This test only affects 32-bit platforms because expandtabs can only take +- # an int as the max value, not a 64-bit C long. If expandtabs is changed +- # to take a 64-bit long, this test should apply to all platforms. +- if sys.maxint > (1 << 32) or struct.calcsize('P') != 4: +- return + self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxint) + + def test__format__(self): +diff -r 3a1db0d2747e Lib/test/test_strptime.py +--- a/Lib/test/test_strptime.py ++++ b/Lib/test/test_strptime.py +@@ -313,7 +313,7 @@ + # when time.tzname[0] == time.tzname[1] and time.daylight + tz_name = time.tzname[0] + if tz_name.upper() in ("UTC", "GMT"): +- return ++ self.skipTest('need non-UTC/GMT timezone') + try: + original_tzname = time.tzname + original_daylight = time.daylight +@@ -526,7 +526,7 @@ + try: + locale.setlocale(locale.LC_TIME, ('en_US', 'UTF8')) + except locale.Error: +- return ++ self.skipTest('test needs en_US.UTF8 locale') + try: + _strptime._strptime_time('10', '%d') + # Get id of current cache object. +@@ -543,7 +543,7 @@ + # If this is the case just suppress the exception and fall-through + # to the resetting to the original locale. + except locale.Error: +- pass ++ self.skipTest('test needs de_DE.UTF8 locale') + # Make sure we don't trample on the locale setting once we leave the + # test. + finally: +diff -r 3a1db0d2747e Lib/test/test_strtod.py +--- a/Lib/test/test_strtod.py ++++ b/Lib/test/test_strtod.py +@@ -249,6 +249,38 @@ + else: + assert False, "expected ValueError" + ++ @test_support.precisionbigmemtest(size=test_support._2G, memuse=3, ++ dry_run=False) ++ def test_oversized_digit_strings(self, maxsize): ++ # Input string whose length doesn't fit in an INT. ++ s = "1." + "1" * int(2.2e9) ++ with self.assertRaises(ValueError): ++ float(s) ++ del s ++ ++ s = "0." + "0" * int(2.2e9) + "1" ++ with self.assertRaises(ValueError): ++ float(s) ++ del s ++ ++ def test_large_exponents(self): ++ # Verify that the clipping of the exponent in strtod doesn't affect the ++ # output values. ++ def positive_exp(n): ++ """ Long string with value 1.0 and exponent n""" ++ return '0.{}1e+{}'.format('0'*(n-1), n) ++ ++ def negative_exp(n): ++ """ Long string with value 1.0 and exponent -n""" ++ return '1{}e-{}'.format('0'*n, n) ++ ++ self.assertEqual(float(positive_exp(10000)), 1.0) ++ self.assertEqual(float(positive_exp(20000)), 1.0) ++ self.assertEqual(float(positive_exp(30000)), 1.0) ++ self.assertEqual(float(negative_exp(10000)), 1.0) ++ self.assertEqual(float(negative_exp(20000)), 1.0) ++ self.assertEqual(float(negative_exp(30000)), 1.0) ++ + def test_particular(self): + # inputs that produced crashes or incorrectly rounded results with + # previous versions of dtoa.c, for various reasons +diff -r 3a1db0d2747e Lib/test/test_struct.py +--- a/Lib/test/test_struct.py ++++ b/Lib/test/test_struct.py +@@ -574,6 +574,18 @@ + self.check_sizeof('0s', 1) + self.check_sizeof('0c', 0) + ++ def test_unicode_format(self): ++ try: ++ unicode ++ except NameError: ++ self.skipTest('no unicode support') ++ # Issue #19099 ++ s = struct.Struct(unichr(ord('I'))) ++ self.assertEqual(s.format, 'I') ++ self.assertIs(type(s.format), str) ++ self.assertRaises(ValueError, struct.Struct, unichr(0x80)) ++ ++ + def test_main(): + support.run_unittest(StructTest) + +diff -r 3a1db0d2747e Lib/test/test_structmembers.py +--- a/Lib/test/test_structmembers.py ++++ b/Lib/test/test_structmembers.py +@@ -1,3 +1,8 @@ ++import unittest ++from test import test_support ++ ++# Skip this test if the _testcapi module isn't available. ++test_support.import_module('_testcapi') + from _testcapi import _test_structmembersType, \ + CHAR_MAX, CHAR_MIN, UCHAR_MAX, \ + SHRT_MAX, SHRT_MIN, USHRT_MAX, \ +@@ -5,9 +10,6 @@ + LONG_MAX, LONG_MIN, ULONG_MAX, \ + LLONG_MAX, LLONG_MIN, ULLONG_MAX + +-import unittest +-from test import test_support +- + ts=_test_structmembersType(False, 1, 2, 3, 4, 5, 6, 7, 8, + 9.99999, 10.1010101010, "hi") + +diff -r 3a1db0d2747e Lib/test/test_sunau.py +--- a/Lib/test/test_sunau.py ++++ b/Lib/test/test_sunau.py +@@ -5,10 +5,12 @@ + import sunau + + +-class SunauPCM8Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): ++class SunauTest(audiotests.AudioWriteTests, ++ audiotests.AudioTestsWithSourceFile): + module = sunau ++ ++ ++class SunauPCM8Test(SunauTest, unittest.TestCase): + sndfilename = 'pluck-pcm8.au' + sndfilenframes = 3307 + nchannels = 2 +@@ -25,10 +27,7 @@ + """) + + +-class SunauPCM16Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = sunau ++class SunauPCM16Test(SunauTest, unittest.TestCase): + sndfilename = 'pluck-pcm16.au' + sndfilenframes = 3307 + nchannels = 2 +@@ -47,10 +46,7 @@ + """) + + +-class SunauPCM32Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = sunau ++class SunauPCM32Test(SunauTest, unittest.TestCase): + sndfilename = 'pluck-pcm32.au' + sndfilenframes = 3307 + nchannels = 2 +@@ -75,10 +71,7 @@ + """) + + +-class SunauULAWTest(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = sunau ++class SunauULAWTest(SunauTest, unittest.TestCase): + sndfilename = 'pluck-ulaw.au' + sndfilenframes = 3307 + nchannels = 2 +diff -r 3a1db0d2747e Lib/test/test_sundry.py +--- a/Lib/test/test_sundry.py ++++ b/Lib/test/test_sundry.py +@@ -49,7 +49,6 @@ + import getpass + import htmlentitydefs + import ihooks +- import imghdr + import imputil + import keyword + import linecache +diff -r 3a1db0d2747e Lib/test/test_support.py +--- a/Lib/test/test_support.py ++++ b/Lib/test/test_support.py +@@ -19,7 +19,6 @@ + import re + import time + import struct +-import _testcapi + import sysconfig + try: + import thread +@@ -271,6 +270,36 @@ + # is exited) but there is a .pyo file. + unlink(os.path.join(dirname, modname + os.extsep + 'pyo')) + ++# On some platforms, should not run gui test even if it is allowed ++# in `use_resources'. ++if sys.platform.startswith('win'): ++ import ctypes ++ import ctypes.wintypes ++ def _is_gui_available(): ++ UOI_FLAGS = 1 ++ WSF_VISIBLE = 0x0001 ++ class USEROBJECTFLAGS(ctypes.Structure): ++ _fields_ = [("fInherit", ctypes.wintypes.BOOL), ++ ("fReserved", ctypes.wintypes.BOOL), ++ ("dwFlags", ctypes.wintypes.DWORD)] ++ dll = ctypes.windll.user32 ++ h = dll.GetProcessWindowStation() ++ if not h: ++ raise ctypes.WinError() ++ uof = USEROBJECTFLAGS() ++ needed = ctypes.wintypes.DWORD() ++ res = dll.GetUserObjectInformationW(h, ++ UOI_FLAGS, ++ ctypes.byref(uof), ++ ctypes.sizeof(uof), ++ ctypes.byref(needed)) ++ if not res: ++ raise ctypes.WinError() ++ return bool(uof.dwFlags & WSF_VISIBLE) ++else: ++ def _is_gui_available(): ++ return True ++ + def is_resource_enabled(resource): + """Test whether a resource is enabled. Known resources are set by + regrtest.py.""" +@@ -281,6 +310,8 @@ + + If the caller's module is __main__ then automatically return True. The + possibility of False being returned occurs when regrtest.py is executing.""" ++ if resource == 'gui' and not _is_gui_available(): ++ raise unittest.SkipTest("Cannot use the 'gui' resource") + # see if the caller's module is __main__ - if so, treat as if + # the resource was set + if sys._getframe(1).f_globals.get("__name__") == "__main__": +@@ -377,9 +408,15 @@ + raise TestFailed("tests should never set the SO_REUSEADDR " \ + "socket option on TCP/IP sockets!") + if hasattr(socket, 'SO_REUSEPORT'): +- if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: +- raise TestFailed("tests should never set the SO_REUSEPORT " \ +- "socket option on TCP/IP sockets!") ++ try: ++ if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: ++ raise TestFailed("tests should never set the SO_REUSEPORT " \ ++ "socket option on TCP/IP sockets!") ++ except EnvironmentError: ++ # Python's socket module was compiled using modern headers ++ # thus defining SO_REUSEPORT but this process is running ++ # under an older kernel that does not support SO_REUSEPORT. ++ pass + if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + +@@ -428,6 +465,52 @@ + + is_jython = sys.platform.startswith('java') + ++# FS_NONASCII: non-ASCII Unicode character encodable by ++# sys.getfilesystemencoding(), or None if there is no such character. ++FS_NONASCII = None ++if have_unicode: ++ for character in ( ++ # First try printable and common characters to have a readable filename. ++ # For each character, the encoding list are just example of encodings able ++ # to encode the character (the list is not exhaustive). ++ ++ # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1 ++ unichr(0x00E6), ++ # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3 ++ unichr(0x0130), ++ # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257 ++ unichr(0x0141), ++ # U+03C6 (Greek Small Letter Phi): cp1253 ++ unichr(0x03C6), ++ # U+041A (Cyrillic Capital Letter Ka): cp1251 ++ unichr(0x041A), ++ # U+05D0 (Hebrew Letter Alef): Encodable to cp424 ++ unichr(0x05D0), ++ # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic ++ unichr(0x060C), ++ # U+062A (Arabic Letter Teh): cp720 ++ unichr(0x062A), ++ # U+0E01 (Thai Character Ko Kai): cp874 ++ unichr(0x0E01), ++ ++ # Then try more "special" characters. "special" because they may be ++ # interpreted or displayed differently depending on the exact locale ++ # encoding and the font. ++ ++ # U+00A0 (No-Break Space) ++ unichr(0x00A0), ++ # U+20AC (Euro Sign) ++ unichr(0x20AC), ++ ): ++ try: ++ character.encode(sys.getfilesystemencoding())\ ++ .decode(sys.getfilesystemencoding()) ++ except UnicodeError: ++ pass ++ else: ++ FS_NONASCII = character ++ break ++ + # Filename used for testing + if os.name == 'java': + # Jython disallows @ in module names +@@ -964,6 +1047,7 @@ + _TPFLAGS_HEAPTYPE = 1<<9 + + def check_sizeof(test, o, size): ++ import _testcapi + result = sys.getsizeof(o) + # add GC header size + if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\ +@@ -1128,6 +1212,8 @@ + return obj + + def requires_resource(resource): ++ if resource == 'gui' and not _is_gui_available(): ++ return unittest.skip("resource 'gui' is not available") + if is_resource_enabled(resource): + return _id + else: +diff -r 3a1db0d2747e Lib/test/test_sys.py +--- a/Lib/test/test_sys.py ++++ b/Lib/test/test_sys.py +@@ -1,5 +1,6 @@ + # -*- coding: iso-8859-1 -*- + import unittest, test.test_support ++from test.script_helper import assert_python_ok, assert_python_failure + import sys, os, cStringIO + import struct + import operator +@@ -114,90 +115,69 @@ + clear_check(exc) + + def test_exit(self): ++ # call with two arguments + self.assertRaises(TypeError, sys.exit, 42, 42) + + # call without argument +- try: +- sys.exit(0) +- except SystemExit, exc: +- self.assertEqual(exc.code, 0) +- except: +- self.fail("wrong exception") +- else: +- self.fail("no exception") ++ with self.assertRaises(SystemExit) as cm: ++ sys.exit() ++ self.assertIsNone(cm.exception.code) ++ ++ rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()') ++ self.assertEqual(rc, 0) ++ self.assertEqual(out, b'') ++ self.assertEqual(err, b'') ++ ++ # call with integer argument ++ with self.assertRaises(SystemExit) as cm: ++ sys.exit(42) ++ self.assertEqual(cm.exception.code, 42) + + # call with tuple argument with one entry + # entry will be unpacked +- try: +- sys.exit(42) +- except SystemExit, exc: +- self.assertEqual(exc.code, 42) +- except: +- self.fail("wrong exception") +- else: +- self.fail("no exception") +- +- # call with integer argument +- try: ++ with self.assertRaises(SystemExit) as cm: + sys.exit((42,)) +- except SystemExit, exc: +- self.assertEqual(exc.code, 42) +- except: +- self.fail("wrong exception") +- else: +- self.fail("no exception") ++ self.assertEqual(cm.exception.code, 42) + + # call with string argument +- try: ++ with self.assertRaises(SystemExit) as cm: + sys.exit("exit") +- except SystemExit, exc: +- self.assertEqual(exc.code, "exit") +- except: +- self.fail("wrong exception") +- else: +- self.fail("no exception") ++ self.assertEqual(cm.exception.code, "exit") + + # call with tuple argument with two entries +- try: ++ with self.assertRaises(SystemExit) as cm: + sys.exit((17, 23)) +- except SystemExit, exc: +- self.assertEqual(exc.code, (17, 23)) +- except: +- self.fail("wrong exception") +- else: +- self.fail("no exception") ++ self.assertEqual(cm.exception.code, (17, 23)) + + # test that the exit machinery handles SystemExits properly +- import subprocess + # both unnormalized... +- rc = subprocess.call([sys.executable, "-c", +- "raise SystemExit, 46"]) ++ rc, out, err = assert_python_failure('-c', 'raise SystemExit, 46') + self.assertEqual(rc, 46) ++ self.assertEqual(out, b'') ++ self.assertEqual(err, b'') + # ... and normalized +- rc = subprocess.call([sys.executable, "-c", +- "raise SystemExit(47)"]) ++ rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)') + self.assertEqual(rc, 47) ++ self.assertEqual(out, b'') ++ self.assertEqual(err, b'') + +- def check_exit_message(code, expected, env=None): +- process = subprocess.Popen([sys.executable, "-c", code], +- stderr=subprocess.PIPE, env=env) +- stdout, stderr = process.communicate() +- self.assertEqual(process.returncode, 1) +- self.assertTrue(stderr.startswith(expected), +- "%s doesn't start with %s" % (repr(stderr), repr(expected))) ++ def check_exit_message(code, expected, **env_vars): ++ rc, out, err = assert_python_failure('-c', code, **env_vars) ++ self.assertEqual(rc, 1) ++ self.assertEqual(out, b'') ++ self.assertTrue(err.startswith(expected), ++ "%s doesn't start with %s" % (repr(err), repr(expected))) + +- # test that stderr buffer if flushed before the exit message is written ++ # test that stderr buffer is flushed before the exit message is written + # into stderr + check_exit_message( + r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', + b"unflushed,message") + + # test that the unicode message is encoded to the stderr encoding +- env = os.environ.copy() +- env['PYTHONIOENCODING'] = 'latin-1' + check_exit_message( + r'import sys; sys.exit(u"h\xe9")', +- b"h\xe9", env=env) ++ b"h\xe9", PYTHONIOENCODING='latin-1') + + def test_getdefaultencoding(self): + if test.test_support.have_unicode: +@@ -266,15 +246,16 @@ + # still has 5 elements + maj, min, buildno, plat, csd = sys.getwindowsversion() + ++ @unittest.skipUnless(hasattr(sys, "setdlopenflags"), ++ 'test needs sys.setdlopenflags()') + def test_dlopenflags(self): +- if hasattr(sys, "setdlopenflags"): +- self.assertTrue(hasattr(sys, "getdlopenflags")) +- self.assertRaises(TypeError, sys.getdlopenflags, 42) +- oldflags = sys.getdlopenflags() +- self.assertRaises(TypeError, sys.setdlopenflags) +- sys.setdlopenflags(oldflags+1) +- self.assertEqual(sys.getdlopenflags(), oldflags+1) +- sys.setdlopenflags(oldflags) ++ self.assertTrue(hasattr(sys, "getdlopenflags")) ++ self.assertRaises(TypeError, sys.getdlopenflags, 42) ++ oldflags = sys.getdlopenflags() ++ self.assertRaises(TypeError, sys.setdlopenflags) ++ sys.setdlopenflags(oldflags+1) ++ self.assertEqual(sys.getdlopenflags(), oldflags+1) ++ sys.setdlopenflags(oldflags) + + def test_refcount(self): + # n here must be a global in order for this test to pass while +@@ -488,6 +469,7 @@ + p.wait() + self.assertIn(executable, ["''", repr(sys.executable)]) + ++@test.test_support.cpython_only + class SizeofTest(unittest.TestCase): + + def setUp(self): +diff -r 3a1db0d2747e Lib/test/test_tarfile.py +--- a/Lib/test/test_tarfile.py ++++ b/Lib/test/test_tarfile.py +@@ -158,6 +158,80 @@ + self._test_fileobj_link("symtype2", "ustar/regtype") + + ++class ListTest(ReadTest, unittest.TestCase): ++ ++ # Override setUp to use default encoding (UTF-8) ++ def setUp(self): ++ self.tar = tarfile.open(self.tarname, mode=self.mode) ++ ++ def test_list(self): ++ with test_support.captured_stdout() as t: ++ self.tar.list(verbose=False) ++ out = t.getvalue() ++ self.assertIn('ustar/conttype', out) ++ self.assertIn('ustar/regtype', out) ++ self.assertIn('ustar/lnktype', out) ++ self.assertIn('ustar' + ('/12345' * 40) + '67/longname', out) ++ self.assertIn('./ustar/linktest2/symtype', out) ++ self.assertIn('./ustar/linktest2/lnktype', out) ++ # Make sure it puts trailing slash for directory ++ self.assertIn('ustar/dirtype/', out) ++ self.assertIn('ustar/dirtype-with-size/', out) ++ # Make sure it is able to print non-ASCII characters ++ self.assertIn('ustar/umlauts-' ++ '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out) ++ self.assertIn('misc/regtype-hpux-signed-chksum-' ++ '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out) ++ self.assertIn('misc/regtype-old-v7-signed-chksum-' ++ '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out) ++ # Make sure it prints files separated by one newline without any ++ # 'ls -l'-like accessories if verbose flag is not being used ++ # ... ++ # ustar/conttype ++ # ustar/regtype ++ # ... ++ self.assertRegexpMatches(out, r'ustar/conttype ?\r?\n' ++ r'ustar/regtype ?\r?\n') ++ # Make sure it does not print the source of link without verbose flag ++ self.assertNotIn('link to', out) ++ self.assertNotIn('->', out) ++ ++ def test_list_verbose(self): ++ with test_support.captured_stdout() as t: ++ self.tar.list(verbose=True) ++ out = t.getvalue() ++ # Make sure it prints files separated by one newline with 'ls -l'-like ++ # accessories if verbose flag is being used ++ # ... ++ # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype ++ # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype ++ # ... ++ self.assertRegexpMatches(out, (r'-rw-r--r-- tarfile/tarfile\s+7011 ' ++ r'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d ' ++ r'ustar/\w+type ?\r?\n') * 2) ++ # Make sure it prints the source of link with verbose flag ++ self.assertIn('ustar/symtype -> regtype', out) ++ self.assertIn('./ustar/linktest2/symtype -> ../linktest1/regtype', out) ++ self.assertIn('./ustar/linktest2/lnktype link to ' ++ './ustar/linktest1/regtype', out) ++ self.assertIn('gnu' + ('/123' * 125) + '/longlink link to gnu' + ++ ('/123' * 125) + '/longname', out) ++ self.assertIn('pax' + ('/123' * 125) + '/longlink link to pax' + ++ ('/123' * 125) + '/longname', out) ++ ++ ++class GzipListTest(ListTest): ++ tarname = gzipname ++ mode = "r:gz" ++ taropen = tarfile.TarFile.gzopen ++ ++ ++class Bz2ListTest(ListTest): ++ tarname = bz2name ++ mode = "r:bz2" ++ taropen = tarfile.TarFile.bz2open ++ ++ + class CommonReadTest(ReadTest): + + def test_empty_tarfile(self): +@@ -181,6 +255,14 @@ + self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode) + self.assertRaises(tarfile.ReadError, tarfile.open, tmpname) + ++ def test_non_existent_tarfile(self): ++ # Test for issue11513: prevent non-existent gzipped tarfiles raising ++ # multiple exceptions. ++ exctype = OSError if '|' in self.mode else IOError ++ with self.assertRaisesRegexp(exctype, "xxx") as ex: ++ tarfile.open("xxx", self.mode) ++ self.assertEqual(ex.exception.errno, errno.ENOENT) ++ + def test_ignore_zeros(self): + # Test TarFile's ignore_zeros option. + if self.mode.endswith(":gz"): +@@ -205,6 +287,7 @@ + + + class MiscReadTest(CommonReadTest): ++ taropen = tarfile.TarFile.taropen + + def test_no_name_argument(self): + fobj = open(self.tarname, "rb") +@@ -225,6 +308,17 @@ + tar = tarfile.open(fileobj=fobj, mode=self.mode) + self.assertEqual(tar.name, None) + ++ def test_illegal_mode_arg(self): ++ with open(tmpname, 'wb'): ++ pass ++ self.addCleanup(os.unlink, tmpname) ++ with self.assertRaisesRegexp(ValueError, 'mode must be '): ++ tar = self.taropen(tmpname, 'q') ++ with self.assertRaisesRegexp(ValueError, 'mode must be '): ++ tar = self.taropen(tmpname, 'rw') ++ with self.assertRaisesRegexp(ValueError, 'mode must be '): ++ tar = self.taropen(tmpname, '') ++ + def test_fileobj_with_offset(self): + # Skip the first member and store values from the second member + # of the testtar. +@@ -260,7 +354,7 @@ + def test_fail_comp(self): + # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file. + if self.mode == "r:": +- return ++ self.skipTest('needs a gz or bz2 mode') + self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode) + fobj = open(tarname, "rb") + self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode) +@@ -446,14 +540,12 @@ + def test_detect_fileobj(self): + self._test_modes(self._testfunc_fileobj) + ++ @unittest.skipUnless(bz2, 'requires bz2') + def test_detect_stream_bz2(self): + # Originally, tarfile's stream detection looked for the string + # "BZh91" at the start of the file. This is incorrect because + # the '9' represents the blocksize (900kB). If the file was + # compressed using another blocksize autodetection fails. +- if not bz2: +- return +- + with open(tarname, "rb") as fobj: + data = fobj.read() + +@@ -639,6 +731,12 @@ + tar.addfile(tarfile.TarInfo("foo")) + tar.close() + self.assertTrue(fobj.closed is False, "external fileobjs must never closed") ++ # Issue #20238: Incomplete gzip output with mode="w:gz" ++ data = fobj.getvalue() ++ del tar ++ test_support.gc_collect() ++ self.assertFalse(fobj.closed) ++ self.assertEqual(data, fobj.getvalue()) + + + class WriteTest(WriteTestBase): +@@ -955,6 +1053,22 @@ + os.unlink(temparchive) + shutil.rmtree(tempdir) + ++ def test_open_nonwritable_fileobj(self): ++ for exctype in IOError, EOFError, RuntimeError: ++ class BadFile(StringIO.StringIO): ++ first = True ++ def write(self, data): ++ if self.first: ++ self.first = False ++ raise exctype ++ ++ f = BadFile() ++ with self.assertRaises(exctype): ++ tar = tarfile.open(tmpname, self.mode, fileobj=f, ++ format=tarfile.PAX_FORMAT, ++ pax_headers={'non': 'empty'}) ++ self.assertFalse(f.closed) ++ + class StreamWriteTest(WriteTestBase): + + mode = "w|" +@@ -982,12 +1096,11 @@ + self.assertTrue(data.count("\0") == tarfile.RECORDSIZE, + "incorrect zero padding") + ++ @unittest.skipIf(sys.platform == 'win32', 'not appropriate for Windows') ++ @unittest.skipUnless(hasattr(os, 'umask'), 'requires os.umask') + def test_file_mode(self): + # Test for issue #8464: Create files with correct + # permissions. +- if sys.platform == "win32" or not hasattr(os, "umask"): +- return +- + if os.path.exists(tmpname): + os.remove(tmpname) + +@@ -1360,15 +1473,13 @@ + self._add_testfile() + self._test(names=["foo", "bar"]) + ++ @unittest.skipUnless(gzip, 'requires gzip') + def test_append_gz(self): +- if gzip is None: +- return + self._create_testtar("w:gz") + self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a") + ++ @unittest.skipUnless(bz2, 'requires bz2') + def test_append_bz2(self): +- if bz2 is None: +- return + self._create_testtar("w:bz2") + self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a") + +@@ -1540,6 +1651,7 @@ + class GzipMiscReadTest(MiscReadTest): + tarname = gzipname + mode = "r:gz" ++ taropen = tarfile.TarFile.gzopen + class GzipUstarReadTest(UstarReadTest): + tarname = gzipname + mode = "r:gz" +@@ -1555,6 +1667,7 @@ + class Bz2MiscReadTest(MiscReadTest): + tarname = bz2name + mode = "r:bz2" ++ taropen = tarfile.TarFile.bz2open + class Bz2UstarReadTest(UstarReadTest): + tarname = bz2name + mode = "r:bz2" +@@ -1607,6 +1720,7 @@ + MemberReadTest, + GNUReadTest, + PaxReadTest, ++ ListTest, + WriteTest, + StreamWriteTest, + GNUWriteTest, +@@ -1638,6 +1752,7 @@ + GzipMiscReadTest, + GzipUstarReadTest, + GzipStreamReadTest, ++ GzipListTest, + GzipWriteTest, + GzipStreamWriteTest, + ] +@@ -1652,6 +1767,7 @@ + Bz2MiscReadTest, + Bz2UstarReadTest, + Bz2StreamReadTest, ++ Bz2ListTest, + Bz2WriteTest, + Bz2StreamWriteTest, + Bz2PartialReadTest, +diff -r 3a1db0d2747e Lib/test/test_tcl.py +--- a/Lib/test/test_tcl.py ++++ b/Lib/test/test_tcl.py +@@ -1,9 +1,6 @@ +-#!/usr/bin/env python +- + import unittest + import sys + import os +-import _testcapi + from test import test_support + from subprocess import Popen, PIPE + +@@ -13,6 +10,11 @@ + from Tkinter import Tcl + from _tkinter import TclError + ++try: ++ from _testcapi import INT_MAX, PY_SSIZE_T_MAX ++except ImportError: ++ INT_MAX = PY_SSIZE_T_MAX = sys.maxsize ++ + tcl_version = _tkinter.TCL_VERSION.split('.') + try: + for i in range(len(tcl_version)): +@@ -21,6 +23,21 @@ + pass + tcl_version = tuple(tcl_version) + ++_tk_patchlevel = None ++def get_tk_patchlevel(): ++ global _tk_patchlevel ++ if _tk_patchlevel is None: ++ tcl = Tcl() ++ patchlevel = [] ++ for x in tcl.call('info', 'patchlevel').split('.'): ++ try: ++ x = int(x, 10) ++ except ValueError: ++ x = -1 ++ patchlevel.append(x) ++ _tk_patchlevel = tuple(patchlevel) ++ return _tk_patchlevel ++ + + class TkinterTest(unittest.TestCase): + +@@ -33,6 +50,7 @@ + + def setUp(self): + self.interp = Tcl() ++ self.wantobjects = self.interp.tk.wantobjects() + + def testEval(self): + tcl = self.interp +@@ -125,6 +143,18 @@ + self.assertEqual(tcl.eval('set b'),'2') + self.assertEqual(tcl.eval('set c'),'3') + ++ def test_evalfile_null_in_result(self): ++ tcl = self.interp ++ with open(test_support.TESTFN, 'wb') as f: ++ self.addCleanup(test_support.unlink, test_support.TESTFN) ++ f.write(""" ++ set a "a\0b" ++ set b "a\\0b" ++ """) ++ tcl.evalfile(test_support.TESTFN) ++ self.assertEqual(tcl.eval('set a'), 'a\xc0\x80b') ++ self.assertEqual(tcl.eval('set b'), 'a\xc0\x80b') ++ + def testEvalFileException(self): + tcl = self.interp + filename = "doesnotexists" +@@ -138,18 +168,15 @@ + tcl = self.interp + self.assertRaises(TclError,tcl.eval,'package require DNE') + ++ @unittest.skipUnless(sys.platform == 'win32', "only applies to Windows") + def testLoadWithUNC(self): +- import sys +- if sys.platform != 'win32': +- return +- + # Build a UNC path from the regular path. + # Something like + # \\%COMPUTERNAME%\c$\python27\python.exe + + fullname = os.path.abspath(sys.executable) + if fullname[1] != ':': +- return ++ self.skipTest('unusable path: %r' % fullname) + unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], + fullname[0], + fullname[3:]) +@@ -158,7 +185,14 @@ + env.unset("TCL_LIBRARY") + cmd = '%s -c "import Tkinter; print Tkinter"' % (unc_name,) + +- p = Popen(cmd, stdout=PIPE, stderr=PIPE) ++ try: ++ p = Popen(cmd, stdout=PIPE, stderr=PIPE) ++ except WindowsError as e: ++ if e.winerror == 5: ++ self.skipTest('Not permitted to start the child process') ++ else: ++ raise ++ + out_data, err_data = p.communicate() + + msg = '\n\n'.join(['"Tkinter.py" not in output', +@@ -171,27 +205,231 @@ + self.assertEqual(p.wait(), 0, 'Non-zero exit code') + + ++ def test_exprstring(self): ++ tcl = self.interp ++ tcl.call('set', 'a', 3) ++ tcl.call('set', 'b', 6) ++ def check(expr, expected): ++ result = tcl.exprstring(expr) ++ self.assertEqual(result, expected) ++ self.assertIsInstance(result, str) ++ ++ self.assertRaises(TypeError, tcl.exprstring) ++ self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6') ++ self.assertRaises(TclError, tcl.exprstring, 'spam') ++ check('', '0') ++ check('8.2 + 6', '14.2') ++ check('3.1 + $a', '6.1') ++ check('2 + "$a.$b"', '5.6') ++ check('4*[llength "6 2"]', '8') ++ check('{word one} < "word $a"', '0') ++ check('4*2 < 7', '0') ++ check('hypot($a, 4)', '5.0') ++ check('5 / 4', '1') ++ check('5 / 4.0', '1.25') ++ check('5 / ( [string length "abcd"] + 0.0 )', '1.25') ++ check('20.0/5.0', '4.0') ++ check('"0x03" > "2"', '1') ++ check('[string length "a\xc2\xbd\xe2\x82\xac"]', '3') ++ check(r'[string length "a\xbd\u20ac"]', '3') ++ check('"abc"', 'abc') ++ check('"a\xc2\xbd\xe2\x82\xac"', 'a\xc2\xbd\xe2\x82\xac') ++ check(r'"a\xbd\u20ac"', 'a\xc2\xbd\xe2\x82\xac') ++ check(r'"a\0b"', 'a\xc0\x80b') ++ if tcl_version >= (8, 5): ++ check('2**64', str(2**64)) ++ ++ def test_exprdouble(self): ++ tcl = self.interp ++ tcl.call('set', 'a', 3) ++ tcl.call('set', 'b', 6) ++ def check(expr, expected): ++ result = tcl.exprdouble(expr) ++ self.assertEqual(result, expected) ++ self.assertIsInstance(result, float) ++ ++ self.assertRaises(TypeError, tcl.exprdouble) ++ self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6') ++ self.assertRaises(TclError, tcl.exprdouble, 'spam') ++ check('', 0.0) ++ check('8.2 + 6', 14.2) ++ check('3.1 + $a', 6.1) ++ check('2 + "$a.$b"', 5.6) ++ check('4*[llength "6 2"]', 8.0) ++ check('{word one} < "word $a"', 0.0) ++ check('4*2 < 7', 0.0) ++ check('hypot($a, 4)', 5.0) ++ check('5 / 4', 1.0) ++ check('5 / 4.0', 1.25) ++ check('5 / ( [string length "abcd"] + 0.0 )', 1.25) ++ check('20.0/5.0', 4.0) ++ check('"0x03" > "2"', 1.0) ++ check('[string length "a\xc2\xbd\xe2\x82\xac"]', 3.0) ++ check(r'[string length "a\xbd\u20ac"]', 3.0) ++ self.assertRaises(TclError, tcl.exprdouble, '"abc"') ++ if tcl_version >= (8, 5): ++ check('2**64', float(2**64)) ++ ++ def test_exprlong(self): ++ tcl = self.interp ++ tcl.call('set', 'a', 3) ++ tcl.call('set', 'b', 6) ++ def check(expr, expected): ++ result = tcl.exprlong(expr) ++ self.assertEqual(result, expected) ++ self.assertIsInstance(result, int) ++ ++ self.assertRaises(TypeError, tcl.exprlong) ++ self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6') ++ self.assertRaises(TclError, tcl.exprlong, 'spam') ++ check('', 0) ++ check('8.2 + 6', 14) ++ check('3.1 + $a', 6) ++ check('2 + "$a.$b"', 5) ++ check('4*[llength "6 2"]', 8) ++ check('{word one} < "word $a"', 0) ++ check('4*2 < 7', 0) ++ check('hypot($a, 4)', 5) ++ check('5 / 4', 1) ++ check('5 / 4.0', 1) ++ check('5 / ( [string length "abcd"] + 0.0 )', 1) ++ check('20.0/5.0', 4) ++ check('"0x03" > "2"', 1) ++ check('[string length "a\xc2\xbd\xe2\x82\xac"]', 3) ++ check(r'[string length "a\xbd\u20ac"]', 3) ++ self.assertRaises(TclError, tcl.exprlong, '"abc"') ++ if tcl_version >= (8, 5): ++ self.assertRaises(TclError, tcl.exprlong, '2**64') ++ ++ def test_exprboolean(self): ++ tcl = self.interp ++ tcl.call('set', 'a', 3) ++ tcl.call('set', 'b', 6) ++ def check(expr, expected): ++ result = tcl.exprboolean(expr) ++ self.assertEqual(result, expected) ++ self.assertIsInstance(result, int) ++ self.assertNotIsInstance(result, bool) ++ ++ self.assertRaises(TypeError, tcl.exprboolean) ++ self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6') ++ self.assertRaises(TclError, tcl.exprboolean, 'spam') ++ check('', False) ++ for value in ('0', 'false', 'no', 'off'): ++ check(value, False) ++ check('"%s"' % value, False) ++ check('{%s}' % value, False) ++ for value in ('1', 'true', 'yes', 'on'): ++ check(value, True) ++ check('"%s"' % value, True) ++ check('{%s}' % value, True) ++ check('8.2 + 6', True) ++ check('3.1 + $a', True) ++ check('2 + "$a.$b"', True) ++ check('4*[llength "6 2"]', True) ++ check('{word one} < "word $a"', False) ++ check('4*2 < 7', False) ++ check('hypot($a, 4)', True) ++ check('5 / 4', True) ++ check('5 / 4.0', True) ++ check('5 / ( [string length "abcd"] + 0.0 )', True) ++ check('20.0/5.0', True) ++ check('"0x03" > "2"', True) ++ check('[string length "a\xc2\xbd\xe2\x82\xac"]', True) ++ check(r'[string length "a\xbd\u20ac"]', True) ++ self.assertRaises(TclError, tcl.exprboolean, '"abc"') ++ if tcl_version >= (8, 5): ++ check('2**64', True) ++ + def test_passing_values(self): + def passValue(value): + return self.interp.call('set', '_', value) +- self.assertEqual(passValue(True), True) +- self.assertEqual(passValue(False), False) ++ ++ self.assertEqual(passValue(True), True if self.wantobjects else '1') ++ self.assertEqual(passValue(False), False if self.wantobjects else '0') + self.assertEqual(passValue('string'), 'string') +- self.assertEqual(passValue('string\u20ac'), 'string\u20ac') ++ self.assertEqual(passValue('string\xbd'), 'string\xbd') ++ self.assertEqual(passValue('string\xe2\x82\xac'), u'string\u20ac') + self.assertEqual(passValue(u'string'), u'string') ++ self.assertEqual(passValue(u'string\xbd'), u'string\xbd') + self.assertEqual(passValue(u'string\u20ac'), u'string\u20ac') ++ self.assertEqual(passValue('str\x00ing'), 'str\x00ing') ++ self.assertEqual(passValue('str\xc0\x80ing'), 'str\x00ing') ++ self.assertEqual(passValue(u'str\x00ing'), u'str\x00ing') ++ self.assertEqual(passValue(u'str\x00ing\xbd'), u'str\x00ing\xbd') ++ self.assertEqual(passValue(u'str\x00ing\u20ac'), u'str\x00ing\u20ac') + for i in (0, 1, -1, int(2**31-1), int(-2**31)): +- self.assertEqual(passValue(i), i) ++ self.assertEqual(passValue(i), i if self.wantobjects else str(i)) + for f in (0.0, 1.0, -1.0, 1//3, 1/3.0, + sys.float_info.min, sys.float_info.max, + -sys.float_info.min, -sys.float_info.max): +- self.assertEqual(passValue(f), f) +- for f in float('nan'), float('inf'), -float('inf'): +- if f != f: # NaN +- self.assertNotEqual(passValue(f), f) ++ if self.wantobjects: ++ self.assertEqual(passValue(f), f) + else: +- self.assertEqual(passValue(f), f) +- self.assertEqual(passValue((1, '2', (3.4,))), (1, '2', (3.4,))) ++ self.assertEqual(float(passValue(f)), f) ++ if self.wantobjects: ++ f = passValue(float('nan')) ++ self.assertNotEqual(f, f) ++ self.assertEqual(passValue(float('inf')), float('inf')) ++ self.assertEqual(passValue(-float('inf')), -float('inf')) ++ else: ++ f = float(passValue(float('nan'))) ++ self.assertNotEqual(f, f) ++ self.assertEqual(float(passValue(float('inf'))), float('inf')) ++ self.assertEqual(float(passValue(-float('inf'))), -float('inf')) ++ self.assertEqual(passValue((1, '2', (3.4,))), ++ (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4') ++ ++ def test_user_command(self): ++ result = [] ++ def testfunc(arg): ++ result.append(arg) ++ return arg ++ self.interp.createcommand('testfunc', testfunc) ++ self.addCleanup(self.interp.tk.deletecommand, 'testfunc') ++ def check(value, expected, expected2=None, eq=self.assertEqual): ++ if expected2 is None: ++ expected2 = expected ++ del result[:] ++ r = self.interp.call('testfunc', value) ++ self.assertEqual(len(result), 1) ++ self.assertIsInstance(result[0], (str, unicode)) ++ eq(result[0], expected2) ++ self.assertIsInstance(r, (str, unicode)) ++ eq(r, expected2) ++ def float_eq(actual, expected): ++ expected = float(expected) ++ self.assertAlmostEqual(float(actual), expected, ++ delta=abs(expected) * 1e-10) ++ def nan_eq(actual, expected): ++ actual = float(actual) ++ self.assertNotEqual(actual, actual) ++ ++ check(True, '1') ++ check(False, '0') ++ check('string', 'string') ++ check('string\xbd', 'string\xbd') ++ check('string\xe2\x82\xac', 'string\xe2\x82\xac', u'string\u20ac') ++ check(u'string', u'string') ++ check(u'string\xbd', 'string\xc2\xbd', u'string\xbd') ++ check(u'string\u20ac', 'string\xe2\x82\xac', u'string\u20ac') ++ check('str\xc0\x80ing', 'str\xc0\x80ing', u'str\x00ing') ++ check('str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac', u'str\x00ing\u20ac') ++ check(u'str\x00ing', 'str\xc0\x80ing', u'str\x00ing') ++ check(u'str\x00ing\xbd', 'str\xc0\x80ing\xc2\xbd', u'str\x00ing\xbd') ++ check(u'str\x00ing\u20ac', 'str\xc0\x80ing\xe2\x82\xac', u'str\x00ing\u20ac') ++ for i in (0, 1, -1, 2**31-1, -2**31): ++ check(i, str(i)) ++ for f in (0.0, 1.0, -1.0): ++ check(f, repr(f)) ++ for f in (1/3.0, sys.float_info.min, sys.float_info.max, ++ -sys.float_info.min, -sys.float_info.max): ++ check(f, f, eq=float_eq) ++ check(float('inf'), 'Inf', eq=float_eq) ++ check(-float('inf'), '-Inf', eq=float_eq) ++ check(float('nan'), 'NaN', eq=nan_eq) ++ check((), '') ++ check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}') + + def test_splitlist(self): + splitlist = self.interp.tk.splitlist +@@ -208,6 +446,7 @@ + (u'a\n b\t\r c\n ', ('a', 'b', 'c')), + ('a \xe2\x82\xac', ('a', '\xe2\x82\xac')), + (u'a \u20ac', ('a', '\xe2\x82\xac')), ++ ('a\xc0\x80b c\xc0\x80d', ('a\xc0\x80b', 'c\xc0\x80d')), + ('a {b c}', ('a', 'b c')), + (r'a b\ c', ('a', 'b c')), + (('a', 'b c'), ('a', 'b c')), +@@ -216,12 +455,21 @@ + ('a 3.4', ('a', '3.4')), + (('a', 3.4), ('a', 3.4)), + ((), ()), +- (call('list', 1, '2', (3.4,)), (1, '2', (3.4,))), ++ (call('list', 1, '2', (3.4,)), ++ (1, '2', (3.4,)) if self.wantobjects else ++ ('1', '2', '3.4')), + ] + if tcl_version >= (8, 5): ++ if not self.wantobjects: ++ expected = ('12', '\xe2\x82\xac', '\xe2\x82\xac', '3.4') ++ elif get_tk_patchlevel() < (8, 5, 5): ++ # Before 8.5.5 dicts were converted to lists through string ++ expected = ('12', u'\u20ac', u'\u20ac', '3.4') ++ else: ++ expected = (12, u'\u20ac', u'\u20ac', (3.4,)) + testcases += [ +- (call('dict', 'create', 1, u'\u20ac', '\xe2\x82\xac', (3.4,)), +- (1, u'\u20ac', u'\u20ac', (3.4,))), ++ (call('dict', 'create', 12, u'\u20ac', '\xe2\x82\xac', (3.4,)), ++ expected), + ] + for arg, res in testcases: + self.assertEqual(splitlist(arg), res) +@@ -243,6 +491,8 @@ + (u'a\n b\t\r c\n ', ('a', 'b', 'c')), + ('a \xe2\x82\xac', ('a', '\xe2\x82\xac')), + (u'a \u20ac', ('a', '\xe2\x82\xac')), ++ ('a\xc0\x80b', 'a\xc0\x80b'), ++ ('a\xc0\x80b c\xc0\x80d', ('a\xc0\x80b', 'c\xc0\x80d')), + ('a {b c}', ('a', ('b', 'c'))), + (r'a b\ c', ('a', ('b', 'c'))), + (('a', 'b c'), ('a', ('b', 'c'))), +@@ -253,12 +503,21 @@ + (('a', 3.4), ('a', 3.4)), + (('a', (2, 3.4)), ('a', (2, 3.4))), + ((), ()), +- (call('list', 1, '2', (3.4,)), (1, '2', (3.4,))), ++ (call('list', 1, '2', (3.4,)), ++ (1, '2', (3.4,)) if self.wantobjects else ++ ('1', '2', '3.4')), + ] + if tcl_version >= (8, 5): ++ if not self.wantobjects: ++ expected = ('12', '\xe2\x82\xac', '\xe2\x82\xac', '3.4') ++ elif get_tk_patchlevel() < (8, 5, 5): ++ # Before 8.5.5 dicts were converted to lists through string ++ expected = ('12', u'\u20ac', u'\u20ac', '3.4') ++ else: ++ expected = (12, u'\u20ac', u'\u20ac', (3.4,)) + testcases += [ + (call('dict', 'create', 12, u'\u20ac', '\xe2\x82\xac', (3.4,)), +- (12, u'\u20ac', u'\u20ac', (3.4,))), ++ expected), + ] + for arg, res in testcases: + self.assertEqual(split(arg), res) +@@ -269,15 +528,20 @@ + def setUp(self): + self.interp = Tcl() + +- @unittest.skipUnless(_testcapi.INT_MAX < _testcapi.PY_SSIZE_T_MAX, +- "needs UINT_MAX < SIZE_MAX") +- @test_support.precisionbigmemtest(size=_testcapi.INT_MAX + 1, memuse=5, +- dry_run=False) ++ @test_support.cpython_only ++ @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") ++ @test_support.precisionbigmemtest(size=INT_MAX + 1, memuse=5, dry_run=False) + def test_huge_string(self, size): + value = ' ' * size + self.assertRaises(OverflowError, self.interp.call, 'set', '_', value) + + ++def setUpModule(): ++ if test_support.verbose: ++ tcl = Tcl() ++ print 'patchlevel =', tcl.call('info', 'patchlevel') ++ ++ + def test_main(): + test_support.run_unittest(TclTest, TkinterTest, BigmemTclTest) + +diff -r 3a1db0d2747e Lib/test/test_telnetlib.py +--- a/Lib/test/test_telnetlib.py ++++ b/Lib/test/test_telnetlib.py +@@ -177,7 +177,6 @@ + self.dataq.join() + data = telnet.read_all() + self.assertEqual(data, ''.join(want[:-1])) +- return + + def _test_blocking(self, func): + self.dataq.put([self.block_long, EOF_sigil]) +diff -r 3a1db0d2747e Lib/test/test_tempfile.py +--- a/Lib/test/test_tempfile.py ++++ b/Lib/test/test_tempfile.py +@@ -342,10 +342,9 @@ + finally: + os.rmdir(dir) + ++ @unittest.skipUnless(has_stat, 'os.stat not available') + def test_file_mode(self): + # _mkstemp_inner creates files with the proper mode +- if not has_stat: +- return # ugh, can't use SkipTest. + + file = self.do_create() + mode = stat.S_IMODE(os.stat(file.name).st_mode) +@@ -357,10 +356,9 @@ + expected = user * (1 + 8 + 64) + self.assertEqual(mode, expected) + ++ @unittest.skipUnless(has_spawnl, 'os.spawnl not available') + def test_noinherit(self): + # _mkstemp_inner file handles are not inherited by child processes +- if not has_spawnl: +- return # ugh, can't use SkipTest. + + if support.verbose: + v="v" +@@ -395,10 +393,9 @@ + "child process caught fatal signal %d" % -retval) + self.assertFalse(retval > 0, "child process reports failure %d"%retval) + ++ @unittest.skipUnless(has_textmode, "text mode not available") + def test_textmode(self): + # _mkstemp_inner can create files in text mode +- if not has_textmode: +- return # ugh, can't use SkipTest. + + self.do_create(bin=0).write("blat\n") + # XXX should test that the file really is a text file +@@ -590,10 +587,9 @@ + finally: + os.rmdir(dir) + ++ @unittest.skipUnless(has_stat, 'os.stat not available') + def test_mode(self): + # mkdtemp creates directories with the proper mode +- if not has_stat: +- return # ugh, can't use SkipTest. + + dir = self.do_create() + try: +diff -r 3a1db0d2747e Lib/test/test_thread.py +--- a/Lib/test/test_thread.py ++++ b/Lib/test/test_thread.py +@@ -70,39 +70,35 @@ + thread.stack_size(0) + self.assertEqual(thread.stack_size(), 0, "stack_size not reset to default") + +- if os.name not in ("nt", "os2", "posix"): +- return +- +- tss_supported = True ++ @unittest.skipIf(os.name not in ("nt", "os2", "posix"), 'test meant for nt, os2, and posix') ++ def test_nt_and_posix_stack_size(self): + try: + thread.stack_size(4096) + except ValueError: + verbose_print("caught expected ValueError setting " + "stack_size(4096)") + except thread.error: +- tss_supported = False +- verbose_print("platform does not support changing thread stack " +- "size") ++ self.skipTest("platform does not support changing thread stack " ++ "size") + +- if tss_supported: +- fail_msg = "stack_size(%d) failed - should succeed" +- for tss in (262144, 0x100000, 0): +- thread.stack_size(tss) +- self.assertEqual(thread.stack_size(), tss, fail_msg % tss) +- verbose_print("successfully set stack_size(%d)" % tss) ++ fail_msg = "stack_size(%d) failed - should succeed" ++ for tss in (262144, 0x100000, 0): ++ thread.stack_size(tss) ++ self.assertEqual(thread.stack_size(), tss, fail_msg % tss) ++ verbose_print("successfully set stack_size(%d)" % tss) + +- for tss in (262144, 0x100000): +- verbose_print("trying stack_size = (%d)" % tss) +- self.next_ident = 0 +- self.created = 0 +- for i in range(NUMTASKS): +- self.newtask() ++ for tss in (262144, 0x100000): ++ verbose_print("trying stack_size = (%d)" % tss) ++ self.next_ident = 0 ++ self.created = 0 ++ for i in range(NUMTASKS): ++ self.newtask() + +- verbose_print("waiting for all tasks to complete") +- self.done_mutex.acquire() +- verbose_print("all tasks done") ++ verbose_print("waiting for all tasks to complete") ++ self.done_mutex.acquire() ++ verbose_print("all tasks done") + +- thread.stack_size(0) ++ thread.stack_size(0) + + def test__count(self): + # Test the _count() function. +diff -r 3a1db0d2747e Lib/test/test_threading.py +--- a/Lib/test/test_threading.py ++++ b/Lib/test/test_threading.py +@@ -1,7 +1,7 @@ + # Very rudimentary test of threading module + + import test.test_support +-from test.test_support import verbose ++from test.test_support import verbose, cpython_only + from test.script_helper import assert_python_ok + + import random +@@ -14,6 +14,10 @@ + import weakref + import os + import subprocess ++try: ++ import _testcapi ++except ImportError: ++ _testcapi = None + + from test import lock_tests + +@@ -125,9 +129,7 @@ + try: + threading.stack_size(262144) + except thread.error: +- if verbose: +- print 'platform does not support changing thread stack size' +- return ++ self.skipTest('platform does not support changing thread stack size') + self.test_various_ops() + threading.stack_size(0) + +@@ -138,9 +140,7 @@ + try: + threading.stack_size(0x100000) + except thread.error: +- if verbose: +- print 'platform does not support changing thread stack size' +- return ++ self.skipTest('platform does not support changing thread stack size') + self.test_various_ops() + threading.stack_size(0) + +@@ -167,9 +167,7 @@ + try: + import ctypes + except ImportError: +- if verbose: +- print "test_PyThreadState_SetAsyncExc can't import ctypes" +- return # can't do anything ++ self.skipTest('requires ctypes') + + set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc + +@@ -275,9 +273,7 @@ + try: + import ctypes + except ImportError: +- if verbose: +- print("test_finalize_with_runnning_thread can't import ctypes") +- return # can't do anything ++ self.skipTest('requires ctypes') + + rc = subprocess.call([sys.executable, "-c", """if 1: + import ctypes, sys, time, thread +@@ -728,6 +724,46 @@ + for t in threads: + t.join() + ++ @cpython_only ++ @unittest.skipIf(_testcapi is None, "need _testcapi module") ++ def test_frame_tstate_tracing(self): ++ # Issue #14432: Crash when a generator is created in a C thread that is ++ # destroyed while the generator is still used. The issue was that a ++ # generator contains a frame, and the frame kept a reference to the ++ # Python state of the destroyed C thread. The crash occurs when a trace ++ # function is setup. ++ ++ def noop_trace(frame, event, arg): ++ # no operation ++ return noop_trace ++ ++ def generator(): ++ while 1: ++ yield "genereator" ++ ++ def callback(): ++ if callback.gen is None: ++ callback.gen = generator() ++ return next(callback.gen) ++ callback.gen = None ++ ++ old_trace = sys.gettrace() ++ sys.settrace(noop_trace) ++ try: ++ # Install a trace function ++ threading.settrace(noop_trace) ++ ++ # Create a generator in a C thread which exits after the call ++ _testcapi.call_in_temporary_c_thread(callback) ++ ++ # Call the generator in a different Python thread, check that the ++ # generator didn't keep a reference to the destroyed thread state ++ for test in range(3): ++ # The trace function is still called here ++ callback() ++ finally: ++ sys.settrace(old_trace) ++ + + class ThreadingExceptionTests(BaseTestCase): + # A RuntimeError should be raised if Thread.start() is called +diff -r 3a1db0d2747e Lib/test/test_timeout.py +--- a/Lib/test/test_timeout.py ++++ b/Lib/test/test_timeout.py +@@ -178,16 +178,19 @@ + "timeout (%g) is %g seconds more than expected (%g)" + %(_delta, self.fuzz, _timeout)) + ++ @unittest.skip('test not implemented') + def testSend(self): + # Test send() timeout + # couldn't figure out how to test it + pass + ++ @unittest.skip('test not implemented') + def testSendto(self): + # Test sendto() timeout + # couldn't figure out how to test it + pass + ++ @unittest.skip('test not implemented') + def testSendall(self): + # Test sendall() timeout + # couldn't figure out how to test it +diff -r 3a1db0d2747e Lib/test/test_tokenize.py +--- a/Lib/test/test_tokenize.py ++++ b/Lib/test/test_tokenize.py +@@ -4,7 +4,7 @@ + >>> import glob, random, sys + + The tests can be really simple. Given a small fragment of source +-code, print out a table with tokens. The ENDMARK is omitted for ++code, print out a table with tokens. The ENDMARKER is omitted for + brevity. + + >>> dump_tokens("1 + 1") +@@ -559,9 +559,10 @@ + + from test import test_support + from tokenize import (untokenize, generate_tokens, NUMBER, NAME, OP, +- STRING, ENDMARKER, tok_name) ++ STRING, ENDMARKER, tok_name, Untokenizer) + from StringIO import StringIO + import os ++from unittest import TestCase + + def dump_tokens(s): + """Print out the tokens in s in a table format. +@@ -614,12 +615,47 @@ + return untokenize(result) + + ++class UntokenizeTest(TestCase): ++ ++ def test_bad_input_order(self): ++ # raise if previous row ++ u = Untokenizer() ++ u.prev_row = 2 ++ u.prev_col = 2 ++ with self.assertRaises(ValueError) as cm: ++ u.add_whitespace((1,3)) ++ self.assertEqual(cm.exception.args[0], ++ 'start (1,3) precedes previous end (2,2)') ++ # raise if previous column in row ++ self.assertRaises(ValueError, u.add_whitespace, (2,1)) ++ ++ def test_backslash_continuation(self): ++ # The problem is that \ leaves no token ++ u = Untokenizer() ++ u.prev_row = 1 ++ u.prev_col = 1 ++ u.tokens = [] ++ u.add_whitespace((2, 0)) ++ self.assertEqual(u.tokens, ['\\\n']) ++ u.prev_row = 2 ++ u.add_whitespace((4, 4)) ++ self.assertEqual(u.tokens, ['\\\n', '\\\n\\\n', ' ']) ++ ++ def test_iter_compat(self): ++ u = Untokenizer() ++ token = (NAME, 'Hello') ++ u.compat(token, iter([])) ++ self.assertEqual(u.tokens, ["Hello "]) ++ u = Untokenizer() ++ self.assertEqual(u.untokenize(iter([token])), 'Hello ') ++ ++ + __test__ = {"doctests" : doctests, 'decistmt': decistmt} + +- + def test_main(): + from test import test_tokenize + test_support.run_doctest(test_tokenize, True) ++ test_support.run_unittest(UntokenizeTest) + + if __name__ == "__main__": + test_main() +diff -r 3a1db0d2747e Lib/test/test_traceback.py +--- a/Lib/test/test_traceback.py ++++ b/Lib/test/test_traceback.py +@@ -1,11 +1,10 @@ + """Test cases for traceback module""" + +-from _testcapi import traceback_print + from StringIO import StringIO + import sys + import unittest + from imp import reload +-from test.test_support import run_unittest, is_jython, Error ++from test.test_support import run_unittest, is_jython, Error, cpython_only + + import traceback + +@@ -35,6 +34,9 @@ + def syntax_error_bad_indentation(self): + compile("def spam():\n print 1\n print 2", "?", "exec") + ++ def syntax_error_bad_indentation2(self): ++ compile(" print(2)", "?", "exec") ++ + def test_caret(self): + err = self.get_exception_format(self.syntax_error_with_caret, + SyntaxError) +@@ -111,6 +113,13 @@ + os.unlink(os.path.join(testdir, f)) + os.rmdir(testdir) + ++ err = self.get_exception_format(self.syntax_error_bad_indentation2, ++ IndentationError) ++ self.assertEqual(len(err), 4) ++ self.assertEqual(err[1].strip(), "print(2)") ++ self.assertIn("^", err[2]) ++ self.assertEqual(err[1].find("p"), err[2].find("^")) ++ + def test_base_exception(self): + # Test that exceptions derived from BaseException are formatted right + e = KeyboardInterrupt() +@@ -171,7 +180,9 @@ + + class TracebackFormatTests(unittest.TestCase): + ++ @cpython_only + def test_traceback_format(self): ++ from _testcapi import traceback_print + try: + raise KeyError('blah') + except KeyError: +diff -r 3a1db0d2747e Lib/test/test_ucn.py +--- a/Lib/test/test_ucn.py ++++ b/Lib/test/test_ucn.py +@@ -9,10 +9,14 @@ + + import unittest + import sys +-import _testcapi + + from test import test_support + ++try: ++ from _testcapi import INT_MAX, PY_SSIZE_T_MAX, UINT_MAX ++except ImportError: ++ INT_MAX = PY_SSIZE_T_MAX = UINT_MAX = 2**64 - 1 ++ + class UnicodeNamesTest(unittest.TestCase): + + def checkletter(self, name, code): +@@ -139,11 +143,10 @@ + unicode, "\\NSPACE", 'unicode-escape', 'strict' + ) + +- @unittest.skipUnless(_testcapi.INT_MAX < _testcapi.PY_SSIZE_T_MAX, +- "needs UINT_MAX < SIZE_MAX") +- @unittest.skipUnless(_testcapi.UINT_MAX < sys.maxint, +- "needs UINT_MAX < sys.maxint") +- @test_support.bigmemtest(minsize=_testcapi.UINT_MAX + 1, ++ @test_support.cpython_only ++ @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") ++ @unittest.skipUnless(UINT_MAX < sys.maxint, "needs UINT_MAX < sys.maxint") ++ @test_support.bigmemtest(minsize=UINT_MAX + 1, + memuse=2 + 4 // len(u'\U00010000')) + def test_issue16335(self, size): + func = self.test_issue16335 +@@ -151,9 +154,8 @@ + raise unittest.SkipTest("not enough memory: %.1fG minimum needed" % + (func.minsize * func.memuse / float(1024**3),)) + # very very long bogus character name +- x = b'\\N{SPACE' + b'x' * int(_testcapi.UINT_MAX + 1) + b'}' +- self.assertEqual(len(x), len(b'\\N{SPACE}') + +- (_testcapi.UINT_MAX + 1)) ++ x = b'\\N{SPACE' + b'x' * int(UINT_MAX + 1) + b'}' ++ self.assertEqual(len(x), len(b'\\N{SPACE}') + (UINT_MAX + 1)) + self.assertRaisesRegexp(UnicodeError, + 'unknown Unicode character name', + x.decode, 'unicode-escape' +diff -r 3a1db0d2747e Lib/test/test_unicode.py +--- a/Lib/test/test_unicode.py ++++ b/Lib/test/test_unicode.py +@@ -644,8 +644,13 @@ + return u'\u1234' + self.assertEqual('%s' % Wrapper(), u'\u1234') + ++ def test_formatting_huge_precision(self): ++ format_string = u"%.{}f".format(sys.maxsize + 1) ++ with self.assertRaises(ValueError): ++ result = format_string % 2.34 ++ + @test_support.cpython_only +- def test_formatting_huge_precision(self): ++ def test_formatting_huge_precision_c_limits(self): + from _testcapi import INT_MAX + format_string = u"%.{}f".format(INT_MAX + 1) + with self.assertRaises(ValueError): +@@ -1278,12 +1283,12 @@ + self.assertEqual(repr(s1()), '\\n') + self.assertEqual(repr(s2()), '\\n') + ++ # This test only affects 32-bit platforms because expandtabs can only take ++ # an int as the max value, not a 64-bit C long. If expandtabs is changed ++ # to take a 64-bit long, this test should apply to all platforms. ++ @unittest.skipIf(sys.maxint > (1 << 32) or struct.calcsize('P') != 4, ++ 'only applies to 32-bit platforms') + def test_expandtabs_overflows_gracefully(self): +- # This test only affects 32-bit platforms because expandtabs can only take +- # an int as the max value, not a 64-bit C long. If expandtabs is changed +- # to take a 64-bit long, this test should apply to all platforms. +- if sys.maxint > (1 << 32) or struct.calcsize('P') != 4: +- return + self.assertRaises(OverflowError, u't\tt\t'.expandtabs, sys.maxint) + + def test__format__(self): +@@ -1633,6 +1638,7 @@ + self.assertEqual("%s" % u, u'__unicode__ overridden') + self.assertEqual("{}".format(u), '__unicode__ overridden') + ++ @test_support.cpython_only + def test_encode_decimal(self): + from _testcapi import unicode_encodedecimal + self.assertEqual(unicode_encodedecimal(u'123'), +@@ -1658,6 +1664,7 @@ + self.assertEqual(unicode_encodedecimal(u"123\u20ac\u0660", "replace"), + b'123?0') + ++ @test_support.cpython_only + def test_encode_decimal_with_surrogates(self): + from _testcapi import unicode_encodedecimal + tests = [(u'\U0001f49d', '💝'), +diff -r 3a1db0d2747e Lib/test/test_urllib.py +--- a/Lib/test/test_urllib.py ++++ b/Lib/test/test_urllib.py +@@ -789,6 +789,26 @@ + self.assertEqual(('user 2', 'ab'),urllib.splitpasswd('user 2:ab')) + self.assertEqual(('user+1', 'a+b'),urllib.splitpasswd('user+1:a+b')) + ++ def test_splitport(self): ++ splitport = urllib.splitport ++ self.assertEqual(splitport('parrot:88'), ('parrot', '88')) ++ self.assertEqual(splitport('parrot'), ('parrot', None)) ++ self.assertEqual(splitport('parrot:'), ('parrot', None)) ++ self.assertEqual(splitport('127.0.0.1'), ('127.0.0.1', None)) ++ self.assertEqual(splitport('parrot:cheese'), ('parrot:cheese', None)) ++ ++ def test_splitnport(self): ++ splitnport = urllib.splitnport ++ self.assertEqual(splitnport('parrot:88'), ('parrot', 88)) ++ self.assertEqual(splitnport('parrot'), ('parrot', -1)) ++ self.assertEqual(splitnport('parrot', 55), ('parrot', 55)) ++ self.assertEqual(splitnport('parrot:'), ('parrot', -1)) ++ self.assertEqual(splitnport('parrot:', 55), ('parrot', 55)) ++ self.assertEqual(splitnport('127.0.0.1'), ('127.0.0.1', -1)) ++ self.assertEqual(splitnport('127.0.0.1', 55), ('127.0.0.1', 55)) ++ self.assertEqual(splitnport('parrot:cheese'), ('parrot', None)) ++ self.assertEqual(splitnport('parrot:cheese', 55), ('parrot', None)) ++ + + class URLopener_Tests(unittest.TestCase): + """Testcase to test the open method of URLopener class.""" +@@ -858,7 +878,7 @@ + # def testTimeoutNone(self): + # # global default timeout is ignored + # import socket +-# self.assertTrue(socket.getdefaulttimeout() is None) ++# self.assertIsNone(socket.getdefaulttimeout()) + # socket.setdefaulttimeout(30) + # try: + # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) +@@ -870,7 +890,7 @@ + # def testTimeoutDefault(self): + # # global default timeout is used + # import socket +-# self.assertTrue(socket.getdefaulttimeout() is None) ++# self.assertIsNone(socket.getdefaulttimeout()) + # socket.setdefaulttimeout(30) + # try: + # ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, []) +diff -r 3a1db0d2747e Lib/test/test_urllib2.py +--- a/Lib/test/test_urllib2.py ++++ b/Lib/test/test_urllib2.py +@@ -591,8 +591,8 @@ + self.assertIsInstance(args[0], Request) + # response from opener.open is None, because there's no + # handler that defines http_open to handle it +- self.assertTrue(args[1] is None or +- isinstance(args[1], MockResponse)) ++ if args[1] is not None: ++ self.assertIsInstance(args[1], MockResponse) + + + def sanepathname2url(path): +@@ -924,7 +924,8 @@ + MockHeaders({"location": to_url})) + except urllib2.HTTPError: + # 307 in response to POST requires user OK +- self.assertTrue(code == 307 and data is not None) ++ self.assertEqual(code, 307) ++ self.assertIsNotNone(data) + self.assertEqual(o.req.get_full_url(), to_url) + try: + self.assertEqual(o.req.get_method(), "GET") +diff -r 3a1db0d2747e Lib/test/test_urllib2_localnet.py +--- a/Lib/test/test_urllib2_localnet.py ++++ b/Lib/test/test_urllib2_localnet.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +- + import urlparse + import urllib2 + import BaseHTTPServer +diff -r 3a1db0d2747e Lib/test/test_urllib2net.py +--- a/Lib/test/test_urllib2net.py ++++ b/Lib/test/test_urllib2net.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +- + import unittest + from test import test_support + from test.test_urllib2 import sanepathname2url +@@ -82,11 +80,11 @@ + # delve deep into response to fetch socket._socketobject + response = _urlopen_with_retry("http://www.python.org/") + abused_fileobject = response.fp +- self.assertTrue(abused_fileobject.__class__ is socket._fileobject) ++ self.assertIs(abused_fileobject.__class__, socket._fileobject) + httpresponse = abused_fileobject._sock +- self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse) ++ self.assertIs(httpresponse.__class__, httplib.HTTPResponse) + fileobject = httpresponse.fp +- self.assertTrue(fileobject.__class__ is socket._fileobject) ++ self.assertIs(fileobject.__class__, socket._fileobject) + + self.assertTrue(not fileobject.closed) + response.close() +@@ -252,14 +250,14 @@ + + class TimeoutTest(unittest.TestCase): + def test_http_basic(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + url = "http://www.python.org" + with test_support.transient_internet(url, timeout=None): + u = _urlopen_with_retry(url) +- self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None) ++ self.assertIsNone(u.fp._sock.fp._sock.gettimeout()) + + def test_http_default_timeout(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + url = "http://www.python.org" + with test_support.transient_internet(url): + socket.setdefaulttimeout(60) +@@ -270,7 +268,7 @@ + self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60) + + def test_http_no_timeout(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + url = "http://www.python.org" + with test_support.transient_internet(url): + socket.setdefaulttimeout(60) +@@ -278,7 +276,7 @@ + u = _urlopen_with_retry(url, timeout=None) + finally: + socket.setdefaulttimeout(None) +- self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None) ++ self.assertIsNone(u.fp._sock.fp._sock.gettimeout()) + + def test_http_timeout(self): + url = "http://www.python.org" +@@ -289,13 +287,13 @@ + FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/" + + def test_ftp_basic(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + with test_support.transient_internet(self.FTP_HOST, timeout=None): + u = _urlopen_with_retry(self.FTP_HOST) +- self.assertTrue(u.fp.fp._sock.gettimeout() is None) ++ self.assertIsNone(u.fp.fp._sock.gettimeout()) + + def test_ftp_default_timeout(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout()) + with test_support.transient_internet(self.FTP_HOST): + socket.setdefaulttimeout(60) + try: +@@ -305,14 +303,14 @@ + self.assertEqual(u.fp.fp._sock.gettimeout(), 60) + + def test_ftp_no_timeout(self): +- self.assertTrue(socket.getdefaulttimeout() is None) ++ self.assertIsNone(socket.getdefaulttimeout(),) + with test_support.transient_internet(self.FTP_HOST): + socket.setdefaulttimeout(60) + try: + u = _urlopen_with_retry(self.FTP_HOST, timeout=None) + finally: + socket.setdefaulttimeout(None) +- self.assertTrue(u.fp.fp._sock.gettimeout() is None) ++ self.assertIsNone(u.fp.fp._sock.gettimeout()) + + def test_ftp_timeout(self): + with test_support.transient_internet(self.FTP_HOST): +diff -r 3a1db0d2747e Lib/test/test_urllibnet.py +--- a/Lib/test/test_urllibnet.py ++++ b/Lib/test/test_urllibnet.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +- + import unittest + from test import test_support + +@@ -94,7 +92,7 @@ + + def test_geturl(self): + # Make sure same URL as opened is returned by geturl. +- URL = "http://www.python.org/" ++ URL = "https://www.python.org/" + open_url = self.urlopen(URL) + try: + gotten_url = open_url.geturl() +@@ -112,12 +110,9 @@ + open_url.close() + self.assertEqual(code, 404) + ++ @unittest.skipIf(sys.platform in ('win32',), 'not appropriate for Windows') ++ @unittest.skipUnless(hasattr(os, 'fdopen'), 'os.fdopen not available') + def test_fileno(self): +- if (sys.platform in ('win32',) or +- not hasattr(os, 'fdopen')): +- # On Windows, socket handles are not file descriptors; this +- # test can't pass on Windows. +- return + # Make sure fd returned by fileno is valid. + open_url = self.urlopen("http://www.python.org/") + fd = open_url.fileno() +@@ -189,7 +184,7 @@ + "header is not an instance of mimetools.Message") + + def test_data_header(self): +- logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png" ++ logo = "http://python.org/static/community_logos/python-logo-master-v3-TM.png" + file_location, fileheaders = self.urlretrieve(logo) + os.unlink(file_location) + datevalue = fileheaders.getheader('Date') +diff -r 3a1db0d2747e Lib/test/test_urlparse.py +--- a/Lib/test/test_urlparse.py ++++ b/Lib/test/test_urlparse.py +@@ -1,5 +1,3 @@ +-#! /usr/bin/env python +- + from test import test_support + import unittest + import urlparse +@@ -364,6 +362,16 @@ + ('http://[::12.34.56.78]/foo/', '::12.34.56.78', None), + ('http://[::ffff:12.34.56.78]/foo/', + '::ffff:12.34.56.78', None), ++ ('http://Test.python.org:/foo/', 'test.python.org', None), ++ ('http://12.34.56.78:/foo/', '12.34.56.78', None), ++ ('http://[::1]:/foo/', '::1', None), ++ ('http://[dead:beef::1]:/foo/', 'dead:beef::1', None), ++ ('http://[dead:beef::]:/foo/', 'dead:beef::', None), ++ ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:/foo/', ++ 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None), ++ ('http://[::12.34.56.78]:/foo/', '::12.34.56.78', None), ++ ('http://[::ffff:12.34.56.78]:/foo/', ++ '::ffff:12.34.56.78', None), + ]: + urlparsed = urlparse.urlparse(url) + self.assertEqual((urlparsed.hostname, urlparsed.port) , (hostname, port)) +diff -r 3a1db0d2747e Lib/test/test_userstring.py +--- a/Lib/test/test_userstring.py ++++ b/Lib/test/test_userstring.py +@@ -1,4 +1,3 @@ +-#!/usr/bin/env python + # UserString is a wrapper around the native builtin string type. + # UserString instances should behave similar to builtin string objects. + +diff -r 3a1db0d2747e Lib/test/test_uuid.py +--- a/Lib/test/test_uuid.py ++++ b/Lib/test/test_uuid.py +@@ -1,5 +1,6 @@ + import unittest + from test import test_support ++import io + import os + import uuid + +@@ -346,6 +347,37 @@ + + self.assertEqual(node1, node2) + ++ @unittest.skipUnless(os.name == 'posix', 'requires Posix') ++ def test_find_mac(self): ++ data = '''\ ++ ++fake hwaddr ++cscotun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 ++eth0 Link encap:Ethernet HWaddr 12:34:56:78:90:ab ++''' ++ def mock_popen(cmd): ++ return io.BytesIO(data) ++ ++ path = os.environ.get("PATH", os.defpath).split(os.pathsep) ++ path.extend(('/sbin', '/usr/sbin')) ++ for dir in path: ++ executable = os.path.join(dir, 'ifconfig') ++ if (os.path.exists(executable) and ++ os.access(executable, os.F_OK | os.X_OK) and ++ not os.path.isdir(executable)): ++ break ++ else: ++ self.skipTest('requires ifconfig') ++ ++ with test_support.swap_attr(os, 'popen', mock_popen): ++ mac = uuid._find_mac( ++ command='ifconfig', ++ args='', ++ hw_identifiers=['hwaddr'], ++ get_index=lambda x: x + 1, ++ ) ++ self.assertEqual(mac, 0x1234567890ab) ++ + @unittest.skipUnless(importable('ctypes'), 'requires ctypes') + def test_uuid1(self): + equal = self.assertEqual +diff -r 3a1db0d2747e Lib/test/test_warnings.py +--- a/Lib/test/test_warnings.py ++++ b/Lib/test/test_warnings.py +@@ -259,11 +259,10 @@ + finally: + warning_tests.__file__ = filename + ++ @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv') + def test_missing_filename_main_with_argv(self): + # If __file__ is not specified and the caller is __main__ and sys.argv + # exists, then use sys.argv[0] as the file. +- if not hasattr(sys, 'argv'): +- return + filename = warning_tests.__file__ + module_name = warning_tests.__name__ + try: +@@ -669,7 +668,7 @@ + # Explicit tests for the test_support convenience wrapper + wmod = self.module + if wmod is not sys.modules['warnings']: +- return ++ self.skipTest('module to test is not loaded warnings module') + with test_support.check_warnings(quiet=False) as w: + self.assertEqual(w.warnings, []) + wmod.simplefilter("always") +diff -r 3a1db0d2747e Lib/test/test_wave.py +--- a/Lib/test/test_wave.py ++++ b/Lib/test/test_wave.py +@@ -5,10 +5,15 @@ + import wave + + +-class WavePCM8Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): ++class WaveTest(audiotests.AudioWriteTests, ++ audiotests.AudioTestsWithSourceFile): + module = wave ++ test_unseekable_write = None ++ test_unseekable_overflowed_write = None ++ test_unseekable_incompleted_write = None ++ ++ ++class WavePCM8Test(WaveTest, unittest.TestCase): + sndfilename = 'pluck-pcm8.wav' + sndfilenframes = 3307 + nchannels = 2 +@@ -25,10 +30,7 @@ + """) + + +-class WavePCM16Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = wave ++class WavePCM16Test(WaveTest, unittest.TestCase): + sndfilename = 'pluck-pcm16.wav' + sndfilenframes = 3307 + nchannels = 2 +@@ -48,14 +50,14 @@ + if sys.byteorder != 'big': + frames = audiotests.byteswap2(frames) + ++ if sys.byteorder == 'big': ++ @unittest.expectedFailure ++ def test_unseekable_incompleted_write(self): ++ super().test_unseekable_incompleted_write() + +-@unittest.skipIf(sys.byteorder == 'big', +- '24-bit wave files are supported only on little-endian ' +- 'platforms') +-class WavePCM24Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = wave ++ ++ ++class WavePCM24Test(WaveTest, unittest.TestCase): + sndfilename = 'pluck-pcm24.wav' + sndfilenframes = 3307 + nchannels = 2 +@@ -82,10 +84,7 @@ + frames = audiotests.byteswap3(frames) + + +-class WavePCM32Test(audiotests.AudioWriteTests, +- audiotests.AudioTestsWithSourceFile, +- unittest.TestCase): +- module = wave ++class WavePCM32Test(WaveTest, unittest.TestCase): + sndfilename = 'pluck-pcm32.wav' + sndfilenframes = 3307 + nchannels = 2 +@@ -111,6 +110,11 @@ + if sys.byteorder != 'big': + frames = audiotests.byteswap4(frames) + ++ if sys.byteorder == 'big': ++ @unittest.expectedFailure ++ def test_unseekable_incompleted_write(self): ++ super().test_unseekable_incompleted_write() ++ + + def test_main(): + run_unittest(WavePCM8Test, WavePCM16Test, WavePCM24Test, WavePCM32Test) +diff -r 3a1db0d2747e Lib/test/test_weakref.py +--- a/Lib/test/test_weakref.py ++++ b/Lib/test/test_weakref.py +@@ -4,6 +4,8 @@ + import UserList + import weakref + import operator ++import contextlib ++import copy + + from test import test_support + +@@ -91,11 +93,9 @@ + ref1 = weakref.ref(o, self.callback) + ref2 = weakref.ref(o, self.callback) + del o +- self.assertTrue(ref1() is None, +- "expected reference to be invalidated") +- self.assertTrue(ref2() is None, +- "expected reference to be invalidated") +- self.assertTrue(self.cbcalled == 2, ++ self.assertIsNone(ref1(), "expected reference to be invalidated") ++ self.assertIsNone(ref2(), "expected reference to be invalidated") ++ self.assertEqual(self.cbcalled, 2, + "callback not called the right number of times") + + def test_multiple_selfref_callbacks(self): +@@ -129,15 +129,15 @@ + self.assertRaises(weakref.ReferenceError, check, ref1) + self.assertRaises(weakref.ReferenceError, check, ref2) + self.assertRaises(weakref.ReferenceError, bool, weakref.proxy(C())) +- self.assertTrue(self.cbcalled == 2) ++ self.assertEqual(self.cbcalled, 2) + + def check_basic_ref(self, factory): + o = factory() + ref = weakref.ref(o) +- self.assertTrue(ref() is not None, ++ self.assertIsNotNone(ref(), + "weak reference to live object should be live") + o2 = ref() +- self.assertTrue(o is o2, ++ self.assertIs(o, o2, + "() should return original object if live") + + def check_basic_callback(self, factory): +@@ -145,9 +145,9 @@ + o = factory() + ref = weakref.ref(o, self.callback) + del o +- self.assertTrue(self.cbcalled == 1, ++ self.assertEqual(self.cbcalled, 1, + "callback did not properly set 'cbcalled'") +- self.assertTrue(ref() is None, ++ self.assertIsNone(ref(), + "ref2 should be dead after deleting object reference") + + def test_ref_reuse(self): +@@ -157,19 +157,19 @@ + # between these two; it should make no difference + proxy = weakref.proxy(o) + ref2 = weakref.ref(o) +- self.assertTrue(ref1 is ref2, ++ self.assertIs(ref1, ref2, + "reference object w/out callback should be re-used") + + o = C() + proxy = weakref.proxy(o) + ref1 = weakref.ref(o) + ref2 = weakref.ref(o) +- self.assertTrue(ref1 is ref2, ++ self.assertIs(ref1, ref2, + "reference object w/out callback should be re-used") +- self.assertTrue(weakref.getweakrefcount(o) == 2, ++ self.assertEqual(weakref.getweakrefcount(o), 2, + "wrong weak ref count for object") + del proxy +- self.assertTrue(weakref.getweakrefcount(o) == 1, ++ self.assertEqual(weakref.getweakrefcount(o), 1, + "wrong weak ref count for object after deleting proxy") + + def test_proxy_reuse(self): +@@ -177,7 +177,7 @@ + proxy1 = weakref.proxy(o) + ref = weakref.ref(o) + proxy2 = weakref.proxy(o) +- self.assertTrue(proxy1 is proxy2, ++ self.assertIs(proxy1, proxy2, + "proxy object w/out callback should have been re-used") + + def test_basic_proxy(self): +@@ -259,19 +259,19 @@ + o = Object(1) + p1 = makeref(o, None) + p2 = makeref(o, None) +- self.assertTrue(p1 is p2, "both callbacks were None in the C API") ++ self.assertIs(p1, p2, "both callbacks were None in the C API") + del p1, p2 + p1 = makeref(o) + p2 = makeref(o, None) +- self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API") ++ self.assertIs(p1, p2, "callbacks were NULL, None in the C API") + del p1, p2 + p1 = makeref(o) + p2 = makeref(o) +- self.assertTrue(p1 is p2, "both callbacks were NULL in the C API") ++ self.assertIs(p1, p2, "both callbacks were NULL in the C API") + del p1, p2 + p1 = makeref(o, None) + p2 = makeref(o) +- self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API") ++ self.assertIs(p1, p2, "callbacks were None, NULL in the C API") + + def test_callable_proxy(self): + o = Callable() +@@ -279,13 +279,13 @@ + + self.check_proxy(o, ref1) + +- self.assertTrue(type(ref1) is weakref.CallableProxyType, ++ self.assertIs(type(ref1), weakref.CallableProxyType, + "proxy is not of callable type") + ref1('twinkies!') +- self.assertTrue(o.bar == 'twinkies!', ++ self.assertEqual(o.bar, 'twinkies!', + "call through proxy not passed through to original") + ref1(x='Splat.') +- self.assertTrue(o.bar == 'Splat.', ++ self.assertEqual(o.bar, 'Splat.', + "call through proxy not passed through to original") + + # expect due to too few args +@@ -296,24 +296,23 @@ + + def check_proxy(self, o, proxy): + o.foo = 1 +- self.assertTrue(proxy.foo == 1, ++ self.assertEqual(proxy.foo, 1, + "proxy does not reflect attribute addition") + o.foo = 2 +- self.assertTrue(proxy.foo == 2, ++ self.assertEqual(proxy.foo, 2, + "proxy does not reflect attribute modification") + del o.foo +- self.assertTrue(not hasattr(proxy, 'foo'), ++ self.assertFalse(hasattr(proxy, 'foo'), + "proxy does not reflect attribute removal") + + proxy.foo = 1 +- self.assertTrue(o.foo == 1, ++ self.assertEqual(o.foo, 1, + "object does not reflect attribute addition via proxy") + proxy.foo = 2 +- self.assertTrue( +- o.foo == 2, ++ self.assertEqual(o.foo, 2, + "object does not reflect attribute modification via proxy") + del proxy.foo +- self.assertTrue(not hasattr(o, 'foo'), ++ self.assertFalse(hasattr(o, 'foo'), + "object does not reflect attribute removal via proxy") + + def test_proxy_deletion(self): +@@ -337,21 +336,21 @@ + o = C() + ref1 = weakref.ref(o) + ref2 = weakref.ref(o, self.callback) +- self.assertTrue(weakref.getweakrefcount(o) == 2, ++ self.assertEqual(weakref.getweakrefcount(o), 2, + "got wrong number of weak reference objects") + + proxy1 = weakref.proxy(o) + proxy2 = weakref.proxy(o, self.callback) +- self.assertTrue(weakref.getweakrefcount(o) == 4, ++ self.assertEqual(weakref.getweakrefcount(o), 4, + "got wrong number of weak reference objects") + + del ref1, ref2, proxy1, proxy2 +- self.assertTrue(weakref.getweakrefcount(o) == 0, ++ self.assertEqual(weakref.getweakrefcount(o), 0, + "weak reference objects not unlinked from" + " referent when discarded.") + + # assumes ints do not support weakrefs +- self.assertTrue(weakref.getweakrefcount(1) == 0, ++ self.assertEqual(weakref.getweakrefcount(1), 0, + "got wrong number of weak reference objects for int") + + def test_getweakrefs(self): +@@ -359,22 +358,22 @@ + ref1 = weakref.ref(o, self.callback) + ref2 = weakref.ref(o, self.callback) + del ref1 +- self.assertTrue(weakref.getweakrefs(o) == [ref2], ++ self.assertEqual(weakref.getweakrefs(o), [ref2], + "list of refs does not match") + + o = C() + ref1 = weakref.ref(o, self.callback) + ref2 = weakref.ref(o, self.callback) + del ref2 +- self.assertTrue(weakref.getweakrefs(o) == [ref1], ++ self.assertEqual(weakref.getweakrefs(o), [ref1], + "list of refs does not match") + + del ref1 +- self.assertTrue(weakref.getweakrefs(o) == [], ++ self.assertEqual(weakref.getweakrefs(o), [], + "list of refs not cleared") + + # assumes ints do not support weakrefs +- self.assertTrue(weakref.getweakrefs(1) == [], ++ self.assertEqual(weakref.getweakrefs(1), [], + "list of refs does not match for int") + + def test_newstyle_number_ops(self): +@@ -382,8 +381,8 @@ + pass + f = F(2.0) + p = weakref.proxy(f) +- self.assertTrue(p + 1.0 == 3.0) +- self.assertTrue(1.0 + p == 3.0) # this used to SEGV ++ self.assertEqual(p + 1.0, 3.0) ++ self.assertEqual(1.0 + p, 3.0) # this used to SEGV + + def test_callbacks_protected(self): + # Callbacks protected from already-set exceptions? +@@ -636,7 +635,7 @@ + c.wr = weakref.ref(d, callback) # this won't trigger + d.wr = weakref.ref(callback, d.cb) # ditto + external_wr = weakref.ref(callback, safe_callback) # but this will +- self.assertTrue(external_wr() is callback) ++ self.assertIs(external_wr(), callback) + + # The weakrefs attached to c and d should get cleared, so that + # C.cb is never called. But external_wr isn't part of the cyclic +@@ -808,11 +807,11 @@ + return super(MyRef, self).__call__() + o = Object("foo") + mr = MyRef(o, value=24) +- self.assertTrue(mr() is o) ++ self.assertIs(mr(), o) + self.assertTrue(mr.called) + self.assertEqual(mr.value, 24) + del o +- self.assertTrue(mr() is None) ++ self.assertIsNone(mr()) + self.assertTrue(mr.called) + + def test_subclass_refs_dont_replace_standard_refs(self): +@@ -821,14 +820,14 @@ + o = Object(42) + r1 = MyRef(o) + r2 = weakref.ref(o) +- self.assertTrue(r1 is not r2) ++ self.assertIsNot(r1, r2) + self.assertEqual(weakref.getweakrefs(o), [r2, r1]) + self.assertEqual(weakref.getweakrefcount(o), 2) + r3 = MyRef(o) + self.assertEqual(weakref.getweakrefcount(o), 3) + refs = weakref.getweakrefs(o) + self.assertEqual(len(refs), 3) +- self.assertTrue(r2 is refs[0]) ++ self.assertIs(r2, refs[0]) + self.assertIn(r1, refs[1:]) + self.assertIn(r3, refs[1:]) + +@@ -838,7 +837,7 @@ + o = Object(42) + r1 = MyRef(o, id) + r2 = MyRef(o, str) +- self.assertTrue(r1 is not r2) ++ self.assertIsNot(r1, r2) + refs = weakref.getweakrefs(o) + self.assertIn(r1, refs) + self.assertIn(r2, refs) +@@ -906,7 +905,7 @@ + def check_len_cycles(self, dict_type, cons): + N = 20 + items = [RefCycle() for i in range(N)] +- dct = dict_type(cons(o) for o in items) ++ dct = dict_type(cons(i, o) for i, o in enumerate(items)) + # Keep an iterator alive + it = dct.iteritems() + try: +@@ -916,18 +915,23 @@ + del items + gc.collect() + n1 = len(dct) ++ list(it) + del it + gc.collect() + n2 = len(dct) +- # one item may be kept alive inside the iterator +- self.assertIn(n1, (0, 1)) ++ # iteration should prevent garbage collection here ++ # Note that this is a test on an implementation detail. The requirement ++ # is only to provide stable iteration, not that the size of the container ++ # stay fixed. ++ self.assertEqual(n1, 20) ++ #self.assertIn(n1, (0, 1)) + self.assertEqual(n2, 0) + + def test_weak_keyed_len_cycles(self): +- self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1)) ++ self.check_len_cycles(weakref.WeakKeyDictionary, lambda n, k: (k, n)) + + def test_weak_valued_len_cycles(self): +- self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k)) ++ self.check_len_cycles(weakref.WeakValueDictionary, lambda n, k: (n, k)) + + def check_len_race(self, dict_type, cons): + # Extended sanity checks for len() in the face of cyclic collection +@@ -965,23 +969,23 @@ + # + dict, objects = self.make_weak_valued_dict() + for o in objects: +- self.assertTrue(weakref.getweakrefcount(o) == 1, ++ self.assertEqual(weakref.getweakrefcount(o), 1, + "wrong number of weak references to %r!" % o) +- self.assertTrue(o is dict[o.arg], ++ self.assertIs(o, dict[o.arg], + "wrong object returned by weak dict!") + items1 = dict.items() + items2 = dict.copy().items() + items1.sort() + items2.sort() +- self.assertTrue(items1 == items2, ++ self.assertEqual(items1, items2, + "cloning of weak-valued dictionary did not work!") + del items1, items2 +- self.assertTrue(len(dict) == self.COUNT) ++ self.assertEqual(len(dict), self.COUNT) + del objects[0] +- self.assertTrue(len(dict) == (self.COUNT - 1), ++ self.assertEqual(len(dict), (self.COUNT - 1), + "deleting object did not cause dictionary update") + del objects, o +- self.assertTrue(len(dict) == 0, ++ self.assertEqual(len(dict), 0, + "deleting the values did not clear the dictionary") + # regression on SF bug #447152: + dict = weakref.WeakValueDictionary() +@@ -996,21 +1000,21 @@ + # + dict, objects = self.make_weak_keyed_dict() + for o in objects: +- self.assertTrue(weakref.getweakrefcount(o) == 1, ++ self.assertEqual(weakref.getweakrefcount(o), 1, + "wrong number of weak references to %r!" % o) +- self.assertTrue(o.arg is dict[o], ++ self.assertIs(o.arg, dict[o], + "wrong object returned by weak dict!") + items1 = dict.items() + items2 = dict.copy().items() +- self.assertTrue(set(items1) == set(items2), ++ self.assertEqual(set(items1), set(items2), + "cloning of weak-keyed dictionary did not work!") + del items1, items2 +- self.assertTrue(len(dict) == self.COUNT) ++ self.assertEqual(len(dict), self.COUNT) + del objects[0] +- self.assertTrue(len(dict) == (self.COUNT - 1), ++ self.assertEqual(len(dict), (self.COUNT - 1), + "deleting object did not cause dictionary update") + del objects, o +- self.assertTrue(len(dict) == 0, ++ self.assertEqual(len(dict), 0, + "deleting the keys did not clear the dictionary") + o = Object(42) + dict[o] = "What is the meaning of the universe?" +@@ -1072,37 +1076,117 @@ + items = dict.items() + for item in dict.iteritems(): + items.remove(item) +- self.assertTrue(len(items) == 0, "iteritems() did not touch all items") ++ self.assertEqual(len(items), 0, "iteritems() did not touch all items") + + # key iterator, via __iter__(): + keys = dict.keys() + for k in dict: + keys.remove(k) +- self.assertTrue(len(keys) == 0, "__iter__() did not touch all keys") ++ self.assertEqual(len(keys), 0, "__iter__() did not touch all keys") + + # key iterator, via iterkeys(): + keys = dict.keys() + for k in dict.iterkeys(): + keys.remove(k) +- self.assertTrue(len(keys) == 0, "iterkeys() did not touch all keys") ++ self.assertEqual(len(keys), 0, "iterkeys() did not touch all keys") + + # value iterator: + values = dict.values() + for v in dict.itervalues(): + values.remove(v) +- self.assertTrue(len(values) == 0, ++ self.assertEqual(len(values), 0, + "itervalues() did not touch all values") + ++ def check_weak_destroy_while_iterating(self, dict, objects, iter_name): ++ n = len(dict) ++ it = iter(getattr(dict, iter_name)()) ++ next(it) # Trigger internal iteration ++ # Destroy an object ++ del objects[-1] ++ gc.collect() # just in case ++ # We have removed either the first consumed object, or another one ++ self.assertIn(len(list(it)), [len(objects), len(objects) - 1]) ++ del it ++ # The removal has been committed ++ self.assertEqual(len(dict), n - 1) ++ ++ def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext): ++ # Check that we can explicitly mutate the weak dict without ++ # interfering with delayed removal. ++ # `testcontext` should create an iterator, destroy one of the ++ # weakref'ed objects and then return a new key/value pair corresponding ++ # to the destroyed object. ++ with testcontext() as (k, v): ++ self.assertFalse(k in dict) ++ with testcontext() as (k, v): ++ self.assertRaises(KeyError, dict.__delitem__, k) ++ self.assertFalse(k in dict) ++ with testcontext() as (k, v): ++ self.assertRaises(KeyError, dict.pop, k) ++ self.assertFalse(k in dict) ++ with testcontext() as (k, v): ++ dict[k] = v ++ self.assertEqual(dict[k], v) ++ ddict = copy.copy(dict) ++ with testcontext() as (k, v): ++ dict.update(ddict) ++ self.assertEqual(dict, ddict) ++ with testcontext() as (k, v): ++ dict.clear() ++ self.assertEqual(len(dict), 0) ++ ++ def test_weak_keys_destroy_while_iterating(self): ++ # Issue #7105: iterators shouldn't crash when a key is implicitly removed ++ dict, objects = self.make_weak_keyed_dict() ++ self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys') ++ self.check_weak_destroy_while_iterating(dict, objects, 'iteritems') ++ self.check_weak_destroy_while_iterating(dict, objects, 'itervalues') ++ self.check_weak_destroy_while_iterating(dict, objects, 'iterkeyrefs') ++ dict, objects = self.make_weak_keyed_dict() ++ @contextlib.contextmanager ++ def testcontext(): ++ try: ++ it = iter(dict.iteritems()) ++ next(it) ++ # Schedule a key/value for removal and recreate it ++ v = objects.pop().arg ++ gc.collect() # just in case ++ yield Object(v), v ++ finally: ++ it = None # should commit all removals ++ self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext) ++ ++ def test_weak_values_destroy_while_iterating(self): ++ # Issue #7105: iterators shouldn't crash when a key is implicitly removed ++ dict, objects = self.make_weak_valued_dict() ++ self.check_weak_destroy_while_iterating(dict, objects, 'iterkeys') ++ self.check_weak_destroy_while_iterating(dict, objects, 'iteritems') ++ self.check_weak_destroy_while_iterating(dict, objects, 'itervalues') ++ self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs') ++ dict, objects = self.make_weak_valued_dict() ++ @contextlib.contextmanager ++ def testcontext(): ++ try: ++ it = iter(dict.iteritems()) ++ next(it) ++ # Schedule a key/value for removal and recreate it ++ k = objects.pop().arg ++ gc.collect() # just in case ++ yield k, Object(k) ++ finally: ++ it = None # should commit all removals ++ self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext) ++ + def test_make_weak_keyed_dict_from_dict(self): + o = Object(3) + dict = weakref.WeakKeyDictionary({o:364}) +- self.assertTrue(dict[o] == 364) ++ self.assertEqual(dict[o], 364) + + def test_make_weak_keyed_dict_from_weak_keyed_dict(self): + o = Object(3) + dict = weakref.WeakKeyDictionary({o:364}) + dict2 = weakref.WeakKeyDictionary(dict) +- self.assertTrue(dict[o] == 364) ++ self.assertEqual(dict[o], 364) + + def make_weak_keyed_dict(self): + dict = weakref.WeakKeyDictionary() +@@ -1122,19 +1206,19 @@ + weakdict = klass() + weakdict[key1] = value1 + weakdict[key2] = value2 +- self.assertTrue(len(weakdict) == 2) ++ self.assertEqual(len(weakdict), 2) + k, v = weakdict.popitem() +- self.assertTrue(len(weakdict) == 1) ++ self.assertEqual(len(weakdict), 1) + if k is key1: +- self.assertTrue(v is value1) ++ self.assertIs(v, value1) + else: +- self.assertTrue(v is value2) ++ self.assertIs(v, value2) + k, v = weakdict.popitem() +- self.assertTrue(len(weakdict) == 0) ++ self.assertEqual(len(weakdict), 0) + if k is key1: +- self.assertTrue(v is value1) ++ self.assertIs(v, value1) + else: +- self.assertTrue(v is value2) ++ self.assertIs(v, value2) + + def test_weak_valued_dict_popitem(self): + self.check_popitem(weakref.WeakValueDictionary, +@@ -1145,7 +1229,7 @@ + C(), "value 1", C(), "value 2") + + def check_setdefault(self, klass, key, value1, value2): +- self.assertTrue(value1 is not value2, ++ self.assertIsNot(value1, value2, + "invalid test" + " -- value parameters must be distinct objects") + weakdict = klass() +@@ -1204,10 +1288,10 @@ + o2 = Object('2') + d[o1] = 'something' + d[o2] = 'something' +- self.assertTrue(len(d) == 2) ++ self.assertEqual(len(d), 2) + del d[o1] +- self.assertTrue(len(d) == 1) +- self.assertTrue(d.keys() == [o2]) ++ self.assertEqual(len(d), 1) ++ self.assertEqual(d.keys(), [o2]) + + def test_weak_valued_delitem(self): + d = weakref.WeakValueDictionary() +@@ -1215,10 +1299,10 @@ + o2 = Object('2') + d['something'] = o1 + d['something else'] = o2 +- self.assertTrue(len(d) == 2) ++ self.assertEqual(len(d), 2) + del d['something'] +- self.assertTrue(len(d) == 1) +- self.assertTrue(d.items() == [('something else', o2)]) ++ self.assertEqual(len(d), 1) ++ self.assertEqual(d.items(), [('something else', o2)]) + + def test_weak_keyed_bad_delitem(self): + d = weakref.WeakKeyDictionary() +diff -r 3a1db0d2747e Lib/test/test_weakset.py +--- a/Lib/test/test_weakset.py ++++ b/Lib/test/test_weakset.py +@@ -11,6 +11,7 @@ + import collections + import gc + import contextlib ++from UserString import UserString as ustr + + + class Foo: +@@ -448,6 +449,59 @@ + self.assertGreaterEqual(n2, 0) + self.assertLessEqual(n2, n1) + ++ def test_weak_destroy_while_iterating(self): ++ # Issue #7105: iterators shouldn't crash when a key is implicitly removed ++ # Create new items to be sure no-one else holds a reference ++ items = [ustr(c) for c in ('a', 'b', 'c')] ++ s = WeakSet(items) ++ it = iter(s) ++ next(it) # Trigger internal iteration ++ # Destroy an item ++ del items[-1] ++ gc.collect() # just in case ++ # We have removed either the first consumed items, or another one ++ self.assertIn(len(list(it)), [len(items), len(items) - 1]) ++ del it ++ # The removal has been committed ++ self.assertEqual(len(s), len(items)) ++ ++ def test_weak_destroy_and_mutate_while_iterating(self): ++ # Issue #7105: iterators shouldn't crash when a key is implicitly removed ++ items = [ustr(c) for c in string.ascii_letters] ++ s = WeakSet(items) ++ @contextlib.contextmanager ++ def testcontext(): ++ try: ++ it = iter(s) ++ # Start iterator ++ yielded = ustr(str(next(it))) ++ # Schedule an item for removal and recreate it ++ u = ustr(str(items.pop())) ++ if yielded == u: ++ # The iterator still has a reference to the removed item, ++ # advance it (issue #20006). ++ next(it) ++ gc.collect() # just in case ++ yield u ++ finally: ++ it = None # should commit all removals ++ ++ with testcontext() as u: ++ self.assertFalse(u in s) ++ with testcontext() as u: ++ self.assertRaises(KeyError, s.remove, u) ++ self.assertFalse(u in s) ++ with testcontext() as u: ++ s.add(u) ++ self.assertTrue(u in s) ++ t = s.copy() ++ with testcontext() as u: ++ s.update(t) ++ self.assertEqual(len(s), len(t)) ++ with testcontext() as u: ++ s.clear() ++ self.assertEqual(len(s), 0) ++ + + def test_main(verbose=None): + test_support.run_unittest(TestWeakSet) +diff -r 3a1db0d2747e Lib/test/test_whichdb.py +--- a/Lib/test/test_whichdb.py ++++ b/Lib/test/test_whichdb.py +@@ -1,4 +1,3 @@ +-#! /usr/bin/env python + """Test script for the whichdb module + based on test_anydbm.py + """ +diff -r 3a1db0d2747e Lib/test/test_winsound.py +--- a/Lib/test/test_winsound.py ++++ b/Lib/test/test_winsound.py +@@ -159,18 +159,15 @@ + ) + + def test_alias_fallback(self): +- # This test can't be expected to work on all systems. The MS +- # PlaySound() docs say: +- # +- # If it cannot find the specified sound, PlaySound uses the +- # default system event sound entry instead. If the function +- # can find neither the system default entry nor the default +- # sound, it makes no sound and returns FALSE. +- # +- # It's known to return FALSE on some real systems. +- +- # winsound.PlaySound('!"$%&/(#+*', winsound.SND_ALIAS) +- return ++ # In the absense of the ability to tell if a sound was actually ++ # played, this test has two acceptable outcomes: success (no error, ++ # sound was theoretically played; although as issue #19987 shows ++ # a box without a soundcard can "succeed") or RuntimeError. Any ++ # other error is a failure. ++ try: ++ winsound.PlaySound('!"$%&/(#+*', winsound.SND_ALIAS) ++ except RuntimeError: ++ pass + + def test_alias_nofallback(self): + if _have_soundcard(): +diff -r 3a1db0d2747e Lib/test/test_with.py +--- a/Lib/test/test_with.py ++++ b/Lib/test/test_with.py +@@ -1,5 +1,3 @@ +-#!/usr/bin/env python +- + """Unit tests for the with statement specified in PEP 343.""" + + +diff -r 3a1db0d2747e Lib/test/test_wsgiref.py +--- a/Lib/test/test_wsgiref.py ++++ b/Lib/test/test_wsgiref.py +@@ -155,7 +155,7 @@ + # Check existing value + env = {key:alt} + util.setup_testing_defaults(env) +- self.assertTrue(env[key] is alt) ++ self.assertIs(env[key], alt) + + def checkCrossDefault(self,key,value,**kw): + util.setup_testing_defaults(kw) +@@ -245,6 +245,7 @@ + def testAppURIs(self): + self.checkAppURI("http://127.0.0.1/") + self.checkAppURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam") ++ self.checkAppURI("http://127.0.0.1/sp%E4m", SCRIPT_NAME="/sp\xe4m") + self.checkAppURI("http://spam.example.com:2071/", + HTTP_HOST="spam.example.com:2071", SERVER_PORT="2071") + self.checkAppURI("http://spam.example.com/", +@@ -258,14 +259,19 @@ + def testReqURIs(self): + self.checkReqURI("http://127.0.0.1/") + self.checkReqURI("http://127.0.0.1/spam", SCRIPT_NAME="/spam") ++ self.checkReqURI("http://127.0.0.1/sp%E4m", SCRIPT_NAME="/sp\xe4m") + self.checkReqURI("http://127.0.0.1/spammity/spam", + SCRIPT_NAME="/spammity", PATH_INFO="/spam") ++ self.checkReqURI("http://127.0.0.1/spammity/sp%E4m", ++ SCRIPT_NAME="/spammity", PATH_INFO="/sp\xe4m") + self.checkReqURI("http://127.0.0.1/spammity/spam;ham", + SCRIPT_NAME="/spammity", PATH_INFO="/spam;ham") + self.checkReqURI("http://127.0.0.1/spammity/spam;cookie=1234,5678", + SCRIPT_NAME="/spammity", PATH_INFO="/spam;cookie=1234,5678") + self.checkReqURI("http://127.0.0.1/spammity/spam?say=ni", + SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni") ++ self.checkReqURI("http://127.0.0.1/spammity/spam?s%E4y=ni", ++ SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="s%E4y=ni") + self.checkReqURI("http://127.0.0.1/spammity/spam", 0, + SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni") + +@@ -296,7 +302,7 @@ + self.assertEqual(Headers(test[:]).keys(), ['x']) + self.assertEqual(Headers(test[:]).values(), ['y']) + self.assertEqual(Headers(test[:]).items(), test) +- self.assertFalse(Headers(test).items() is test) # must be copy! ++ self.assertIsNot(Headers(test).items(), test) # must be copy! + + h=Headers([]) + del h['foo'] # should not raise an error +diff -r 3a1db0d2747e Lib/test/test_xml_etree.py +--- a/Lib/test/test_xml_etree.py ++++ b/Lib/test/test_xml_etree.py +@@ -713,14 +713,21 @@ + end {namespace}root + end-ns None + ++ >>> import StringIO ++ ++ >>> events = ('start-ns', 'end-ns') ++ >>> context = ET.iterparse(StringIO.StringIO(r""), events) ++ >>> for action, elem in context: ++ ... print action, elem ++ start-ns ('', '') ++ end-ns None ++ + >>> events = ("start", "end", "bogus") + >>> with open(SIMPLE_XMLFILE, "rb") as f: + ... iterparse(f, events) + Traceback (most recent call last): + ValueError: unknown event 'bogus' + +- >>> import StringIO +- + >>> source = StringIO.StringIO( + ... "\\n" + ... " len(diff)) ++ self.assertGreater(len(msg), len(diff)) + self.assertNotIn(omitted, msg) + + self.maxDiff = None +@@ -627,7 +627,7 @@ + msg = e.args[0] + else: + self.fail('assertSequenceEqual did not fail.') +- self.assertTrue(len(msg) > len(diff)) ++ self.assertGreater(len(msg), len(diff)) + self.assertNotIn(omitted, msg) + + def testTruncateMessage(self): +diff -r 3a1db0d2747e Lib/unittest/test/test_loader.py +--- a/Lib/unittest/test/test_loader.py ++++ b/Lib/unittest/test/test_loader.py +@@ -1279,7 +1279,7 @@ + # "The default value is the TestSuite class" + def test_suiteClass__default_value(self): + loader = unittest.TestLoader() +- self.assertTrue(loader.suiteClass is unittest.TestSuite) ++ self.assertIs(loader.suiteClass, unittest.TestSuite) + + # Make sure the dotted name resolution works even if the actual + # function doesn't have the same name as is used to find it. +diff -r 3a1db0d2747e Lib/unittest/test/test_result.py +--- a/Lib/unittest/test/test_result.py ++++ b/Lib/unittest/test/test_result.py +@@ -176,7 +176,7 @@ + self.assertEqual(result.shouldStop, False) + + test_case, formatted_exc = result.failures[0] +- self.assertTrue(test_case is test) ++ self.assertIs(test_case, test) + self.assertIsInstance(formatted_exc, str) + + # "addError(test, err)" +@@ -224,7 +224,7 @@ + self.assertEqual(result.shouldStop, False) + + test_case, formatted_exc = result.errors[0] +- self.assertTrue(test_case is test) ++ self.assertIs(test_case, test) + self.assertIsInstance(formatted_exc, str) + + def testGetDescriptionWithoutDocstring(self): +diff -r 3a1db0d2747e Lib/urllib.py +--- a/Lib/urllib.py ++++ b/Lib/urllib.py +@@ -1125,10 +1125,13 @@ + global _portprog + if _portprog is None: + import re +- _portprog = re.compile('^(.*):([0-9]+)$') ++ _portprog = re.compile('^(.*):([0-9]*)$') + + match = _portprog.match(host) +- if match: return match.group(1, 2) ++ if match: ++ host, port = match.groups() ++ if port: ++ return host, port + return host, None + + _nportprog = None +@@ -1145,12 +1148,12 @@ + match = _nportprog.match(host) + if match: + host, port = match.group(1, 2) +- try: +- if not port: raise ValueError, "no digits" +- nport = int(port) +- except ValueError: +- nport = None +- return host, nport ++ if port: ++ try: ++ nport = int(port) ++ except ValueError: ++ nport = None ++ return host, nport + return host, defport + + _queryprog = None +diff -r 3a1db0d2747e Lib/urlparse.py +--- a/Lib/urlparse.py ++++ b/Lib/urlparse.py +@@ -109,10 +109,11 @@ + netloc = self.netloc.split('@')[-1].split(']')[-1] + if ':' in netloc: + port = netloc.split(':')[1] +- port = int(port, 10) +- # verify legal port +- if (0 <= port <= 65535): +- return port ++ if port: ++ port = int(port, 10) ++ # verify legal port ++ if (0 <= port <= 65535): ++ return port + return None + + from collections import namedtuple +diff -r 3a1db0d2747e Lib/uuid.py +--- a/Lib/uuid.py ++++ b/Lib/uuid.py +@@ -293,25 +293,38 @@ + + def _find_mac(command, args, hw_identifiers, get_index): + import os +- for dir in ['', '/sbin/', '/usr/sbin']: ++ path = os.environ.get("PATH", os.defpath).split(os.pathsep) ++ path.extend(('/sbin', '/usr/sbin')) ++ for dir in path: + executable = os.path.join(dir, command) +- if not os.path.exists(executable): +- continue ++ if (os.path.exists(executable) and ++ os.access(executable, os.F_OK | os.X_OK) and ++ not os.path.isdir(executable)): ++ break ++ else: ++ return None + +- try: +- # LC_ALL to get English output, 2>/dev/null to +- # prevent output on stderr +- cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args) +- with os.popen(cmd) as pipe: +- for line in pipe: +- words = line.lower().split() +- for i in range(len(words)): +- if words[i] in hw_identifiers: ++ try: ++ # LC_ALL to ensure English output, 2>/dev/null to ++ # prevent output on stderr ++ cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args) ++ with os.popen(cmd) as pipe: ++ for line in pipe: ++ words = line.lower().split() ++ for i in range(len(words)): ++ if words[i] in hw_identifiers: ++ try: + return int( + words[get_index(i)].replace(':', ''), 16) +- except IOError: +- continue +- return None ++ except (ValueError, IndexError): ++ # Virtual interfaces, such as those provided by ++ # VPNs, do not have a colon-delimited MAC address ++ # as expected, but a 16-byte HWAddr separated by ++ # dashes. These should be ignored in favor of a ++ # real MAC address ++ pass ++ except IOError: ++ pass + + def _ifconfig_getnode(): + """Get the hardware address on Unix by running ifconfig.""" +diff -r 3a1db0d2747e Lib/wave.py +--- a/Lib/wave.py ++++ b/Lib/wave.py +@@ -82,14 +82,15 @@ + + _array_fmts = None, 'b', 'h', None, 'i' + +-# Determine endian-ness + import struct +-if struct.pack("h", 1) == "\000\001": +- big_endian = 1 +-else: +- big_endian = 0 ++import sys ++from chunk import Chunk + +-from chunk import Chunk ++def _byteswap3(data): ++ ba = bytearray(data) ++ ba[::3] = data[2::3] ++ ba[2::3] = data[::3] ++ return bytes(ba) + + class Wave_read: + """Variables used in this class: +@@ -231,7 +232,7 @@ + self._data_seek_needed = 0 + if nframes == 0: + return '' +- if self._sampwidth > 1 and big_endian: ++ if self._sampwidth in (2, 4) and sys.byteorder == 'big': + # unfortunately the fromfile() method does not take + # something that only looks like a file object, so + # we have to reach into the innards of the chunk object +@@ -252,6 +253,8 @@ + data = data.tostring() + else: + data = self._data_chunk.read(nframes * self._framesize) ++ if self._sampwidth == 3 and sys.byteorder == 'big': ++ data = _byteswap3(data) + if self._convert and data: + data = self._convert(data) + self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) +@@ -419,14 +422,18 @@ + nframes = len(data) // (self._sampwidth * self._nchannels) + if self._convert: + data = self._convert(data) +- if self._sampwidth > 1 and big_endian: ++ if self._sampwidth in (2, 4) and sys.byteorder == 'big': + import array +- data = array.array(_array_fmts[self._sampwidth], data) ++ a = array.array(_array_fmts[self._sampwidth]) ++ a.fromstring(data) ++ data = a + assert data.itemsize == self._sampwidth + data.byteswap() + data.tofile(self._file) + self._datawritten = self._datawritten + len(data) * self._sampwidth + else: ++ if self._sampwidth == 3 and sys.byteorder == 'big': ++ data = _byteswap3(data) + self._file.write(data) + self._datawritten = self._datawritten + len(data) + self._nframeswritten = self._nframeswritten + nframes +diff -r 3a1db0d2747e Lib/weakref.py +--- a/Lib/weakref.py ++++ b/Lib/weakref.py +@@ -20,7 +20,7 @@ + ProxyType, + ReferenceType) + +-from _weakrefset import WeakSet ++from _weakrefset import WeakSet, _IterationGuard + + from exceptions import ReferenceError + +@@ -48,10 +48,24 @@ + def remove(wr, selfref=ref(self)): + self = selfref() + if self is not None: +- del self.data[wr.key] ++ if self._iterating: ++ self._pending_removals.append(wr.key) ++ else: ++ del self.data[wr.key] + self._remove = remove ++ # A list of keys to be removed ++ self._pending_removals = [] ++ self._iterating = set() + UserDict.UserDict.__init__(self, *args, **kw) + ++ def _commit_removals(self): ++ l = self._pending_removals ++ d = self.data ++ # We shouldn't encounter any KeyError, because this method should ++ # always be called *before* mutating the dict. ++ while l: ++ del d[l.pop()] ++ + def __getitem__(self, key): + o = self.data[key]() + if o is None: +@@ -59,6 +73,11 @@ + else: + return o + ++ def __delitem__(self, key): ++ if self._pending_removals: ++ self._commit_removals() ++ del self.data[key] ++ + def __contains__(self, key): + try: + o = self.data[key]() +@@ -77,8 +96,15 @@ + return "" % id(self) + + def __setitem__(self, key, value): ++ if self._pending_removals: ++ self._commit_removals() + self.data[key] = KeyedRef(value, self._remove, key) + ++ def clear(self): ++ if self._pending_removals: ++ self._commit_removals() ++ self.data.clear() ++ + def copy(self): + new = WeakValueDictionary() + for key, wr in self.data.items(): +@@ -120,16 +146,18 @@ + return L + + def iteritems(self): +- for wr in self.data.itervalues(): +- value = wr() +- if value is not None: +- yield wr.key, value ++ with _IterationGuard(self): ++ for wr in self.data.itervalues(): ++ value = wr() ++ if value is not None: ++ yield wr.key, value + + def iterkeys(self): +- return self.data.iterkeys() ++ with _IterationGuard(self): ++ for k in self.data.iterkeys(): ++ yield k + +- def __iter__(self): +- return self.data.iterkeys() ++ __iter__ = iterkeys + + def itervaluerefs(self): + """Return an iterator that yields the weak references to the values. +@@ -141,15 +169,20 @@ + keep the values around longer than needed. + + """ +- return self.data.itervalues() ++ with _IterationGuard(self): ++ for wr in self.data.itervalues(): ++ yield wr + + def itervalues(self): +- for wr in self.data.itervalues(): +- obj = wr() +- if obj is not None: +- yield obj ++ with _IterationGuard(self): ++ for wr in self.data.itervalues(): ++ obj = wr() ++ if obj is not None: ++ yield obj + + def popitem(self): ++ if self._pending_removals: ++ self._commit_removals() + while 1: + key, wr = self.data.popitem() + o = wr() +@@ -157,6 +190,8 @@ + return key, o + + def pop(self, key, *args): ++ if self._pending_removals: ++ self._commit_removals() + try: + o = self.data.pop(key)() + except KeyError: +@@ -172,12 +207,16 @@ + try: + wr = self.data[key] + except KeyError: ++ if self._pending_removals: ++ self._commit_removals() + self.data[key] = KeyedRef(default, self._remove, key) + return default + else: + return wr() + + def update(self, dict=None, **kwargs): ++ if self._pending_removals: ++ self._commit_removals() + d = self.data + if dict is not None: + if not hasattr(dict, "items"): +@@ -245,9 +284,29 @@ + def remove(k, selfref=ref(self)): + self = selfref() + if self is not None: +- del self.data[k] ++ if self._iterating: ++ self._pending_removals.append(k) ++ else: ++ del self.data[k] + self._remove = remove +- if dict is not None: self.update(dict) ++ # A list of dead weakrefs (keys to be removed) ++ self._pending_removals = [] ++ self._iterating = set() ++ if dict is not None: ++ self.update(dict) ++ ++ def _commit_removals(self): ++ # NOTE: We don't need to call this method before mutating the dict, ++ # because a dead weakref never compares equal to a live weakref, ++ # even if they happened to refer to equal objects. ++ # However, it means keys may already have been removed. ++ l = self._pending_removals ++ d = self.data ++ while l: ++ try: ++ del d[l.pop()] ++ except KeyError: ++ pass + + def __delitem__(self, key): + del self.data[ref(key)] +@@ -306,10 +365,11 @@ + return L + + def iteritems(self): +- for wr, value in self.data.iteritems(): +- key = wr() +- if key is not None: +- yield key, value ++ with _IterationGuard(self): ++ for wr, value in self.data.iteritems(): ++ key = wr() ++ if key is not None: ++ yield key, value + + def iterkeyrefs(self): + """Return an iterator that yields the weak references to the keys. +@@ -321,19 +381,23 @@ + keep the keys around longer than needed. + + """ +- return self.data.iterkeys() ++ with _IterationGuard(self): ++ for wr in self.data.iterkeys(): ++ yield wr + + def iterkeys(self): +- for wr in self.data.iterkeys(): +- obj = wr() +- if obj is not None: +- yield obj ++ with _IterationGuard(self): ++ for wr in self.data.iterkeys(): ++ obj = wr() ++ if obj is not None: ++ yield obj + +- def __iter__(self): +- return self.iterkeys() ++ __iter__ = iterkeys + + def itervalues(self): +- return self.data.itervalues() ++ with _IterationGuard(self): ++ for value in self.data.itervalues(): ++ yield value + + def keyrefs(self): + """Return a list of weak references to the keys. +diff -r 3a1db0d2747e Lib/xml/etree/ElementInclude.py +--- a/Lib/xml/etree/ElementInclude.py ++++ b/Lib/xml/etree/ElementInclude.py +@@ -75,14 +75,13 @@ + # @throws IOError If the loader fails to load the resource. + + def default_loader(href, parse, encoding=None): +- file = open(href) +- if parse == "xml": +- data = ElementTree.parse(file).getroot() +- else: +- data = file.read() +- if encoding: +- data = data.decode(encoding) +- file.close() ++ with open(href) as file: ++ if parse == "xml": ++ data = ElementTree.parse(file).getroot() ++ else: ++ data = file.read() ++ if encoding: ++ data = data.decode(encoding) + return data + + ## +diff -r 3a1db0d2747e Lib/xmlrpclib.py +--- a/Lib/xmlrpclib.py ++++ b/Lib/xmlrpclib.py +@@ -1617,21 +1617,14 @@ + + if __name__ == "__main__": + +- # simple test program (from the XML-RPC specification) +- +- # server = ServerProxy("http://localhost:8000") # local server +- server = ServerProxy("http://time.xmlrpc.com/RPC2") ++ server = ServerProxy("http://localhost:8000") + + print server + +- try: +- print server.currentTime.getCurrentTime() +- except Error, v: +- print "ERROR", v +- + multi = MultiCall(server) +- multi.currentTime.getCurrentTime() +- multi.currentTime.getCurrentTime() ++ multi.pow(2, 9) ++ multi.add(5, 1) ++ multi.add(24, 11) + try: + for response in multi(): + print response +diff -r 3a1db0d2747e Lib/zipfile.py +--- a/Lib/zipfile.py ++++ b/Lib/zipfile.py +@@ -606,7 +606,11 @@ + """Returns buffered bytes without advancing the position.""" + if n > len(self._readbuffer) - self._offset: + chunk = self.read(n) +- self._offset -= len(chunk) ++ if len(chunk) > self._offset: ++ self._readbuffer = chunk + self._readbuffer[self._offset:] ++ self._offset = 0 ++ else: ++ self._offset -= len(chunk) + + # Return up to 512 bytes to reduce allocation overhead for tight loops. + return self._readbuffer[self._offset: self._offset + 512] +@@ -918,10 +922,10 @@ + @comment.setter + def comment(self, comment): + # check for valid comment length +- if len(comment) >= ZIP_MAX_COMMENT: +- if self.debug: +- print('Archive comment is too long; truncating to %d bytes' +- % ZIP_MAX_COMMENT) ++ if len(comment) > ZIP_MAX_COMMENT: ++ import warnings ++ warnings.warn('Archive comment is too long; truncating to %d bytes' ++ % ZIP_MAX_COMMENT, stacklevel=2) + comment = comment[:ZIP_MAX_COMMENT] + self._comment = comment + self._didModify = True +@@ -1084,8 +1088,8 @@ + def _writecheck(self, zinfo): + """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 ++ import warnings ++ warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3) + if self.mode not in ("w", "a"): + raise RuntimeError, 'write() requires mode "w" or "a"' + if not self.fp: +diff -r 3a1db0d2747e Mac/IDLE/Info.plist.in +--- a/Mac/IDLE/Info.plist.in ++++ b/Mac/IDLE/Info.plist.in +@@ -36,7 +36,7 @@ + CFBundleExecutable + IDLE + CFBundleGetInfoString +- %VERSION%, © 2001-2013 Python Software Foundation ++ %VERSION%, © 2001-2014 Python Software Foundation + CFBundleIconFile + IDLE.icns + CFBundleIdentifier +diff -r 3a1db0d2747e Mac/Modules/carbonevt/_CarbonEvtmodule.c +--- a/Mac/Modules/carbonevt/_CarbonEvtmodule.c ++++ b/Mac/Modules/carbonevt/_CarbonEvtmodule.c +@@ -1051,8 +1051,7 @@ + _err = RemoveEventHandler(_self->ob_itself); + if (_err != noErr) return PyMac_Error(_err); + _self->ob_itself = NULL; +- Py_DECREF(_self->ob_callback); +- _self->ob_callback = NULL; ++ Py_CLEAR(_self->ob_callback); + Py_INCREF(Py_None); + _res = Py_None; + return _res; +diff -r 3a1db0d2747e Mac/Modules/list/_Listmodule.c +--- a/Mac/Modules/list/_Listmodule.c ++++ b/Mac/Modules/list/_Listmodule.c +@@ -76,8 +76,7 @@ + + static void ListObj_dealloc(ListObject *self) + { +- Py_XDECREF(self->ob_ldef_func); +- self->ob_ldef_func = NULL; ++ Py_CLEAR(self->ob_ldef_func); + SetListRefCon(self->ob_itself, (long)0); + if (self->ob_must_be_disposed && self->ob_itself) LDispose(self->ob_itself); + self->ob_type->tp_free((PyObject *)self); +diff -r 3a1db0d2747e Mac/PythonLauncher/Info.plist.in +--- a/Mac/PythonLauncher/Info.plist.in ++++ b/Mac/PythonLauncher/Info.plist.in +@@ -40,7 +40,7 @@ + CFBundleExecutable + PythonLauncher + CFBundleGetInfoString +- %VERSION%, © 2001-2013 Python Software Foundation ++ %VERSION%, © 2001-2014 Python Software Foundation + CFBundleIconFile + PythonLauncher.icns + CFBundleIdentifier +diff -r 3a1db0d2747e Mac/README +--- a/Mac/README ++++ b/Mac/README +@@ -81,6 +81,13 @@ + + $ ./configure --enable-universalsdk=/ + ++In general, universal builds depend on specific features provided by the ++Apple-supplied compilers and other build tools included in Apple's Xcode ++development tools. You should install Xcode and the command line tools ++component appropriate for the OS X release you are running on. See the ++Python Developer's Guide (http://docs.python.org/devguide/setup.html) ++for more information. ++ + 2.1 Flavours of universal binaries + .................................. + +diff -r 3a1db0d2747e Mac/Resources/app/Info.plist.in +--- a/Mac/Resources/app/Info.plist.in ++++ b/Mac/Resources/app/Info.plist.in +@@ -20,7 +20,7 @@ + CFBundleExecutable + Python + CFBundleGetInfoString +- %version%, (c) 2004-2013 Python Software Foundation. ++ %version%, (c) 2004-2014 Python Software Foundation. + CFBundleHelpBookFolder + + Documentation +@@ -37,7 +37,7 @@ + CFBundleInfoDictionaryVersion + 6.0 + CFBundleLongVersionString +- %version%, (c) 2004-2013 Python Software Foundation. ++ %version%, (c) 2004-2014 Python Software Foundation. + CFBundleName + Python + CFBundlePackageType +@@ -55,7 +55,7 @@ + NSAppleScriptEnabled + + NSHumanReadableCopyright +- (c) 2013 Python Software Foundation. ++ (c) 2014 Python Software Foundation. + NSHighResolutionCapable + + +diff -r 3a1db0d2747e Mac/Resources/framework/Info.plist.in +--- a/Mac/Resources/framework/Info.plist.in ++++ b/Mac/Resources/framework/Info.plist.in +@@ -17,9 +17,9 @@ + CFBundlePackageType + FMWK + CFBundleShortVersionString +- %VERSION%, (c) 2004-2013 Python Software Foundation. ++ %VERSION%, (c) 2004-2014 Python Software Foundation. + CFBundleLongVersionString +- %VERSION%, (c) 2004-2013 Python Software Foundation. ++ %VERSION%, (c) 2004-2014 Python Software Foundation. + CFBundleSignature + ???? + CFBundleVersion +diff -r 3a1db0d2747e Makefile.pre.in +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -750,7 +750,8 @@ + Include/warnings.h \ + Include/weakrefobject.h \ + pyconfig.h \ +- $(PARSER_HEADERS) ++ $(PARSER_HEADERS) \ ++ $(AST_H) + + $(LIBRARY_OBJS) $(MODOBJS) Modules/python.o: $(PYTHON_HEADERS) + +@@ -930,7 +931,9 @@ + PLATMACPATH=:plat-mac:plat-mac/lib-scriptpackages + LIBSUBDIRS= lib-tk lib-tk/test lib-tk/test/test_tkinter \ + lib-tk/test/test_ttk site-packages test test/audiodata test/data \ +- test/cjkencodings test/decimaltestdata test/xmltestdata test/subprocessdata \ ++ test/cjkencodings test/decimaltestdata test/xmltestdata \ ++ test/imghdrdata \ ++ test/subprocessdata \ + test/tracedmodules \ + encodings compiler hotshot \ + email email/mime email/test email/test/data \ +@@ -939,7 +942,8 @@ + logging bsddb bsddb/test csv importlib wsgiref \ + lib2to3 lib2to3/fixes lib2to3/pgen2 lib2to3/tests \ + lib2to3/tests/data lib2to3/tests/data/fixers lib2to3/tests/data/fixers/myfixes \ +- ctypes ctypes/test ctypes/macholib idlelib idlelib/Icons \ ++ ctypes ctypes/test ctypes/macholib \ ++ idlelib idlelib/Icons idlelib/idle_test \ + distutils distutils/command distutils/tests $(XMLLIBSUBDIRS) \ + multiprocessing multiprocessing/dummy \ + unittest unittest/test \ +diff -r 3a1db0d2747e Misc/ACKS +--- a/Misc/ACKS ++++ b/Misc/ACKS +@@ -1,4 +1,3 @@ +- + Acknowledgements + ---------------- + +@@ -14,39 +13,53 @@ + + Aahz + Michael Abbott ++Rajiv Abraham + David Abrahams ++Marc Abramowitz ++Ron Adam ++Ali Afshar + Jim Ahlstrom + Farhan Ahmad ++Matthew Ahrens + Nir Aides + Yaniv Aknin + Jyrki Alakuijala + Steve Alexander + Fred Allen ++Ray Allen + Billy G. Allie + Kevin Altis + Joe Amenta + A. Amoroso + Mark Anacker ++Shashwat Anand + Anders Andersen + John Anderson + Pehr Anderson + Erik Andersén + Oliver Andrich + Ross Andrus ++Juancarlo Añez ++Chris Angelico ++Jérémy Anger + Ankur Ankan ++Jon Anglin + Heidi Annexstad ++Ramchandra Apte + Éric Araujo ++Alicia Arlen + Jeffrey Armstrong + Jason Asbahr + David Ascher + Chris AtLee ++Aymeric Augustin + John Aycock +-Jan-Hein Bührman + Donovan Baarda + Arne Babenhauserheide + Attila Babo ++Matt Bachmann ++Marcin Bachry + Alfonso Baciero +-Marcin Bachry + Dwayne Bailey + Stig Bakken + Greg Ball +@@ -54,53 +67,66 @@ + Jeff Balogh + Manuel Balsera + Matt Bandy ++Dmi Baranov + Michael J. Barber + Daniel Barclay ++Nicolas Bareil + Chris Barker + Anton Barkovsky + Nick Barnes + Quentin Barnes ++David Barnett + Matthew Barnett + Richard Barran + Cesar Eduardo Barros + Des Barry + Ulf Bartelt + Don Bashford ++Pior Bastida + Nick Bastin + Ned Batchelder + Jeff Bauer +-Mike Bayer + Michael R Bax + Anthony Baxter ++Mike Bayer + Samuel L. Bayer + Donald Beaudry + David Beazley ++Neal Becker + Robin Becker +-Neal Becker + Torsten Becker + Bill Bedford ++Stefan Behnel + Reimer Behrends + Ben Bell + Thomas Bellman + Alexander “Саша†Belopolsky ++Eli Bendersky + David Benjamin + Oscar Benjamin + Andrew Bennetts + Andy Bensky + Bennett Benson ++Ezra Berch + Michel Van den Bergh ++Julian Berman ++Brice Berna ++Olivier Bernard + Eric Beser + Steven Bethard + Stephen Bevan + Ron Bickers + Natalia B. Bidart ++Adrian von Bidder + David Binger + Dominic Binks + Philippe Biondi + Michael Birtwell + Stuart Bishop + Roy Bixler ++Daniel Black + Jonathan Black ++Renaud Blanch + Mike Bland + Martin Bless + Pablo Bleyer +@@ -113,9 +139,13 @@ + David Bolen + Wouter Bolsterlee + Gawain Bolton ++Forest Bond + Gregory Bond ++Matias Bordese ++Jonas Borgström + Jurjen Bos + Peter Bosch ++Dan Boswell + Eric Bouck + Thierry Bousch + Sebastian Boving +@@ -126,44 +156,58 @@ + Georg Brandl + Christopher Brannon + Terrence Brannon ++Germán M. Bravo ++Sven Brauch + Erik Bray + Brian Brazil ++Demian Brecht + Dave Brennan + Tom Bridgman ++Anthony Briggs + Keith Briggs ++Tobias Brink + Richard Brodie + Michael Broghton + Daniel Brotsky + Jean Brouwers + Gary S. Brown ++Titus Brown + Oleg Broytmann + Dave Brueck + Francisco Martín Brugué + Ian Bruntlett ++Floris Bruynooghe ++Matt Bryant + Stan Bubrouski + Erik de Bueger ++Jan-Hein Bührman ++Lars Buitinck + Dick Bulterman + Bill Bumgarner + Jimmy Burgett ++Edmond Burnett + Tommy Burnette + Roger Burnham + Alastair Burt + Tarn Weisner Burton + Lee Busby + Ralph Butler ++Nicolas Cadou + Jp Calderone + Arnaud Calmettes + Daniel Calvelo + Tony Campbell + Brett Cannon + Mike Carlton ++Pierre Carrier + Terry Carroll +-Damien Cassou ++Edward Catmur + Lorenzo M. Catucci + Donn Cave + Charles Cazabon + Jesús Cea Avión + Per Cederqvist ++Matej Cepl + Carl Cerecke + Octavian Cerna + Dave Chambers +@@ -171,13 +215,16 @@ + John Chandler + Hye-Shik Chang + Jeffrey Chang ++Godefroid Chapelle ++Brad Chapman ++Greg Chapman + Mitch Chapman +-Greg Chapman +-Brad Chapman + Yogesh Chaudhari + David Chaum + Nicolas Chauvat ++Jerry Chen + Michael Chermside ++Ingrid Cheung + Albert Chin-A-Young + Adal Chiriliuc + Matt Chisholm +@@ -188,21 +235,30 @@ + David Cinege + Craig Citro + Gilles Civario ++Chris Clark ++Laurie Clark-Michalek + Mike Clarkson + Andrew Clegg + Brad Clements ++Robbie Clemons + Steve Clift ++Hervé Coatanhay + Nick Coghlan + Josh Cogliati + Dave Cole ++Terrence Cole + Benjamin Collar + Jeffery Collins + Robert Collins + Paul Colomiets ++Christophe Combelles + Geremy Condra ++Denver Coneybeare ++Phil Connell + Juan José Conti + Matt Conway + David M. Cooke ++Jason R. Coombs + Garrett Cooper + Greg Copeland + Aldo Cortesi +@@ -224,8 +280,10 @@ + Joaquin Cuenca Abela + John Cugini + Tom Culliton ++Antonio Cuni + Brian Curtin + Lisandro Dalcin ++Darren Dale + Andrew Dalke + Lars Damerow + Evan Dandrea +@@ -234,35 +292,45 @@ + Ben Darnell + Kushal Das + Jonathan Dasteel ++Pierre-Yves David + A. Jesse Jiryu Davis ++Merlijn van Deen + John DeGood + Ned Deily + Vincent Delft + Arnaud Delobelle ++Konrad Delong + Erik Demaine + John Dennis + L. Peter Deutsch + Roger Dev + Philippe Devalkeneer + Raghuram Devarakonda ++Caleb Deveraux + Catherine Devlin + Scott Dial + Toby Dickenson + Mark Dickinson + Jack Diederich + Daniel Diniz ++Humberto Diogenes + Yves Dionne + Daniel Dittmar ++Josip Djolonga + Jaromir Dolecek + Ismail Donmez + Robert Donohue + Marcos Donolo + Dima Dorfman ++Yves Dorfsman + Cesar Douady + Dean Draayer + Fred L. Drake, Jr. ++Derk Drukker + John DuBois + Paul Dubois ++Jacques Ducasse ++Andrei Dorian Duma + Graham Dumpleton + Quinn Dunkan + Robin Dunn +@@ -276,36 +344,52 @@ + Maxim Dzumanenko + Walter Dörwald + Hans Eckardt ++Rodolpho Eckhardt ++Ulrich Eckhardt + David Edelsohn ++John Edmonds + Grant Edwards + John Ehresman ++Tal Einat + Eric Eisner + Andrew Eland ++Julien Élie + Lance Ellinghaus ++Daniel Ellis ++Phil Elson + David Ely + Jeff Epler + Tom Epperly ++Gökcen Eraslan + Stoffel Erasmus + Jürgen A. Erhard + Michael Ernst + Ben Escoto + Andy Eskilsson ++André Espaze + Stefan Esser ++Nicolas Estibals ++Carey Evans + Stephen D Evans +-Carey Evans + Tim Everett + Paul Everitt + David Everly + Daniel Evers ++Winston Ewert + Greg Ewing + Martijn Faassen + Clovis Fabricio + Andreas Faerber + Bill Fancher ++Michael Farrell + Troy J. Farrell + Mark Favas ++Boris Feld ++Thomas Fenzl + Niels Ferguson + Sebastian Fernandez ++Florian Festi ++John Feuerstein + Carl Feynman + Vincent Fiack + Tomer Filiba +@@ -322,16 +406,20 @@ + Amaury Forgeot d'Arc + Doug Fort + John Fouhy ++Andrew Francis + Stefan Franke + Martin Franklin ++Kent Frazier + Bruce Frederiksen + Robin Friedrich + Bradley Froehle + Ivan Frohne ++Matthias Fuchs + Jim Fulton + Tadayoshi Funaba + Gyro Funch + Peter Funk ++Ethan Furman + Geoff Furnish + Ulisses Furquim + Hagen Fürstenau +@@ -343,6 +431,7 @@ + Yitzchak Gale + Matthew Gallagher + Quentin Gallet-Gilles ++Riccardo Attilio Galli + Raymund Galvin + Nitin Ganatra + Fred Gansevles +@@ -356,15 +445,23 @@ + Thomas Gellekum + Gabriel Genellina + Christos Georgiou ++Elazar Gershuni + Ben Gertzfield + Nadim Ghaznavi + Dinu Gherman + Jonathan Giddy + Johannes Gijsbers + Michael Gilfix ++Julian Gindi ++Yannick Gingras ++Matt Giuca + Wim Glenn ++Michael Goderbauer ++Jeroen Van Goey + Christoph Gohlke + Tim Golden ++Guilherme Gonçalves ++Tiago Gonçalves + Chris Gonnerman + Shelley Gooch + David Goodger +@@ -372,15 +469,18 @@ + Nathaniel Gray + Eddy De Greef + Grant Griffin ++Andrea Griffini + Duncan Grisby + Fabian Groffen +-John S. Gruber ++Eric Groo + Dag Gruneau + Filip GruszczyÅ„ski + Thomas Guettler ++Anuj Gupta + Michael Guravage + Lars Gustäbel + Thomas Güttler ++Jonas H. + Barry Haddow + Philipp Hagemeister + Paul ten Hagen +@@ -388,9 +488,11 @@ + Peter Haight + Václav Haisman + Zbigniew Halas ++Walker Hale IV + Bob Halley + Jesse Hallio + Jun Hamano ++Alexandre Hamelin + Anders Hammarquist + Mark Hammond + Harald Hanche-Olsen +@@ -401,6 +503,8 @@ + Lynda Hardman + Derek Harland + Jason Harper ++Brian Harring ++Jonathan Hartley + Travis B. Hartwell + Larry Hastings + Tim Hatch +@@ -409,12 +513,14 @@ + Rycharde Hawkes + Ben Hayden + Jochen Hayek ++Tim Heaney + Henrik Heimbuerger + Christian Heimes + Thomas Heller + Malte Helmert + Lance Finn Helsten + Jonathan Hendry ++Michael Henry + James Henstridge + Kasun Herath + Chris Herborth +@@ -427,6 +533,7 @@ + Magnus L. Hetland + Raymond Hettinger + Kevan Heydon ++Kelsey Hightower + Jason Hildebrand + Richie Hindle + Konrad Hinsen +@@ -445,6 +552,7 @@ + Gerrit Holl + Shane Holloway + Rune Holm ++Thomas Holmes + Philip Homburg + Naofumi Honda + Jeffrey Honig +@@ -453,85 +561,111 @@ + Brian Hooper + Randall Hopper + Nadav Horesh ++Alon Horev + Jan Hosang ++Alan Hourihane + Ken Howard + Brad Howes + Mike Hoy + Chih-Hao Huang ++Christian Hudon + Lawrence Hudson + Michael Hudson + Jim Hugunin + Greg Humphreys + Eric Huss ++Nehal Hussain ++Taihyun Hwang + Jeremy Hylton + Ludwig Hähne + Gerhard Häring + Fredrik Håård + Catalin Iacob + Mihai Ibanescu ++Ali Ikinci ++Aaron Iles + Lars Immisch + Bobby Impollonia + Meador Inge ++Peter Ingebretson + Tony Ingraldi + John Interrante + Bob Ippolito + Roger Irwin + Atsuo Ishimoto ++Adam Jackson ++Ben Jackson + Paul Jackson +-Ben Jackson + Manuel Jacob + David Jacobs + Kevin Jacobs + Kjetil Jacobsen ++Bertrand Janin + Geert Jansen + Jack Jansen + Bill Janssen + Thomas Jarosch ++Juhana Jauhiainen + Rajagopalasarma Jayakrishnan ++Zbigniew JÄ™drzejewski-Szmek ++Julien Jehannet + Drew Jenkins + Flemming Kjær Jensen + Philip H. Jensen + Philip Jenvey ++MunSic Jeong + Chris Jerdonek +-Jiba ++Jim Jewett + Pedro Diaz Jimenez + Orjan Johansen + Fredrik Johansson + Gregory K. Johnson + Kent Johnson ++Michael Johnson + Simon Johnston ++Matt Joiner ++Thomas Jollans + Nicolas Joly ++Brian K. Jones + Evan Jones + Jeremy Jones + Richard Jones + Irmen de Jong + Lucas de Jonge ++Kristján Valur Jónsson ++Jens B. Jorgensen + John Jorgensen +-Jens B. Jorgensen + Sijin Joseph + Andreas Jung + Tattoo Mabonzo K. + Sarah K. ++Sunny K + Bohuslav Kabrda ++Alexey Kachayev + Bob Kahn + Kurt B. Kaiser + Tamito Kajiyama ++Jan Kaliszewski + Peter van Kampen ++Rafe Kaplan + Jacob Kaplan-Moss +-Piotr Kasprzyk ++Janne Karila ++Per Øyvind Karlsen + Anton Kasyanov + Lou Kates + Hiroaki Kawai + Sebastien Keim + Ryan Kelly ++Dan Kenigsberg ++Randall Kern + Robert Kern +-Randall Kern + Jim Kerr + Magnus Kessler + Lawrence Kesteloot +-Rafe Kettler + Vivek Khera ++Dhiru Kholia + Mads Kiilerich ++Jason Killen + Jan Kim + Taek Joo Kim + W. Trevor King +@@ -541,6 +675,7 @@ + Kamil Kisiel + Akira Kitada + Ron Klatchko ++Reid Kleckner + Bastian Kleineidam + Bob Kline + Matthias Klose +@@ -550,12 +685,17 @@ + Lenny Kneler + Pat Knight + Jeff Knupp ++Kubilay Kocak + Greg Kochanski + Damon Kohler + Marko Kohtala + Vajrasky Kok + Guido Kollerie ++Jacek Konieczny ++Марк Коренберг ++Arkady Koplyarov + Peter A. Koren ++Vlad Korolev + Joseph Koshy + Daniel Kozan + Jerzy Kozera +@@ -567,34 +707,45 @@ + Michael Kremer + Fabian Kreutz + Cédric Krier ++Pedro Kroger + Hannu Krosing + Andrej Krpic + Ivan Krstić + Steven Kryskalla + Andrew Kuchling +-Ralf W. Grosse-Kunstleve + Dave Kuhlman ++Jon Kuhn ++Toshio Kuratomi + Vladimir Kushnir + Erno Kuusela +-Kirill Kuzminykh (Кирилл Кузьминых) + Ross Lagerwall + Cameron Laird ++David Lam + Thomas Lamb ++Valerie Lambert ++Jean-Baptiste "Jiba" Lamy ++Ronan Lamy + Torsten Landschoff + Åukasz Langa + Tino Lange ++Glenn Langford + Andrew Langmead + Detlef Lannert + Soren Larsen ++Amos Latteier + Piers Lauder + Ben Laurie + Simon Law ++Julia Lawall + Chris Lawrence + Brian Leair ++Mathieu Leduc-Hamel ++Christopher Lee ++Inyeol Lee ++James Lee + John J. Lee +-Inyeol Lee + Thomas Lee +-Christopher Lee ++Tennessee Leeuwenburg + Luc Lefebvre + Pierre Paul Lefebvre + Glyph Lefkowitz +@@ -609,14 +760,20 @@ + Mateusz Lenik + John Lenton + Kostyantyn Leschenko ++Benno Leslie + Christopher Tur Lesniewski-Laas ++Alain Leufroy + Mark Levinson ++Mark Levitt + William Lewis ++Akira Li + Xuanji Li + Robert van Liere + Ross Light + Shawn Ligocki + Martin Ligr ++Gediminas Liktaras ++Grant Limberg + Christopher Lindblad + Ulf A. Lindgren + Björn Lindqvist +@@ -627,47 +784,63 @@ + Mirko Liss + Nick Lockwood + Stephanie Lockwood ++Hugo Lopes Tavares + Anne Lord + Tom Loredo + Justin Love ++Ned Jackson Lovely + Jason Lowe + Tony Lownds + Ray Loyzaga ++Kang-Hao (Kenny) Lu + Lukas Lueg + Loren Luke + Fredrik Lundh + Zhongyue Luo + Mark Lutz ++Taras Lyapun + Jim Lynch + Mikael Lyngvig + Martin von Löwis +-Till Maas ++Guillermo López-Anglada + Jeff MacDonald + John Machin + Andrew I MacIntyre + Tim MacKenzie + Nick Maclaren ++Don MacMillen ++Tomasz Maćkowiak + Steve Majewski ++Marek Majkowski + Grzegorz Makarewicz + David Malcolm ++Greg Malcolm ++William Mallard + Ken Manheimer + Vladimir Marangozov ++Colin Marc + Vincent Marchetti + David Marek + Doug Marien + Sven Marnach + Alex Martelli + Anthony Martin ++Owen Martin + Westley Martínez + Sébastien Martini ++Sidney San Martín + Roger Masse + Nick Mathewson ++Simon Mathieu + Laura Matson + Graham Matthews + Martin Matusiak + Dieter Maurer + Daniel May ++Madison May ++Lucas Maystre + Arnaud Mazin ++Matt McClure + Rebecca McCreary + Kirk McDonald + Chris McDonough +@@ -675,10 +848,11 @@ + Alan McIntyre + Jessica McKellar + Michael McLay ++Brendan McLoughlin + Mark Mc Mahon + Gordon McMillan ++Andrew McNamara + Caolan McNamara +-Andrew McNamara + Jeff McNeil + Craig McPheeters + Lambert Meertens +@@ -691,38 +865,55 @@ + Carl Meyer + Mike Meyer + Piotr Meyer ++Alexis Métaireau + Steven Miale ++Trent Mick + Jason Michalski +-Trent Mick ++Franck Michea + Tom Middleton ++Thomas Miedema + Stan Mihai ++Stefan Mihaila + Aristotelis Mikropoulos + Paolo Milani ++Chad Miller + Damien Miller +-Chad Miller + Jason V. Miller + Jay T. Miller ++Katie Miller + Roman Milner ++Julien Miotte + Andrii V. Mishkovskyi ++Dom Mitchell + Dustin J. Mitchell +-Dom Mitchell ++Zubin Mithra + Florian Mladitsch + Doug Moen + The Dragon De Monsyne ++Bastien Montagne + Skip Montanaro ++Peter Moody + Paul Moore + Ross Moore ++Ben Morgan + Derek Morr + James A Morrison ++Martin Morrison ++Derek McTavish Mounce + Alessandro Moura + Pablo Mouzo ++Mher Movsisyan + Ruslan Mstoi ++Valentina Mukhamedzhanova ++Michael Mulich ++Sape Mullender + Sjoerd Mullender +-Sape Mullender + Michael Muller + Neil Muller ++Louis Munro + R. David Murray + Matti Mäki ++Jörg Müller + Dale Nagata + John Nagle + Takahiro Nakayama +@@ -730,17 +921,18 @@ + Charles-François Natali + Vilmos Nebehaj + Fredrik Nehr ++Tony Nelson + Trent Nelson +-Tony Nelson + Chad Netzer + Max Neunhöffer + George Neville-Neil + Hieu Nguyen + Johannes Nicolai + Samuel Nicolary ++Jonathan Niehof + Gustavo Niemeyer + Oscar Nierstrasz +-Hrvoje Niksic ++Hrvoje NikÅ¡ić + Gregory Nofi + Jesse Noller + Bill Noon +@@ -748,13 +940,19 @@ + Tim Northover + Joe Norton + Neal Norwitz ++Mikhail Novikov + Michal Nowikowski + Steffen Daode Nurpmeso + Nigel O'Brian ++John O'Connor + Kevin O'Connor + Tim O'Malley + Zooko O'Whielacronx ++Aaron Oakley ++James Oakley + Elena Oat ++Jon Oberheide ++Milan Oberkirch + Pascal Oberndoerfer + Jeffrey Ollie + Adam Olsen +@@ -767,6 +965,7 @@ + Michele Orrù + Oleg Oshmyan + Denis S. Otkidach ++Peter Otten + Michael Otteneder + R. M. Oudkerk + Russel Owen +@@ -778,6 +977,7 @@ + Todd R. Palmer + Juan David Ibáñez Palomar + Jan Palus ++Mathias Panzenböck + M. Papillon + Peter Parente + Alexandre Parenteau +@@ -785,56 +985,82 @@ + William Park + Heikki Partanen + Harri Pasanen ++Gaël Pasgrimaud ++Ashish Nitin Patil + Randy Pausch + Samuele Pedroni ++Justin Peel + Marcel van der Peijl + Berker Peksag + Andreas Pelme + Steven Pemberton + Bo Peng + Santiago Peresón ++George Peristerakis ++Mathieu Perreault + Mark Perrego + Trevor Perrin + Gabriel de Perthuis + Tim Peters + Benjamin Peterson ++Joe Peterson + Chris Petrilli ++Roumen Petrov + Bjorn Pettersen + Justin D. Pettit ++Esa Peuha ++Ronny Pfannschmidt + Geoff Philbrick + Gavrie Philipson + Adrian Phillips + Christopher J. Phoenix + Neale Pickett +-Matti Picus + Jim St. Pierre + Dan Pierson + Martijn Pieters ++Anand B. Pillai + François Pinard + Tom Pinckney + Zach Pincus ++Zero Piraeus + Michael Piotrowski + Antoine Pitrou + Jean-François Piéronne + Oleg Plakhotnyuk ++Remi Pointel ++Ariel Poliak + Guilherme Polo ++Illia Polosukhin + Michael Pomraning ++Martin Pool + Iustin Pop ++Claudiu Popa + John Popplewell ++Guillaume Pratte + Amrit Prem + Paul Prescod + Donovan Preston ++Paul Price ++Iuliia Proskurnia ++Jyrki Pulliainen + Steve Purcell ++Eduardo Pérez + Fernando Pérez +-Eduardo Pérez ++Pierre Quentel + Brian Quinlan ++Kevin Jing Qiu + Anders Qvist + Thomas Rachel ++Ram Rachum ++Jérôme Radix + Burton Radons + Jeff Ramnani + Brodie Rao ++Senko Rasic + Antti Rasinen ++Nikolaus Rath + Sridhar Ratnakumar ++Ysj Ray + Eric S. Raymond + Edward K. Ream + Chris Rebert +@@ -844,36 +1070,47 @@ + Gareth Rees + Steve Reeves + Lennart Regebro ++John Regehr ++Federico Reghenzani + Ofir Reichenberg + Sean Reifschneider + Michael P. Reilly + Bernhard Reiter + Steven Reiz + Roeland Rengelink ++Antoine Reversat ++Flávio Ribeiro ++Francesco Ricciardi + Tim Rice +-Francesco Ricciardi + Jan Pieter Riegel + Armin Rigo ++Arc Riley + Nicholas Riley + Jean-Claude Rimbault + Vlad Riscutia + Wes Rishel +-Dan Riti ++Daniel Riti + Juan M. Bello Rivas + Davide Rizzo + Anthony Roach + Carl Robben + Mark Roberts ++Andy Robinson + Jim Robinson +-Andy Robinson ++Mark Roddy + Kevin Rodgers ++Sean Rodman + Giampaolo Rodola ++Elson Rodriguez + Adi Roiban ++Luis Rojas + Mike Romberg + Armin Ronacher + Case Roole + Timothy Roscoe ++Erik Rose + Jim Roskind ++Brian Rosner + Guido van Rossum + Just van Rossum + Hugo van Rossum +@@ -885,22 +1122,29 @@ + Clinton Roy + Paul Rubin + Sam Ruby ++Demur Rumed + Audun S. Runde + Eran Rundstein + Rauli Ruohonen + Jeff Rush + Sam Rushing + Mark Russell ++Rusty Russell + Nick Russo + Chris Ryland + Constantina S. ++Patrick Sabin + Sébastien Sablé + Suman Saha + Hajime Saitou + George Sakkis + Rich Salz + Kevin Samborn ++Adrian Sampson ++James Sanders + Ilya Sandler ++Rafael Santos ++Simon Sapin + Mark Sapiro + Ty Sarna + Hugh Sasse +@@ -908,39 +1152,46 @@ + Ben Sayer + sbt + Marco Scataglini ++Andrew Schaaf + Michael Scharf ++Andreas Schawo + Neil Schemenauer + David Scherer ++Wolfgang Scherer + Hynek Schlawack ++Bob Schmertz + Gregor Schmid + Ralf Schmitt + Michael Schneider + Peter Schneider-Kamp + Arvin Schnell + Scott Schram ++Robin Schreiber + Chad J. Schroeder + Christian Schubert + Sam Schulenburg + Stefan Schwarzer + Dietmar Schwertberger + Federico Schwindt ++Barry Scott + Steven Scott +-Barry Scott + Nick Seidenman +-Žiga Seilnach ++Žiga Seilnacht + Yury Selivanov + Fred Sells + Jiwon Seo ++Iñigo Serna + Joakim Sernbrant +-Roger Serwy ++Roger D. Serwy + Jerry Seutter + Pete Sevander + Denis Severson + Ian Seyer +-Aman Shah ++Daniel Shahaf + Ha Shao + Mark Shannon + Richard Shapiro ++Varun Sharma + Vlad Shcherbina + Justin Sheehy + Charlie Shepherd +@@ -950,18 +1201,18 @@ + Michael Shiplett + John W. Shipman + Joel Shprentz +-Itamar Shtull-Trauring + Yue Shuaijie + Terrel Shumway + Eric Siegerman + Paul Sijben ++SilentGhost + Tim Silk + Michael Simcich + Ionel Simionescu + Kirill Simonov + Nathan Paul Simons + Guilherme Simões +-Kyle Simpson ++Adam Simpkins + Ravi Sinha + Janne Sinkkonen + Ng Pheng Siong +@@ -969,15 +1220,21 @@ + J. Sipprell + Kragen Sitaker + Michael Sloan ++Nick Sloan ++Václav Å milauer ++Christopher Smith + Eric V. Smith +-Christopher Smith + Gregory P. Smith ++Mark Smith + Roy Smith ++Ryan Smith-Roberts + Rafal Smotrzyk ++Eric Snow + Dirk Soede + Paul Sokolovsky + Evgeny Sologubov + Cody Somerville ++Edoardo Spadolini + Clay Spence + Stefan Sperling + Nicholas Spies +@@ -989,10 +1246,13 @@ + Tage Stabell-Kulo + Quentin Stafford-Fraser + Frank Stajano ++Joel Stanley + Anthony Starks + Oliver Steele + Greg Stein ++Baruch Sterin + Chris Stern ++Alex Stewart + Victor Stinner + Richard Stoakley + Peter Stoehr +@@ -1000,28 +1260,34 @@ + Michael Stone + Serhiy Storchaka + Ken Stox +-Patrick Strawderman + Dan Stromberg ++Donald Stufft + Daniel Stutzbach + Andreas Stührk ++Colin Su ++Pal Subbiah + Nathan Sullivan + Mark Summerfield + Reuben Sumner ++Marek Å uppa + Hisao Suzuki ++Kalle Svensson + Andrew Svetlov +-Kalle Svensson + Paul Swartz + Thenault Sylvain + Péter Szabó + Amir Szekely + Arfrever Frehtes Taifersar Arahesis ++Hideaki Takahashi ++Indra Talip ++Neil Tallim + Geoff Talvola ++Musashi Tamura + William Tanksley + Christian Tanzer +-Stefano Taschini + Steven Taschuk ++Amy Taylor + Monty Taylor +-Amy Taylor + Anatoly Techtonik + Mikhail Terekhov + Victor Terrón +@@ -1032,28 +1298,40 @@ + Nicolas M. Thiéry + James Thomas + Robin Thomas ++Brian Thorne + Stephen Thorne ++Jeremy Thurgood + Eric Tiedemann ++July Tikhonov + Tracy Tims + Oren Tirosh + Jason Tishler + Christian Tismer + Jim Tittsler + Frank J. Tobin ++Bennett Todd + R Lindsay Todd +-Bennett Todd + Eugene Toder ++Erik Tollerud ++Stephen Tonkin + Matias Torchinsky + Sandro Tosi + Richard Townsend ++David Townshend ++Nathan Trapuzzano + Laurence Tratt ++Alberto Trevino ++Matthias Troffaes + Tom Tromey + John Tromp ++Diane Trout + Jason Trowbridge + Brent Tubbs + Anthony Tuininga ++Erno Tukia + David Turner + Stephen Turner ++Itamar Turner-Trauring + Theodore Turocy + Bill Tutt + Fraser Tweedale +@@ -1061,19 +1339,23 @@ + Eren Türkay + Lionel Ulmer + Roger Upole ++Daniel Urban + Michael Urman + Hector Urtubia + Ville Vainio + Andi Vajda + Case Van Horsen + Kyle VanderBeek ++Andrew Vant + Atul Varma + Dmitry Vasiliev + Sebastian Ortiz Vasquez + Alexandre Vassalotti ++Nadeem Vawda + Frank Vercruesse + Mike Verdone + Jaap Vermeulen ++Nikita Vetoshkin + Al Vezza + Jacques A. Vidrine + John Viega +@@ -1081,22 +1363,28 @@ + Kannan Vijayan + Kurt Vile + Norman Vine ++Pauli Virtanen + Frank Visser + Johannes Vogel + Alex Volkov + Martijn Vries ++Sjoerd de Vries + Niki W. Waibel + Wojtek Walczak + Charles Waldman + Richard Walker + Larry Wall + Kevin Walzer ++Rodrigo Steinmuller Wanderley + Ke Wang + Greg Ward ++Tom Wardill + Zachary Ware ++Jonas Wagner + Barry Warsaw + Steve Waterbury + Bob Watson ++David Watson + Aaron Watters + Henrik Weber + Corran Webster +@@ -1116,12 +1404,14 @@ + Felix Wiemann + Gerry Wiener + Frank Wierzbicki ++Santoso Wijaya + Bryce "Zooko" Wilcox-O'Hearn + Timothy Wild ++Jakub Wilk ++Gerald S. Williams + Jason Williams + John Williams + Sue Williams +-Gerald S. Williams + Steven Willis + Frank Willison + Geoff Wilson +@@ -1137,25 +1427,30 @@ + John Wiseman + Chris Withers + Stefan Witzel ++Irek Wlizlo + David Wolever + Klaus-Juergen Wolf + Dan Wolfe + Richard Wolff + Adam Woodbeck + Steven Work ++Gordon Worley + Darren Worrall +-Gordon Worley + Thomas Wouters ++Daniel Wozniak + Heiko Wundram + Doug Wyatt + Robert Xiao + Florent Xicluna + Hirokazu Yamamoto + Ka-Ping Yee ++Jason Yeo ++EungJun Yi + Bob Yodlowski + Danny Yoo + Rory Yorke + George Yoshida ++Kazuhiro Yoshida + Masazumi Yoshikawa + Arnaud Ysmal + Bernard Yue +@@ -1166,7 +1461,10 @@ + Yury V. Zaytsev + Siebren van der Zee + Nickolai Zeldovich ++Yuxiao Zeng + Uwe Zessin + Cheng Zhang ++Kai Zhu + Tarek Ziadé ++Gennadiy Zlobin + Peter Ã…strand +diff -r 3a1db0d2747e Misc/NEWS +--- a/Misc/NEWS ++++ b/Misc/NEWS +@@ -1,6 +1,337 @@ +++++++++++++ + Python News + +++++++++++ + ++What's New in Python 2.7.7? ++=========================== ++ ++*Release date: XXXX-XX-XX* ++ ++Core and Builtins ++----------------- ++ ++- Issue #20437: Fixed 43 potential bugs when deleting objects references. ++ ++- Issue #20494: Ensure that free()d memory arenas are really released on POSIX ++ systems supporting anonymous memory mappings. Patch by Charles-François ++ Natali. ++ ++- Issue #17825: Cursor "^" is correctly positioned for SyntaxError and ++ IndentationError. ++ ++- Raise a better error when non-unicode codecs are used for a file's coding ++ cookie. ++ ++- Issue #17976: Fixed potential problem with file.write() not detecting IO error ++ by inspecting the return value of fwrite(). Based on patches by Jaakko Moisio ++ and Victor Stinner. ++ ++- Issue #14432: Generator now clears the borrowed reference to the thread ++ state. Fix a crash when a generator is created in a C thread that is ++ destroyed while the generator is still used. The issue was that a generator ++ contains a frame, and the frame kept a reference to the Python state of the ++ destroyed C thread. The crash occurs when a trace function is setup. ++ ++- Issue #19932: Fix typo in import.h, missing whitespaces in function prototypes. ++ ++- Issue #19638: Fix possible crash / undefined behaviour from huge (more than 2 ++ billion characters) input strings in _Py_dg_strtod. ++ ++Library ++------- ++ ++- Issue #20283: RE pattern methods now accept the string keyword parameters ++ as documented. The pattern and source keyword parameters are left as ++ deprecated aliases. ++ ++- Issue #11599: When an external command (e.g. compiler) fails, distutils now ++ prints out the whole command line (instead of just the command name) if the ++ environment variable DISTUTILS_DEBUG is set. ++ ++- Issue #4931: distutils should not produce unhelpful "error: None" messages ++ anymore. distutils.util.grok_environment_error is kept but doc-deprecated. ++ ++- Improve the random module's default seeding to use 256 bits of entropy ++ from os.urandom(). This was already done for Python 3, mildly improving ++ security with a bigger seed space. ++ ++- Issue #15618: Make turtle.py compatible with 'from __future__ import ++ unicode_literals'. Initial patch by Juancarlo Añez. ++ ++- Issue #20501: fileinput module no longer reads whole file into memory when using ++ fileinput.hook_encoded. ++ ++- Issue #6815: os.path.expandvars() now supports non-ASCII Unicode environment ++ variables names and values. ++ ++- Issue #20635: Fixed grid_columnconfigure() and grid_rowconfigure() methods of ++ Tkinter widgets to work in wantobjects=True mode. ++ ++- Issue #17671: Fixed a crash when use non-initialized io.BufferedRWPair. ++ Based on patch by Stephen Tu. ++ ++- Issue #8478: Untokenizer.compat processes first token from iterator input. ++ Patch based on lines from Georg Brandl, Eric Snow, and Gareth Rees. ++ ++- Issue #20594: Avoid name clash with the libc function posix_close. ++ ++- Issue #19856: shutil.move() failed to move a directory to other directory ++ on Windows if source name ends with os.altsep. ++ ++- Issue #14983: email.generator now always adds a line end after each MIME ++ boundary marker, instead of doing so only when there is an epilogue. This ++ fixes an RFC compliance bug and solves an issue with signed MIME parts. ++ ++- Issue #20013: Some imap servers disconnect if the current mailbox is ++ deleted, and imaplib did not handle that case gracefully. Now it ++ handles the 'bye' correctly. ++ ++- Issue #20426: When passing the re.DEBUG flag, re.compile() displays the ++ debug output every time it is called, regardless of the compilation cache. ++ ++- Issue #20368: The null character now correctly passed from Tcl to Python (in ++ unicode strings only). Improved error handling in variables-related commands. ++ ++- Issue #20435: Fix _pyio.StringIO.getvalue() to take into account newline ++ translation settings. ++ ++- Issue #20288: fix handling of invalid numeric charrefs in HTMLParser. ++ ++- Issue #19456: ntpath.join() now joins relative paths correctly when a drive ++ is present. ++ ++- Issue #8260: The read(), readline() and readlines() methods of ++ codecs.StreamReader returned incomplete data when were called after ++ readline() or read(size). Based on patch by Amaury Forgeot d'Arc. ++ ++- Issue #20374: Fix build with GNU readline >= 6.3. ++ ++- Issue #14548: Make multiprocessing finalizers check pid before ++ running to cope with possibility of gc running just after fork. ++ (Backport from 3.x.) ++ ++- Issue #20262: Warnings are raised now when duplicate names are added in the ++ ZIP file or too long ZIP file comment is truncated. ++ ++- Issue #20270: urllib and urlparse now support empty ports. ++ ++- Issue #20243: TarFile no longer raise ReadError when opened in write mode. ++ ++- Issue #20245: The open functions in the tarfile module now correctly handle ++ empty mode. ++ ++- Issue #20086: Restored the use of locale-independent mapping instead of ++ locale-dependent str.lower() in locale.normalize(). ++ ++- Issue #20246: Fix buffer overflow in socket.recvfrom_into. ++ ++- Issue #19082: Working SimpleXMLRPCServer and xmlrpclib examples, both in ++ modules and documentation. ++ ++- Issue #13107: argparse and optparse no longer raises an exception when output ++ a help on environment with too small COLUMNS. Based on patch by ++ Elazar Gershuni. ++ ++- Issue #20207: Always disable SSLv2 except when PROTOCOL_SSLv2 is explicitly ++ asked for. ++ ++- Issue #20072: Fixed multiple errors in tkinter with wantobjects is False. ++ ++- Issue #1065986: pydoc can now handle unicode strings. ++ ++- Issue #16039: CVE-2013-1752: Change use of readline in imaplib module to ++ limit line length. Patch by Emil Lind. ++ ++- Issue #19422: Explicitly disallow non-SOCK_STREAM sockets in the ssl ++ module, rather than silently let them emit clear text data. ++ ++- Issue #20027: Fixed locale aliases for devanagari locales. ++ ++- Issue #20067: Tkinter variables now work when wantobjects is false. ++ ++- Issue #19020: Tkinter now uses splitlist() instead of split() in configure ++ methods. ++ ++- Issue #12226: HTTPS is now used by default when connecting to PyPI. ++ ++- Issue #20048: Fixed ZipExtFile.peek() when it is called on the boundary of ++ the uncompress buffer and read() goes through more than one readbuffer. ++ ++- Issue #20034: Updated alias mapping to most recent locale.alias file ++ from X.org distribution using makelocalealias.py. ++ ++- Issue #5815: Fixed support for locales with modifiers. Fixed support for ++ locale encodings with hyphens. ++ ++- Issue #20026: Fix the sqlite module to handle correctly invalid isolation ++ level (wrong type). ++ ++- Issue #18829: csv.Dialect() now checks type for delimiter, escapechar and ++ quotechar fields. Original patch by Vajrasky Kok. ++ ++- Issue #19855: uuid.getnode() on Unix now looks on the PATH for the ++ executables used to find the mac address, with /sbin and /usr/sbin as ++ fallbacks. ++ ++- Issue #20007: HTTPResponse.read(0) no more prematurely closes connection. ++ Original patch by Simon Sapin. ++ ++- Issue #19912: Fixed numerous bugs in ntpath.splitunc(). ++ ++- Issue #19623: Fixed writing to unseekable files in the aifc module. ++ Fixed writing 'ulaw' (lower case) compressed AIFC files. ++ ++- Issue #17919: select.poll.register() again works with poll.POLLNVAL on AIX. ++ Fixed integer overflow in the eventmask parameter. ++ ++- Issue #17200: telnetlib's read_until and expect timeout was broken by the ++ fix to Issue #14635 in Python 2.7.4 to be interpreted as milliseconds ++ instead of seconds when the platform supports select.poll (ie: everywhere). ++ It is now treated as seconds once again. ++ ++- Issue #19099: The struct module now supports Unicode format strings. ++ ++- Issue #19878: Fix segfault in bz2 module after calling __init__ twice with ++ non-existent filename. Initial patch by Vajrasky Kok. ++ ++- Issue #16373: Prevent infinite recursion for ABC Set class comparisons. ++ ++- Issue #19138: doctest's IGNORE_EXCEPTION_DETAIL now allows a match when ++ no exception detail exists (no colon following the exception's name, or ++ a colon does follow but no text follows the colon). ++ ++- Issue #16231: Fixed pickle.Pickler to only fallback to its default pickling ++ behaviour when Pickler.persistent_id returns None, but not for any other ++ false values. This allows false values other than None to be used as ++ persistent IDs. This behaviour is consistent with cPickle. ++ ++- Issue #11508: Fixed uuid.getnode() and uuid.uuid1() on environment with ++ virtual interface. Original patch by Kent Frazier. ++ ++- Issue #11489: JSON decoder now accepts lone surrogates. ++ ++- Fix test.test_support.bind_port() to not cause an error when Python was ++ compiled on a system with SO_REUSEPORT defined in the headers but run on ++ a system with an OS kernel that does not support that new socket option. ++ ++- Issue #19633: Fixed writing not compressed 16- and 32-bit wave files on ++ big-endian platforms. ++ ++- Issue #19449: in csv's writerow, handle non-string keys when generating the ++ error message that certain keys are not in the 'fieldnames' list. ++ ++- Issue #12853: Fix NameError in distutils.command.upload. ++ ++- Issue #19523: Closed FileHandler leak which occurred when delay was set. ++ ++- Issue #1575020: Fixed support of 24-bit wave files on big-endian platforms. ++ ++- Issue #19480: HTMLParser now accepts all valid start-tag names as defined ++ by the HTML5 standard. ++ ++- Issue #17827: Add the missing documentation for ``codecs.encode`` and ++ ``codecs.decode``. ++ ++- Issue #6157: Fixed Tkinter.Text.debug(). Original patch by Guilherme Polo. ++ ++- Issue #6160: The bbox() method of tkinter.Spinbox now returns a tuple of ++ integers instead of a string. Based on patch by Guilherme Polo. ++ ++- Issue #19286: Directories in ``package_data`` are no longer added to ++ the filelist, preventing failure outlined in the ticket. ++ ++Tools/Demos ++----------- ++ ++- Issue #19936: Added executable bits or shebang lines to Python scripts which ++ requires them. Disable executable bits and shebang lines in test and ++ benchmark files in order to prevent using a random system python, and in ++ source files of modules which don't provide command line interface. ++ ++IDLE ++---- ++ ++- Issue #20406: Use Python application icons for Idle window title bars. ++ Patch mostly by Serhiy Storchaka. ++ ++- Issue #17721: Remove non-functional configuration dialog help button until we ++ make it actually gives some help when clicked. Patch by Guilherme Simões. ++ ++- Issue #17390: Add Python version to Idle editor window title bar. ++ Original patches by Edmond Burnett and Kent Johnson. ++ ++- Issue #20058: sys.stdin.readline() in IDLE now always returns only one line. ++ ++- Issue #19481: print() of unicode, str or bytearray subclass instance in IDLE ++ no more hangs. ++ ++- Issue #18270: Prevent possible IDLE AttributeError on OS X when no initial ++ shell window is present. ++ ++Tests ++----- ++ ++- Issue #20946: Correct alignment assumptions of some ctypes tests. ++ ++- Issue #20743: Fix a reference leak in test_tcl. ++ ++- Issue #20510: Rewrote test_exit in test_sys to match existing comments, ++ use modern unittest features, and use helpers from test.script_helper ++ instead of using subprocess directly. Initial patch by Gareth Rees. ++ ++- Issue #20532: Tests which use _testcapi now are marked as CPython only. ++ ++- Issue #19920: Added tests for TarFile.list(). Based on patch by Vajrasky Kok. ++ ++- Issue #19990: Added tests for the imghdr module. Based on patch by ++ Claudiu Popa. ++ ++- Issue #19804: The test_find_mac test in test_uuid is now skipped if the ++ ifconfig executable is not available. ++ ++- Issue #19886: Use better estimated memory requirements for bigmem tests. ++ ++- Backported tests for Tkinter variables. ++ ++- Issue #19320: test_tcl no longer fails when wantobjects is false. ++ ++- Issue #19683: Removed empty tests from test_minidom. Initial patch by ++ Ajitesh Gupta. ++ ++- Issue #19928: Implemented a test for repr() of cell objects. ++ ++- Issue #19595, #19987: Re-enabled a long-disabled test in test_winsound. ++ ++- Issue #19588: Fixed tests in test_random that were silently skipped most ++ of the time. Patch by Julian Gindi. ++ ++- Issue #17883: Tweak test_tcl testLoadWithUNC to skip the test in the ++ event of a permission error on Windows and to properly report other ++ skip conditions. ++ ++- Issue #17883: Backported _is_gui_available() in test.test_support to ++ avoid hanging Windows buildbots on test_ttk_guionly. ++ ++- Issue #18702, #19572: All skipped tests now reported as skipped. ++ ++- Issue #19085: Added basic tests for all tkinter widget options. ++ ++- Issue #20605: Make test_socket getaddrinfo OS X segfault test more robust. ++ ++- Issue #20939: Fix test_geturl failure in test_urllibnet due to ++ new redirect of http://www.python.org/ to https://www.python.org. ++ ++Documentation ++------------- ++ ++- Issue #20255: Update the about and bugs pages. ++ ++- Issue #18840: Introduce the json module in the tutorial, and de-emphasize ++ the pickle module. ++ ++- Issue #19795: Improved markup of True/False constants. ++ ++ + Whats' New in Python 2.7.6? + =========================== + +diff -r 3a1db0d2747e Modules/_bsddb.c +--- a/Modules/_bsddb.c ++++ b/Modules/_bsddb.c +@@ -949,8 +949,7 @@ + * DBTxns and closing any open DBs first. */ + if (makeDBError(err)) { + if (self->myenvobj) { +- Py_DECREF(self->myenvobj); +- self->myenvobj = NULL; ++ Py_CLEAR(self->myenvobj); + } + Py_DECREF(self); + self = NULL; +@@ -982,20 +981,16 @@ + PyObject_ClearWeakRefs((PyObject *) self); + } + if (self->myenvobj) { +- Py_DECREF(self->myenvobj); +- self->myenvobj = NULL; ++ Py_CLEAR(self->myenvobj); + } + if (self->associateCallback != NULL) { +- Py_DECREF(self->associateCallback); +- self->associateCallback = NULL; ++ Py_CLEAR(self->associateCallback); + } + if (self->btCompareCallback != NULL) { +- Py_DECREF(self->btCompareCallback); +- self->btCompareCallback = NULL; ++ Py_CLEAR(self->btCompareCallback); + } + if (self->dupCompareCallback != NULL) { +- Py_DECREF(self->dupCompareCallback); +- self->dupCompareCallback = NULL; ++ Py_CLEAR(self->dupCompareCallback); + } + Py_DECREF(self->private_obj); + PyObject_Del(self); +@@ -1160,8 +1155,7 @@ + PyErr_Clear(); + } + +- Py_XDECREF(self->event_notifyCallback); +- self->event_notifyCallback = NULL; ++ Py_CLEAR(self->event_notifyCallback); + + if (self->in_weakreflist != NULL) { + PyObject_ClearWeakRefs((PyObject *) self); +@@ -1640,8 +1634,7 @@ + MYDB_END_ALLOW_THREADS; + + if (err) { +- Py_XDECREF(secondaryDB->associateCallback); +- secondaryDB->associateCallback = NULL; ++ Py_CLEAR(secondaryDB->associateCallback); + secondaryDB->primaryDBType = 0; + } + +diff -r 3a1db0d2747e Modules/_collectionsmodule.c +--- a/Modules/_collectionsmodule.c ++++ b/Modules/_collectionsmodule.c +@@ -1612,11 +1612,13 @@ + } + + PyDoc_STRVAR(defdict_doc, +-"defaultdict(default_factory) --> dict with default factory\n\ ++"defaultdict(default_factory[, ...]) --> dict with default factory\n\ + \n\ + The default factory is called without arguments to produce\n\ + a new value when a key is not present, in __getitem__ only.\n\ + A defaultdict compares equal to a dict with the same items.\n\ ++All remaining arguments are treated the same as if they were\n\ ++passed to the dict constructor, including keyword arguments.\n\ + "); + + /* See comment in xxsubtype.c */ +diff -r 3a1db0d2747e Modules/_csv.c +--- a/Modules/_csv.c ++++ b/Modules/_csv.c +@@ -239,19 +239,24 @@ + if (src == NULL) + *target = dflt; + else { +- if (src == Py_None || PyString_Size(src) == 0) +- *target = '\0'; +- else if (!PyString_Check(src) || PyString_Size(src) != 1) { +- PyErr_Format(PyExc_TypeError, +- "\"%s\" must be an 1-character string", +- name); +- return -1; +- } +- else { +- char *s = PyString_AsString(src); +- if (s == NULL) ++ *target = '\0'; ++ if (src != Py_None) { ++ Py_ssize_t len; ++ if (!PyString_Check(src)) { ++ PyErr_Format(PyExc_TypeError, ++ "\"%s\" must be string, not %.200s", name, ++ src->ob_type->tp_name); + return -1; +- *target = s[0]; ++ } ++ len = PyString_GET_SIZE(src); ++ if (len > 1) { ++ PyErr_Format(PyExc_TypeError, ++ "\"%s\" must be an 1-character string", ++ name); ++ return -1; ++ } ++ if (len > 0) ++ *target = *PyString_AS_STRING(src); + } + } + return 0; +@@ -267,7 +272,7 @@ + *target = NULL; + else if (!IS_BASESTRING(src)) { + PyErr_Format(PyExc_TypeError, +- "\"%s\" must be an string", name); ++ "\"%s\" must be a string", name); + return -1; + } + else { +@@ -426,7 +431,8 @@ + if (dialect_check_quoting(self->quoting)) + goto err; + if (self->delimiter == 0) { +- PyErr_SetString(PyExc_TypeError, "delimiter must be set"); ++ PyErr_SetString(PyExc_TypeError, ++ "\"delimiter\" must be an 1-character string"); + goto err; + } + if (quotechar == Py_None && quoting == NULL) +diff -r 3a1db0d2747e Modules/_ctypes/_ctypes.c +--- a/Modules/_ctypes/_ctypes.c ++++ b/Modules/_ctypes/_ctypes.c +@@ -194,10 +194,8 @@ + if (-1 == PyDict_DelItem(self->dict, self->key)) + /* XXX Error context */ + PyErr_WriteUnraisable(Py_None); +- Py_DECREF(self->key); +- self->key = NULL; +- Py_DECREF(self->dict); +- self->dict = NULL; ++ Py_CLEAR(self->key); ++ Py_CLEAR(self->dict); + } + Py_INCREF(Py_None); + return Py_None; +@@ -3040,10 +3038,8 @@ + PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob) + { + if (ob == NULL) { +- Py_XDECREF(self->restype); +- self->restype = NULL; +- Py_XDECREF(self->checker); +- self->checker = NULL; ++ Py_CLEAR(self->restype); ++ Py_CLEAR(self->checker); + return 0; + } + if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) { +@@ -3086,10 +3082,8 @@ + PyObject *converters; + + if (ob == NULL || ob == Py_None) { +- Py_XDECREF(self->converters); +- self->converters = NULL; +- Py_XDECREF(self->argtypes); +- self->argtypes = NULL; ++ Py_CLEAR(self->converters); ++ Py_CLEAR(self->argtypes); + } else { + converters = converters_from_argtypes(ob); + if (!converters) +diff -r 3a1db0d2747e Modules/_ctypes/cfield.c +--- a/Modules/_ctypes/cfield.c ++++ b/Modules/_ctypes/cfield.c +@@ -1687,9 +1687,9 @@ + /* + #define CHAR_ALIGN (sizeof(s_char) - sizeof(char)) + #define SHORT_ALIGN (sizeof(s_short) - sizeof(short)) +-#define INT_ALIGN (sizeof(s_int) - sizeof(int)) + #define LONG_ALIGN (sizeof(s_long) - sizeof(long)) + */ ++#define INT_ALIGN (sizeof(s_int) - sizeof(int)) + #define FLOAT_ALIGN (sizeof(s_float) - sizeof(float)) + #define DOUBLE_ALIGN (sizeof(s_double) - sizeof(double)) + #define LONGDOUBLE_ALIGN (sizeof(s_long_double) - sizeof(long double)) +@@ -1731,8 +1731,8 @@ + ffi_type ffi_type_uint16 = { 2, 2, FFI_TYPE_UINT16 }; + ffi_type ffi_type_sint16 = { 2, 2, FFI_TYPE_SINT16 }; + +-ffi_type ffi_type_uint32 = { 4, 4, FFI_TYPE_UINT32 }; +-ffi_type ffi_type_sint32 = { 4, 4, FFI_TYPE_SINT32 }; ++ffi_type ffi_type_uint32 = { 4, INT_ALIGN, FFI_TYPE_UINT32 }; ++ffi_type ffi_type_sint32 = { 4, INT_ALIGN, FFI_TYPE_SINT32 }; + + ffi_type ffi_type_uint64 = { 8, LONG_LONG_ALIGN, FFI_TYPE_UINT64 }; + ffi_type ffi_type_sint64 = { 8, LONG_LONG_ALIGN, FFI_TYPE_SINT64 }; +diff -r 3a1db0d2747e Modules/_elementtree.c +--- a/Modules/_elementtree.c ++++ b/Modules/_elementtree.c +@@ -2338,7 +2338,10 @@ + PyObject* sprefix = NULL; + PyObject* suri = NULL; + +- suri = makestring(uri, strlen(uri)); ++ if (uri) ++ suri = makestring(uri, strlen(uri)); ++ else ++ suri = PyString_FromStringAndSize("", 0); + if (!suri) + return; + +@@ -2736,10 +2739,10 @@ + target->events = events; + + /* clear out existing events */ +- Py_XDECREF(target->start_event_obj); target->start_event_obj = NULL; +- Py_XDECREF(target->end_event_obj); target->end_event_obj = NULL; +- Py_XDECREF(target->start_ns_event_obj); target->start_ns_event_obj = NULL; +- Py_XDECREF(target->end_ns_event_obj); target->end_ns_event_obj = NULL; ++ Py_CLEAR(target->start_event_obj); ++ Py_CLEAR(target->end_event_obj); ++ Py_CLEAR(target->start_ns_event_obj); ++ Py_CLEAR(target->end_ns_event_obj); + + if (event_set == Py_None) { + /* default is "end" only */ +diff -r 3a1db0d2747e Modules/_io/bufferedio.c +--- a/Modules/_io/bufferedio.c ++++ b/Modules/_io/bufferedio.c +@@ -2129,9 +2129,14 @@ + static PyObject * + _forward_call(buffered *self, const char *name, PyObject *args) + { +- PyObject *func = PyObject_GetAttrString((PyObject *)self, name); +- PyObject *ret; ++ PyObject *func, *ret; ++ if (self == NULL) { ++ PyErr_SetString(PyExc_ValueError, ++ "I/O operation on uninitialized object"); ++ return NULL; ++ } + ++ func = PyObject_GetAttrString((PyObject *)self, name); + if (func == NULL) { + PyErr_SetString(PyExc_AttributeError, name); + return NULL; +diff -r 3a1db0d2747e Modules/_json.c +--- a/Modules/_json.c ++++ b/Modules/_json.c +@@ -524,16 +524,10 @@ + } + #ifdef Py_UNICODE_WIDE + /* Surrogate pair */ +- if ((c & 0xfc00) == 0xd800) { ++ if ((c & 0xfc00) == 0xd800 && end + 6 < len && ++ buf[next++] == '\\' && ++ buf[next++] == 'u') { + Py_UNICODE c2 = 0; +- if (end + 6 >= len) { +- raise_errmsg("Unpaired high surrogate", pystr, end - 5); +- goto bail; +- } +- if (buf[next++] != '\\' || buf[next++] != 'u') { +- raise_errmsg("Unpaired high surrogate", pystr, end - 5); +- goto bail; +- } + end += 6; + /* Decode 4 hex digits */ + for (; next < end; next++) { +@@ -554,15 +548,10 @@ + goto bail; + } + } +- if ((c2 & 0xfc00) != 0xdc00) { +- raise_errmsg("Unpaired high surrogate", pystr, end - 5); +- goto bail; +- } +- c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); +- } +- else if ((c & 0xfc00) == 0xdc00) { +- raise_errmsg("Unpaired low surrogate", pystr, end - 5); +- goto bail; ++ if ((c2 & 0xfc00) == 0xdc00) ++ c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); ++ else ++ end -= 6; + } + #endif + } +@@ -703,16 +692,9 @@ + } + #ifdef Py_UNICODE_WIDE + /* Surrogate pair */ +- if ((c & 0xfc00) == 0xd800) { ++ if ((c & 0xfc00) == 0xd800 && end + 6 < len && ++ buf[next++] == '\\' && buf[next++] == 'u') { + Py_UNICODE c2 = 0; +- if (end + 6 >= len) { +- raise_errmsg("Unpaired high surrogate", pystr, end - 5); +- goto bail; +- } +- if (buf[next++] != '\\' || buf[next++] != 'u') { +- raise_errmsg("Unpaired high surrogate", pystr, end - 5); +- goto bail; +- } + end += 6; + /* Decode 4 hex digits */ + for (; next < end; next++) { +@@ -733,15 +715,10 @@ + goto bail; + } + } +- if ((c2 & 0xfc00) != 0xdc00) { +- raise_errmsg("Unpaired high surrogate", pystr, end - 5); +- goto bail; +- } +- c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); +- } +- else if ((c & 0xfc00) == 0xdc00) { +- raise_errmsg("Unpaired low surrogate", pystr, end - 5); +- goto bail; ++ if ((c2 & 0xfc00) == 0xdc00) ++ c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00)); ++ else ++ end -= 6; + } + #endif + } +diff -r 3a1db0d2747e Modules/_sqlite/connection.c +--- a/Modules/_sqlite/connection.c ++++ b/Modules/_sqlite/connection.c +@@ -152,7 +152,10 @@ + Py_INCREF(isolation_level); + } + self->isolation_level = NULL; +- pysqlite_connection_set_isolation_level(self, isolation_level); ++ if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) { ++ Py_DECREF(isolation_level); ++ return -1; ++ } + Py_DECREF(isolation_level); + + self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements); +@@ -366,8 +369,7 @@ + if (self->apsw_connection) { + ret = PyObject_CallMethod(self->apsw_connection, "close", ""); + Py_XDECREF(ret); +- Py_XDECREF(self->apsw_connection); +- self->apsw_connection = NULL; ++ Py_CLEAR(self->apsw_connection); + self->db = NULL; + } else { + Py_BEGIN_ALLOW_THREADS +diff -r 3a1db0d2747e Modules/_sqlite/cursor.c +--- a/Modules/_sqlite/cursor.c ++++ b/Modules/_sqlite/cursor.c +@@ -231,8 +231,7 @@ + if (converter != Py_None) { + Py_DECREF(converter); + } +- Py_XDECREF(self->row_cast_map); +- self->row_cast_map = NULL; ++ Py_CLEAR(self->row_cast_map); + + return -1; + } +@@ -468,8 +467,7 @@ + allow_8bit_chars = ((self->connection->text_factory != (PyObject*)&PyUnicode_Type) && + (self->connection->text_factory != pysqlite_OptimizedUnicode)); + +- Py_XDECREF(self->next_row); +- self->next_row = NULL; ++ Py_CLEAR(self->next_row); + + if (multiple) { + /* executemany() */ +@@ -896,8 +894,7 @@ + if (!self->next_row) { + if (self->statement) { + (void)pysqlite_statement_reset(self->statement); +- Py_DECREF(self->statement); +- self->statement = NULL; ++ Py_CLEAR(self->statement); + } + return NULL; + } +diff -r 3a1db0d2747e Modules/_sre.c +--- a/Modules/_sre.c ++++ b/Modules/_sre.c +@@ -1875,18 +1875,62 @@ + PyObject_DEL(self); + } + ++static int ++check_args_size(const char *name, PyObject* args, PyObject* kw, int n) ++{ ++ Py_ssize_t m = PyTuple_GET_SIZE(args) + (kw ? PyDict_Size(kw) : 0); ++ if (m <= n) ++ return 1; ++ PyErr_Format(PyExc_TypeError, ++ "%s() takes at most %d positional arguments (%zd given)", ++ name, n, m); ++ return 0; ++} ++ ++static PyObject* ++fix_string_param(PyObject *string, PyObject *string2, const char *oldname) ++{ ++ if (string2 != NULL) { ++ char buf[100]; ++ if (string != NULL) { ++ PyErr_Format(PyExc_TypeError, ++ "Argument given by name ('%s') and position (1)", ++ oldname); ++ return NULL; ++ } ++ sprintf(buf, "The '%s' keyword parameter name is deprecated. " ++ "Use 'string' instead.", oldname); ++ if (PyErr_Warn(PyExc_DeprecationWarning, buf) < 0) ++ return NULL; ++ return string2; ++ } ++ if (string == NULL) { ++ PyErr_SetString(PyExc_TypeError, ++ "Required argument 'string' (pos 1) not found"); ++ return NULL; ++ } ++ return string; ++} ++ + static PyObject* + pattern_match(PatternObject* self, PyObject* args, PyObject* kw) + { + SRE_STATE state; + int status; + +- PyObject* string; ++ PyObject *string = NULL, *string2 = NULL; + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; +- static char* kwlist[] = { "pattern", "pos", "endpos", NULL }; +- if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:match", kwlist, +- &string, &start, &end)) ++ static char* kwlist[] = { "string", "pos", "endpos", "pattern", NULL }; ++ if (!check_args_size("match", args, kw, 3)) ++ return NULL; ++ ++ if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnnO:match", kwlist, ++ &string, &start, &end, &string2)) ++ return NULL; ++ ++ string = fix_string_param(string, string2, "pattern"); ++ if (!string) + return NULL; + + string = state_init(&state, self, string, start, end); +@@ -1920,12 +1964,19 @@ + SRE_STATE state; + int status; + +- PyObject* string; ++ PyObject *string = NULL, *string2 = NULL; + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; +- static char* kwlist[] = { "pattern", "pos", "endpos", NULL }; +- if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:search", kwlist, +- &string, &start, &end)) ++ static char* kwlist[] = { "string", "pos", "endpos", "pattern", NULL }; ++ if (!check_args_size("search", args, kw, 3)) ++ return NULL; ++ ++ if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnnO:search", kwlist, ++ &string, &start, &end, &string2)) ++ return NULL; ++ ++ string = fix_string_param(string, string2, "pattern"); ++ if (!string) + return NULL; + + string = state_init(&state, self, string, start, end); +@@ -2055,12 +2106,19 @@ + int status; + Py_ssize_t i, b, e; + +- PyObject* string; ++ PyObject *string = NULL, *string2 = NULL; + Py_ssize_t start = 0; + Py_ssize_t end = PY_SSIZE_T_MAX; +- static char* kwlist[] = { "source", "pos", "endpos", NULL }; +- if (!PyArg_ParseTupleAndKeywords(args, kw, "O|nn:findall", kwlist, +- &string, &start, &end)) ++ static char* kwlist[] = { "string", "pos", "endpos", "source", NULL }; ++ if (!check_args_size("findall", args, kw, 3)) ++ return NULL; ++ ++ if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnnO:findall", kwlist, ++ &string, &start, &end, &string2)) ++ return NULL; ++ ++ string = fix_string_param(string, string2, "source"); ++ if (!string) + return NULL; + + string = state_init(&state, self, string, start, end); +@@ -2185,11 +2243,18 @@ + Py_ssize_t i; + void* last; + +- PyObject* string; ++ PyObject *string = NULL, *string2 = NULL; + Py_ssize_t maxsplit = 0; +- static char* kwlist[] = { "source", "maxsplit", NULL }; +- if (!PyArg_ParseTupleAndKeywords(args, kw, "O|n:split", kwlist, +- &string, &maxsplit)) ++ static char* kwlist[] = { "string", "maxsplit", "source", NULL }; ++ if (!check_args_size("split", args, kw, 2)) ++ return NULL; ++ ++ if (!PyArg_ParseTupleAndKeywords(args, kw, "|OnO:split", kwlist, ++ &string, &maxsplit, &string2)) ++ return NULL; ++ ++ string = fix_string_param(string, string2, "source"); ++ if (!string) + return NULL; + + string = state_init(&state, self, string, 0, PY_SSIZE_T_MAX); +@@ -2753,8 +2818,7 @@ + \_________\_____/ / + \____________/ + +- It also helps that SRE_CODE is always an unsigned type, either 2 bytes or 4 +- bytes wide (the latter if Python is compiled for "wide" unicode support). ++ It also helps that SRE_CODE is always an unsigned type. + */ + + /* Defining this one enables tracing of the validator */ +diff -r 3a1db0d2747e Modules/_ssl.c +--- a/Modules/_ssl.c ++++ b/Modules/_ssl.c +@@ -273,6 +273,7 @@ + char *errstr = NULL; + int ret; + int verification_mode; ++ long options; + + self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */ + if (self == NULL) +@@ -372,8 +373,10 @@ + } + + /* ssl compatibility */ +- SSL_CTX_set_options(self->ctx, +- SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); ++ options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; ++ if (proto_version != PY_SSL_VERSION_SSL2) ++ options |= SSL_OP_NO_SSLv2; ++ SSL_CTX_set_options(self->ctx, options); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) +diff -r 3a1db0d2747e Modules/_struct.c +--- a/Modules/_struct.c ++++ b/Modules/_struct.c +@@ -1371,13 +1371,28 @@ + + assert(PyStruct_Check(self)); + +- if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist, ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist, + &o_format)) + return -1; + +- Py_INCREF(o_format); +- Py_CLEAR(soself->s_format); +- soself->s_format = o_format; ++ if (PyString_Check(o_format)) { ++ Py_INCREF(o_format); ++ Py_CLEAR(soself->s_format); ++ soself->s_format = o_format; ++ } ++ else if (PyUnicode_Check(o_format)) { ++ PyObject *str = PyUnicode_AsEncodedString(o_format, "ascii", NULL); ++ if (str == NULL) ++ return -1; ++ Py_CLEAR(soself->s_format); ++ soself->s_format = str; ++ } ++ else { ++ PyErr_Format(PyExc_TypeError, ++ "Struct() argument 1 must be string, not %s", ++ Py_TYPE(o_format)->tp_name); ++ return -1; ++ } + + ret = prepare_s(soself); + return ret; +diff -r 3a1db0d2747e Modules/_testcapimodule.c +--- a/Modules/_testcapimodule.c ++++ b/Modules/_testcapimodule.c +@@ -1687,6 +1687,96 @@ + Py_RETURN_NONE; + } + ++#ifdef WITH_THREAD ++typedef struct { ++ PyThread_type_lock start_event; ++ PyThread_type_lock exit_event; ++ PyObject *callback; ++} test_c_thread_t; ++ ++static void ++temporary_c_thread(void *data) ++{ ++ test_c_thread_t *test_c_thread = data; ++ PyGILState_STATE state; ++ PyObject *res; ++ ++ PyThread_release_lock(test_c_thread->start_event); ++ ++ /* Allocate a Python thread state for this thread */ ++ state = PyGILState_Ensure(); ++ ++ res = PyObject_CallFunction(test_c_thread->callback, "", NULL); ++ Py_CLEAR(test_c_thread->callback); ++ ++ if (res == NULL) { ++ PyErr_Print(); ++ } ++ else { ++ Py_DECREF(res); ++ } ++ ++ /* Destroy the Python thread state for this thread */ ++ PyGILState_Release(state); ++ ++ PyThread_release_lock(test_c_thread->exit_event); ++ ++ PyThread_exit_thread(); ++} ++ ++static PyObject * ++call_in_temporary_c_thread(PyObject *self, PyObject *callback) ++{ ++ PyObject *res = NULL; ++ test_c_thread_t test_c_thread; ++ long thread; ++ ++ PyEval_InitThreads(); ++ ++ test_c_thread.start_event = PyThread_allocate_lock(); ++ test_c_thread.exit_event = PyThread_allocate_lock(); ++ test_c_thread.callback = NULL; ++ if (!test_c_thread.start_event || !test_c_thread.exit_event) { ++ PyErr_SetString(PyExc_RuntimeError, "could not allocate lock"); ++ goto exit; ++ } ++ ++ Py_INCREF(callback); ++ test_c_thread.callback = callback; ++ ++ PyThread_acquire_lock(test_c_thread.start_event, 1); ++ PyThread_acquire_lock(test_c_thread.exit_event, 1); ++ ++ thread = PyThread_start_new_thread(temporary_c_thread, &test_c_thread); ++ if (thread == -1) { ++ PyErr_SetString(PyExc_RuntimeError, "unable to start the thread"); ++ PyThread_release_lock(test_c_thread.start_event); ++ PyThread_release_lock(test_c_thread.exit_event); ++ goto exit; ++ } ++ ++ PyThread_acquire_lock(test_c_thread.start_event, 1); ++ PyThread_release_lock(test_c_thread.start_event); ++ ++ Py_BEGIN_ALLOW_THREADS ++ PyThread_acquire_lock(test_c_thread.exit_event, 1); ++ PyThread_release_lock(test_c_thread.exit_event); ++ Py_END_ALLOW_THREADS ++ ++ Py_INCREF(Py_None); ++ res = Py_None; ++ ++exit: ++ Py_CLEAR(test_c_thread.callback); ++ if (test_c_thread.start_event) ++ PyThread_free_lock(test_c_thread.start_event); ++ if (test_c_thread.exit_event) ++ PyThread_free_lock(test_c_thread.exit_event); ++ return res; ++} ++#endif /* WITH_THREAD */ ++ ++ + static PyMethodDef TestMethods[] = { + {"raise_exception", raise_exception, METH_VARARGS}, + {"test_config", (PyCFunction)test_config, METH_NOARGS}, +@@ -1745,6 +1835,10 @@ + {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, + METH_VARARGS | METH_KEYWORDS}, + {"sequence_delitem", (PyCFunction)sequence_delitem, METH_VARARGS}, ++#ifdef WITH_THREAD ++ {"call_in_temporary_c_thread", call_in_temporary_c_thread, METH_O, ++ PyDoc_STR("set_error_class(error_class) -> None")}, ++#endif + {NULL, NULL} /* sentinel */ + }; + +diff -r 3a1db0d2747e Modules/_tkinter.c +--- a/Modules/_tkinter.c ++++ b/Modules/_tkinter.c +@@ -456,6 +456,68 @@ + + + ++#ifdef Py_USING_UNICODE ++static PyObject * ++unicode_FromTclStringAndSize(const char *s, Py_ssize_t size) ++{ ++ PyObject *r = PyUnicode_DecodeUTF8(s, size, NULL); ++ if (!r && PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { ++ /* Tcl encodes null character as \xc0\x80 */ ++ if (memchr(s, '\xc0', size)) { ++ char *buf, *q; ++ const char *e = s + size; ++ PyErr_Clear(); ++ q = buf = (char *)PyMem_Malloc(size); ++ if (buf == NULL) ++ return NULL; ++ while (s != e) { ++ if (s + 1 != e && s[0] == '\xc0' && s[1] == '\x80') { ++ *q++ = '\0'; ++ s += 2; ++ } ++ else ++ *q++ = *s++; ++ } ++ s = buf; ++ size = q - s; ++ r = PyUnicode_DecodeUTF8(s, size, NULL); ++ PyMem_Free(buf); ++ } ++ } ++ return r; ++} ++#endif ++ ++static PyObject * ++fromTclStringAndSize(const char *s, Py_ssize_t size) ++{ ++ PyObject *r; ++#ifdef Py_USING_UNICODE ++ Py_ssize_t i; ++ /* If Tcl string contains any bytes with the top bit set, ++ it's UTF-8 and we should decode it to Unicode */ ++ for (i = 0; i < size; i++) ++ if (s[i] & 0x80) ++ break; ++ if (i != size) { ++ /* It isn't an ASCII string. */ ++ r = unicode_FromTclStringAndSize(s, size); ++ if (r) ++ return r; ++ PyErr_Clear(); ++ } ++#endif ++ r = PyString_FromStringAndSize(s, size); ++ return r; ++} ++ ++static PyObject * ++fromTclString(const char *s) ++{ ++ return fromTclStringAndSize(s, strlen(s)); ++} ++ ++ + static PyObject * + Split(char *list) + { +@@ -841,27 +903,10 @@ + static PyObject * + PyTclObject_string(PyTclObject *self, void *ignored) + { +- char *s; +- int i, len; + if (!self->string) { +- s = Tcl_GetStringFromObj(self->value, &len); +- for (i = 0; i < len; i++) +- if (s[i] & 0x80) +- break; +-#ifdef Py_USING_UNICODE +- if (i == len) +- /* It is an ASCII string. */ +- self->string = PyString_FromStringAndSize(s, len); +- else { +- self->string = PyUnicode_DecodeUTF8(s, len, "strict"); +- if (!self->string) { +- PyErr_Clear(); +- self->string = PyString_FromStringAndSize(s, len); +- } +- } +-#else +- self->string = PyString_FromStringAndSize(s, len); +-#endif ++ int len; ++ char *s = Tcl_GetStringFromObj(self->value, &len); ++ self->string = fromTclStringAndSize(s, len); + if (!self->string) + return NULL; + } +@@ -883,7 +928,7 @@ + } + /* XXX Could chache result if it is non-ASCII. */ + s = Tcl_GetStringFromObj(self->value, &len); +- return PyUnicode_DecodeUTF8(s, len, "strict"); ++ return unicode_FromTclStringAndSize(s, len); + } + #endif + +@@ -1022,6 +1067,8 @@ + PyErr_SetString(PyExc_OverflowError, "string is too long"); + return NULL; + } ++ if (sizeof(Py_UNICODE) == sizeof(Tcl_UniChar)) ++ return Tcl_NewUnicodeObj(inbuf, size); + allocsize = ((size_t)size) * sizeof(Tcl_UniChar); + if (allocsize >= size) + outbuf = (Tcl_UniChar*)ckalloc(allocsize); +@@ -1073,30 +1120,7 @@ + TkappObject *app = (TkappObject*)tkapp; + + if (value->typePtr == NULL) { +- /* If the result contains any bytes with the top bit set, +- it's UTF-8 and we should decode it to Unicode */ +-#ifdef Py_USING_UNICODE +- int i; +- char *s = value->bytes; +- int len = value->length; +- for (i = 0; i < len; i++) { +- if (value->bytes[i] & 0x80) +- break; +- } +- +- if (i == value->length) +- result = PyString_FromStringAndSize(s, len); +- else { +- /* Convert UTF-8 to Unicode string */ +- result = PyUnicode_DecodeUTF8(s, len, "strict"); +- if (result == NULL) { +- PyErr_Clear(); +- result = PyString_FromStringAndSize(s, len); +- } +- } +-#else +- result = PyString_FromStringAndSize(value->bytes, value->length); +-#endif ++ result = fromTclStringAndSize(value->bytes, value->length); + return result; + } + +@@ -1273,8 +1297,8 @@ + Tkapp_CallResult(TkappObject *self) + { + PyObject *res = NULL; ++ Tcl_Obj *value = Tcl_GetObjResult(self->interp); + if(self->wantobjects) { +- Tcl_Obj *value = Tcl_GetObjResult(self->interp); + /* Not sure whether the IncrRef is necessary, but something + may overwrite the interpreter result while we are + converting it. */ +@@ -1282,33 +1306,9 @@ + res = FromObj((PyObject*)self, value); + Tcl_DecrRefCount(value); + } else { +- const char *s = Tcl_GetStringResult(self->interp); +- const char *p = s; +- +- /* If the result contains any bytes with the top bit set, +- it's UTF-8 and we should decode it to Unicode */ +-#ifdef Py_USING_UNICODE +- while (*p != '\0') { +- if (*p & 0x80) +- break; +- p++; +- } +- +- if (*p == '\0') +- res = PyString_FromStringAndSize(s, (int)(p-s)); +- else { +- /* Convert UTF-8 to Unicode string */ +- p = strchr(p, '\0'); +- res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict"); +- if (res == NULL) { +- PyErr_Clear(); +- res = PyString_FromStringAndSize(s, (int)(p-s)); +- } +- } +-#else +- p = strchr(p, '\0'); +- res = PyString_FromStringAndSize(s, (int)(p-s)); +-#endif ++ int len; ++ const char *s = Tcl_GetStringFromObj(value, &len); ++ res = fromTclStringAndSize(s, len); + } + return res; + } +@@ -1611,16 +1611,28 @@ + static int + varname_converter(PyObject *in, void *_out) + { ++ char *s; + char **out = (char**)_out; + if (PyString_Check(in)) { +- *out = PyString_AsString(in); ++ if (PyString_Size(in) > INT_MAX) { ++ PyErr_SetString(PyExc_OverflowError, "string is too long"); ++ return 0; ++ } ++ s = PyString_AsString(in); ++ if (strlen(s) != PyString_Size(in)) { ++ PyErr_SetString(PyExc_ValueError, "null character in string"); ++ return 0; ++ } ++ *out = s; + return 1; + } + if (PyTclObject_Check(in)) { + *out = PyTclObject_TclString(in); + return 1; + } +- /* XXX: Should give diagnostics. */ ++ PyErr_Format(PyExc_TypeError, ++ "must be str or Tcl_Obj, not %.50s", ++ in->ob_type->tp_name); + return 0; + } + +@@ -1706,8 +1718,11 @@ + PyObject *res = NULL; + Tcl_Obj *newval, *ok; + +- if (PyArg_ParseTuple(args, "O&O:setvar", +- varname_converter, &name1, &newValue)) { ++ switch (PyTuple_GET_SIZE(args)) { ++ case 2: ++ if (!PyArg_ParseTuple(args, "O&O:setvar", ++ varname_converter, &name1, &newValue)) ++ return NULL; + /* XXX Acquire tcl lock??? */ + newval = AsObj(newValue); + if (newval == NULL) +@@ -1723,27 +1738,27 @@ + Py_INCREF(res); + } + LEAVE_OVERLAP_TCL +- } +- else { +- PyErr_Clear(); +- if (PyArg_ParseTuple(args, "ssO:setvar", +- &name1, &name2, &newValue)) { +- /* XXX must hold tcl lock already??? */ +- newval = AsObj(newValue); +- ENTER_TCL +- ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); +- ENTER_OVERLAP +- if (!ok) +- Tkinter_Error(self); +- else { +- res = Py_None; +- Py_INCREF(res); +- } +- LEAVE_OVERLAP_TCL ++ break; ++ case 3: ++ if (!PyArg_ParseTuple(args, "ssO:setvar", ++ &name1, &name2, &newValue)) ++ return NULL; ++ /* XXX must hold tcl lock already??? */ ++ newval = AsObj(newValue); ++ ENTER_TCL ++ ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags); ++ ENTER_OVERLAP ++ if (!ok) ++ Tkinter_Error(self); ++ else { ++ res = Py_None; ++ Py_INCREF(res); + } +- else { +- return NULL; +- } ++ LEAVE_OVERLAP_TCL ++ break; ++ default: ++ PyErr_SetString(PyExc_TypeError, "setvar requires 2 to 3 arguments"); ++ return NULL; + } + return res; + } +@@ -1783,7 +1798,9 @@ + res = FromObj(self, tres); + } + else { +- res = PyString_FromString(Tcl_GetString(tres)); ++ int len; ++ char *s = Tcl_GetStringFromObj(tres, &len); ++ res = PyString_FromStringAndSize(s, len); + } + } + LEAVE_OVERLAP_TCL +@@ -1921,7 +1938,7 @@ + if (retval == TCL_ERROR) + res = Tkinter_Error(self); + else +- res = Py_BuildValue("s", Tkapp_Result(self)); ++ res = PyString_FromString(Tkapp_Result(self)); + LEAVE_OVERLAP_TCL + return res; + } +@@ -2158,7 +2175,7 @@ + return PythonCmd_Error(interp); + + for (i = 0; i < (argc - 1); i++) { +- PyObject *s = PyString_FromString(argv[i + 1]); ++ PyObject *s = fromTclString(argv[i + 1]); + if (!s || PyTuple_SetItem(arg, i, s)) { + Py_DECREF(arg); + return PythonCmd_Error(interp); +diff -r 3a1db0d2747e Modules/bz2module.c +--- a/Modules/bz2module.c ++++ b/Modules/bz2module.c +@@ -1206,12 +1206,16 @@ + 0, NULL, NULL); + break; + } +- if (self->fp) { +- PyFile_DecUseCount((PyFileObject *)self->file); +- self->fp = NULL; ++ if (self->file) { ++ if (self->fp) ++ PyFile_DecUseCount((PyFileObject *)self->file); ++ ret = PyObject_CallMethod(self->file, "close", NULL); ++ } else { ++ Py_INCREF(Py_None); ++ ret = Py_None; + } ++ self->fp = NULL; + self->mode = MODE_CLOSED; +- ret = PyObject_CallMethod(self->file, "close", NULL); + if (bzerror != BZ_OK) { + Util_CatchBZ2Error(bzerror); + Py_XDECREF(ret); +@@ -1479,10 +1483,9 @@ + 0, NULL, NULL); + break; + } +- if (self->fp) { ++ if (self->fp != NULL && self->file != NULL) + PyFile_DecUseCount((PyFileObject *)self->file); +- self->fp = NULL; +- } ++ self->fp = NULL; + Util_DropReadAhead(self); + Py_XDECREF(self->file); + Py_TYPE(self)->tp_free((PyObject *)self); +diff -r 3a1db0d2747e Modules/cPickle.c +--- a/Modules/cPickle.c ++++ b/Modules/cPickle.c +@@ -324,8 +324,7 @@ + + #define FREE_ARG_TUP(self) { \ + if (Py_REFCNT(self->arg) > 1) { \ +- Py_DECREF(self->arg); \ +- self->arg=NULL; \ ++ Py_CLEAR(self->arg); \ + } \ + } + +diff -r 3a1db0d2747e Modules/cdmodule.c +--- a/Modules/cdmodule.c ++++ b/Modules/cdmodule.c +@@ -535,10 +535,8 @@ + + /* no sense in keeping the callbacks, so remove them */ + for (i = 0; i < NCALLBACKS; i++) { +- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback); +- self->ob_cdcallbacks[i].ob_cdcallback = NULL; +- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg); +- self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; ++ Py_CLEAR(self->ob_cdcallbacks[i].ob_cdcallback); ++ Py_CLEAR(self->ob_cdcallbacks[i].ob_cdcallbackarg); + } + + Py_INCREF(Py_None); +@@ -588,11 +586,9 @@ + + CDremovecallback(self->ob_cdparser, (CDDATATYPES) type); + +- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback); +- self->ob_cdcallbacks[type].ob_cdcallback = NULL; ++ Py_CLEAR(self->ob_cdcallbacks[type].ob_cdcallback); + +- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); +- self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL; ++ Py_CLEAR(self->ob_cdcallbacks[type].ob_cdcallbackarg); + + Py_INCREF(Py_None); + return Py_None; +@@ -668,10 +664,8 @@ + int i; + + for (i = 0; i < NCALLBACKS; i++) { +- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback); +- self->ob_cdcallbacks[i].ob_cdcallback = NULL; +- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg); +- self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; ++ Py_CLEAR(self->ob_cdcallbacks[i].ob_cdcallback); ++ Py_CLEAR(self->ob_cdcallbacks[i].ob_cdcallbackarg); + } + CDdeleteparser(self->ob_cdparser); + PyObject_Del(self); +diff -r 3a1db0d2747e Modules/fcntlmodule.c +--- a/Modules/fcntlmodule.c ++++ b/Modules/fcntlmodule.c +@@ -27,7 +27,7 @@ + } + + +-/* fcntl(fd, opt, [arg]) */ ++/* fcntl(fd, op, [arg]) */ + + static PyObject * + fcntl_fcntl(PyObject *self, PyObject *args) +@@ -77,11 +77,12 @@ + } + + PyDoc_STRVAR(fcntl_doc, +-"fcntl(fd, opt, [arg])\n\ ++"fcntl(fd, op, [arg])\n\ + \n\ +-Perform the requested operation on file descriptor fd. The operation\n\ +-is defined by op and is operating system dependent. These constants are\n\ +-available from the fcntl module. The argument arg is optional, and\n\ ++Perform the operation op on file descriptor fd. The values used\n\ ++for op are operating system dependent, and are available\n\ ++as constants in the fcntl module, using the same names as used in\n\ ++the relevant C header files. The argument arg is optional, and\n\ + defaults to 0; it may be an int or a string. If arg is given as a string,\n\ + the return value of fcntl is a string of that length, containing the\n\ + resulting value put in the arg buffer by the operating system. The length\n\ +@@ -90,7 +91,7 @@ + corresponding to the return value of the fcntl call in the C code."); + + +-/* ioctl(fd, opt, [arg]) */ ++/* ioctl(fd, op, [arg]) */ + + static PyObject * + fcntl_ioctl(PyObject *self, PyObject *args) +@@ -104,7 +105,7 @@ + whereas the system expects it to be a 32bit bit field value + regardless of it being passed as an int or unsigned long on + various platforms. See the termios.TIOCSWINSZ constant across +- platforms for an example of thise. ++ platforms for an example of this. + + If any of the 64bit platforms ever decide to use more than 32bits + in their unsigned long ioctl codes this will break and need +@@ -212,11 +213,12 @@ + } + + PyDoc_STRVAR(ioctl_doc, +-"ioctl(fd, opt[, arg[, mutate_flag]])\n\ ++"ioctl(fd, op[, arg[, mutate_flag]])\n\ + \n\ +-Perform the requested operation on file descriptor fd. The operation is\n\ +-defined by opt and is operating system dependent. Typically these codes are\n\ +-retrieved from the fcntl or termios library modules.\n\ ++Perform the operation op on file descriptor fd. The values used for op\n\ ++are operating system dependent, and are available as constants in the\n\ ++fcntl or termios library modules, using the same names as used in the\n\ ++relevant C header files.\n\ + \n\ + The argument arg is optional, and defaults to 0; it may be an int or a\n\ + buffer containing character data (most likely a string or an array). \n\ +diff -r 3a1db0d2747e Modules/flmodule.c +--- a/Modules/flmodule.c ++++ b/Modules/flmodule.c +@@ -97,10 +97,8 @@ + { + int i, n; + +- Py_XDECREF(g->ob_callback); +- g->ob_callback = NULL; +- Py_XDECREF(g->ob_callback_arg); +- g->ob_callback_arg = NULL; ++ Py_CLEAR(g->ob_callback); ++ Py_CLEAR(g->ob_callback_arg); + if (allgenerics == NULL) + return; /* No objects known yet */ + n = PyList_Size(allgenerics); +@@ -132,10 +130,8 @@ + /* The object is now unreachable for + do_forms and check_forms, so + delete it from the list of known objects */ +- Py_XDECREF(g->ob_callback); +- g->ob_callback = NULL; +- Py_XDECREF(g->ob_callback_arg); +- g->ob_callback_arg = NULL; ++ Py_CLEAR(g->ob_callback); ++ Py_CLEAR(g->ob_callback_arg); + PyList_SetItem(allgenerics, i, (PyObject *)NULL); + nfreeslots++; + } +diff -r 3a1db0d2747e Modules/gcmodule.c +--- a/Modules/gcmodule.c ++++ b/Modules/gcmodule.c +@@ -113,7 +113,7 @@ + + /* + NOTE: about untracking of mutable objects. +- ++ + Certain types of container cannot participate in a reference cycle, and + so do not need to be tracked by the garbage collector. Untracking these + objects reduces the cost of garbage collections. However, determining +@@ -131,10 +131,10 @@ + not survive until garbage collection. It is therefore not worthwhile + to untrack eligible tuples at creation time. + +- Instead, all tuples except the empty tuple are tracked when created. +- During garbage collection it is determined whether any surviving tuples +- can be untracked. A tuple can be untracked if all of its contents are +- already not tracked. Tuples are examined for untracking in all garbage ++ Instead, all tuples except the empty tuple are tracked when created. ++ During garbage collection it is determined whether any surviving tuples ++ can be untracked. A tuple can be untracked if all of its contents are ++ already not tracked. Tuples are examined for untracking in all garbage + collection cycles. It may take more than one cycle to untrack a tuple. + + Dictionaries containing only immutable objects also do not need to be +@@ -147,8 +147,8 @@ + The module provides the python function is_tracked(obj), which returns + the CURRENT tracking status of the object. Subsequent garbage + collections may change the tracking status of the object. +- +- Untracking of certain containers was introduced in issue #4688, and ++ ++ Untracking of certain containers was introduced in issue #4688, and + the algorithm was refined in response to issue #14775. + */ + +diff -r 3a1db0d2747e Modules/ossaudiodev.c +--- a/Modules/ossaudiodev.c ++++ b/Modules/ossaudiodev.c +@@ -490,7 +490,6 @@ + { + int wanted_fmt, wanted_channels, wanted_rate, strict=0; + int fmt, channels, rate; +- PyObject * rv; /* return tuple (fmt, channels, rate) */ + + if (!PyArg_ParseTuple(args, "iii|i:setparameters", + &wanted_fmt, &wanted_channels, &wanted_rate, +@@ -532,13 +531,7 @@ + + /* Construct the return value: a (fmt, channels, rate) tuple that + tells what the audio hardware was actually set to. */ +- rv = PyTuple_New(3); +- if (rv == NULL) +- return NULL; +- PyTuple_SET_ITEM(rv, 0, PyInt_FromLong(fmt)); +- PyTuple_SET_ITEM(rv, 1, PyInt_FromLong(channels)); +- PyTuple_SET_ITEM(rv, 2, PyInt_FromLong(rate)); +- return rv; ++ return Py_BuildValue("(iii)", fmt, channels, rate); + } + + static int +diff -r 3a1db0d2747e Modules/posixmodule.c +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -6581,8 +6581,12 @@ + "close(fd)\n\n\ + Close a file descriptor (for low level IO)."); + +-static PyObject * +-posix_close(PyObject *self, PyObject *args) ++/* ++The underscore at end of function name avoids a name clash with the libc ++function posix_close. ++*/ ++static PyObject * ++posix_close_(PyObject *self, PyObject *args) + { + int fd, res; + if (!PyArg_ParseTuple(args, "i:close", &fd)) +@@ -6663,7 +6667,8 @@ + + PyDoc_STRVAR(posix_lseek__doc__, + "lseek(fd, pos, how) -> newpos\n\n\ +-Set the current position of a file descriptor."); ++Set the current position of a file descriptor.\n\ ++Return the new cursor position in bytes, starting from the beginning."); + + static PyObject * + posix_lseek(PyObject *self, PyObject *args) +@@ -8960,7 +8965,7 @@ + {"tcsetpgrp", posix_tcsetpgrp, METH_VARARGS, posix_tcsetpgrp__doc__}, + #endif /* HAVE_TCSETPGRP */ + {"open", posix_open, METH_VARARGS, posix_open__doc__}, +- {"close", posix_close, METH_VARARGS, posix_close__doc__}, ++ {"close", posix_close_, METH_VARARGS, posix_close__doc__}, + {"closerange", posix_closerange, METH_VARARGS, posix_closerange__doc__}, + {"dup", posix_dup, METH_VARARGS, posix_dup__doc__}, + {"dup2", posix_dup2, METH_VARARGS, posix_dup2__doc__}, +diff -r 3a1db0d2747e Modules/readline.c +--- a/Modules/readline.c ++++ b/Modules/readline.c +@@ -206,8 +206,7 @@ + if (!PyArg_ParseTuple(args, buf, &function)) + return NULL; + if (function == Py_None) { +- Py_XDECREF(*hook_var); +- *hook_var = NULL; ++ Py_CLEAR(*hook_var); + } + else if (PyCallable_Check(function)) { + PyObject *tmp = *hook_var; +@@ -750,14 +749,22 @@ + } + + static int ++#if defined(_RL_FUNCTION_TYPEDEF) + on_startup_hook(void) ++#else ++on_startup_hook() ++#endif + { + return on_hook(startup_hook); + } + + #ifdef HAVE_RL_PRE_INPUT_HOOK + static int ++#if defined(_RL_FUNCTION_TYPEDEF) + on_pre_input_hook(void) ++#else ++on_pre_input_hook() ++#endif + { + return on_hook(pre_input_hook); + } +@@ -852,7 +859,7 @@ + * before calling the normal completer */ + + static char ** +-flex_complete(char *text, int start, int end) ++flex_complete(const char *text, int start, int end) + { + #ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER + rl_completion_append_character ='\0'; +@@ -911,12 +918,12 @@ + rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); + rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); + /* Set our hook functions */ +- rl_startup_hook = (Function *)on_startup_hook; ++ rl_startup_hook = on_startup_hook; + #ifdef HAVE_RL_PRE_INPUT_HOOK +- rl_pre_input_hook = (Function *)on_pre_input_hook; ++ rl_pre_input_hook = on_pre_input_hook; + #endif + /* Set our completion function */ +- rl_attempted_completion_function = (CPPFunction *)flex_complete; ++ rl_attempted_completion_function = flex_complete; + /* Set Python word break characters */ + completer_word_break_characters = + rl_completer_word_break_characters = +diff -r 3a1db0d2747e Modules/selectmodule.c +--- a/Modules/selectmodule.c ++++ b/Modules/selectmodule.c +@@ -71,8 +71,7 @@ + { + int i; + for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) { +- Py_XDECREF(fd2obj[i].obj); +- fd2obj[i].obj = NULL; ++ Py_CLEAR(fd2obj[i].obj); + } + fd2obj[0].sentinel = -1; + } +@@ -347,7 +346,7 @@ + assert(i < self->ufd_len); + /* Never overflow */ + self->ufds[i].fd = (int)PyInt_AsLong(key); +- self->ufds[i].events = (short)PyInt_AsLong(value); ++ self->ufds[i].events = (short)(unsigned short)PyInt_AsLong(value); + i++; + } + assert(i == self->ufd_len); +@@ -355,6 +354,24 @@ + return 1; + } + ++static int ++ushort_converter(PyObject *obj, void *ptr) ++{ ++ unsigned long uval; ++ ++ uval = PyLong_AsUnsignedLong(obj); ++ if (uval == (unsigned long)-1 && PyErr_Occurred()) ++ return 0; ++ if (uval > USHRT_MAX) { ++ PyErr_SetString(PyExc_OverflowError, ++ "Python int too large for C unsigned short"); ++ return 0; ++ } ++ ++ *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short); ++ return 1; ++} ++ + PyDoc_STRVAR(poll_register_doc, + "register(fd [, eventmask] ) -> None\n\n\ + Register a file descriptor with the polling object.\n\ +@@ -367,12 +384,11 @@ + { + PyObject *o, *key, *value; + int fd; +- short events = POLLIN | POLLPRI | POLLOUT; ++ unsigned short events = POLLIN | POLLPRI | POLLOUT; + int err; + +- if (!PyArg_ParseTuple(args, "O|h:register", &o, &events)) { ++ if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events)) + return NULL; +- } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; +@@ -410,12 +426,12 @@ + poll_modify(pollObject *self, PyObject *args) + { + PyObject *o, *key, *value; +- int fd, events; ++ int fd; ++ unsigned short events; + int err; + +- if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) { ++ if (!PyArg_ParseTuple(args, "OO&:modify", &o, ushort_converter, &events)) + return NULL; +- } + + fd = PyObject_AsFileDescriptor(o); + if (fd == -1) return NULL; +diff -r 3a1db0d2747e Modules/socketmodule.c +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -2732,7 +2732,6 @@ + &recvlen, &flags)) + return NULL; + buflen = buf.len; +- assert(buf.buf != 0 && buflen > 0); + + if (recvlen < 0) { + PyErr_SetString(PyExc_ValueError, +@@ -2742,6 +2741,10 @@ + if (recvlen == 0) { + /* If nbytes was not specified, use the buffer's length */ + recvlen = buflen; ++ } else if (recvlen > buflen) { ++ PyErr_SetString(PyExc_ValueError, ++ "nbytes is greater than the length of the buffer"); ++ goto error; + } + + readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr); +diff -r 3a1db0d2747e Modules/svmodule.c +--- a/Modules/svmodule.c ++++ b/Modules/svmodule.c +@@ -279,8 +279,7 @@ + (void)svUnlockCaptureData(self->ob_svideo->ob_svideo, + self->ob_capture); + self->ob_capture = NULL; +- Py_DECREF(self->ob_svideo); +- self->ob_svideo = NULL; ++ Py_CLEAR(self->ob_svideo); + } + PyObject_Del(self); + } +diff -r 3a1db0d2747e Objects/descrobject.c +--- a/Objects/descrobject.c ++++ b/Objects/descrobject.c +@@ -1363,21 +1363,25 @@ + "\n" + "fget is a function to be used for getting an attribute value, and likewise\n" + "fset is a function for setting, and fdel a function for del'ing, an\n" +-"attribute. Typical use is to define a managed attribute x:\n" ++"attribute. Typical use is to define a managed attribute x:\n\n" + "class C(object):\n" + " def getx(self): return self._x\n" + " def setx(self, value): self._x = value\n" + " def delx(self): del self._x\n" + " x = property(getx, setx, delx, \"I'm the 'x' property.\")\n" + "\n" +-"Decorators make defining new properties or modifying existing ones easy:\n" ++"Decorators make defining new properties or modifying existing ones easy:\n\n" + "class C(object):\n" + " @property\n" +-" def x(self): return self._x\n" ++" def x(self):\n" ++" \"I am the 'x' property.\"\n" ++" return self._x\n" + " @x.setter\n" +-" def x(self, value): self._x = value\n" ++" def x(self, value):\n" ++" self._x = value\n" + " @x.deleter\n" +-" def x(self): del self._x\n" ++" def x(self):\n" ++" del self._x\n" + ); + + static int +diff -r 3a1db0d2747e Objects/fileobject.c +--- a/Objects/fileobject.c ++++ b/Objects/fileobject.c +@@ -1804,6 +1804,7 @@ + const char *s; + Py_ssize_t n, n2; + PyObject *encoded = NULL; ++ int err_flag = 0, err; + + if (f->f_fp == NULL) + return err_closed(); +@@ -1849,11 +1850,16 @@ + FILE_BEGIN_ALLOW_THREADS(f) + errno = 0; + n2 = fwrite(s, 1, n, f->f_fp); ++ if (n2 != n || ferror(f->f_fp)) { ++ err_flag = 1; ++ err = errno; ++ } + FILE_END_ALLOW_THREADS(f) + Py_XDECREF(encoded); + if (f->f_binary) + PyBuffer_Release(&pbuf); +- if (n2 != n) { ++ if (err_flag) { ++ errno = err; + PyErr_SetFromErrno(PyExc_IOError); + clearerr(f->f_fp); + return NULL; +diff -r 3a1db0d2747e Objects/genobject.c +--- a/Objects/genobject.c ++++ b/Objects/genobject.c +@@ -76,6 +76,7 @@ + + /* Generators always return to their most recent caller, not + * necessarily their creator. */ ++ f->f_tstate = tstate; + Py_XINCREF(tstate->frame); + assert(f->f_back == NULL); + f->f_back = tstate->frame; +@@ -89,6 +90,8 @@ + * cycle. */ + assert(f->f_back == tstate->frame); + Py_CLEAR(f->f_back); ++ /* Clear the borrowed reference to the thread state */ ++ f->f_tstate = NULL; + + /* If the generator just returned (as opposed to yielding), signal + * that the generator is exhausted. */ +diff -r 3a1db0d2747e Objects/moduleobject.c +--- a/Objects/moduleobject.c ++++ b/Objects/moduleobject.c +@@ -122,7 +122,8 @@ + if (s[0] == '_' && s[1] != '_') { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[1] %s\n", s); +- PyDict_SetItem(d, key, Py_None); ++ if (PyDict_SetItem(d, key, Py_None) != 0) ++ PyErr_Clear(); + } + } + } +@@ -135,7 +136,8 @@ + if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# clear[2] %s\n", s); +- PyDict_SetItem(d, key, Py_None); ++ if (PyDict_SetItem(d, key, Py_None) != 0) ++ PyErr_Clear(); + } + } + } +diff -r 3a1db0d2747e Objects/obmalloc.c +--- a/Objects/obmalloc.c ++++ b/Objects/obmalloc.c +@@ -2,6 +2,13 @@ + + #ifdef WITH_PYMALLOC + ++#ifdef HAVE_MMAP ++ #include ++ #ifdef MAP_ANONYMOUS ++ #define ARENAS_USE_MMAP ++ #endif ++#endif ++ + #ifdef WITH_VALGRIND + #include + +@@ -75,7 +82,8 @@ + * Allocation strategy abstract: + * + * For small requests, the allocator sub-allocates blocks of memory. +- * Requests greater than 256 bytes are routed to the system's allocator. ++ * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the ++ * system's allocator. + * + * Small requests are grouped in size classes spaced 8 bytes apart, due + * to the required valid alignment of the returned address. Requests of +@@ -107,10 +115,11 @@ + * 57-64 64 7 + * 65-72 72 8 + * ... ... ... +- * 241-248 248 30 +- * 249-256 256 31 ++ * 497-504 504 62 ++ * 505-512 512 63 + * +- * 0, 257 and up: routed to the underlying allocator. ++ * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying ++ * allocator. + */ + + /*==========================================================================*/ +@@ -143,10 +152,13 @@ + * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256 + * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT + * ++ * Note: a size threshold of 512 guarantees that newly created dictionaries ++ * will be allocated from preallocated memory pools on 64-bit. ++ * + * Although not required, for better performance and space efficiency, + * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2. + */ +-#define SMALL_REQUEST_THRESHOLD 256 ++#define SMALL_REQUEST_THRESHOLD 512 + #define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) + + /* +@@ -174,15 +186,15 @@ + /* + * The allocator sub-allocates blocks of memory (called arenas) aligned + * on a page boundary. This is a reserved virtual address space for the +- * current process (obtained through a malloc call). In no way this means +- * that the memory arenas will be used entirely. A malloc() is usually +- * an address range reservation for bytes, unless all pages within this +- * space are referenced subsequently. So malloc'ing big blocks and not using +- * them does not mean "wasting memory". It's an addressable range wastage... ++ * current process (obtained through a malloc()/mmap() call). In no way this ++ * means that the memory arenas will be used entirely. A malloc() is ++ * usually an address range reservation for bytes, unless all pages within ++ * this space are referenced subsequently. So malloc'ing big blocks and not ++ * using them does not mean "wasting memory". It's an addressable range ++ * wastage... + * +- * Therefore, allocating arenas with malloc is not optimal, because there is +- * some address space wastage, but this is the most portable way to request +- * memory from the system across various platforms. ++ * Arenas are allocated with mmap() on systems supporting anonymous memory ++ * mappings to reduce heap fragmentation. + */ + #define ARENA_SIZE (256 << 10) /* 256KB */ + +@@ -440,6 +452,9 @@ + , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) + #if NB_SMALL_SIZE_CLASSES > 56 + , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) ++#if NB_SMALL_SIZE_CLASSES > 64 ++#error "NB_SMALL_SIZE_CLASSES should be less than 64" ++#endif /* NB_SMALL_SIZE_CLASSES > 64 */ + #endif /* NB_SMALL_SIZE_CLASSES > 56 */ + #endif /* NB_SMALL_SIZE_CLASSES > 48 */ + #endif /* NB_SMALL_SIZE_CLASSES > 40 */ +@@ -577,7 +592,12 @@ + arenaobj = unused_arena_objects; + unused_arena_objects = arenaobj->nextarena; + assert(arenaobj->address == 0); ++#ifdef ARENAS_USE_MMAP ++ arenaobj->address = (uptr)mmap(NULL, ARENA_SIZE, PROT_READ|PROT_WRITE, ++ MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); ++#else + arenaobj->address = (uptr)malloc(ARENA_SIZE); ++#endif + if (arenaobj->address == 0) { + /* The allocation failed: return NULL after putting the + * arenaobj back. +@@ -1054,7 +1074,11 @@ + unused_arena_objects = ao; + + /* Free the entire arena. */ ++#ifdef ARENAS_USE_MMAP ++ munmap((void *)ao->address, ARENA_SIZE); ++#else + free((void *)ao->address); ++#endif + ao->address = 0; /* mark unassociated */ + --narenas_currently_allocated; + +diff -r 3a1db0d2747e Objects/tupleobject.c +--- a/Objects/tupleobject.c ++++ b/Objects/tupleobject.c +@@ -881,8 +881,7 @@ + _Py_ForgetReference((PyObject *) v); + /* DECREF items deleted by shrinkage */ + for (i = newsize; i < oldsize; i++) { +- Py_XDECREF(v->ob_item[i]); +- v->ob_item[i] = NULL; ++ Py_CLEAR(v->ob_item[i]); + } + sv = PyObject_GC_Resize(PyTupleObject, v, newsize); + if (sv == NULL) { +@@ -928,8 +927,7 @@ + #if PyTuple_MAXSAVESIZE > 0 + /* empty tuples are used all over the place and applications may + * rely on the fact that an empty tuple is a singleton. */ +- Py_XDECREF(free_list[0]); +- free_list[0] = NULL; ++ Py_CLEAR(free_list[0]); + + (void)PyTuple_ClearFreeList(); + #endif +diff -r 3a1db0d2747e Objects/unicodeobject.c +--- a/Objects/unicodeobject.c ++++ b/Objects/unicodeobject.c +@@ -3520,8 +3520,7 @@ + goto onError; + return; + onError: +- Py_DECREF(*exceptionObject); +- *exceptionObject = NULL; ++ Py_CLEAR(*exceptionObject); + } + } + +@@ -4826,8 +4825,7 @@ + goto onError; + return; + onError: +- Py_DECREF(*exceptionObject); +- *exceptionObject = NULL; ++ Py_CLEAR(*exceptionObject); + } + } + +@@ -5620,7 +5618,7 @@ + PyObject *item; + Py_ssize_t i; + +- fseq = PySequence_Fast(seq, ""); ++ fseq = PySequence_Fast(seq, "can only join an iterable"); + if (fseq == NULL) { + return NULL; + } +diff -r 3a1db0d2747e PC/_winreg.c +--- a/PC/_winreg.c ++++ b/PC/_winreg.c +@@ -948,8 +948,10 @@ + + fixupMultiSZ(str, retDataBuf, retDataSize); + obData = PyList_New(s); +- if (obData == NULL) ++ if (obData == NULL) { ++ free(str); + return NULL; ++ } + for (index = 0; index < s; index++) + { + size_t len = _mbstrlen(str[index]); +@@ -957,6 +959,7 @@ + PyErr_SetString(PyExc_OverflowError, + "registry string is too long for a Python string"); + Py_DECREF(obData); ++ free(str); + return NULL; + } + PyList_SetItem(obData, +diff -r 3a1db0d2747e PC/python_nt.rc +--- a/PC/python_nt.rc ++++ b/PC/python_nt.rc +@@ -61,7 +61,7 @@ + VALUE "FileDescription", "Python Core\0" + VALUE "FileVersion", PYTHON_VERSION + VALUE "InternalName", "Python DLL\0" +- VALUE "LegalCopyright", "Copyright © 2001-2008 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0" ++ VALUE "LegalCopyright", "Copyright © 2001-2014 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0" + VALUE "OriginalFilename", PYTHON_DLL_NAME "\0" + VALUE "ProductName", "Python\0" + VALUE "ProductVersion", PYTHON_VERSION +diff -r 3a1db0d2747e PCbuild/readme.txt +--- a/PCbuild/readme.txt ++++ b/PCbuild/readme.txt +@@ -1,7 +1,7 @@ + Building Python using VC++ 9.0 + ------------------------------ + +-This directory is used to build Python for Win32 and x64 platforms, e.g. ++This directory is used to build Python for Win32 and x64 platforms, e.g. + Windows 2000, XP, Vista and Windows Server 2008. In order to build 32-bit + debug and release executables, Microsoft Visual C++ 2008 Express Edition is + required at the very least. In order to build 64-bit debug and release +@@ -27,7 +27,7 @@ + + The solution is configured to build the projects in the correct order. "Build + Solution" or F7 takes care of dependencies except for x64 builds. To make +-cross compiling x64 builds on a 32bit OS possible the x64 builds require a ++cross compiling x64 builds on a 32bit OS possible the x64 builds require a + 32bit version of Python. + + NOTE: +@@ -37,7 +37,7 @@ + running a Python core buildbot test slave; see SUBPROJECTS below) + + When using the Debug setting, the output files have a _d added to +-their name: python30_d.dll, python_d.exe, parser_d.pyd, and so on. Both ++their name: python27_d.dll, python_d.exe, parser_d.pyd, and so on. Both + the build and rt batch files accept a -d option for debug builds. + + The 32bit builds end up in the solution folder PCbuild while the x64 builds +@@ -47,7 +47,7 @@ + Legacy support + -------------- + +-You can find build directories for older versions of Visual Studio and ++You can find build directories for older versions of Visual Studio and + Visual C++ in the PC directory. The legacy build directories are no longer + actively maintained and may not work out of the box. + +@@ -64,7 +64,7 @@ + + Visual Studio 2008 uses version 9 of the C runtime (MSVCRT9). The executables + are linked to a CRT "side by side" assembly which must be present on the target +-machine. This is avalible under the VC/Redist folder of your visual studio ++machine. This is available under the VC/Redist folder of your visual studio + distribution. On XP and later operating systems that support + side-by-side assemblies it is not enough to have the msvcrt90.dll present, + it has to be there as a whole assembly, that is, a folder with the .dll +@@ -105,16 +105,16 @@ + Python-controlled subprojects that wrap external projects: + _bsddb + Wraps Berkeley DB 4.7.25, which is currently built by _bsddb.vcproj. +- project (see below). ++ project. + _sqlite3 +- Wraps SQLite 3.6.21, which is currently built by sqlite3.vcproj (see below). ++ Wraps SQLite 3.6.21, which is currently built by sqlite3.vcproj. + _tkinter + Wraps the Tk windowing system. Unlike _bsddb and _sqlite3, there's no + corresponding tcltk.vcproj-type project that builds Tcl/Tk from vcproj's + within our pcbuild.sln, which means this module expects to find a + pre-built Tcl/Tk in either ..\..\tcltk for 32-bit or ..\..\tcltk64 for + 64-bit (relative to this directory). See below for instructions to build +- Tcl/Tk. ++ Tcl/Tk. + bz2 + Python wrapper for the libbz2 compression library. Homepage + http://sources.redhat.com/bzip2/ +@@ -127,16 +127,6 @@ + obtaining external sources then you don't need to manually get the source + above via subversion. ** + +- A custom pre-link step in the bz2 project settings should manage to +- build bzip2-1.0.6\libbz2.lib by magic before bz2.pyd (or bz2_d.pyd) is +- linked in PCbuild\. +- However, the bz2 project is not smart enough to remove anything under +- bzip2-1.0.6\ when you do a clean, so if you want to rebuild bzip2.lib +- you need to clean up bzip2-1.0.6\ by hand. +- +- All of this managed to build libbz2.lib in +- bzip2-1.0.6\$platform-$configuration\, which the Python project links in. +- + _ssl + Python wrapper for the secure sockets library. + +@@ -154,18 +144,16 @@ + + You must install the NASM assembler from + http://nasm.sf.net +- for x86 builds. Put nasmw.exe anywhere in your PATH. +- Note: recent releases of nasm only have nasm.exe. Just rename it to +- nasmw.exe. ++ for x86 builds. Put nasm.exe anywhere in your PATH. + + You can also install ActivePerl from + http://www.activestate.com/activeperl/ +- if you like to use the official sources instead of the files from ++ if you like to use the official sources instead of the files from + python's subversion repository. The svn version contains pre-build + makefiles and assembly files. + + The build process makes sure that no patented algorithms are included. +- For now RC5, MDC2 and IDEA are excluded from the build. You may have ++ For now RC5, MDC2 and IDEA are excluded from the build. You may have + to manually remove $(OBJ_D)\i_*.obj from ms\nt.mak if the build process + complains about missing files or forbidden IDEA. Again the files provided + in the subversion repository are already fixed. +@@ -186,16 +174,16 @@ + this by hand. + + The subprojects above wrap external projects Python doesn't control, and as +-such, a little more work is required in order to download the relevant source ++such, a little more work is required in order to download the relevant source + files for each project before they can be built. The buildbots do this each +-time they're built, so the easiest approach is to run either external.bat or ++time they're built, so the easiest approach is to run either external.bat or + external-amd64.bat in the ..\Tools\buildbot directory from ..\, i.e.: + + C:\..\svn.python.org\projects\python\trunk\PCbuild>cd .. + C:\..\svn.python.org\projects\python\trunk>Tools\buildbot\external.bat + + This extracts all the external subprojects from http://svn.python.org/external +-via Subversion (so you'll need an svn.exe on your PATH) and places them in ++via Subversion (so you'll need an svn.exe on your PATH) and places them in + ..\.. (relative to this directory). The external(-amd64).bat scripts will + also build a debug build of Tcl/Tk; there aren't any equivalent batch files + for building release versions of Tcl/Tk lying around in the Tools\buildbot +@@ -238,7 +226,7 @@ + junction as follows (using the directory structure above as an example): + + C:\..\python\trunk\external <- already exists and has built versions +- of the external subprojects ++ of the external subprojects + + C:\..\python\branches\py3k>linkd.exe external ..\..\trunk\external + Link created at: external +@@ -251,19 +239,9 @@ + Building for Itanium + -------------------- + +-NOTE: + Official support for Itanium builds have been dropped from the build. Please + contact us and provide patches if you are interested in Itanium builds. + +-The project files support a ReleaseItanium configuration which creates +-Win64/Itanium binaries. For this to work, you need to install the Platform +-SDK, in particular the 64-bit support. This includes an Itanium compiler +-(future releases of the SDK likely include an AMD64 compiler as well). +-In addition, you need the Visual Studio plugin for external C compilers, +-from http://sf.net/projects/vsextcomp. The plugin will wrap cl.exe, to +-locate the proper target compiler, and convert compiler options +-accordingly. The project files require at least version 0.9. +- + Building for AMD64 + ------------------ + +@@ -283,7 +261,7 @@ + + The solution has two configurations for PGO. The PGInstrument + configuration must be build first. The PGInstrument binaries are +-lniked against a profiling library and contain extra debug ++linked against a profiling library and contain extra debug + information. The PGUpdate configuration takes the profiling data and + generates optimized binaries. + +@@ -291,22 +269,22 @@ + creates the PGI files, runs the unit test suite or PyBench with the PGI + python and finally creates the optimized files. + +-http://msdn2.microsoft.com/en-us/library/e7k32f4k(VS.90).aspx ++http://msdn.microsoft.com/en-us/library/e7k32f4k(VS.90).aspx + + Static library + -------------- + + The solution has no configuration for static libraries. However it is easy +-it build a static library instead of a DLL. You simply have to set the ++it build a static library instead of a DLL. You simply have to set the + "Configuration Type" to "Static Library (.lib)" and alter the preprocessor + macro "Py_ENABLE_SHARED" to "Py_NO_ENABLE_SHARED". You may also have to +-change the "Runtime Library" from "Multi-threaded DLL (/MD)" to ++change the "Runtime Library" from "Multi-threaded DLL (/MD)" to + "Multi-threaded (/MT)". + + Visual Studio properties + ------------------------ + +-The PCbuild solution makes heavy use of Visual Studio property files ++The PCbuild solution makes heavy use of Visual Studio property files + (*.vsprops). The properties can be viewed and altered in the Property + Manager (View -> Other Windows -> Property Manager). + +diff -r 3a1db0d2747e Parser/tokenizer.c +--- a/Parser/tokenizer.c ++++ b/Parser/tokenizer.c +@@ -400,6 +400,12 @@ + buf = PyObject_CallObject(tok->decoding_readline, NULL); + if (buf == NULL) + return error_ret(tok); ++ if (!PyUnicode_Check(buf)) { ++ Py_DECREF(buf); ++ PyErr_SetString(PyExc_SyntaxError, ++ "codec did not return a unicode object"); ++ return error_ret(tok); ++ } + } else { + tok->decoding_buffer = NULL; + if (PyString_CheckExact(buf)) +diff -r 3a1db0d2747e Python/ceval.c +--- a/Python/ceval.c ++++ b/Python/ceval.c +@@ -3240,8 +3240,7 @@ + if (co->co_flags & CO_GENERATOR) { + /* Don't need to keep the reference to f_back, it will be set + * when the generator is resumed. */ +- Py_XDECREF(f->f_back); +- f->f_back = NULL; ++ Py_CLEAR(f->f_back); + + PCALL(PCALL_GENERATOR); + +diff -r 3a1db0d2747e Python/dtoa.c +--- a/Python/dtoa.c ++++ b/Python/dtoa.c +@@ -204,7 +204,24 @@ + MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP + should fit into an int. */ + #ifndef MAX_ABS_EXP +-#define MAX_ABS_EXP 19999U ++#define MAX_ABS_EXP 1100000000U ++#endif ++/* Bound on length of pieces of input strings in _Py_dg_strtod; specifically, ++ this is used to bound the total number of digits ignoring leading zeros and ++ the number of digits that follow the decimal point. Ideally, MAX_DIGITS ++ should satisfy MAX_DIGITS + 400 < MAX_ABS_EXP; that ensures that the ++ exponent clipping in _Py_dg_strtod can't affect the value of the output. */ ++#ifndef MAX_DIGITS ++#define MAX_DIGITS 1000000000U ++#endif ++ ++/* Guard against trying to use the above values on unusual platforms with ints ++ * of width less than 32 bits. */ ++#if MAX_ABS_EXP > INT_MAX ++#error "MAX_ABS_EXP should fit in an int" ++#endif ++#if MAX_DIGITS > INT_MAX ++#error "MAX_DIGITS should fit in an int" + #endif + + /* The following definition of Storeinc is appropriate for MIPS processors. +@@ -1498,6 +1515,7 @@ + Long L; + BCinfo bc; + Bigint *bb, *bb1, *bd, *bd0, *bs, *delta; ++ size_t ndigits, fraclen; + + dval(&rv) = 0.; + +@@ -1520,40 +1538,53 @@ + c = *++s; + lz = s != s1; + +- /* Point s0 at the first nonzero digit (if any). nd0 will be the position +- of the point relative to s0. nd will be the total number of digits +- ignoring leading zeros. */ ++ /* Point s0 at the first nonzero digit (if any). fraclen will be the ++ number of digits between the decimal point and the end of the ++ digit string. ndigits will be the total number of digits ignoring ++ leading zeros. */ + s0 = s1 = s; + while ('0' <= c && c <= '9') + c = *++s; +- nd0 = nd = s - s1; ++ ndigits = s - s1; ++ fraclen = 0; + + /* Parse decimal point and following digits. */ + if (c == '.') { + c = *++s; +- if (!nd) { ++ if (!ndigits) { + s1 = s; + while (c == '0') + c = *++s; + lz = lz || s != s1; +- nd0 -= s - s1; ++ fraclen += (s - s1); + s0 = s; + } + s1 = s; + while ('0' <= c && c <= '9') + c = *++s; +- nd += s - s1; ++ ndigits += s - s1; ++ fraclen += s - s1; + } + +- /* Now lz is true if and only if there were leading zero digits, and nd +- gives the total number of digits ignoring leading zeros. A valid input +- must have at least one digit. */ +- if (!nd && !lz) { ++ /* Now lz is true if and only if there were leading zero digits, and ++ ndigits gives the total number of digits ignoring leading zeros. A ++ valid input must have at least one digit. */ ++ if (!ndigits && !lz) { + if (se) + *se = (char *)s00; + goto parse_error; + } + ++ /* Range check ndigits and fraclen to make sure that they, and values ++ computed with them, can safely fit in an int. */ ++ if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) { ++ if (se) ++ *se = (char *)s00; ++ goto parse_error; ++ } ++ nd = (int)ndigits; ++ nd0 = (int)ndigits - (int)fraclen; ++ + /* Parse exponent. */ + e = 0; + if (c == 'e' || c == 'E') { +@@ -1886,20 +1917,20 @@ + bd2++; + + /* At this stage bd5 - bb5 == e == bd2 - bb2 + bbe, bb2 - bs2 == 1, +- and bs == 1, so: ++ and bs == 1, so: + + tdv == bd * 10**e = bd * 2**(bbe - bb2 + bd2) * 5**(bd5 - bb5) + srv == bb * 2**bbe = bb * 2**(bbe - bb2 + bb2) +- 0.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2) ++ 0.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2) + +- It follows that: ++ It follows that: + + M * tdv = bd * 2**bd2 * 5**bd5 + M * srv = bb * 2**bb2 * 5**bb5 + M * 0.5 ulp(srv) = bs * 2**bs2 * 5**bb5 + +- for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but +- this fact is not needed below.) ++ for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but ++ this fact is not needed below.) + */ + + /* Remove factor of 2**i, where i = min(bb2, bd2, bs2). */ +diff -r 3a1db0d2747e Python/getcopyright.c +--- a/Python/getcopyright.c ++++ b/Python/getcopyright.c +@@ -4,7 +4,7 @@ + + static char cprt[] = + "\ +-Copyright (c) 2001-2013 Python Software Foundation.\n\ ++Copyright (c) 2001-2014 Python Software Foundation.\n\ + All Rights Reserved.\n\ + \n\ + Copyright (c) 2000 BeOpen.com.\n\ +diff -r 3a1db0d2747e Python/symtable.c +--- a/Python/symtable.c ++++ b/Python/symtable.c +@@ -468,7 +468,7 @@ + */ + if (PyDict_SetItem(scope, name, w) < 0) + goto error; +- if (!PyDict_DelItem(free, name) < 0) ++ if (PyDict_DelItem(free, name) < 0) + goto error; + } + success = 1; +diff -r 3a1db0d2747e Python/sysmodule.c +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -367,8 +367,7 @@ + result = call_trampoline(tstate, callback, frame, what, arg); + if (result == NULL) { + PyEval_SetTrace(NULL, NULL); +- Py_XDECREF(frame->f_trace); +- frame->f_trace = NULL; ++ Py_CLEAR(frame->f_trace); + return -1; + } + if (result != Py_None) { +@@ -616,6 +615,10 @@ + PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wSuiteMask)); + PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wProductType)); + ++ if (PyErr_Occurred()) { ++ Py_DECREF(version); ++ return NULL; ++ } + return version; + } + +@@ -1261,6 +1264,7 @@ + #undef SetFlag + + if (PyErr_Occurred()) { ++ Py_DECREF(seq); + return NULL; + } + return seq; +diff -r 3a1db0d2747e README +--- a/README ++++ b/README +@@ -2,7 +2,7 @@ + ============================ + + Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, +-2012, 2013 Python Software Foundation. All rights reserved. ++2012, 2013, 2014 Python Software Foundation. All rights reserved. + + Copyright (c) 2000 BeOpen.com. + All rights reserved. +diff -r 3a1db0d2747e Tools/gdb/libpython.py +--- a/Tools/gdb/libpython.py ++++ b/Tools/gdb/libpython.py +@@ -39,10 +39,20 @@ + + The module also extends gdb with some python-specific commands. + ''' +-from __future__ import with_statement ++ ++# NOTE: some gdbs are linked with Python 3, so this file should be dual-syntax ++# compatible (2.6+ and 3.0+). See #19308. ++ ++from __future__ import print_function, with_statement + import gdb ++import os + import sys + ++if sys.version_info[0] >= 3: ++ unichr = chr ++ xrange = range ++ long = int ++ + # Look up the gdb.Type for some standard types: + _type_char_ptr = gdb.lookup_type('char').pointer() # char* + _type_unsigned_char_ptr = gdb.lookup_type('unsigned char').pointer() # unsigned char* +@@ -51,17 +61,17 @@ + SIZEOF_VOID_P = _type_void_ptr.sizeof + + +-Py_TPFLAGS_HEAPTYPE = (1L << 9) ++Py_TPFLAGS_HEAPTYPE = (1 << 9) + +-Py_TPFLAGS_INT_SUBCLASS = (1L << 23) +-Py_TPFLAGS_LONG_SUBCLASS = (1L << 24) +-Py_TPFLAGS_LIST_SUBCLASS = (1L << 25) +-Py_TPFLAGS_TUPLE_SUBCLASS = (1L << 26) +-Py_TPFLAGS_STRING_SUBCLASS = (1L << 27) +-Py_TPFLAGS_UNICODE_SUBCLASS = (1L << 28) +-Py_TPFLAGS_DICT_SUBCLASS = (1L << 29) +-Py_TPFLAGS_BASE_EXC_SUBCLASS = (1L << 30) +-Py_TPFLAGS_TYPE_SUBCLASS = (1L << 31) ++Py_TPFLAGS_INT_SUBCLASS = (1 << 23) ++Py_TPFLAGS_LONG_SUBCLASS = (1 << 24) ++Py_TPFLAGS_LIST_SUBCLASS = (1 << 25) ++Py_TPFLAGS_TUPLE_SUBCLASS = (1 << 26) ++Py_TPFLAGS_STRING_SUBCLASS = (1 << 27) ++Py_TPFLAGS_UNICODE_SUBCLASS = (1 << 28) ++Py_TPFLAGS_DICT_SUBCLASS = (1 << 29) ++Py_TPFLAGS_BASE_EXC_SUBCLASS = (1 << 30) ++Py_TPFLAGS_TYPE_SUBCLASS = (1 << 31) + + + MAX_OUTPUT_LEN=1024 +@@ -80,7 +90,7 @@ + def safe_range(val): + # As per range, but don't trust the value too much: cap it to a safety + # threshold in case the data was corrupted +- return xrange(safety_limit(val)) ++ return xrange(safety_limit(int(val))) + + + class StringTruncated(RuntimeError): +@@ -292,8 +302,8 @@ + # class + return cls + +- #print 'tp_flags = 0x%08x' % tp_flags +- #print 'tp_name = %r' % tp_name ++ #print('tp_flags = 0x%08x' % tp_flags) ++ #print('tp_name = %r' % tp_name) + + name_map = {'bool': PyBoolObjectPtr, + 'classobj': PyClassObjectPtr, +@@ -758,14 +768,14 @@ + ''' + ob_size = long(self.field('ob_size')) + if ob_size == 0: +- return 0L ++ return 0 + + ob_digit = self.field('ob_digit') + + if gdb.lookup_type('digit').sizeof == 2: +- SHIFT = 15L ++ SHIFT = 15 + else: +- SHIFT = 30L ++ SHIFT = 30 + + digits = [long(ob_digit[i]) * 2**(SHIFT*i) + for i in safe_range(abs(ob_size))] +@@ -774,6 +784,12 @@ + result = -result + return result + ++ def write_repr(self, out, visited): ++ # This ensures the trailing 'L' is printed when gdb is linked ++ # with a Python 3 interpreter. ++ out.write(repr(self.proxyval(visited)).rstrip('L')) ++ out.write('L') ++ + + class PyNoneStructPtr(PyObjectPtr): + """ +@@ -969,11 +985,19 @@ + field_ob_size = self.field('ob_size') + field_ob_sval = self.field('ob_sval') + char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr) ++ # When gdb is linked with a Python 3 interpreter, this is really ++ # a latin-1 mojibake decoding of the original string... + return ''.join([chr(char_ptr[i]) for i in safe_range(field_ob_size)]) + + def proxyval(self, visited): + return str(self) + ++ def write_repr(self, out, visited): ++ val = repr(self.proxyval(visited)) ++ if sys.version_info[0] >= 3: ++ val = val.encode('ascii', 'backslashreplace').decode('ascii') ++ out.write(val) ++ + class PyTupleObjectPtr(PyObjectPtr): + _typename = 'PyTupleObject' + +@@ -1072,6 +1096,15 @@ + result = u''.join([_unichr(ucs) for ucs in Py_UNICODEs]) + return result + ++ def write_repr(self, out, visited): ++ val = repr(self.proxyval(visited)) ++ if sys.version_info[0] >= 3: ++ val = val.encode('ascii', 'backslashreplace').decode('ascii') ++ # This ensures the 'u' prefix is printed when gdb is linked ++ # with a Python 3 interpreter. ++ out.write('u') ++ out.write(val.lstrip('u')) ++ + + def int_from_int(gdbval): + return int(str(gdbval)) +@@ -1295,12 +1328,12 @@ + + frame = Frame.get_selected_python_frame() + if not frame: +- print 'Unable to locate python frame' ++ print('Unable to locate python frame') + return + + pyop = frame.get_pyop() + if not pyop or pyop.is_optimized_out(): +- print 'Unable to read information on python frame' ++ print('Unable to read information on python frame') + return + + filename = pyop.filename() +@@ -1350,9 +1383,9 @@ + frame = iter_frame + + if move_up: +- print 'Unable to find an older python frame' ++ print('Unable to find an older python frame') + else: +- print 'Unable to find a newer python frame' ++ print('Unable to find a newer python frame') + + class PyUp(gdb.Command): + 'Select and print the python stack frame that called this one (if any)' +@@ -1415,23 +1448,23 @@ + + frame = Frame.get_selected_python_frame() + if not frame: +- print 'Unable to locate python frame' ++ print('Unable to locate python frame') + return + + pyop_frame = frame.get_pyop() + if not pyop_frame: +- print 'Unable to read information on python frame' ++ print('Unable to read information on python frame') + return + + pyop_var, scope = pyop_frame.get_var_by_name(name) + + if pyop_var: +- print ('%s %r = %s' ++ print('%s %r = %s' + % (scope, + name, + pyop_var.get_truncated_repr(MAX_OUTPUT_LEN))) + else: +- print '%r not found' % name ++ print('%r not found' % name) + + PyPrint() + +@@ -1449,16 +1482,16 @@ + + frame = Frame.get_selected_python_frame() + if not frame: +- print 'Unable to locate python frame' ++ print('Unable to locate python frame') + return + + pyop_frame = frame.get_pyop() + if not pyop_frame: +- print 'Unable to read information on python frame' ++ print('Unable to read information on python frame') + return + + for pyop_name, pyop_value in pyop_frame.iter_locals(): +- print ('%s = %s' ++ print('%s = %s' + % (pyop_name.proxyval(set()), + pyop_value.get_truncated_repr(MAX_OUTPUT_LEN))) + +diff -r 3a1db0d2747e Tools/i18n/makelocalealias.py +--- a/Tools/i18n/makelocalealias.py ++++ b/Tools/i18n/makelocalealias.py +@@ -23,6 +23,12 @@ + if line[:1] == '#': + continue + locale, alias = line.split() ++ # Fix non-standard locale names, e.g. ks_IN@devanagari.UTF-8 ++ if '@' in alias: ++ alias_lang, _, alias_mod = alias.partition('@') ++ if '.' in alias_mod: ++ alias_mod, _, alias_enc = alias_mod.partition('.') ++ alias = alias_lang + '.' + alias_enc + '@' + alias_mod + # Strip ':' + if locale[-1] == ':': + locale = locale[:-1] +diff -r 3a1db0d2747e Tools/i18n/pygettext.py +--- a/Tools/i18n/pygettext.py ++++ b/Tools/i18n/pygettext.py +@@ -1,6 +1,6 @@ + #! /usr/bin/env python + # -*- coding: iso-8859-1 -*- +-# Originally written by Barry Warsaw ++# Originally written by Barry Warsaw + # + # Minimally patched to make it even more xgettext compatible + # by Peter Funk +diff -r 3a1db0d2747e Tools/msi/uuids.py +--- a/Tools/msi/uuids.py ++++ b/Tools/msi/uuids.py +@@ -63,4 +63,6 @@ + '2.7.5150':'{DBDD570E-0952-475f-9453-AB88F3DD5659}', # 2.7.5 + '2.7.6121':'{D1EBC07F-A7B1-4163-83DB-AE813CEF392F}', # 2.7.6rc1 + '2.7.6150':'{C3CC4DF5-39A5-4027-B136-2B3E1F5AB6E2}', # 2.7.6 ++ '2.7.7121':'{5E0D187D-238B-4e96-9C75-C4CF141F5385}', # 2.7.7rc1 ++ '2.7.7150':'{049CA433-77A0-4e48-AC76-180A282C4E10}', # 2.7.7 + } +diff -r 3a1db0d2747e config.guess +--- a/config.guess ++++ b/config.guess +@@ -1,10 +1,8 @@ + #! /bin/sh + # Attempt to guess a canonical system name. +-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +-# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +-# 2011, 2012, 2013 Free Software Foundation, Inc. ++# Copyright 1992-2013 Free Software Foundation, Inc. + +-timestamp='2012-12-29' ++timestamp='2013-06-10' + + # This file is free software; you can redistribute it and/or modify it + # under the terms of the GNU General Public License as published by +@@ -26,7 +24,7 @@ + # program. This Exception is an additional permission under section 7 + # of the GNU General Public License, version 3 ("GPLv3"). + # +-# Originally written by Per Bothner. ++# Originally written by Per Bothner. + # + # You can get the latest version of this script from: + # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD +@@ -52,9 +50,7 @@ + GNU config.guess ($timestamp) + + Originally written by Per Bothner. +-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, +-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, +-2012, 2013 Free Software Foundation, Inc. ++Copyright 1992-2013 Free Software Foundation, Inc. + + This is free software; see the source for copying conditions. There is NO + warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." +@@ -136,6 +132,27 @@ + UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown + UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + ++case "${UNAME_SYSTEM}" in ++Linux|GNU|GNU/*) ++ # If the system lacks a compiler, then just pick glibc. ++ # We could probably try harder. ++ LIBC=gnu ++ ++ eval $set_cc_for_build ++ cat <<-EOF > $dummy.c ++ #include ++ #if defined(__UCLIBC__) ++ LIBC=uclibc ++ #elif defined(__dietlibc__) ++ LIBC=dietlibc ++ #else ++ LIBC=gnu ++ #endif ++ EOF ++ eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` ++ ;; ++esac ++ + # Note: order is significant - the case branches are not exclusive. + + case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in +@@ -857,21 +874,21 @@ + exit ;; + *:GNU:*:*) + # the GNU system +- echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` ++ echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland +- echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu ++ echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + aarch64:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + aarch64_be:Linux:*:*) + UNAME_MACHINE=aarch64_be +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in +@@ -884,59 +901,54 @@ + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 +- if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi +- echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} ++ if test "$?" = 0 ; then LIBC="gnulibc1" ; fi ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} ++ exit ;; ++ arc:Linux:*:* | arceb:Linux:*:*) ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + arm*:Linux:*:*) + eval $set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + else + if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_PCS_VFP + then +- echo ${UNAME_MACHINE}-unknown-linux-gnueabi ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi + else +- echo ${UNAME_MACHINE}-unknown-linux-gnueabihf ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf + fi + fi + exit ;; + avr32*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + cris:Linux:*:*) +- echo ${UNAME_MACHINE}-axis-linux-gnu ++ echo ${UNAME_MACHINE}-axis-linux-${LIBC} + exit ;; + crisv32:Linux:*:*) +- echo ${UNAME_MACHINE}-axis-linux-gnu ++ echo ${UNAME_MACHINE}-axis-linux-${LIBC} + exit ;; + frv:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + hexagon:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + i*86:Linux:*:*) +- LIBC=gnu +- eval $set_cc_for_build +- sed 's/^ //' << EOF >$dummy.c +- #ifdef __dietlibc__ +- LIBC=dietlibc +- #endif +-EOF +- eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` +- echo "${UNAME_MACHINE}-pc-linux-${LIBC}" ++ echo ${UNAME_MACHINE}-pc-linux-${LIBC} + exit ;; + ia64:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + m32r*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + m68*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + mips:Linux:*:* | mips64:Linux:*:*) + eval $set_cc_for_build +@@ -955,54 +967,63 @@ + #endif + EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` +- test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } ++ test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } + ;; ++ or1k:Linux:*:*) ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} ++ exit ;; + or32:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + padre:Linux:*:*) +- echo sparc-unknown-linux-gnu ++ echo sparc-unknown-linux-${LIBC} + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) +- echo hppa64-unknown-linux-gnu ++ echo hppa64-unknown-linux-${LIBC} + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in +- PA7*) echo hppa1.1-unknown-linux-gnu ;; +- PA8*) echo hppa2.0-unknown-linux-gnu ;; +- *) echo hppa-unknown-linux-gnu ;; ++ PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; ++ PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; ++ *) echo hppa-unknown-linux-${LIBC} ;; + esac + exit ;; + ppc64:Linux:*:*) +- echo powerpc64-unknown-linux-gnu ++ echo powerpc64-unknown-linux-${LIBC} + exit ;; + ppc:Linux:*:*) +- echo powerpc-unknown-linux-gnu ++ echo powerpc-unknown-linux-${LIBC} ++ exit ;; ++ ppc64le:Linux:*:*) ++ echo powerpc64le-unknown-linux-${LIBC} ++ exit ;; ++ ppcle:Linux:*:*) ++ echo powerpcle-unknown-linux-${LIBC} + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) +- echo ${UNAME_MACHINE}-ibm-linux ++ echo ${UNAME_MACHINE}-ibm-linux-${LIBC} + exit ;; + sh64*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + sh*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + tile*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + vax:Linux:*:*) +- echo ${UNAME_MACHINE}-dec-linux-gnu ++ echo ${UNAME_MACHINE}-dec-linux-${LIBC} + exit ;; + x86_64:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + xtensa*:Linux:*:*) +- echo ${UNAME_MACHINE}-unknown-linux-gnu ++ echo ${UNAME_MACHINE}-unknown-linux-${LIBC} + exit ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. +@@ -1235,19 +1256,21 @@ + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown +- case $UNAME_PROCESSOR in +- i386) +- eval $set_cc_for_build +- if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then +- if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ +- (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ +- grep IS_64BIT_ARCH >/dev/null +- then +- UNAME_PROCESSOR="x86_64" +- fi +- fi ;; +- unknown) UNAME_PROCESSOR=powerpc ;; +- esac ++ eval $set_cc_for_build ++ if test "$UNAME_PROCESSOR" = unknown ; then ++ UNAME_PROCESSOR=powerpc ++ fi ++ if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then ++ if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ ++ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ ++ grep IS_64BIT_ARCH >/dev/null ++ then ++ case $UNAME_PROCESSOR in ++ i386) UNAME_PROCESSOR=x86_64 ;; ++ powerpc) UNAME_PROCESSOR=powerpc64 ;; ++ esac ++ fi ++ fi + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) +diff -r 3a1db0d2747e config.sub +--- a/config.sub ++++ b/config.sub +@@ -1,10 +1,8 @@ + #! /bin/sh + # Configuration validation subroutine script. +-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +-# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +-# 2011, 2012, 2013 Free Software Foundation, Inc. ++# Copyright 1992-2013 Free Software Foundation, Inc. + +-timestamp='2012-12-29' ++timestamp='2013-08-10' + + # This file is free software; you can redistribute it and/or modify it + # under the terms of the GNU General Public License as published by +@@ -70,9 +68,7 @@ + version="\ + GNU config.sub ($timestamp) + +-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, +-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, +-2012, 2013 Free Software Foundation, Inc. ++Copyright 1992-2013 Free Software Foundation, Inc. + + This is free software; see the source for copying conditions. There is NO + warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." +@@ -256,12 +252,12 @@ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ +- | arc \ ++ | arc | arceb \ + | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \ + | avr | avr32 \ + | be32 | be64 \ + | bfin \ +- | c4x | clipper \ ++ | c4x | c8051 | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | epiphany \ + | fido | fr30 | frv \ +@@ -290,16 +286,17 @@ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ ++ | mipsr5900 | mipsr5900el \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | moxie \ + | mt \ + | msp430 \ + | nds32 | nds32le | nds32be \ +- | nios | nios2 \ ++ | nios | nios2 | nios2eb | nios2el \ + | ns16k | ns32k \ + | open8 \ +- | or32 \ ++ | or1k | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle \ + | pyramid \ +@@ -369,13 +366,13 @@ + | aarch64-* | aarch64_be-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ +- | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ ++ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | be32-* | be64-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* \ +- | clipper-* | craynv-* | cydra-* \ ++ | c8051-* | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ +@@ -407,12 +404,13 @@ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ ++ | mipsr5900-* | mipsr5900el-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nds32-* | nds32le-* | nds32be-* \ +- | nios-* | nios2-* \ ++ | nios-* | nios2-* | nios2eb-* | nios2el-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | open8-* \ + | orion-* \ +@@ -796,7 +794,7 @@ + os=-mingw64 + ;; + mingw32) +- basic_machine=i386-pc ++ basic_machine=i686-pc + os=-mingw32 + ;; + mingw32ce) +@@ -832,7 +830,7 @@ + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + msys) +- basic_machine=i386-pc ++ basic_machine=i686-pc + os=-msys + ;; + mvs) +@@ -1354,7 +1352,7 @@ + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ +- | -sym* | -kopensolaris* \ ++ | -sym* | -kopensolaris* | -plan9* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* | -aros* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ +@@ -1500,9 +1498,6 @@ + -aros*) + os=-aros + ;; +- -kaos*) +- os=-kaos +- ;; + -zvmoe) + os=-zvmoe + ;; +@@ -1551,6 +1546,9 @@ + c4x-* | tic4x-*) + os=-coff + ;; ++ c8051-*) ++ os=-elf ++ ;; + hexagon-*) + os=-elf + ;; +@@ -1594,6 +1592,9 @@ + mips*-*) + os=-elf + ;; ++ or1k-*) ++ os=-elf ++ ;; + or32-*) + os=-coff + ;; +diff -r 3a1db0d2747e configure.ac +--- a/configure.ac ++++ b/configure.ac +@@ -2905,7 +2905,7 @@ + clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \ + gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ + getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \ +- initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime \ ++ initgroups kill killpg lchmod lchown lstat mkfifo mknod mktime mmap \ + mremap nice pathconf pause plock poll pthread_init \ + putenv readlink realpath \ + select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \ +diff -r 3a1db0d2747e pyconfig.h.in +--- a/pyconfig.h.in ++++ b/pyconfig.h.in +@@ -475,6 +475,9 @@ + /* Define to 1 if you have the `mktime' function. */ + #undef HAVE_MKTIME + ++/* Define to 1 if you have the `mmap' function. */ ++#undef HAVE_MMAP ++ + /* Define to 1 if you have the `mremap' function. */ + #undef HAVE_MREMAP + +diff -r 3a1db0d2747e setup.py +--- a/setup.py ++++ b/setup.py +@@ -1187,7 +1187,6 @@ + include_dirs=["Modules/_sqlite", + sqlite_incdir], + library_dirs=sqlite_libdir, +- runtime_library_dirs=sqlite_libdir, + extra_link_args=sqlite_extra_link_args, + libraries=["sqlite3",])) + else: --- python2.7-2.7.6.orig/debian/patches/hotshot-import.diff +++ python2.7-2.7.6/debian/patches/hotshot-import.diff @@ -0,0 +1,17 @@ +# DP: hotshot: Check for the availability of the profile and pstats modules. + +--- a/Lib/hotshot/stats.py ++++ b/Lib/hotshot/stats.py +@@ -1,7 +1,10 @@ + """Statistics analyzer for HotShot.""" + +-import profile +-import pstats ++try: ++ import profile ++ import pstats ++except ImportError, e: ++ raise ImportError, str(e) + '; please install the python-profiler package' + + import hotshot.log + --- python2.7-2.7.6.orig/debian/patches/hurd-disable-nonworking-constants.diff +++ python2.7-2.7.6/debian/patches/hurd-disable-nonworking-constants.diff @@ -0,0 +1,34 @@ +# DP: Comment out constant exposed on the API which are not implemented on +# DP: GNU/Hurd. They would not work at runtime anyway. + +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9218,12 +9218,14 @@ + #ifdef O_LARGEFILE + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + #endif ++#ifndef __GNU__ + #ifdef O_SHLOCK + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + #endif + #ifdef O_EXLOCK + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + #endif ++#endif + + /* MS Windows */ + #ifdef O_NOINHERIT +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -4902,9 +4902,11 @@ + #ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); + #endif ++#ifndef __GNU__ + #ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); + #endif ++#endif + #ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); + #endif --- python2.7-2.7.6.orig/debian/patches/installed-testsuite.diff +++ python2.7-2.7.6/debian/patches/installed-testsuite.diff @@ -0,0 +1,35 @@ +# DP: Changes needed to run the installed testsuite. +# DP: Also removed: +# DP: - ctypes/test/test_macholib.py +# DP: - distutils/tests/test_bdist_wininst.py + +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -83,27 +83,6 @@ + self.assertTrue(isinstance(xx.Null(), xx.Null)) + self.assertTrue(isinstance(xx.Str(), xx.Str)) + +- def test_solaris_enable_shared(self): +- dist = Distribution({'name': 'xx'}) +- cmd = build_ext(dist) +- old = sys.platform +- +- sys.platform = 'sunos' # fooling finalize_options +- from distutils.sysconfig import _config_vars +- old_var = _config_vars.get('Py_ENABLE_SHARED') +- _config_vars['Py_ENABLE_SHARED'] = 1 +- try: +- cmd.ensure_finalized() +- finally: +- sys.platform = old +- if old_var is None: +- del _config_vars['Py_ENABLE_SHARED'] +- else: +- _config_vars['Py_ENABLE_SHARED'] = old_var +- +- # make sure we get some library dirs under solaris +- self.assertTrue(len(cmd.library_dirs) > 0) +- + def test_user_site(self): + # site.USER_SITE was introduced in 2.6 + if sys.version < '2.6': --- python2.7-2.7.6.orig/debian/patches/issue670664.diff +++ python2.7-2.7.6/debian/patches/issue670664.diff @@ -0,0 +1,54 @@ +# DP: Proposed patch for issue #670664. + +--- a/Lib/HTMLParser.py ++++ b/Lib/HTMLParser.py +@@ -96,6 +96,7 @@ + self.rawdata = '' + self.lasttag = '???' + self.interesting = interesting_normal ++ self.cdata_tag = None + markupbase.ParserBase.reset(self) + + def feed(self, data): +@@ -120,11 +121,13 @@ + """Return full source of start tag: '<...>'.""" + return self.__starttag_text + +- def set_cdata_mode(self): ++ def set_cdata_mode(self, tag): + self.interesting = interesting_cdata ++ self.cdata_tag = tag.lower() + + def clear_cdata_mode(self): + self.interesting = interesting_normal ++ self.cdata_tag = None + + # Internal -- handle data as far as reasonable. May leave state + # and data to be processed by a subsequent call. If 'end' is +@@ -270,7 +273,7 @@ + else: + self.handle_starttag(tag, attrs) + if tag in self.CDATA_CONTENT_ELEMENTS: +- self.set_cdata_mode() ++ self.set_cdata_mode(tag) + return endpos + + # Internal -- check to see if we have a complete starttag; return end +@@ -314,10 +317,16 @@ + j = match.end() + match = endtagfind.match(rawdata, i) # + if not match: ++ if self.cdata_tag is not None: return j + self.error("bad end tag: %r" % (rawdata[i:j],)) +- tag = match.group(1) ++ tag = match.group(1).strip() ++ ++ if self.cdata_tag is not None: ++ if tag.lower() != self.cdata_tag: return j ++ + self.handle_endtag(tag.lower()) + self.clear_cdata_mode() ++ + return j + + # Overridable -- finish processing of start+end tag: --- python2.7-2.7.6.orig/debian/patches/issue9012a.diff +++ python2.7-2.7.6/debian/patches/issue9012a.diff @@ -0,0 +1,13 @@ +# DP: Link _math.o only once to the static library. + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -169,7 +169,7 @@ + # Modules that should always be present (non UNIX dependent): + + #array arraymodule.c # array objects +-#cmath cmathmodule.c _math.c # -lm # complex math library functions ++#cmath cmathmodule.c # -lm # complex math library functions + #math mathmodule.c _math.c # -lm # math library functions, e.g. sin() + #_struct _struct.c # binary structure packing/unpacking + #time timemodule.c # -lm # time operations and variables --- python2.7-2.7.6.orig/debian/patches/issue9189.diff +++ python2.7-2.7.6/debian/patches/issue9189.diff @@ -0,0 +1,332 @@ +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -231,11 +231,19 @@ + done[n] = v + + # do variable interpolation here +- while notdone: +- for name in notdone.keys(): ++ variables = list(notdone.keys()) ++ ++ # Variables with a 'PY_' prefix in the makefile. These need to ++ # be made available without that prefix through sysconfig. ++ # Special care is needed to ensure that variable expansion works, even ++ # if the expansion uses the name without a prefix. ++ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') ++ ++ while len(variables) > 0: ++ for name in tuple(variables): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) +- if m: ++ if m is not None: + n = m.group(1) + found = True + if n in done: +@@ -246,23 +254,48 @@ + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] ++ ++ elif n in renamed_variables: ++ if name.startswith('PY_') and name[3:] in renamed_variables: ++ item = "" ++ ++ elif 'PY_' + n in notdone: ++ found = False ++ ++ else: ++ item = str(done['PY_' + n]) ++ + else: + done[n] = item = "" ++ + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: +- try: value = int(value) ++ try: ++ value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value +- del notdone[name] ++ variables.remove(name) ++ ++ if name.startswith('PY_') \ ++ and name[3:] in renamed_variables: ++ ++ name = name[3:] ++ if name not in done: ++ done[name] = value ++ ++ + else: +- # bogus variable reference; just drop it since we can't deal +- del notdone[name] ++ # bogus variable reference (e.g. "prefix=$/opt/python"); ++ # just drop it since we can't deal ++ done[name] = value ++ variables.remove(name) ++ + # strip spurious spaces + for k, v in done.items(): + if isinstance(v, str): +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -68,12 +68,18 @@ + # Compiler options + OPT= @OPT@ + BASECFLAGS= @BASECFLAGS@ +-CFLAGS= $(BASECFLAGS) @CFLAGS@ $(OPT) $(EXTRA_CFLAGS) ++CONFIGURE_CFLAGS= @CFLAGS@ ++CONFIGURE_CPPFLAGS= @CPPFLAGS@ ++CONFIGURE_LDFLAGS= @LDFLAGS@ ++# Avoid assigning CFLAGS, LDFLAGS, etc. so users can use them on the ++# command line to append to these values without stomping the pre-set ++# values. ++PY_CFLAGS= $(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS) + # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to + # be able to build extension modules using the directories specified in the + # environment variables +-CPPFLAGS= -I. -IInclude -I$(srcdir)/Include @CPPFLAGS@ +-LDFLAGS= @LDFLAGS@ ++PY_CPPFLAGS= -I. -IInclude -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS) ++PY_LDFLAGS= $(CONFIGURE_LDFLAGS) $(LDFLAGS) + LDLAST= @LDLAST@ + SGI_ABI= @SGI_ABI@ + CCSHARED= @CCSHARED@ +@@ -82,7 +88,7 @@ + # Extra C flags added for building the interpreter object files. + CFLAGSFORSHARED=@CFLAGSFORSHARED@ + # C flags used for building the interpreter object files +-PY_CFLAGS= $(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE ++PY_CORE_CFLAGS= $(PY_CFLAGS) $(PY_CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE + + + # Machine-dependent subdirectories +@@ -437,7 +443,7 @@ + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +- $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ ++ $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ + $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + +@@ -459,7 +465,7 @@ + *\ -s*|s*) quiet="-q";; \ + *) quiet="";; \ + esac; \ +- $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' \ ++ $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' \ + _TCLTK_INCLUDES='$(TCLTK_INCLUDES)' _TCLTK_LIBS='$(TCLTK_LIBS)' \ + $(PYTHON_FOR_BUILD) $(srcdir)/setup.py $$quiet build + +@@ -477,18 +483,18 @@ + + libpython$(VERSION).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ +- $(BLDSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(BLDSHARED) $(PY_LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ + else \ +- $(BLDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(BLDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + fi + + libpython$(VERSION).dylib: $(LIBRARY_OBJS) +- $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + + + libpython$(VERSION).sl: $(LIBRARY_OBJS) +- $(LDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) ++ $(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) + + # Copy up the gdb python hooks into a position where they can be automatically + # loaded by gdb during Lib/test/test_gdb.py +@@ -527,7 +533,7 @@ + # for a shared core library; otherwise, this rule is a noop. + $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS) + if test -n "$(DLLLIBRARY)"; then \ +- $(LDSHARED) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ ++ $(LDSHARED) $(PY_LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ + $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST); \ + else true; \ + fi +@@ -571,7 +577,7 @@ + $(SIGNAL_OBJS) \ + $(MODOBJS) \ + $(srcdir)/Modules/getbuildinfo.c +- $(CC) -c $(PY_CFLAGS) \ ++ $(CC) -c $(PY_CORE_CFLAGS) \ + -DSVNVERSION="\"`LC_ALL=C $(SVNVERSION)`\"" \ + -DHGVERSION="\"`LC_ALL=C $(HGVERSION)`\"" \ + -DHGTAG="\"`LC_ALL=C $(HGTAG)`\"" \ +@@ -579,7 +585,7 @@ + -o $@ $(srcdir)/Modules/getbuildinfo.c + + Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile +- $(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ ++ $(CC) -c $(PY_CORE_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ + -DPREFIX='"$(prefix)"' \ + -DEXEC_PREFIX='"$(exec_prefix)"' \ + -DVERSION='"$(VERSION)"' \ +@@ -587,7 +593,7 @@ + -o $@ $(srcdir)/Modules/getpath.c + + Modules/python.o: $(srcdir)/Modules/python.c +- $(MAINCC) -c $(PY_CFLAGS) -o $@ $(srcdir)/Modules/python.c ++ $(MAINCC) -c $(PY_CORE_CFLAGS) -o $@ $(srcdir)/Modules/python.c + + Modules/posixmodule.o: $(srcdir)/Modules/posixmodule.c $(srcdir)/Modules/posixmodule.h + +@@ -604,7 +610,7 @@ + touch $(GRAMMAR_C) + + $(PGEN): $(PGENOBJS) +- $(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) ++ $(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) + + Parser/grammar.o: $(srcdir)/Parser/grammar.c \ + $(srcdir)/Include/token.h \ +@@ -626,10 +632,10 @@ + Python/compile.o Python/symtable.o Python/ast.o: $(GRAMMAR_H) $(AST_H) + + Python/getplatform.o: $(srcdir)/Python/getplatform.c +- $(CC) -c $(PY_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c ++ $(CC) -c $(PY_CORE_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c + + Python/importdl.o: $(srcdir)/Python/importdl.c +- $(CC) -c $(PY_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c ++ $(CC) -c $(PY_CORE_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c + + Objects/unicodectype.o: $(srcdir)/Objects/unicodectype.c \ + $(srcdir)/Objects/unicodetype_db.h +@@ -1231,7 +1237,7 @@ + + # Some make's put the object file in the current directory + .c.o: +- $(CC) -c $(PY_CFLAGS) -o $@ $< ++ $(CC) -c $(PY_CORE_CFLAGS) -o $@ $< + + # Run reindent on the library + reindent: +--- a/Modules/makesetup ++++ b/Modules/makesetup +@@ -219,7 +219,7 @@ + case $doconfig in + no) cc="$cc \$(CCSHARED) \$(CFLAGS) \$(CPPFLAGS)";; + *) +- cc="$cc \$(PY_CFLAGS)";; ++ cc="$cc \$(PY_CORE_CFLAGS)";; + esac + rule="$obj: $src; $cc $cpps -c $src -o $obj" + echo "$rule" >>$rulesf +--- a/configure.ac ++++ b/configure.ac +@@ -607,14 +607,13 @@ + fi + fi + +-# If the user set CFLAGS, use this instead of the automatically +-# determined setting +-preset_cflags="$CFLAGS" +-AC_PROG_CC +-if test ! -z "$preset_cflags" +-then +- CFLAGS=$preset_cflags ++# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2 ++# when the compiler supports them, but we don't always want -O2, and ++# we set -g later. ++if test -z "$CFLAGS"; then ++ CFLAGS= + fi ++AC_PROG_CC + + AC_SUBST(CXX) + AC_SUBST(MAINCC) +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -319,11 +319,19 @@ + done[n] = v + + # do variable interpolation here +- while notdone: +- for name in notdone.keys(): ++ variables = list(notdone.keys()) ++ ++ # Variables with a 'PY_' prefix in the makefile. These need to ++ # be made available without that prefix through sysconfig. ++ # Special care is needed to ensure that variable expansion works, even ++ # if the expansion uses the name without a prefix. ++ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') ++ ++ while len(variables) > 0: ++ for name in tuple(variables): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) +- if m: ++ if m is not None: + n = m.group(1) + found = True + if n in done: +@@ -334,25 +342,47 @@ + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] ++ ++ elif n in renamed_variables: ++ if name.startswith('PY_') and name[3:] in renamed_variables: ++ item = "" ++ ++ elif 'PY_' + n in notdone: ++ found = False ++ ++ else: ++ item = str(done['PY_' + n]) ++ + else: + done[n] = item = "" ++ + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: +- try: value = int(value) ++ try: ++ value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value +- del notdone[name] +- else: +- # bogus variable reference; just drop it since we can't deal +- del notdone[name] ++ variables.remove(name) ++ ++ if name.startswith('PY_') \ ++ and name[3:] in renamed_variables: + +- fp.close() ++ name = name[3:] ++ if name not in done: ++ done[name] = value ++ ++ ++ else: ++ # bogus variable reference (e.g. "prefix=$/opt/python"); ++ # just drop it since we can't deal ++ done[name] = value ++ variables.remove(name) + + # strip spurious spaces + for k, v in done.items(): --- python2.7-2.7.6.orig/debian/patches/langpack-gettext.diff +++ python2.7-2.7.6/debian/patches/langpack-gettext.diff @@ -0,0 +1,34 @@ +# DP: Description: support alternative gettext tree in +# DP: /usr/share/locale-langpack; if a file is present in both trees, +# DP: prefer the newer one +# DP: Upstream status: Ubuntu-Specific + +--- a/Lib/gettext.py ++++ b/Lib/gettext.py +@@ -446,11 +446,26 @@ + if lang == 'C': + break + mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) ++ mofile_lp = os.path.join("/usr/share/locale-langpack", lang, ++ 'LC_MESSAGES', '%s.mo' % domain) ++ ++ # first look into the standard locale dir, then into the ++ # langpack locale dir ++ ++ # standard mo file + if os.path.exists(mofile): + if all: + result.append(mofile) + else: + return mofile ++ ++ # langpack mofile -> use it ++ if os.path.exists(mofile_lp): ++ if all: ++ result.append(mofile_lp) ++ else: ++ return mofile_lp ++ + return result + + --- python2.7-2.7.6.orig/debian/patches/lib2to3-no-pickled-grammar.diff +++ python2.7-2.7.6/debian/patches/lib2to3-no-pickled-grammar.diff @@ -0,0 +1,14 @@ +--- a/Lib/lib2to3/pgen2/driver.py ++++ b/Lib/lib2to3/pgen2/driver.py +@@ -119,7 +119,10 @@ + if force or not _newer(gp, gt): + logger.info("Generating grammar tables from %s", gt) + g = pgen.generate_grammar(gt) +- if save: ++ # the pickle files mismatch, when built on different architectures. ++ # don't save these for now. An alternative solution might be to ++ # include the multiarch triplet into the file name ++ if False: + logger.info("Writing grammar tables to %s", gp) + try: + g.dump(gp) --- python2.7-2.7.6.orig/debian/patches/libffi-shared.diff +++ python2.7-2.7.6/debian/patches/libffi-shared.diff @@ -0,0 +1,11 @@ +--- a/setup.py ++++ b/setup.py +@@ -2127,7 +2127,7 @@ + break + ffi_lib = None + if ffi_inc is not None: +- for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'): ++ for lib_name in ('ffi', 'ffi_convenience', 'ffi_pic', 'ffi'): + if (self.compiler.find_library_file(lib_dirs, lib_name)): + ffi_lib = lib_name + break --- python2.7-2.7.6.orig/debian/patches/libre.diff +++ python2.7-2.7.6/debian/patches/libre.diff @@ -0,0 +1,9 @@ +--- Doc/lib/libre.tex~ 2003-07-25 09:29:22.000000000 +0200 ++++ Doc/lib/libre.tex 2003-07-25 09:30:58.000000000 +0200 +@@ -919,5 +919,5 @@ + Starting with Python 2.3, simple uses of the \regexp{*?} pattern are + special-cased to avoid recursion. Thus, the above regular expression + can avoid recursion by being recast as +-\regexp{Begin [a-zA-Z0-9_ ]*?end}. As a further benefit, such regular ++`Begin [a-zA-Z0-9_ ]*?end'. As a further benefit, such regular + expressions will run faster than their recursive equivalents. --- python2.7-2.7.6.orig/debian/patches/linecache.diff +++ python2.7-2.7.6/debian/patches/linecache.diff @@ -0,0 +1,16 @@ +# DP: Proper handling of packages in linecache.py + +--- a/Lib/linecache.py ++++ b/Lib/linecache.py +@@ -108,6 +108,11 @@ + if os.path.isabs(filename): + return [] + ++ # Take care to handle packages ++ if basename == '__init__.py': ++ # filename referes to a package ++ basename = filename ++ + for dirname in sys.path: + # When using imputil, sys.path may contain things other than + # strings; ignore them when it happens. --- python2.7-2.7.6.orig/debian/patches/link-opt.diff +++ python2.7-2.7.6/debian/patches/link-opt.diff @@ -0,0 +1,24 @@ +# DP: Call the linker with -O1 -Bsymbolic-functions + +--- a/configure.ac ++++ b/configure.ac +@@ -2024,8 +2024,8 @@ + fi + ;; + Linux*|GNU*|QNX*) +- LDSHARED='$(CC) -shared' +- LDCXXSHARED='$(CXX) -shared';; ++ LDSHARED='$(CC) -shared -Wl,-O1 -Wl,-Bsymbolic-functions' ++ LDCXXSHARED='$(CXX) -shared -Wl,-O1 -Wl,-Bsymbolic-functions';; + BSD/OS*/4*) + LDSHARED="gcc -shared" + LDCXXSHARED="g++ -shared";; +@@ -2127,7 +2127,7 @@ + LINKFORSHARED="-Wl,-E -Wl,+s";; + # LINKFORSHARED="-Wl,-E -Wl,+s -Wl,+b\$(BINLIBDEST)/lib-dynload";; + BSD/OS/4*) LINKFORSHARED="-Xlinker -export-dynamic";; +- Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic";; ++ Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + # -u _PyMac_Error is needed to pull in the mac toolbox glue, --- python2.7-2.7.6.orig/debian/patches/link-system-expat.diff +++ python2.7-2.7.6/debian/patches/link-system-expat.diff @@ -0,0 +1,22 @@ +# DP: Link with the system expat + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -181,7 +181,7 @@ + #itertools itertoolsmodule.c # Functions creating iterators for efficient looping + #strop stropmodule.c # String manipulations + #_functools _functoolsmodule.c # Tools for working with functions and callable objects +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #datetime datetimemodule.c # date/time type + #_bisect _bisectmodule.c # Bisection algorithms +@@ -475,7 +475,7 @@ + # + # More information on Expat can be found at www.libexpat.org. + # +-#pyexpat expat/xmlparse.c expat/xmlrole.c expat/xmltok.c pyexpat.c -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI ++#pyexpat pyexpat.c -lexpat + + + # Hye-Shik Chang's CJKCodecs --- python2.7-2.7.6.orig/debian/patches/link-whole-archive.diff +++ python2.7-2.7.6/debian/patches/link-whole-archive.diff @@ -0,0 +1,13 @@ +# DP: Link libpython with --whole-archive. + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -447,7 +447,7 @@ + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) + $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ +- $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) ++ -Wl,--whole-archive $(BLDLIBRARY) -Wl,--no-whole-archive $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + + platform: $(BUILDPYTHON) pybuilddir.txt + $(RUNSHARED) $(PYTHON_FOR_BUILD) -c 'import sys ; from sysconfig import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform --- python2.7-2.7.6.orig/debian/patches/locale-module.diff +++ python2.7-2.7.6/debian/patches/locale-module.diff @@ -0,0 +1,17 @@ +# DP: * Lib/locale.py: +# DP: - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding +# DP: for glibc. + +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -1528,8 +1528,8 @@ + 'uk_ua.iso88595': 'uk_UA.ISO8859-5', + 'uk_ua.koi8u': 'uk_UA.KOI8-U', + 'uk_ua.microsoftcp1251': 'uk_UA.CP1251', +- 'univ': 'en_US.utf', +- 'universal': 'en_US.utf', ++ 'univ': 'en_US.UTF-8', ++ 'universal': 'en_US.UTF-8', + 'universal.utf8@ucs4': 'en_US.UTF-8', + 'ur': 'ur_PK.CP1256', + 'ur_pk': 'ur_PK.CP1256', --- python2.7-2.7.6.orig/debian/patches/lto-link-flags.diff +++ python2.7-2.7.6/debian/patches/lto-link-flags.diff @@ -0,0 +1,22 @@ +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -123,8 +123,8 @@ + + # Symbols used for using shared libraries + SO= @SO@ +-LDSHARED= @LDSHARED@ $(LDFLAGS) +-BLDSHARED= @BLDSHARED@ $(LDFLAGS) ++LDSHARED= @LDSHARED@ $(PY_LDFLAGS) ++BLDSHARED= @BLDSHARED@ $(PY_LDFLAGS) $(PY_CFLAGS) + LDCXXSHARED= @LDCXXSHARED@ + DESTSHARED= $(BINLIBDEST)/lib-dynload + +@@ -445,7 +445,7 @@ + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +- $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ ++ $(LINKCC) $(PY_LDFLAGS) $(PY_CFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ + -Wl,--whole-archive $(BLDLIBRARY) -Wl,--no-whole-archive $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + --- python2.7-2.7.6.orig/debian/patches/makesetup-bashism.diff +++ python2.7-2.7.6/debian/patches/makesetup-bashism.diff @@ -0,0 +1,13 @@ +# DP: Fix bashism in makesetup shell script + +--- a/Modules/makesetup ++++ b/Modules/makesetup +@@ -281,7 +281,7 @@ + -) ;; + *) sedf="@sed.in.$$" + trap 'rm -f $sedf' 0 1 2 3 +- echo "1i\\" >$sedf ++ printf "1i\\" >$sedf + str="# Generated automatically from $makepre by makesetup." + echo "$str" >>$sedf + echo "s%_MODOBJS_%$OBJS%" >>$sedf --- python2.7-2.7.6.orig/debian/patches/multiarch.diff +++ python2.7-2.7.6/debian/patches/multiarch.diff @@ -0,0 +1,154 @@ +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -332,7 +332,7 @@ + def _get_makefile_filename(): + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") ++ return os.path.join(get_config_var('LIBPL'), "Makefile") + + def _generate_posix_vars(): + """Generate the Python module containing build-time variables.""" +@@ -528,6 +528,12 @@ + # the init-function. + _CONFIG_VARS['userbase'] = _getuserbase() + ++ multiarch = get_config_var('MULTIARCH') ++ if multiarch: ++ _CONFIG_VARS['multiarchsubdir'] = '/' + multiarch ++ else: ++ _CONFIG_VARS['multiarchsubdir'] = '' ++ + if 'srcdir' not in _CONFIG_VARS: + _CONFIG_VARS['srcdir'] = _PROJECT_BASE + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -97,6 +97,9 @@ + # Multiarch directory (may be empty) + MULTIARCH= @MULTIARCH@ + ++# Multiarch directory (may be empty) ++MULTIARCH= @MULTIARCH@ ++ + # Install prefix for architecture-independent files + prefix= @prefix@ + +@@ -558,6 +561,10 @@ + @mv config.c Modules + @echo "The Makefile was updated, you may need to re-run make." + ++Python/dynload_shlib.o: $(srcdir)/Python/dynload_shlib.c Makefile ++ $(CC) -c $(PY_CORE_CFLAGS) \ ++ $(if $(MULTIARCH),-DMULTIARCH='"$(MULTIARCH)"') \ ++ -o $@ $(srcdir)/Python/dynload_shlib.c + + Modules/Setup: $(srcdir)/Modules/Setup.dist + @if test -f Modules/Setup; then \ +@@ -921,7 +928,7 @@ + (cd $(DESTDIR)$(MANDIR)/man1; $(LN) -s python2.1 python.1) + + # Install the library +-PLATDIR= plat-$(MACHDEP) ++PLATDIR= plat-$(MULTIARCH) + EXTRAPLATDIR= @EXTRAPLATDIR@ + EXTRAMACHDEPPATH=@EXTRAMACHDEPPATH@ + MACHDEPS= $(PLATDIR) $(EXTRAPLATDIR) +@@ -1079,10 +1086,10 @@ + + # Install the library and miscellaneous stuff needed for extending/embedding + # This goes into $(exec_prefix)$(DEBUG_EXT) +-LIBPL= $(LIBP)/config$(DEBUG_EXT) ++LIBPL= $(LIBP)/config-$(MULTIARCH)$(DEBUG_EXT) + + # pkgconfig directory +-LIBPC= $(LIBDIR)/pkgconfig ++LIBPC= $(LIBDIR)/$(MULTIARCH)/pkgconfig + + libainstall: all python-config + @for i in $(LIBDIR) $(LIBP) $(LIBPL) $(LIBPC); \ +@@ -1357,6 +1364,11 @@ + + Python/thread.o: @THREADHEADERS@ + ++Python/sysmodule.o: $(srcdir)/Python/sysmodule.c Makefile ++ $(CC) -c $(PY_CORE_CFLAGS) \ ++ -DMULTIARCH='"$(MULTIARCH)"' \ ++ -o $@ $(srcdir)/Python/sysmodule.c ++ + # Declare targets that aren't real files + .PHONY: all build_all sharedmods oldsharedmods test quicktest memtest + .PHONY: install altinstall oldsharedinstall bininstall altbininstall +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -91,7 +91,7 @@ + TESTPATH= + + # Path components for machine- or system-dependent modules and shared libraries +-MACHDEPPATH=:plat-$(MACHDEP) ++MACHDEPPATH=:plat-$(MULTIARCH) + EXTRAMACHDEPPATH= + + # Path component for the Tkinter-related modules +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -49,6 +49,12 @@ + #ifdef Py_DEBUG + {"_d.so", "rb", C_EXTENSION}, + {"module_d.so", "rb", C_EXTENSION}, ++# ifdef MULTIARCH ++ {"." MULTIARCH "_d.so", "rb", C_EXTENSION}, ++# endif ++#endif ++#ifdef MULTIARCH ++ {"." MULTIARCH ".so", "rb", C_EXTENSION}, + #endif + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, +--- a/configure.ac ++++ b/configure.ac +@@ -672,6 +672,9 @@ + MULTIARCH=$($CC --print-multiarch 2>/dev/null) + AC_SUBST(MULTIARCH) + ++MULTIARCH=$($CC --print-multiarch 2>/dev/null) ++AC_SUBST(MULTIARCH) ++ + + # checks for UNIX variants that set C preprocessor variables + AC_USE_SYSTEM_EXTENSIONS +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -90,7 +90,11 @@ + # Include is located in the srcdir + inc_dir = os.path.join(srcdir, "Include") + return inc_dir +- return os.path.join(prefix, "include", "python" + get_python_version())+(sys.pydebug and "_d" or "") ++ else: ++ if plat_specific: ++ return get_config_var('CONFINCLUDEPY') ++ else: ++ return get_config_var('INCLUDEPY') + elif os.name == "nt": + return os.path.join(prefix, "include") + elif os.name == "os2": +@@ -251,7 +255,7 @@ + if python_build: + return os.path.join(project_base, "Makefile") + lib_dir = get_python_lib(plat_specific=1, standard_lib=1) +- return os.path.join(lib_dir, "config"+(sys.pydebug and "_d" or ""), "Makefile") ++ return os.path.join(get_config_var('LIBPL'), "Makefile") + + + def parse_config_h(fp, g=None): +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1435,6 +1435,8 @@ + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("long_info", + PyLong_GetInfo()); ++ SET_SYS_FROM_STRING("_multiarch", ++ PyString_FromString(MULTIARCH)); + #ifdef Py_USING_UNICODE + SET_SYS_FROM_STRING("maxunicode", + PyInt_FromLong(PyUnicode_GetMax())); --- python2.7-2.7.6.orig/debian/patches/ncursesw-incdir.diff +++ python2.7-2.7.6/debian/patches/ncursesw-incdir.diff @@ -0,0 +1,66 @@ +# DP: use the correct include directory when linking with ncursesw. + +--- a/setup.py ++++ b/setup.py +@@ -1346,13 +1346,17 @@ + # Curses support, requiring the System V version of curses, often + # provided by the ncurses library. + panel_library = 'panel' ++ curses_incs = None + if curses_library.startswith('ncurses'): + if curses_library == 'ncursesw': + # Bug 1464056: If _curses.so links with ncursesw, + # _curses_panel.so must link with panelw. + panel_library = 'panelw' + curses_libs = [curses_library] ++ curses_incs = find_file('curses.h', inc_dirs, ++ [os.path.join(d, 'ncursesw') for d in inc_dirs]) + exts.append( Extension('_curses', ['_cursesmodule.c'], ++ include_dirs = curses_incs, + libraries = curses_libs) ) + elif curses_library == 'curses' and host_platform != 'darwin': + # OSX has an old Berkeley curses, not good enough for +@@ -1373,6 +1377,7 @@ + if (module_enabled(exts, '_curses') and + self.compiler.find_library_file(lib_dirs, panel_library)): + exts.append( Extension('_curses_panel', ['_curses_panel.c'], ++ include_dirs = curses_incs, + libraries = [panel_library] + curses_libs) ) + else: + missing.append('_curses_panel') +--- a/configure.ac ++++ b/configure.ac +@@ -1513,6 +1513,8 @@ + + # checks for header files + AC_HEADER_STDC ++ac_save_cppflags="$CPPFLAGS" ++CPPFLAGS="$CPPFLAGS -I/usr/include/ncursesw" + AC_CHECK_HEADERS(asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ + fcntl.h grp.h \ + ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +@@ -1534,6 +1536,7 @@ + #include + #endif + ]) ++CPPFLAGS=$ac_save_cppflags + + # On Linux, netlink.h requires asm/types.h + AC_CHECK_HEADERS(linux/netlink.h,,,[ +@@ -4311,6 +4314,8 @@ + [Define if you have struct stat.st_mtimensec]) + fi + ++ac_save_cppflags="$CPPFLAGS" ++CPPFLAGS="$CPPFLAGS -I/usr/include/ncursesw" + # On HP/UX 11.0, mvwdelch is a block with a return statement + AC_MSG_CHECKING(whether mvwdelch is an expression) + AC_CACHE_VAL(ac_cv_mvwdelch_is_expression, +@@ -4365,6 +4370,7 @@ + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] + ) ++CPPFLAGS=$ac_save_cppflags + + AC_MSG_NOTICE([checking for device files]) + --- python2.7-2.7.6.orig/debian/patches/no-large-file-support.diff +++ python2.7-2.7.6/debian/patches/no-large-file-support.diff @@ -0,0 +1,14 @@ +# DP: disable large file support for GNU/Hurd + +--- a/configure.ac ++++ b/configure.ac +@@ -1434,6 +1434,9 @@ + use_lfs=no + fi + ++# Don't use largefile support anyway. ++use_lfs=no ++ + if test "$use_lfs" = "yes"; then + # Two defines needed to enable largefile support on various platforms + # These may affect some typedefs --- python2.7-2.7.6.orig/debian/patches/no-zip-on-sys.path.diff +++ python2.7-2.7.6/debian/patches/no-zip-on-sys.path.diff @@ -0,0 +1,52 @@ +# DP: Do not add /usr/lib/pythonXY.zip on sys.path. + +--- a/Modules/getpath.c ++++ b/Modules/getpath.c +@@ -395,7 +395,9 @@ + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + char argv0_path[MAXPATHLEN+1]; ++#ifdef WITH_ZIP_PATH + char zip_path[MAXPATHLEN+1]; ++#endif + int pfound, efound; /* 1 if found; -1 if found build directory */ + char *buf; + size_t bufsz; +@@ -535,6 +537,7 @@ + else + reduce(prefix); + ++#ifdef WITH_ZIP_PATH + strncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ +@@ -547,6 +550,7 @@ + bufsz = strlen(zip_path); /* Replace "00" with version */ + zip_path[bufsz - 6] = VERSION[0]; + zip_path[bufsz - 5] = VERSION[2]; ++#endif + + if (!(efound = search_for_exec_prefix(argv0_path, home))) { + if (!Py_FrozenFlag) +@@ -586,7 +590,9 @@ + defpath = delim + 1; + } + ++#ifdef WITH_ZIP_PATH + bufsz += strlen(zip_path) + 1; ++#endif + bufsz += strlen(exec_prefix) + 1; + + /* This is the only malloc call in this file */ +@@ -607,9 +613,11 @@ + else + buf[0] = '\0'; + ++#ifdef WITH_ZIP_PATH + /* Next is the default zip path */ + strcat(buf, zip_path); + strcat(buf, delimiter); ++#endif + + /* Next goes merge of compile-time $PYTHONPATH with + * dynamically located prefix. --- python2.7-2.7.6.orig/debian/patches/plat-gnukfreebsd.diff +++ python2.7-2.7.6/debian/patches/plat-gnukfreebsd.diff @@ -0,0 +1,2478 @@ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/IN.py +@@ -0,0 +1,809 @@ ++# Generated by h2py from /usr/include/netinet/in.h ++_NETINET_IN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from stdint.h ++_STDINT_H = 1 ++ ++# Included from bits/wchar.h ++_BITS_WCHAR_H = 1 ++__WCHAR_MAX = (2147483647) ++__WCHAR_MIN = (-__WCHAR_MAX - 1) ++def __INT64_C(c): return c ## L ++ ++def __UINT64_C(c): return c ## UL ++ ++def __INT64_C(c): return c ## LL ++ ++def __UINT64_C(c): return c ## ULL ++ ++INT8_MIN = (-128) ++INT16_MIN = (-32767-1) ++INT32_MIN = (-2147483647-1) ++INT64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT8_MAX = (127) ++INT16_MAX = (32767) ++INT32_MAX = (2147483647) ++INT64_MAX = (__INT64_C(9223372036854775807)) ++UINT8_MAX = (255) ++UINT16_MAX = (65535) ++UINT64_MAX = (__UINT64_C(18446744073709551615)) ++INT_LEAST8_MIN = (-128) ++INT_LEAST16_MIN = (-32767-1) ++INT_LEAST32_MIN = (-2147483647-1) ++INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_LEAST8_MAX = (127) ++INT_LEAST16_MAX = (32767) ++INT_LEAST32_MAX = (2147483647) ++INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_LEAST8_MAX = (255) ++UINT_LEAST16_MAX = (65535) ++UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) ++INT_FAST8_MIN = (-128) ++INT_FAST16_MIN = (-9223372036854775807L-1) ++INT_FAST32_MIN = (-9223372036854775807L-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807L) ++INT_FAST32_MAX = (9223372036854775807L) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807L-1) ++INTPTR_MAX = (9223372036854775807L) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807L-1) ++PTRDIFF_MAX = (9223372036854775807L) ++PTRDIFF_MIN = (-2147483647-1) ++PTRDIFF_MAX = (2147483647) ++SIG_ATOMIC_MIN = (-2147483647-1) ++SIG_ATOMIC_MAX = (2147483647) ++WCHAR_MIN = __WCHAR_MIN ++WCHAR_MAX = __WCHAR_MAX ++def INT8_C(c): return c ++ ++def INT16_C(c): return c ++ ++def INT32_C(c): return c ++ ++def INT64_C(c): return c ## L ++ ++def INT64_C(c): return c ## LL ++ ++def UINT8_C(c): return c ++ ++def UINT16_C(c): return c ++ ++def UINT32_C(c): return c ## U ++ ++def UINT64_C(c): return c ## UL ++ ++def UINT64_C(c): return c ## ULL ++ ++def INTMAX_C(c): return c ## L ++ ++def UINTMAX_C(c): return c ## UL ++ ++def INTMAX_C(c): return c ## LL ++ ++def UINTMAX_C(c): return c ## ULL ++ ++ ++# Included from sys/socket.h ++_SYS_SOCKET_H = 1 ++ ++# Included from sys/uio.h ++_SYS_UIO_H = 1 ++from TYPES import * ++ ++# Included from bits/uio.h ++_BITS_UIO_H = 1 ++from TYPES import * ++UIO_MAXIOV = 1024 ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++ ++# Included from bits/socket.h ++__BITS_SOCKET_H = 1 ++ ++# Included from limits.h ++_LIBC_LIMITS_H_ = 1 ++MB_LEN_MAX = 16 ++_LIMITS_H = 1 ++CHAR_BIT = 8 ++SCHAR_MIN = (-128) ++SCHAR_MAX = 127 ++UCHAR_MAX = 255 ++CHAR_MIN = 0 ++CHAR_MAX = UCHAR_MAX ++CHAR_MIN = SCHAR_MIN ++CHAR_MAX = SCHAR_MAX ++SHRT_MIN = (-32768) ++SHRT_MAX = 32767 ++USHRT_MAX = 65535 ++INT_MAX = 2147483647 ++LONG_MAX = 9223372036854775807L ++LONG_MAX = 2147483647L ++LONG_MIN = (-LONG_MAX - 1L) ++ ++# Included from bits/posix1_lim.h ++_BITS_POSIX1_LIM_H = 1 ++_POSIX_AIO_LISTIO_MAX = 2 ++_POSIX_AIO_MAX = 1 ++_POSIX_ARG_MAX = 4096 ++_POSIX_CHILD_MAX = 25 ++_POSIX_CHILD_MAX = 6 ++_POSIX_DELAYTIMER_MAX = 32 ++_POSIX_HOST_NAME_MAX = 255 ++_POSIX_LINK_MAX = 8 ++_POSIX_LOGIN_NAME_MAX = 9 ++_POSIX_MAX_CANON = 255 ++_POSIX_MAX_INPUT = 255 ++_POSIX_MQ_OPEN_MAX = 8 ++_POSIX_MQ_PRIO_MAX = 32 ++_POSIX_NAME_MAX = 14 ++_POSIX_NGROUPS_MAX = 8 ++_POSIX_NGROUPS_MAX = 0 ++_POSIX_OPEN_MAX = 20 ++_POSIX_OPEN_MAX = 16 ++_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX ++_POSIX_PATH_MAX = 256 ++_POSIX_PIPE_BUF = 512 ++_POSIX_RE_DUP_MAX = 255 ++_POSIX_RTSIG_MAX = 8 ++_POSIX_SEM_NSEMS_MAX = 256 ++_POSIX_SEM_VALUE_MAX = 32767 ++_POSIX_SIGQUEUE_MAX = 32 ++_POSIX_SSIZE_MAX = 32767 ++_POSIX_STREAM_MAX = 8 ++_POSIX_SYMLINK_MAX = 255 ++_POSIX_SYMLOOP_MAX = 8 ++_POSIX_TIMER_MAX = 32 ++_POSIX_TTY_NAME_MAX = 9 ++_POSIX_TZNAME_MAX = 6 ++_POSIX_QLIMIT = 1 ++_POSIX_HIWAT = _POSIX_PIPE_BUF ++_POSIX_UIO_MAXIOV = 16 ++_POSIX_CLOCKRES_MIN = 20000000 ++ ++# Included from bits/local_lim.h ++ ++# Included from sys/syslimits.h ++ARG_MAX = 262144 ++CHILD_MAX = 40 ++LINK_MAX = 32767 ++MAX_CANON = 255 ++MAX_INPUT = 255 ++NAME_MAX = 255 ++NGROUPS_MAX = 1023 ++OPEN_MAX = 64 ++PATH_MAX = 1024 ++PIPE_BUF = 512 ++IOV_MAX = 1024 ++_POSIX_THREAD_KEYS_MAX = 128 ++PTHREAD_KEYS_MAX = 1024 ++_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4 ++PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS ++_POSIX_THREAD_THREADS_MAX = 64 ++PTHREAD_THREADS_MAX = 1024 ++AIO_PRIO_DELTA_MAX = 20 ++PTHREAD_STACK_MIN = 16384 ++TIMER_MAX = 256 ++DELAYTIMER_MAX = 2147483647 ++SSIZE_MAX = LONG_MAX ++NGROUPS_MAX = 8 ++ ++# Included from bits/posix2_lim.h ++_BITS_POSIX2_LIM_H = 1 ++_POSIX2_BC_BASE_MAX = 99 ++_POSIX2_BC_DIM_MAX = 2048 ++_POSIX2_BC_SCALE_MAX = 99 ++_POSIX2_BC_STRING_MAX = 1000 ++_POSIX2_COLL_WEIGHTS_MAX = 2 ++_POSIX2_EXPR_NEST_MAX = 32 ++_POSIX2_LINE_MAX = 2048 ++_POSIX2_RE_DUP_MAX = 255 ++_POSIX2_CHARCLASS_NAME_MAX = 14 ++BC_BASE_MAX = _POSIX2_BC_BASE_MAX ++BC_DIM_MAX = _POSIX2_BC_DIM_MAX ++BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX ++BC_STRING_MAX = _POSIX2_BC_STRING_MAX ++COLL_WEIGHTS_MAX = 255 ++EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX ++LINE_MAX = _POSIX2_LINE_MAX ++CHARCLASS_NAME_MAX = 2048 ++RE_DUP_MAX = (0x7fff) ++ ++# Included from bits/xopen_lim.h ++_XOPEN_LIM_H = 1 ++ ++# Included from bits/stdio_lim.h ++L_tmpnam = 20 ++TMP_MAX = 238328 ++FILENAME_MAX = 1024 ++L_ctermid = 9 ++L_cuserid = 9 ++FOPEN_MAX = 64 ++IOV_MAX = 1024 ++_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV ++NL_ARGMAX = _POSIX_ARG_MAX ++NL_LANGMAX = _POSIX2_LINE_MAX ++NL_MSGMAX = INT_MAX ++NL_NMAX = INT_MAX ++NL_SETMAX = INT_MAX ++NL_TEXTMAX = INT_MAX ++NZERO = 20 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 32 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 64 ++LONG_BIT = 32 ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++PF_UNSPEC = 0 ++PF_LOCAL = 1 ++PF_UNIX = PF_LOCAL ++PF_FILE = PF_LOCAL ++PF_INET = 2 ++PF_IMPLINK = 3 ++PF_PUP = 4 ++PF_CHAOS = 5 ++PF_NS = 6 ++PF_ISO = 7 ++PF_OSI = PF_ISO ++PF_ECMA = 8 ++PF_DATAKIT = 9 ++PF_CCITT = 10 ++PF_SNA = 11 ++PF_DECnet = 12 ++PF_DLI = 13 ++PF_LAT = 14 ++PF_HYLINK = 15 ++PF_APPLETALK = 16 ++PF_ROUTE = 17 ++PF_LINK = 18 ++PF_XTP = 19 ++PF_COIP = 20 ++PF_CNT = 21 ++PF_RTIP = 22 ++PF_IPX = 23 ++PF_SIP = 24 ++PF_PIP = 25 ++PF_ISDN = 26 ++PF_KEY = 27 ++PF_INET6 = 28 ++PF_NATM = 29 ++PF_ATM = 30 ++PF_HDRCMPLT = 31 ++PF_NETGRAPH = 32 ++PF_MAX = 33 ++AF_UNSPEC = PF_UNSPEC ++AF_LOCAL = PF_LOCAL ++AF_UNIX = PF_UNIX ++AF_FILE = PF_FILE ++AF_INET = PF_INET ++AF_IMPLINK = PF_IMPLINK ++AF_PUP = PF_PUP ++AF_CHAOS = PF_CHAOS ++AF_NS = PF_NS ++AF_ISO = PF_ISO ++AF_OSI = PF_OSI ++AF_ECMA = PF_ECMA ++AF_DATAKIT = PF_DATAKIT ++AF_CCITT = PF_CCITT ++AF_SNA = PF_SNA ++AF_DECnet = PF_DECnet ++AF_DLI = PF_DLI ++AF_LAT = PF_LAT ++AF_HYLINK = PF_HYLINK ++AF_APPLETALK = PF_APPLETALK ++AF_ROUTE = PF_ROUTE ++AF_LINK = PF_LINK ++pseudo_AF_XTP = PF_XTP ++AF_COIP = PF_COIP ++AF_CNT = PF_CNT ++pseudo_AF_RTIP = PF_RTIP ++AF_IPX = PF_IPX ++AF_SIP = PF_SIP ++pseudo_AF_PIP = PF_PIP ++AF_ISDN = PF_ISDN ++AF_E164 = AF_ISDN ++pseudo_AF_KEY = PF_KEY ++AF_INET6 = PF_INET6 ++AF_NATM = PF_NATM ++AF_ATM = PF_ATM ++pseudo_AF_HDRCMPLT = PF_HDRCMPLT ++AF_NETGRAPH = PF_NETGRAPH ++AF_MAX = PF_MAX ++SOMAXCONN = 128 ++ ++# Included from bits/sockaddr.h ++_BITS_SOCKADDR_H = 1 ++def __SOCKADDR_COMMON(sa_prefix): return \ ++ ++_HAVE_SA_LEN = 1 ++_SS_SIZE = 128 ++def CMSG_FIRSTHDR(mhdr): return \ ++ ++CMGROUP_MAX = 16 ++SOL_SOCKET = 0xffff ++LOCAL_PEERCRED = 0x001 ++LOCAL_CREDS = 0x002 ++LOCAL_CONNWAIT = 0x004 ++ ++# Included from bits/socket2.h ++def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) ++ ++IN_CLASSA_NET = (-16777216) ++IN_CLASSA_NSHIFT = 24 ++IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET) ++IN_CLASSA_MAX = 128 ++def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) ++ ++IN_CLASSB_NET = (-65536) ++IN_CLASSB_NSHIFT = 16 ++IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET) ++IN_CLASSB_MAX = 65536 ++def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) ++ ++IN_CLASSC_NET = (-256) ++IN_CLASSC_NSHIFT = 8 ++IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) ++def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912)) ++ ++def IN_MULTICAST(a): return IN_CLASSD(a) ++ ++def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) ++ ++def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456)) ++ ++IN_LOOPBACKNET = 127 ++INET_ADDRSTRLEN = 16 ++INET6_ADDRSTRLEN = 46 ++ ++# Included from bits/in.h ++IMPLINK_IP = 155 ++IMPLINK_LOWEXPER = 156 ++IMPLINK_HIGHEXPER = 158 ++IPPROTO_DIVERT = 258 ++SOL_IP = 0 ++IP_OPTIONS = 1 ++IP_HDRINCL = 2 ++IP_TOS = 3 ++IP_TTL = 4 ++IP_RECVOPTS = 5 ++IP_RECVRETOPTS = 6 ++IP_RECVDSTADDR = 7 ++IP_SENDSRCADDR = IP_RECVDSTADDR ++IP_RETOPTS = 8 ++IP_MULTICAST_IF = 9 ++IP_MULTICAST_TTL = 10 ++IP_MULTICAST_LOOP = 11 ++IP_ADD_MEMBERSHIP = 12 ++IP_DROP_MEMBERSHIP = 13 ++IP_MULTICAST_VIF = 14 ++IP_RSVP_ON = 15 ++IP_RSVP_OFF = 16 ++IP_RSVP_VIF_ON = 17 ++IP_RSVP_VIF_OFF = 18 ++IP_PORTRANGE = 19 ++IP_RECVIF = 20 ++IP_IPSEC_POLICY = 21 ++IP_FAITH = 22 ++IP_ONESBCAST = 23 ++IP_NONLOCALOK = 24 ++IP_FW_TABLE_ADD = 40 ++IP_FW_TABLE_DEL = 41 ++IP_FW_TABLE_FLUSH = 42 ++IP_FW_TABLE_GETSIZE = 43 ++IP_FW_TABLE_LIST = 44 ++IP_FW_ADD = 50 ++IP_FW_DEL = 51 ++IP_FW_FLUSH = 52 ++IP_FW_ZERO = 53 ++IP_FW_GET = 54 ++IP_FW_RESETLOG = 55 ++IP_FW_NAT_CFG = 56 ++IP_FW_NAT_DEL = 57 ++IP_FW_NAT_GET_CONFIG = 58 ++IP_FW_NAT_GET_LOG = 59 ++IP_DUMMYNET_CONFIGURE = 60 ++IP_DUMMYNET_DEL = 61 ++IP_DUMMYNET_FLUSH = 62 ++IP_DUMMYNET_GET = 64 ++IP_RECVTTL = 65 ++IP_MINTTL = 66 ++IP_DONTFRAG = 67 ++IP_ADD_SOURCE_MEMBERSHIP = 70 ++IP_DROP_SOURCE_MEMBERSHIP = 71 ++IP_BLOCK_SOURCE = 72 ++IP_UNBLOCK_SOURCE = 73 ++IP_MSFILTER = 74 ++MCAST_JOIN_GROUP = 80 ++MCAST_LEAVE_GROUP = 81 ++MCAST_JOIN_SOURCE_GROUP = 82 ++MCAST_LEAVE_SOURCE_GROUP = 83 ++MCAST_BLOCK_SOURCE = 84 ++MCAST_UNBLOCK_SOURCE = 85 ++IP_DEFAULT_MULTICAST_TTL = 1 ++IP_DEFAULT_MULTICAST_LOOP = 1 ++IP_MIN_MEMBERSHIPS = 31 ++IP_MAX_MEMBERSHIPS = 4095 ++IP_MAX_SOURCE_FILTER = 1024 ++MCAST_UNDEFINED = 0 ++MCAST_INCLUDE = 1 ++MCAST_EXCLUDE = 2 ++IP_PORTRANGE_DEFAULT = 0 ++IP_PORTRANGE_HIGH = 1 ++IP_PORTRANGE_LOW = 2 ++IPCTL_FORWARDING = 1 ++IPCTL_SENDREDIRECTS = 2 ++IPCTL_DEFTTL = 3 ++IPCTL_DEFMTU = 4 ++IPCTL_RTEXPIRE = 5 ++IPCTL_RTMINEXPIRE = 6 ++IPCTL_RTMAXCACHE = 7 ++IPCTL_SOURCEROUTE = 8 ++IPCTL_DIRECTEDBROADCAST = 9 ++IPCTL_INTRQMAXLEN = 10 ++IPCTL_INTRQDROPS = 11 ++IPCTL_STATS = 12 ++IPCTL_ACCEPTSOURCEROUTE = 13 ++IPCTL_FASTFORWARDING = 14 ++IPCTL_KEEPFAITH = 15 ++IPCTL_GIF_TTL = 16 ++IPCTL_MAXID = 17 ++IPV6_SOCKOPT_RESERVED1 = 3 ++IPV6_UNICAST_HOPS = 4 ++IPV6_MULTICAST_IF = 9 ++IPV6_MULTICAST_HOPS = 10 ++IPV6_MULTICAST_LOOP = 11 ++IPV6_JOIN_GROUP = 12 ++IPV6_LEAVE_GROUP = 13 ++IPV6_PORTRANGE = 14 ++ICMP6_FILTER = 18 ++IPV6_CHECKSUM = 26 ++IPV6_V6ONLY = 27 ++IPV6_IPSEC_POLICY = 28 ++IPV6_FAITH = 29 ++IPV6_FW_ADD = 30 ++IPV6_FW_DEL = 31 ++IPV6_FW_FLUSH = 32 ++IPV6_FW_ZERO = 33 ++IPV6_FW_GET = 34 ++IPV6_RTHDRDSTOPTS = 35 ++IPV6_RECVPKTINFO = 36 ++IPV6_RECVHOPLIMIT = 37 ++IPV6_RECVRTHDR = 38 ++IPV6_RECVHOPOPTS = 39 ++IPV6_RECVDSTOPTS = 40 ++IPV6_USE_MIN_MTU = 42 ++IPV6_RECVPATHMTU = 43 ++IPV6_PATHMTU = 44 ++IPV6_PKTINFO = 46 ++IPV6_HOPLIMIT = 47 ++IPV6_NEXTHOP = 48 ++IPV6_HOPOPTS = 49 ++IPV6_DSTOPTS = 50 ++IPV6_RTHDR = 51 ++IPV6_RECVTCLASS = 57 ++IPV6_AUTOFLOWLABEL = 59 ++IPV6_TCLASS = 61 ++IPV6_DONTFRAG = 62 ++IPV6_PREFER_TEMPADDR = 63 ++IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP ++IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP ++IPV6_RXHOPOPTS = IPV6_HOPOPTS ++IPV6_RXDSTOPTS = IPV6_DSTOPTS ++SOL_IPV6 = 41 ++SOL_ICMPV6 = 58 ++IPV6_DEFAULT_MULTICAST_HOPS = 1 ++IPV6_DEFAULT_MULTICAST_LOOP = 1 ++IPV6_PORTRANGE_DEFAULT = 0 ++IPV6_PORTRANGE_HIGH = 1 ++IPV6_PORTRANGE_LOW = 2 ++IPV6_RTHDR_LOOSE = 0 ++IPV6_RTHDR_STRICT = 1 ++IPV6_RTHDR_TYPE_0 = 0 ++IPV6CTL_FORWARDING = 1 ++IPV6CTL_SENDREDIRECTS = 2 ++IPV6CTL_DEFHLIM = 3 ++IPV6CTL_FORWSRCRT = 5 ++IPV6CTL_STATS = 6 ++IPV6CTL_MRTSTATS = 7 ++IPV6CTL_MRTPROTO = 8 ++IPV6CTL_MAXFRAGPACKETS = 9 ++IPV6CTL_SOURCECHECK = 10 ++IPV6CTL_SOURCECHECK_LOGINT = 11 ++IPV6CTL_ACCEPT_RTADV = 12 ++IPV6CTL_KEEPFAITH = 13 ++IPV6CTL_LOG_INTERVAL = 14 ++IPV6CTL_HDRNESTLIMIT = 15 ++IPV6CTL_DAD_COUNT = 16 ++IPV6CTL_AUTO_FLOWLABEL = 17 ++IPV6CTL_DEFMCASTHLIM = 18 ++IPV6CTL_GIF_HLIM = 19 ++IPV6CTL_KAME_VERSION = 20 ++IPV6CTL_USE_DEPRECATED = 21 ++IPV6CTL_RR_PRUNE = 22 ++IPV6CTL_V6ONLY = 24 ++IPV6CTL_RTEXPIRE = 25 ++IPV6CTL_RTMINEXPIRE = 26 ++IPV6CTL_RTMAXCACHE = 27 ++IPV6CTL_USETEMPADDR = 32 ++IPV6CTL_TEMPPLTIME = 33 ++IPV6CTL_TEMPVLTIME = 34 ++IPV6CTL_AUTO_LINKLOCAL = 35 ++IPV6CTL_RIP6STATS = 36 ++IPV6CTL_PREFER_TEMPADDR = 37 ++IPV6CTL_ADDRCTLPOLICY = 38 ++IPV6CTL_USE_DEFAULTZONE = 39 ++IPV6CTL_MAXFRAGS = 41 ++IPV6CTL_MCAST_PMTU = 44 ++IPV6CTL_STEALTH = 45 ++ICMPV6CTL_ND6_ONLINKNSRFC4861 = 47 ++IPV6CTL_MAXID = 48 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++def ntohl(x): return (x) ++ ++def ntohs(x): return (x) ++ ++def htonl(x): return (x) ++ ++def htons(x): return (x) ++ ++def ntohl(x): return __bswap_32 (x) ++ ++def ntohs(x): return __bswap_16 (x) ++ ++def htonl(x): return __bswap_32 (x) ++ ++def htons(x): return __bswap_16 (x) ++ ++def IN6_IS_ADDR_UNSPECIFIED(a): return \ ++ ++def IN6_IS_ADDR_LOOPBACK(a): return \ ++ ++def IN6_IS_ADDR_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_V4MAPPED(a): return \ ++ ++def IN6_IS_ADDR_V4COMPAT(a): return \ ++ ++def IN6_IS_ADDR_MC_NODELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_GLOBAL(a): return \ ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/TYPES.py +@@ -0,0 +1,303 @@ ++# Generated by h2py from /usr/include/sys/types.h ++_SYS_TYPES_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++ ++# Included from time.h ++_TIME_H = 1 ++ ++# Included from bits/time.h ++_BITS_TIME_H = 1 ++CLOCKS_PER_SEC = 1000000l ++CLK_TCK = 128 ++CLOCK_REALTIME = 0 ++CLOCK_PROCESS_CPUTIME_ID = 2 ++CLOCK_THREAD_CPUTIME_ID = 3 ++CLOCK_MONOTONIC = 4 ++CLOCK_VIRTUAL = 1 ++CLOCK_PROF = 2 ++CLOCK_UPTIME = 5 ++CLOCK_UPTIME_PRECISE = 7 ++CLOCK_UPTIME_FAST = 8 ++CLOCK_REALTIME_PRECISE = 9 ++CLOCK_REALTIME_FAST = 10 ++CLOCK_MONOTONIC_PRECISE = 11 ++CLOCK_MONOTONIC_FAST = 12 ++CLOCK_SECOND = 13 ++TIMER_RELTIME = 0 ++TIMER_ABSTIME = 1 ++_STRUCT_TIMEVAL = 1 ++CLK_TCK = CLOCKS_PER_SEC ++__clock_t_defined = 1 ++__time_t_defined = 1 ++__clockid_t_defined = 1 ++__timer_t_defined = 1 ++__timespec_defined = 1 ++ ++# Included from xlocale.h ++_XLOCALE_H = 1 ++def __isleap(year): return \ ++ ++__BIT_TYPES_DEFINED__ = 1 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++ ++# Included from sys/select.h ++_SYS_SELECT_H = 1 ++ ++# Included from bits/select.h ++def __FD_ZERO(fdsp): return \ ++ ++def __FD_ZERO(set): return \ ++ ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++def __FDELT(d): return ((d) / __NFDBITS) ++ ++FD_SETSIZE = __FD_SETSIZE ++def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) ++ ++ ++# Included from sys/sysmacros.h ++_SYS_SYSMACROS_H = 1 ++def minor(dev): return ((int)((dev) & (-65281))) ++ ++def gnu_dev_major(dev): return major (dev) ++ ++def gnu_dev_minor(dev): return minor (dev) ++ ++ ++# Included from bits/pthreadtypes.h ++_BITS_PTHREADTYPES_H = 1 ++ ++# Included from bits/sched.h ++SCHED_OTHER = 2 ++SCHED_FIFO = 1 ++SCHED_RR = 3 ++CSIGNAL = 0x000000ff ++CLONE_VM = 0x00000100 ++CLONE_FS = 0x00000200 ++CLONE_FILES = 0x00000400 ++CLONE_SIGHAND = 0x00000800 ++CLONE_PTRACE = 0x00002000 ++CLONE_VFORK = 0x00004000 ++CLONE_SYSVSEM = 0x00040000 ++__defined_schedparam = 1 ++__CPU_SETSIZE = 128 ++def __CPUELT(cpu): return ((cpu) / __NCPUBITS) ++ ++def __CPU_ALLOC_SIZE(count): return \ ++ ++def __CPU_ALLOC(count): return __sched_cpualloc (count) ++ ++def __CPU_FREE(cpuset): return __sched_cpufree (cpuset) ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/DLFCN.py +@@ -0,0 +1,118 @@ ++# Generated by h2py from /usr/include/dlfcn.h ++_DLFCN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/dlfcn.h ++RTLD_LAZY = 0x00001 ++RTLD_NOW = 0x00002 ++RTLD_BINDING_MASK = 0x3 ++RTLD_NOLOAD = 0x00004 ++RTLD_DEEPBIND = 0x00008 ++RTLD_GLOBAL = 0x00100 ++RTLD_LOCAL = 0 ++RTLD_NODELETE = 0x01000 ++LM_ID_BASE = 0 ++LM_ID_NEWLM = -1 +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/IN.py +@@ -0,0 +1,809 @@ ++# Generated by h2py from /usr/include/netinet/in.h ++_NETINET_IN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from stdint.h ++_STDINT_H = 1 ++ ++# Included from bits/wchar.h ++_BITS_WCHAR_H = 1 ++__WCHAR_MAX = (2147483647) ++__WCHAR_MIN = (-__WCHAR_MAX - 1) ++def __INT64_C(c): return c ## L ++ ++def __UINT64_C(c): return c ## UL ++ ++def __INT64_C(c): return c ## LL ++ ++def __UINT64_C(c): return c ## ULL ++ ++INT8_MIN = (-128) ++INT16_MIN = (-32767-1) ++INT32_MIN = (-2147483647-1) ++INT64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT8_MAX = (127) ++INT16_MAX = (32767) ++INT32_MAX = (2147483647) ++INT64_MAX = (__INT64_C(9223372036854775807)) ++UINT8_MAX = (255) ++UINT16_MAX = (65535) ++UINT64_MAX = (__UINT64_C(18446744073709551615)) ++INT_LEAST8_MIN = (-128) ++INT_LEAST16_MIN = (-32767-1) ++INT_LEAST32_MIN = (-2147483647-1) ++INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_LEAST8_MAX = (127) ++INT_LEAST16_MAX = (32767) ++INT_LEAST32_MAX = (2147483647) ++INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_LEAST8_MAX = (255) ++UINT_LEAST16_MAX = (65535) ++UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) ++INT_FAST8_MIN = (-128) ++INT_FAST16_MIN = (-9223372036854775807L-1) ++INT_FAST32_MIN = (-9223372036854775807L-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807L) ++INT_FAST32_MAX = (9223372036854775807L) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807L-1) ++INTPTR_MAX = (9223372036854775807L) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807L-1) ++PTRDIFF_MAX = (9223372036854775807L) ++PTRDIFF_MIN = (-2147483647-1) ++PTRDIFF_MAX = (2147483647) ++SIG_ATOMIC_MIN = (-2147483647-1) ++SIG_ATOMIC_MAX = (2147483647) ++WCHAR_MIN = __WCHAR_MIN ++WCHAR_MAX = __WCHAR_MAX ++def INT8_C(c): return c ++ ++def INT16_C(c): return c ++ ++def INT32_C(c): return c ++ ++def INT64_C(c): return c ## L ++ ++def INT64_C(c): return c ## LL ++ ++def UINT8_C(c): return c ++ ++def UINT16_C(c): return c ++ ++def UINT32_C(c): return c ## U ++ ++def UINT64_C(c): return c ## UL ++ ++def UINT64_C(c): return c ## ULL ++ ++def INTMAX_C(c): return c ## L ++ ++def UINTMAX_C(c): return c ## UL ++ ++def INTMAX_C(c): return c ## LL ++ ++def UINTMAX_C(c): return c ## ULL ++ ++ ++# Included from sys/socket.h ++_SYS_SOCKET_H = 1 ++ ++# Included from sys/uio.h ++_SYS_UIO_H = 1 ++from TYPES import * ++ ++# Included from bits/uio.h ++_BITS_UIO_H = 1 ++from TYPES import * ++UIO_MAXIOV = 1024 ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++ ++# Included from bits/socket.h ++__BITS_SOCKET_H = 1 ++ ++# Included from limits.h ++_LIBC_LIMITS_H_ = 1 ++MB_LEN_MAX = 16 ++_LIMITS_H = 1 ++CHAR_BIT = 8 ++SCHAR_MIN = (-128) ++SCHAR_MAX = 127 ++UCHAR_MAX = 255 ++CHAR_MIN = 0 ++CHAR_MAX = UCHAR_MAX ++CHAR_MIN = SCHAR_MIN ++CHAR_MAX = SCHAR_MAX ++SHRT_MIN = (-32768) ++SHRT_MAX = 32767 ++USHRT_MAX = 65535 ++INT_MAX = 2147483647 ++LONG_MAX = 9223372036854775807L ++LONG_MAX = 2147483647L ++LONG_MIN = (-LONG_MAX - 1L) ++ ++# Included from bits/posix1_lim.h ++_BITS_POSIX1_LIM_H = 1 ++_POSIX_AIO_LISTIO_MAX = 2 ++_POSIX_AIO_MAX = 1 ++_POSIX_ARG_MAX = 4096 ++_POSIX_CHILD_MAX = 25 ++_POSIX_CHILD_MAX = 6 ++_POSIX_DELAYTIMER_MAX = 32 ++_POSIX_HOST_NAME_MAX = 255 ++_POSIX_LINK_MAX = 8 ++_POSIX_LOGIN_NAME_MAX = 9 ++_POSIX_MAX_CANON = 255 ++_POSIX_MAX_INPUT = 255 ++_POSIX_MQ_OPEN_MAX = 8 ++_POSIX_MQ_PRIO_MAX = 32 ++_POSIX_NAME_MAX = 14 ++_POSIX_NGROUPS_MAX = 8 ++_POSIX_NGROUPS_MAX = 0 ++_POSIX_OPEN_MAX = 20 ++_POSIX_OPEN_MAX = 16 ++_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX ++_POSIX_PATH_MAX = 256 ++_POSIX_PIPE_BUF = 512 ++_POSIX_RE_DUP_MAX = 255 ++_POSIX_RTSIG_MAX = 8 ++_POSIX_SEM_NSEMS_MAX = 256 ++_POSIX_SEM_VALUE_MAX = 32767 ++_POSIX_SIGQUEUE_MAX = 32 ++_POSIX_SSIZE_MAX = 32767 ++_POSIX_STREAM_MAX = 8 ++_POSIX_SYMLINK_MAX = 255 ++_POSIX_SYMLOOP_MAX = 8 ++_POSIX_TIMER_MAX = 32 ++_POSIX_TTY_NAME_MAX = 9 ++_POSIX_TZNAME_MAX = 6 ++_POSIX_QLIMIT = 1 ++_POSIX_HIWAT = _POSIX_PIPE_BUF ++_POSIX_UIO_MAXIOV = 16 ++_POSIX_CLOCKRES_MIN = 20000000 ++ ++# Included from bits/local_lim.h ++ ++# Included from sys/syslimits.h ++ARG_MAX = 262144 ++CHILD_MAX = 40 ++LINK_MAX = 32767 ++MAX_CANON = 255 ++MAX_INPUT = 255 ++NAME_MAX = 255 ++NGROUPS_MAX = 1023 ++OPEN_MAX = 64 ++PATH_MAX = 1024 ++PIPE_BUF = 512 ++IOV_MAX = 1024 ++_POSIX_THREAD_KEYS_MAX = 128 ++PTHREAD_KEYS_MAX = 1024 ++_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4 ++PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS ++_POSIX_THREAD_THREADS_MAX = 64 ++PTHREAD_THREADS_MAX = 1024 ++AIO_PRIO_DELTA_MAX = 20 ++PTHREAD_STACK_MIN = 16384 ++TIMER_MAX = 256 ++DELAYTIMER_MAX = 2147483647 ++SSIZE_MAX = LONG_MAX ++NGROUPS_MAX = 8 ++ ++# Included from bits/posix2_lim.h ++_BITS_POSIX2_LIM_H = 1 ++_POSIX2_BC_BASE_MAX = 99 ++_POSIX2_BC_DIM_MAX = 2048 ++_POSIX2_BC_SCALE_MAX = 99 ++_POSIX2_BC_STRING_MAX = 1000 ++_POSIX2_COLL_WEIGHTS_MAX = 2 ++_POSIX2_EXPR_NEST_MAX = 32 ++_POSIX2_LINE_MAX = 2048 ++_POSIX2_RE_DUP_MAX = 255 ++_POSIX2_CHARCLASS_NAME_MAX = 14 ++BC_BASE_MAX = _POSIX2_BC_BASE_MAX ++BC_DIM_MAX = _POSIX2_BC_DIM_MAX ++BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX ++BC_STRING_MAX = _POSIX2_BC_STRING_MAX ++COLL_WEIGHTS_MAX = 255 ++EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX ++LINE_MAX = _POSIX2_LINE_MAX ++CHARCLASS_NAME_MAX = 2048 ++RE_DUP_MAX = (0x7fff) ++ ++# Included from bits/xopen_lim.h ++_XOPEN_LIM_H = 1 ++ ++# Included from bits/stdio_lim.h ++L_tmpnam = 20 ++TMP_MAX = 238328 ++FILENAME_MAX = 1024 ++L_ctermid = 9 ++L_cuserid = 9 ++FOPEN_MAX = 64 ++IOV_MAX = 1024 ++_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV ++NL_ARGMAX = _POSIX_ARG_MAX ++NL_LANGMAX = _POSIX2_LINE_MAX ++NL_MSGMAX = INT_MAX ++NL_NMAX = INT_MAX ++NL_SETMAX = INT_MAX ++NL_TEXTMAX = INT_MAX ++NZERO = 20 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 32 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 64 ++LONG_BIT = 32 ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++PF_UNSPEC = 0 ++PF_LOCAL = 1 ++PF_UNIX = PF_LOCAL ++PF_FILE = PF_LOCAL ++PF_INET = 2 ++PF_IMPLINK = 3 ++PF_PUP = 4 ++PF_CHAOS = 5 ++PF_NS = 6 ++PF_ISO = 7 ++PF_OSI = PF_ISO ++PF_ECMA = 8 ++PF_DATAKIT = 9 ++PF_CCITT = 10 ++PF_SNA = 11 ++PF_DECnet = 12 ++PF_DLI = 13 ++PF_LAT = 14 ++PF_HYLINK = 15 ++PF_APPLETALK = 16 ++PF_ROUTE = 17 ++PF_LINK = 18 ++PF_XTP = 19 ++PF_COIP = 20 ++PF_CNT = 21 ++PF_RTIP = 22 ++PF_IPX = 23 ++PF_SIP = 24 ++PF_PIP = 25 ++PF_ISDN = 26 ++PF_KEY = 27 ++PF_INET6 = 28 ++PF_NATM = 29 ++PF_ATM = 30 ++PF_HDRCMPLT = 31 ++PF_NETGRAPH = 32 ++PF_MAX = 33 ++AF_UNSPEC = PF_UNSPEC ++AF_LOCAL = PF_LOCAL ++AF_UNIX = PF_UNIX ++AF_FILE = PF_FILE ++AF_INET = PF_INET ++AF_IMPLINK = PF_IMPLINK ++AF_PUP = PF_PUP ++AF_CHAOS = PF_CHAOS ++AF_NS = PF_NS ++AF_ISO = PF_ISO ++AF_OSI = PF_OSI ++AF_ECMA = PF_ECMA ++AF_DATAKIT = PF_DATAKIT ++AF_CCITT = PF_CCITT ++AF_SNA = PF_SNA ++AF_DECnet = PF_DECnet ++AF_DLI = PF_DLI ++AF_LAT = PF_LAT ++AF_HYLINK = PF_HYLINK ++AF_APPLETALK = PF_APPLETALK ++AF_ROUTE = PF_ROUTE ++AF_LINK = PF_LINK ++pseudo_AF_XTP = PF_XTP ++AF_COIP = PF_COIP ++AF_CNT = PF_CNT ++pseudo_AF_RTIP = PF_RTIP ++AF_IPX = PF_IPX ++AF_SIP = PF_SIP ++pseudo_AF_PIP = PF_PIP ++AF_ISDN = PF_ISDN ++AF_E164 = AF_ISDN ++pseudo_AF_KEY = PF_KEY ++AF_INET6 = PF_INET6 ++AF_NATM = PF_NATM ++AF_ATM = PF_ATM ++pseudo_AF_HDRCMPLT = PF_HDRCMPLT ++AF_NETGRAPH = PF_NETGRAPH ++AF_MAX = PF_MAX ++SOMAXCONN = 128 ++ ++# Included from bits/sockaddr.h ++_BITS_SOCKADDR_H = 1 ++def __SOCKADDR_COMMON(sa_prefix): return \ ++ ++_HAVE_SA_LEN = 1 ++_SS_SIZE = 128 ++def CMSG_FIRSTHDR(mhdr): return \ ++ ++CMGROUP_MAX = 16 ++SOL_SOCKET = 0xffff ++LOCAL_PEERCRED = 0x001 ++LOCAL_CREDS = 0x002 ++LOCAL_CONNWAIT = 0x004 ++ ++# Included from bits/socket2.h ++def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) ++ ++IN_CLASSA_NET = (-16777216) ++IN_CLASSA_NSHIFT = 24 ++IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET) ++IN_CLASSA_MAX = 128 ++def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) ++ ++IN_CLASSB_NET = (-65536) ++IN_CLASSB_NSHIFT = 16 ++IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET) ++IN_CLASSB_MAX = 65536 ++def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) ++ ++IN_CLASSC_NET = (-256) ++IN_CLASSC_NSHIFT = 8 ++IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) ++def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912)) ++ ++def IN_MULTICAST(a): return IN_CLASSD(a) ++ ++def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) ++ ++def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456)) ++ ++IN_LOOPBACKNET = 127 ++INET_ADDRSTRLEN = 16 ++INET6_ADDRSTRLEN = 46 ++ ++# Included from bits/in.h ++IMPLINK_IP = 155 ++IMPLINK_LOWEXPER = 156 ++IMPLINK_HIGHEXPER = 158 ++IPPROTO_DIVERT = 258 ++SOL_IP = 0 ++IP_OPTIONS = 1 ++IP_HDRINCL = 2 ++IP_TOS = 3 ++IP_TTL = 4 ++IP_RECVOPTS = 5 ++IP_RECVRETOPTS = 6 ++IP_RECVDSTADDR = 7 ++IP_SENDSRCADDR = IP_RECVDSTADDR ++IP_RETOPTS = 8 ++IP_MULTICAST_IF = 9 ++IP_MULTICAST_TTL = 10 ++IP_MULTICAST_LOOP = 11 ++IP_ADD_MEMBERSHIP = 12 ++IP_DROP_MEMBERSHIP = 13 ++IP_MULTICAST_VIF = 14 ++IP_RSVP_ON = 15 ++IP_RSVP_OFF = 16 ++IP_RSVP_VIF_ON = 17 ++IP_RSVP_VIF_OFF = 18 ++IP_PORTRANGE = 19 ++IP_RECVIF = 20 ++IP_IPSEC_POLICY = 21 ++IP_FAITH = 22 ++IP_ONESBCAST = 23 ++IP_NONLOCALOK = 24 ++IP_FW_TABLE_ADD = 40 ++IP_FW_TABLE_DEL = 41 ++IP_FW_TABLE_FLUSH = 42 ++IP_FW_TABLE_GETSIZE = 43 ++IP_FW_TABLE_LIST = 44 ++IP_FW_ADD = 50 ++IP_FW_DEL = 51 ++IP_FW_FLUSH = 52 ++IP_FW_ZERO = 53 ++IP_FW_GET = 54 ++IP_FW_RESETLOG = 55 ++IP_FW_NAT_CFG = 56 ++IP_FW_NAT_DEL = 57 ++IP_FW_NAT_GET_CONFIG = 58 ++IP_FW_NAT_GET_LOG = 59 ++IP_DUMMYNET_CONFIGURE = 60 ++IP_DUMMYNET_DEL = 61 ++IP_DUMMYNET_FLUSH = 62 ++IP_DUMMYNET_GET = 64 ++IP_RECVTTL = 65 ++IP_MINTTL = 66 ++IP_DONTFRAG = 67 ++IP_ADD_SOURCE_MEMBERSHIP = 70 ++IP_DROP_SOURCE_MEMBERSHIP = 71 ++IP_BLOCK_SOURCE = 72 ++IP_UNBLOCK_SOURCE = 73 ++IP_MSFILTER = 74 ++MCAST_JOIN_GROUP = 80 ++MCAST_LEAVE_GROUP = 81 ++MCAST_JOIN_SOURCE_GROUP = 82 ++MCAST_LEAVE_SOURCE_GROUP = 83 ++MCAST_BLOCK_SOURCE = 84 ++MCAST_UNBLOCK_SOURCE = 85 ++IP_DEFAULT_MULTICAST_TTL = 1 ++IP_DEFAULT_MULTICAST_LOOP = 1 ++IP_MIN_MEMBERSHIPS = 31 ++IP_MAX_MEMBERSHIPS = 4095 ++IP_MAX_SOURCE_FILTER = 1024 ++MCAST_UNDEFINED = 0 ++MCAST_INCLUDE = 1 ++MCAST_EXCLUDE = 2 ++IP_PORTRANGE_DEFAULT = 0 ++IP_PORTRANGE_HIGH = 1 ++IP_PORTRANGE_LOW = 2 ++IPCTL_FORWARDING = 1 ++IPCTL_SENDREDIRECTS = 2 ++IPCTL_DEFTTL = 3 ++IPCTL_DEFMTU = 4 ++IPCTL_RTEXPIRE = 5 ++IPCTL_RTMINEXPIRE = 6 ++IPCTL_RTMAXCACHE = 7 ++IPCTL_SOURCEROUTE = 8 ++IPCTL_DIRECTEDBROADCAST = 9 ++IPCTL_INTRQMAXLEN = 10 ++IPCTL_INTRQDROPS = 11 ++IPCTL_STATS = 12 ++IPCTL_ACCEPTSOURCEROUTE = 13 ++IPCTL_FASTFORWARDING = 14 ++IPCTL_KEEPFAITH = 15 ++IPCTL_GIF_TTL = 16 ++IPCTL_MAXID = 17 ++IPV6_SOCKOPT_RESERVED1 = 3 ++IPV6_UNICAST_HOPS = 4 ++IPV6_MULTICAST_IF = 9 ++IPV6_MULTICAST_HOPS = 10 ++IPV6_MULTICAST_LOOP = 11 ++IPV6_JOIN_GROUP = 12 ++IPV6_LEAVE_GROUP = 13 ++IPV6_PORTRANGE = 14 ++ICMP6_FILTER = 18 ++IPV6_CHECKSUM = 26 ++IPV6_V6ONLY = 27 ++IPV6_IPSEC_POLICY = 28 ++IPV6_FAITH = 29 ++IPV6_FW_ADD = 30 ++IPV6_FW_DEL = 31 ++IPV6_FW_FLUSH = 32 ++IPV6_FW_ZERO = 33 ++IPV6_FW_GET = 34 ++IPV6_RTHDRDSTOPTS = 35 ++IPV6_RECVPKTINFO = 36 ++IPV6_RECVHOPLIMIT = 37 ++IPV6_RECVRTHDR = 38 ++IPV6_RECVHOPOPTS = 39 ++IPV6_RECVDSTOPTS = 40 ++IPV6_USE_MIN_MTU = 42 ++IPV6_RECVPATHMTU = 43 ++IPV6_PATHMTU = 44 ++IPV6_PKTINFO = 46 ++IPV6_HOPLIMIT = 47 ++IPV6_NEXTHOP = 48 ++IPV6_HOPOPTS = 49 ++IPV6_DSTOPTS = 50 ++IPV6_RTHDR = 51 ++IPV6_RECVTCLASS = 57 ++IPV6_AUTOFLOWLABEL = 59 ++IPV6_TCLASS = 61 ++IPV6_DONTFRAG = 62 ++IPV6_PREFER_TEMPADDR = 63 ++IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP ++IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP ++IPV6_RXHOPOPTS = IPV6_HOPOPTS ++IPV6_RXDSTOPTS = IPV6_DSTOPTS ++SOL_IPV6 = 41 ++SOL_ICMPV6 = 58 ++IPV6_DEFAULT_MULTICAST_HOPS = 1 ++IPV6_DEFAULT_MULTICAST_LOOP = 1 ++IPV6_PORTRANGE_DEFAULT = 0 ++IPV6_PORTRANGE_HIGH = 1 ++IPV6_PORTRANGE_LOW = 2 ++IPV6_RTHDR_LOOSE = 0 ++IPV6_RTHDR_STRICT = 1 ++IPV6_RTHDR_TYPE_0 = 0 ++IPV6CTL_FORWARDING = 1 ++IPV6CTL_SENDREDIRECTS = 2 ++IPV6CTL_DEFHLIM = 3 ++IPV6CTL_FORWSRCRT = 5 ++IPV6CTL_STATS = 6 ++IPV6CTL_MRTSTATS = 7 ++IPV6CTL_MRTPROTO = 8 ++IPV6CTL_MAXFRAGPACKETS = 9 ++IPV6CTL_SOURCECHECK = 10 ++IPV6CTL_SOURCECHECK_LOGINT = 11 ++IPV6CTL_ACCEPT_RTADV = 12 ++IPV6CTL_KEEPFAITH = 13 ++IPV6CTL_LOG_INTERVAL = 14 ++IPV6CTL_HDRNESTLIMIT = 15 ++IPV6CTL_DAD_COUNT = 16 ++IPV6CTL_AUTO_FLOWLABEL = 17 ++IPV6CTL_DEFMCASTHLIM = 18 ++IPV6CTL_GIF_HLIM = 19 ++IPV6CTL_KAME_VERSION = 20 ++IPV6CTL_USE_DEPRECATED = 21 ++IPV6CTL_RR_PRUNE = 22 ++IPV6CTL_V6ONLY = 24 ++IPV6CTL_RTEXPIRE = 25 ++IPV6CTL_RTMINEXPIRE = 26 ++IPV6CTL_RTMAXCACHE = 27 ++IPV6CTL_USETEMPADDR = 32 ++IPV6CTL_TEMPPLTIME = 33 ++IPV6CTL_TEMPVLTIME = 34 ++IPV6CTL_AUTO_LINKLOCAL = 35 ++IPV6CTL_RIP6STATS = 36 ++IPV6CTL_PREFER_TEMPADDR = 37 ++IPV6CTL_ADDRCTLPOLICY = 38 ++IPV6CTL_USE_DEFAULTZONE = 39 ++IPV6CTL_MAXFRAGS = 41 ++IPV6CTL_MCAST_PMTU = 44 ++IPV6CTL_STEALTH = 45 ++ICMPV6CTL_ND6_ONLINKNSRFC4861 = 47 ++IPV6CTL_MAXID = 48 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++def ntohl(x): return (x) ++ ++def ntohs(x): return (x) ++ ++def htonl(x): return (x) ++ ++def htons(x): return (x) ++ ++def ntohl(x): return __bswap_32 (x) ++ ++def ntohs(x): return __bswap_16 (x) ++ ++def htonl(x): return __bswap_32 (x) ++ ++def htons(x): return __bswap_16 (x) ++ ++def IN6_IS_ADDR_UNSPECIFIED(a): return \ ++ ++def IN6_IS_ADDR_LOOPBACK(a): return \ ++ ++def IN6_IS_ADDR_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_V4MAPPED(a): return \ ++ ++def IN6_IS_ADDR_V4COMPAT(a): return \ ++ ++def IN6_IS_ADDR_MC_NODELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_GLOBAL(a): return \ ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/TYPES.py +@@ -0,0 +1,303 @@ ++# Generated by h2py from /usr/include/sys/types.h ++_SYS_TYPES_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++ ++# Included from time.h ++_TIME_H = 1 ++ ++# Included from bits/time.h ++_BITS_TIME_H = 1 ++CLOCKS_PER_SEC = 1000000l ++CLK_TCK = 128 ++CLOCK_REALTIME = 0 ++CLOCK_PROCESS_CPUTIME_ID = 2 ++CLOCK_THREAD_CPUTIME_ID = 3 ++CLOCK_MONOTONIC = 4 ++CLOCK_VIRTUAL = 1 ++CLOCK_PROF = 2 ++CLOCK_UPTIME = 5 ++CLOCK_UPTIME_PRECISE = 7 ++CLOCK_UPTIME_FAST = 8 ++CLOCK_REALTIME_PRECISE = 9 ++CLOCK_REALTIME_FAST = 10 ++CLOCK_MONOTONIC_PRECISE = 11 ++CLOCK_MONOTONIC_FAST = 12 ++CLOCK_SECOND = 13 ++TIMER_RELTIME = 0 ++TIMER_ABSTIME = 1 ++_STRUCT_TIMEVAL = 1 ++CLK_TCK = CLOCKS_PER_SEC ++__clock_t_defined = 1 ++__time_t_defined = 1 ++__clockid_t_defined = 1 ++__timer_t_defined = 1 ++__timespec_defined = 1 ++ ++# Included from xlocale.h ++_XLOCALE_H = 1 ++def __isleap(year): return \ ++ ++__BIT_TYPES_DEFINED__ = 1 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++ ++# Included from sys/select.h ++_SYS_SELECT_H = 1 ++ ++# Included from bits/select.h ++def __FD_ZERO(fdsp): return \ ++ ++def __FD_ZERO(set): return \ ++ ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++def __FDELT(d): return ((d) / __NFDBITS) ++ ++FD_SETSIZE = __FD_SETSIZE ++def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) ++ ++ ++# Included from sys/sysmacros.h ++_SYS_SYSMACROS_H = 1 ++def minor(dev): return ((int)((dev) & (-65281))) ++ ++def gnu_dev_major(dev): return major (dev) ++ ++def gnu_dev_minor(dev): return minor (dev) ++ ++ ++# Included from bits/pthreadtypes.h ++_BITS_PTHREADTYPES_H = 1 ++ ++# Included from bits/sched.h ++SCHED_OTHER = 2 ++SCHED_FIFO = 1 ++SCHED_RR = 3 ++CSIGNAL = 0x000000ff ++CLONE_VM = 0x00000100 ++CLONE_FS = 0x00000200 ++CLONE_FILES = 0x00000400 ++CLONE_SIGHAND = 0x00000800 ++CLONE_PTRACE = 0x00002000 ++CLONE_VFORK = 0x00004000 ++CLONE_SYSVSEM = 0x00040000 ++__defined_schedparam = 1 ++__CPU_SETSIZE = 128 ++def __CPUELT(cpu): return ((cpu) / __NCPUBITS) ++ ++def __CPU_ALLOC_SIZE(count): return \ ++ ++def __CPU_ALLOC(count): return __sched_cpualloc (count) ++ ++def __CPU_FREE(cpuset): return __sched_cpufree (cpuset) ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/DLFCN.py +@@ -0,0 +1,118 @@ ++# Generated by h2py from /usr/include/dlfcn.h ++_DLFCN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/dlfcn.h ++RTLD_LAZY = 0x00001 ++RTLD_NOW = 0x00002 ++RTLD_BINDING_MASK = 0x3 ++RTLD_NOLOAD = 0x00004 ++RTLD_DEEPBIND = 0x00008 ++RTLD_GLOBAL = 0x00100 ++RTLD_LOCAL = 0 ++RTLD_NODELETE = 0x01000 ++LM_ID_BASE = 0 ++LM_ID_NEWLM = -1 --- python2.7-2.7.6.orig/debian/patches/plat-linux2_alpha.diff +++ python2.7-2.7.6/debian/patches/plat-linux2_alpha.diff @@ -0,0 +1,73 @@ +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -436,43 +436,43 @@ + # Included from asm/socket.h + + # Included from asm/sockios.h +-FIOSETOWN = 0x8901 +-SIOCSPGRP = 0x8902 +-FIOGETOWN = 0x8903 +-SIOCGPGRP = 0x8904 +-SIOCATMARK = 0x8905 ++FIOSETOWN = 0x8004667c ++SIOCSPGRP = 0x80047308 ++FIOGETOWN = 0x4004667b ++SIOCGPGRP = 0x40047309 ++SIOCATMARK = 0x40047307 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 + SO_NO_CHECK = 11 + SO_PRIORITY = 12 +-SO_LINGER = 13 ++SO_LINGER = 0x0080 + SO_BSDCOMPAT = 14 + SO_PASSCRED = 16 + SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 +-SO_SECURITY_AUTHENTICATION = 22 +-SO_SECURITY_ENCRYPTION_TRANSPORT = 23 +-SO_SECURITY_ENCRYPTION_NETWORK = 24 ++SO_RCVLOWAT = 0x1010 ++SO_SNDLOWAT = 0x1011 ++SO_RCVTIMEO = 0x1012 ++SO_SNDTIMEO = 0x1013 ++SO_SECURITY_AUTHENTICATION = 19 ++SO_SECURITY_ENCRYPTION_TRANSPORT = 20 ++SO_SECURITY_ENCRYPTION_NETWORK = 21 + SO_BINDTODEVICE = 25 + SO_ATTACH_FILTER = 26 + SO_DETACH_FILTER = 27 + SO_PEERNAME = 28 + SO_TIMESTAMP = 29 + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 ++SO_ACCEPTCONN = 0x1014 + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 --- python2.7-2.7.6.orig/debian/patches/plat-linux2_hppa.diff +++ python2.7-2.7.6/debian/patches/plat-linux2_hppa.diff @@ -0,0 +1,72 @@ +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -442,37 +442,37 @@ + SIOCGPGRP = 0x8904 + SIOCATMARK = 0x8905 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 +-SO_NO_CHECK = 11 +-SO_PRIORITY = 12 +-SO_LINGER = 13 +-SO_BSDCOMPAT = 14 +-SO_PASSCRED = 16 +-SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 +-SO_SECURITY_AUTHENTICATION = 22 +-SO_SECURITY_ENCRYPTION_TRANSPORT = 23 +-SO_SECURITY_ENCRYPTION_NETWORK = 24 +-SO_BINDTODEVICE = 25 +-SO_ATTACH_FILTER = 26 +-SO_DETACH_FILTER = 27 +-SO_PEERNAME = 28 +-SO_TIMESTAMP = 29 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 ++SO_NO_CHECK = 0x400b ++SO_PRIORITY = 0x400c ++SO_LINGER = 0x0080 ++SO_BSDCOMPAT = 0x400e ++SO_PASSCRED = 0x4010 ++SO_PEERCRED = 0x4011 ++SO_RCVLOWAT = 0x1004 ++SO_SNDLOWAT = 0x1003 ++SO_RCVTIMEO = 0x1006 ++SO_SNDTIMEO = 0x1005 ++SO_SECURITY_AUTHENTICATION = 0x4016 ++SO_SECURITY_ENCRYPTION_TRANSPORT = 0x4017 ++SO_SECURITY_ENCRYPTION_NETWORK = 0x4018 ++SO_BINDTODEVICE = 0x4019 ++SO_ATTACH_FILTER = 0x401a ++SO_DETACH_FILTER = 0x401b ++SO_PEERNAME = 0x2000 ++SO_TIMESTAMP = 0x4012 + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 ++SO_ACCEPTCONN = 0x401c + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 --- python2.7-2.7.6.orig/debian/patches/plat-linux2_mips.diff +++ python2.7-2.7.6/debian/patches/plat-linux2_mips.diff @@ -0,0 +1,88 @@ +Index: Lib/plat-linux2/DLFCN.py +=================================================================== +--- ./Lib/plat-linux2/DLFCN.py (Revision 77754) ++++ ./Lib/plat-linux2/DLFCN.py (Arbeitskopie) +@@ -77,7 +77,7 @@ + RTLD_LAZY = 0x00001 + RTLD_NOW = 0x00002 + RTLD_BINDING_MASK = 0x3 +-RTLD_NOLOAD = 0x00004 +-RTLD_GLOBAL = 0x00100 ++RTLD_NOLOAD = 0x00008 ++RTLD_GLOBAL = 0x00004 + RTLD_LOCAL = 0 + RTLD_NODELETE = 0x01000 +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -436,33 +436,33 @@ + # Included from asm/socket.h + + # Included from asm/sockios.h +-FIOSETOWN = 0x8901 +-SIOCSPGRP = 0x8902 +-FIOGETOWN = 0x8903 +-SIOCGPGRP = 0x8904 +-SIOCATMARK = 0x8905 ++FIOSETOWN = 0x8004667c ++SIOCSPGRP = 0x80047308 ++FIOGETOWN = 0x4004667b ++SIOCGPGRP = 0x40047309 ++SIOCATMARK = 0x40047307 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 + SO_NO_CHECK = 11 + SO_PRIORITY = 12 +-SO_LINGER = 13 ++SO_LINGER = 0x0080 + SO_BSDCOMPAT = 14 +-SO_PASSCRED = 16 +-SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 ++SO_PASSCRED = 17 ++SO_PEERCRED = 18 ++SO_RCVLOWAT = 0x1004 ++SO_SNDLOWAT = 0x1003 ++SO_RCVTIMEO = 0x1006 ++SO_SNDTIMEO = 0x1005 + SO_SECURITY_AUTHENTICATION = 22 + SO_SECURITY_ENCRYPTION_TRANSPORT = 23 + SO_SECURITY_ENCRYPTION_NETWORK = 24 +@@ -472,9 +472,9 @@ + SO_PEERNAME = 28 + SO_TIMESTAMP = 29 + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 +-SOCK_STREAM = 1 +-SOCK_DGRAM = 2 ++SO_ACCEPTCONN = 0x1009 ++SOCK_STREAM = 2 ++SOCK_DGRAM = 1 + SOCK_RAW = 3 + SOCK_RDM = 4 + SOCK_SEQPACKET = 5 --- python2.7-2.7.6.orig/debian/patches/plat-linux2_sparc.diff +++ python2.7-2.7.6/debian/patches/plat-linux2_sparc.diff @@ -0,0 +1,72 @@ +Index: Lib/plat-linux2/IN.py +=================================================================== +--- ./Lib/plat-linux2/IN.py (Revision 77754) ++++ ./Lib/plat-linux2/IN.py (Arbeitskopie) +@@ -442,37 +442,37 @@ + SIOCGPGRP = 0x8904 + SIOCATMARK = 0x8905 + SIOCGSTAMP = 0x8906 +-SOL_SOCKET = 1 +-SO_DEBUG = 1 +-SO_REUSEADDR = 2 +-SO_TYPE = 3 +-SO_ERROR = 4 +-SO_DONTROUTE = 5 +-SO_BROADCAST = 6 +-SO_SNDBUF = 7 +-SO_RCVBUF = 8 +-SO_KEEPALIVE = 9 +-SO_OOBINLINE = 10 +-SO_NO_CHECK = 11 +-SO_PRIORITY = 12 +-SO_LINGER = 13 +-SO_BSDCOMPAT = 14 +-SO_PASSCRED = 16 +-SO_PEERCRED = 17 +-SO_RCVLOWAT = 18 +-SO_SNDLOWAT = 19 +-SO_RCVTIMEO = 20 +-SO_SNDTIMEO = 21 +-SO_SECURITY_AUTHENTICATION = 22 +-SO_SECURITY_ENCRYPTION_TRANSPORT = 23 +-SO_SECURITY_ENCRYPTION_NETWORK = 24 +-SO_BINDTODEVICE = 25 +-SO_ATTACH_FILTER = 26 +-SO_DETACH_FILTER = 27 +-SO_PEERNAME = 28 +-SO_TIMESTAMP = 29 ++SOL_SOCKET = 0xffff ++SO_DEBUG = 0x0001 ++SO_REUSEADDR = 0x0004 ++SO_TYPE = 0x1008 ++SO_ERROR = 0x1007 ++SO_DONTROUTE = 0x0010 ++SO_BROADCAST = 0x0020 ++SO_SNDBUF = 0x1001 ++SO_RCVBUF = 0x1002 ++SO_KEEPALIVE = 0x0008 ++SO_OOBINLINE = 0x0100 ++SO_NO_CHECK = 0x000b ++SO_PRIORITY = 0x000c ++SO_LINGER = 0x0080 ++SO_BSDCOMPAT = 0x0400 ++SO_PASSCRED = 0x0002 ++SO_PEERCRED = 0x0040 ++SO_RCVLOWAT = 0x0800 ++SO_SNDLOWAT = 0x1000 ++SO_RCVTIMEO = 0x2000 ++SO_SNDTIMEO = 0x4000 ++SO_SECURITY_AUTHENTICATION = 0x5001 ++SO_SECURITY_ENCRYPTION_TRANSPORT = 0x5002 ++SO_SECURITY_ENCRYPTION_NETWORK = 0x5004 ++SO_BINDTODEVICE = 0x000d ++SO_ATTACH_FILTER = 0x001a ++SO_DETACH_FILTER = 0x001b ++SO_PEERNAME = 0x001c ++SO_TIMESTAMP = 0x001d + SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 ++SO_ACCEPTCONN = 0x8000 + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 --- python2.7-2.7.6.orig/debian/patches/platform-lsbrelease.diff +++ python2.7-2.7.6/debian/patches/platform-lsbrelease.diff @@ -0,0 +1,50 @@ +# DP: Use /etc/lsb-release to identify the platform. + +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -259,7 +259,7 @@ + _supported_dists = ( + 'SuSE', 'debian', 'fedora', 'redhat', 'centos', + 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', +- 'UnitedLinux', 'turbolinux') ++ 'UnitedLinux', 'turbolinux', 'Ubuntu') + + def _parse_release_file(firstline): + +@@ -288,6 +288,10 @@ + id = l[1] + return '', version, id + ++_distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I) ++_release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I) ++_codename_file_re = re.compile("(?:DISTRIB_CODENAME\s*=)\s*(.*)", re.I) ++ + def linux_distribution(distname='', version='', id='', + + supported_dists=_supported_dists, +@@ -312,6 +316,25 @@ + args given as parameters. + + """ ++ # check for the LSB /etc/lsb-release file first, needed so ++ # that the distribution doesn't get identified as Debian. ++ try: ++ with open("/etc/lsb-release", "rU") as etclsbrel: ++ for line in etclsbrel: ++ m = _distributor_id_file_re.search(line) ++ if m: ++ _u_distname = m.group(1).strip() ++ m = _release_file_re.search(line) ++ if m: ++ _u_version = m.group(1).strip() ++ m = _codename_file_re.search(line) ++ if m: ++ _u_id = m.group(1).strip() ++ if _u_distname and _u_version: ++ return (_u_distname, _u_version, _u_id) ++ except (EnvironmentError, UnboundLocalError): ++ pass ++ + try: + etc = os.listdir('/etc') + except os.error: --- python2.7-2.7.6.orig/debian/patches/profiled-build.diff +++ python2.7-2.7.6/debian/patches/profiled-build.diff @@ -0,0 +1,28 @@ +# DP: Fix profiled build; don't use Python/thread.gc*, gcc complains + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -428,19 +428,19 @@ + $(MAKE) build_all_use_profile + + build_all_generate_profile: +- $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" ++ $(MAKE) all PY_CFLAGS="$(PY_CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" + + run_profile_task: + : # FIXME: can't run for a cross build +- ./$(BUILDPYTHON) $(PROFILE_TASK) ++ -./$(BUILDPYTHON) $(PROFILE_TASK) + + build_all_use_profile: +- $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" ++ $(MAKE) all PY_CFLAGS="$(PY_CFLAGS) -fprofile-use -fprofile-correction" + + coverage: + @echo "Building with support for coverage checking:" + $(MAKE) clean +- $(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov" ++ $(MAKE) all PY_CFLAGS="$(PY_CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov" + + + # Build the interpreter --- python2.7-2.7.6.orig/debian/patches/revert-unittest-loader-symlinks19352.diff +++ python2.7-2.7.6/debian/patches/revert-unittest-loader-symlinks19352.diff @@ -0,0 +1,64 @@ +Description: DP: Revert patch from http://bugs.python.org/issue19352 as it completely breaks unittest discovery on Debian/Ubuntu +Bug-Ubuntu: https://launchpad.net/bugs/1255505 + +--- a/Lib/unittest/loader.py ++++ b/Lib/unittest/loader.py +@@ -256,8 +256,8 @@ + yield _make_failed_import_test(name, self.suiteClass) + else: + mod_file = os.path.abspath(getattr(module, '__file__', full_path)) +- realpath = os.path.splitext(os.path.realpath(mod_file))[0] +- fullpath_noext = os.path.splitext(os.path.realpath(full_path))[0] ++ realpath = os.path.splitext(mod_file)[0] ++ fullpath_noext = os.path.splitext(full_path)[0] + if realpath.lower() != fullpath_noext.lower(): + module_dir = os.path.dirname(realpath) + mod_name = os.path.splitext(os.path.basename(full_path))[0] +--- a/Lib/unittest/test/test_discovery.py 2013-11-28 17:29:32.092312004 +0100 ++++ b/Lib/unittest/test/test_discovery.py 2013-11-28 17:29:49.224311629 +0100 +@@ -314,7 +314,7 @@ + self.assertTrue(program.failfast) + self.assertTrue(program.catchbreak) + +- def setup_module_clash(self): ++ def test_detect_module_clash(self): + class Module(object): + __file__ = 'bar/foo.py' + sys.modules['foo'] = Module +@@ -341,10 +341,7 @@ + os.listdir = listdir + os.path.isfile = isfile + os.path.isdir = isdir +- return full_path + +- def test_detect_module_clash(self): +- full_path = self.setup_module_clash() + loader = unittest.TestLoader() + + mod_dir = os.path.abspath('bar') +@@ -357,25 +354,6 @@ + ) + self.assertEqual(sys.path[0], full_path) + +- def test_module_symlink_ok(self): +- full_path = self.setup_module_clash() +- +- original_realpath = os.path.realpath +- +- mod_dir = os.path.abspath('bar') +- expected_dir = os.path.abspath('foo') +- +- def cleanup(): +- os.path.realpath = original_realpath +- self.addCleanup(cleanup) +- +- def realpath(path): +- if path == os.path.join(mod_dir, 'foo.py'): +- return os.path.join(expected_dir, 'foo.py') +- return path +- os.path.realpath = realpath +- loader = unittest.TestLoader() +- loader.discover(start_dir='foo', pattern='foo.py') + + def test_discovery_from_dotted_path(self): + loader = unittest.TestLoader() --- python2.7-2.7.6.orig/debian/patches/series.in +++ python2.7-2.7.6/debian/patches/series.in @@ -0,0 +1,82 @@ +hg-updates.diff +issue9189.diff +build-libpython.diff +deb-setup.diff +deb-locations.diff +site-locations.diff +distutils-install-layout.diff +locale-module.diff +distutils-link.diff +distutils-sysconfig.diff +test-sundry.diff +tkinter-import.diff +link-opt.diff +debug-build.diff +hotshot-import.diff +linecache.diff +doc-nodownload.diff +profiled-build.diff +no-zip-on-sys.path.diff +platform-lsbrelease.diff +bdist-wininst-notfound.diff +setup-modules-ssl.diff +makesetup-bashism.diff +hurd-disable-nonworking-constants.diff +#ifdef WITH_FPECTL +enable-fpectl.diff +#endif +statvfs-f_flag-constants.diff +#if defined (arch_alpha) +plat-linux2_alpha.diff +#elif defined (arch_hppa) +plat-linux2_hppa.diff +#elif defined (arch_mips) || defined(arch_mipsel) +plat-linux2_mips.diff +#elif defined (arch_sparc) || defined (arch_sparc64) +plat-linux2_sparc.diff +#endif +#if defined (BROKEN_UTIMES) +disable-utimes.diff +#endif +#if defined (Ubuntu) +langpack-gettext.diff +#endif +#if defined (arch_os_hurd) +no-large-file-support.diff +cthreads.diff +#endif +issue9012a.diff +link-system-expat.diff +plat-gnukfreebsd.diff +link-whole-archive.diff +bsddb-libpath.diff +disable-sem-check.diff +ncursesw-incdir.diff +ctypes-arm.diff +lto-link-flags.diff +do-not-italicize-punctuation.patch +multiarch.diff +lib2to3-no-pickled-grammar.diff +add-python-config-sh.diff +ssl.match_hostname.diff +ext-no-libpython-link.diff +build-hash.diff +libffi-shared.diff +atomic-pyc-rename.diff +revert-unittest-loader-symlinks19352.diff +sphinx-no-refcounting.diff +enable-sqlite-loadext.diff +CVE-2013-1752-httplib-2.patch +CVE-2013-1752-poplib.patch +CVE-2013-1752-smtplib.patch +CVE-2013-1753.patch +CVE-2014-4616.patch +CVE-2014-4650.patch +CVE-2014-7185.patch +CVE-2016-0772.patch +CVE-2016-1000110-pre.patch +CVE-2016-1000110.patch +CVE-2016-5636-pre.patch +CVE-2016-5636.patch +CVE-2016-5699.patch +CVE-2017-1000158.patch --- python2.7-2.7.6.orig/debian/patches/setup-modules-ssl.diff +++ python2.7-2.7.6/debian/patches/setup-modules-ssl.diff @@ -0,0 +1,24 @@ +# DP: Modules/Setup.dist: patch to build _hashlib and _ssl extensions statically + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -215,10 +215,7 @@ + + # Socket module helper for SSL support; you must comment out the other + # socket line above, and possibly edit the SSL variable: +-#SSL=/usr/local/ssl +-#_ssl _ssl.c \ +-# -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ +-# -L$(SSL)/lib -lssl -lcrypto ++#_ssl _ssl.c -lssl -lcrypto + + # The crypt module is now disabled by default because it breaks builds + # on many systems (where -lcrypt is needed), e.g. Linux (I believe). +@@ -261,6 +258,7 @@ + #_sha256 sha256module.c + #_sha512 sha512module.c + ++#_hashlib _hashopenssl.c -lssl -lcrypto + + # SGI IRIX specific modules -- off by default. + --- python2.7-2.7.6.orig/debian/patches/site-locations.diff +++ python2.7-2.7.6/debian/patches/site-locations.diff @@ -0,0 +1,32 @@ +# DP: Set site-packages/dist-packages + +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -19,6 +19,12 @@ + resulting directories, if they exist, are appended to sys.path, and + also inspected for path configuration files. + ++For Debian and derivatives, this sys.path is augmented with directories ++for packages distributed within the distribution. Local addons go ++into /usr/local/lib/python/dist-packages, Debian addons ++install into /usr/{lib,share}/python/dist-packages. ++/usr/lib/python/site-packages is not used. ++ + A path configuration file is a file whose name has the form + .pth; its contents are additional directories (one per line) + to be added to sys.path. Non-existing directories (or +@@ -288,10 +294,12 @@ + if sys.platform in ('os2emx', 'riscos'): + sitepackages.append(os.path.join(prefix, "Lib", "site-packages")) + elif os.sep == '/': ++ sitepackages.append(os.path.join(prefix, "local/lib", ++ "python" + sys.version[:3], ++ "dist-packages")) + sitepackages.append(os.path.join(prefix, "lib", + "python" + sys.version[:3], +- "site-packages")) +- sitepackages.append(os.path.join(prefix, "lib", "site-python")) ++ "dist-packages")) + else: + sitepackages.append(prefix) + sitepackages.append(os.path.join(prefix, "lib", "site-packages")) --- python2.7-2.7.6.orig/debian/patches/sphinx-no-refcounting.diff +++ python2.7-2.7.6/debian/patches/sphinx-no-refcounting.diff @@ -0,0 +1,15 @@ +# DP: Use the included sphinx refcounting extension. + +Index: b/Doc/conf.py +=================================================================== +--- a/Doc/conf.py ++++ b/Doc/conf.py +@@ -13,7 +13,7 @@ + # General configuration + # --------------------- + +-extensions = ['sphinx.ext.refcounting', 'sphinx.ext.coverage', ++extensions = ['sphinx.ext.coverage', + 'sphinx.ext.doctest', 'pyspecific'] + templates_path = ['tools/sphinxext'] + --- python2.7-2.7.6.orig/debian/patches/ssl.match_hostname.diff +++ python2.7-2.7.6/debian/patches/ssl.match_hostname.diff @@ -0,0 +1,147 @@ +Index: b/Lib/ssl.py +=================================================================== +--- a/Lib/ssl.py ++++ b/Lib/ssl.py +@@ -56,6 +56,7 @@ + """ + + import textwrap ++import re + + import _ssl # if we can't import it, let the error propagate + +@@ -97,6 +98,100 @@ + # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') + _DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2' + ++class CertificateError(ValueError): ++ pass ++ ++ ++def _dnsname_match(dn, hostname, max_wildcards=1): ++ """Matching according to RFC 6125, section 6.4.3 ++ ++ http://tools.ietf.org/html/rfc6125#section-6.4.3 ++ """ ++ pats = [] ++ if not dn: ++ return False ++ ++ dn_split = dn.split(r'.') ++ leftmost = dn_split[0] ++ remainder = dn_split[1:] ++ ++ wildcards = leftmost.count('*') ++ if wildcards > max_wildcards: ++ # Issue #17980: avoid denials of service by refusing more ++ # than one wildcard per fragment. A survery of established ++ # policy among SSL implementations showed it to be a ++ # reasonable choice. ++ raise CertificateError( ++ "too many wildcards in certificate DNS name: " + repr(dn)) ++ ++ # speed up common case w/o wildcards ++ if not wildcards: ++ return dn.lower() == hostname.lower() ++ ++ # RFC 6125, section 6.4.3, subitem 1. ++ # The client SHOULD NOT attempt to match a presented identifier in which ++ # the wildcard character comprises a label other than the left-most label. ++ if leftmost == '*': ++ # When '*' is a fragment by itself, it matches a non-empty dotless ++ # fragment. ++ pats.append('[^.]+') ++ elif leftmost.startswith('xn--') or hostname.startswith('xn--'): ++ # RFC 6125, section 6.4.3, subitem 3. ++ # The client SHOULD NOT attempt to match a presented identifier ++ # where the wildcard character is embedded within an A-label or ++ # U-label of an internationalized domain name. ++ pats.append(re.escape(leftmost)) ++ else: ++ # Otherwise, '*' matches any dotless string, e.g. www* ++ pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) ++ ++ # add the remaining fragments, ignore any wildcards ++ for frag in remainder: ++ pats.append(re.escape(frag)) ++ ++ pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) ++ return pat.match(hostname) ++ ++ ++def match_hostname(cert, hostname): ++ """Verify that *cert* (in decoded format as returned by ++ SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 ++ rules are followed, but IP addresses are not accepted for *hostname*. ++ ++ CertificateError is raised on failure. On success, the function ++ returns nothing. ++ """ ++ if not cert: ++ raise ValueError("empty or no certificate") ++ dnsnames = [] ++ san = cert.get('subjectAltName', ()) ++ for key, value in san: ++ if key == 'DNS': ++ if _dnsname_match(value, hostname): ++ return ++ dnsnames.append(value) ++ if not dnsnames: ++ # The subject is only checked when there is no dNSName entry ++ # in subjectAltName ++ for sub in cert.get('subject', ()): ++ for key, value in sub: ++ # XXX according to RFC 2818, the most specific Common Name ++ # must be used. ++ if key == 'commonName': ++ if _dnsname_match(value, hostname): ++ return ++ dnsnames.append(value) ++ if len(dnsnames) > 1: ++ raise CertificateError("hostname %r " ++ "doesn't match either of %s" ++ % (hostname, ', '.join(map(repr, dnsnames)))) ++ elif len(dnsnames) == 1: ++ raise CertificateError("hostname %r " ++ "doesn't match %r" ++ % (hostname, dnsnames[0])) ++ else: ++ raise CertificateError("no appropriate commonName or " ++ "subjectAltName fields were found") + + class SSLSocket(socket): + +Index: b/Doc/library/ssl.rst +=================================================================== +--- a/Doc/library/ssl.rst ++++ b/Doc/library/ssl.rst +@@ -536,6 +536,29 @@ + certificate, and no one else will have it in their cache of known (and trusted) + root certificates. + ++.. function:: match_hostname(cert, hostname) ++ ++ Verify that *cert* (in decoded format as returned by ++ :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules ++ applied are those for checking the identity of HTTPS servers as outlined ++ in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently ++ supported. In addition to HTTPS, this function should be suitable for ++ checking the identity of servers in various SSL-based protocols such as ++ FTPS, IMAPS, POPS and others. ++ ++ :exc:`CertificateError` is raised on failure. On success, the function ++ returns nothing:: ++ ++ >>> cert = {'subject': ((('commonName', 'example.com'),),)} ++ >>> ssl.match_hostname(cert, "example.com") ++ >>> ssl.match_hostname(cert, "example.org") ++ Traceback (most recent call last): ++ File "", line 1, in ++ File "/home/py3k/Lib/ssl.py", line 130, in match_hostname ++ ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' ++ ++ Not part of the 2.7 upstream releases. Backported for Debian/Ubuntu. ++ + + Examples + -------- --- python2.7-2.7.6.orig/debian/patches/statvfs-f_flag-constants.diff +++ python2.7-2.7.6/debian/patches/statvfs-f_flag-constants.diff @@ -0,0 +1,57 @@ +From 21fda4c78000d78cb1824fdf0373031d07f5325a Mon Sep 17 00:00:00 2001 +From: Peter Jones +Date: Wed, 6 Jan 2010 15:22:38 -0500 +Subject: [PATCH] Add flags for statvfs.f_flag to constant list. + +You really need these to figure out what statvfs is trying to say to +you, so add them here. +--- + Modules/posixmodule.c | 37 +++++++++++++++++++++++++++++++++++++ + 1 files changed, 37 insertions(+), 0 deletions(-) + +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9326,6 +9326,43 @@ + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + #endif /* EX_NOTFOUND */ + ++ /* These came from statvfs.h */ ++#ifdef ST_RDONLY ++ if (ins(d, "ST_RDONLY", (long)ST_RDONLY)) return -1; ++#endif /* ST_RDONLY */ ++#ifdef ST_NOSUID ++ if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1; ++#endif /* ST_NOSUID */ ++ ++ /* GNU extensions */ ++#ifdef ST_NODEV ++ if (ins(d, "ST_NODEV", (long)ST_NODEV)) return -1; ++#endif /* ST_NODEV */ ++#ifdef ST_NOEXEC ++ if (ins(d, "ST_NOEXEC", (long)ST_NOEXEC)) return -1; ++#endif /* ST_NOEXEC */ ++#ifdef ST_SYNCHRONOUS ++ if (ins(d, "ST_SYNCHRONOUS", (long)ST_SYNCHRONOUS)) return -1; ++#endif /* ST_SYNCHRONOUS */ ++#ifdef ST_MANDLOCK ++ if (ins(d, "ST_MANDLOCK", (long)ST_MANDLOCK)) return -1; ++#endif /* ST_MANDLOCK */ ++#ifdef ST_WRITE ++ if (ins(d, "ST_WRITE", (long)ST_WRITE)) return -1; ++#endif /* ST_WRITE */ ++#ifdef ST_APPEND ++ if (ins(d, "ST_APPEND", (long)ST_APPEND)) return -1; ++#endif /* ST_APPEND */ ++#ifdef ST_NOATIME ++ if (ins(d, "ST_NOATIME", (long)ST_NOATIME)) return -1; ++#endif /* ST_NOATIME */ ++#ifdef ST_NODIRATIME ++ if (ins(d, "ST_NODIRATIME", (long)ST_NODIRATIME)) return -1; ++#endif /* ST_NODIRATIME */ ++#ifdef ST_RELATIME ++ if (ins(d, "ST_RELATIME", (long)ST_RELATIME)) return -1; ++#endif /* ST_RELATIME */ ++ + #ifdef HAVE_SPAWNV + #if defined(PYOS_OS2) && defined(PYCC_GCC) + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; --- python2.7-2.7.6.orig/debian/patches/sys-multiarch.diff +++ python2.7-2.7.6/debian/patches/sys-multiarch.diff @@ -0,0 +1,25 @@ +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -1357,6 +1357,11 @@ + + Python/thread.o: @THREADHEADERS@ + ++Python/sysmodule.o: $(srcdir)/Python/sysmodule.c Makefile ++ $(CC) -c $(PY_CORE_CFLAGS) \ ++ -DMULTIARCH='"$(MULTIARCH)"' \ ++ -o $@ $(srcdir)/Python/sysmodule.c ++ + # Declare targets that aren't real files + .PHONY: all build_all sharedmods oldsharedmods test quicktest memtest + .PHONY: install altinstall oldsharedinstall bininstall altbininstall +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1435,6 +1435,8 @@ + PyFloat_GetInfo()); + SET_SYS_FROM_STRING("long_info", + PyLong_GetInfo()); ++ SET_SYS_FROM_STRING("_multiarch", ++ PyString_FromString(MULTIARCH)); + #ifdef Py_USING_UNICODE + SET_SYS_FROM_STRING("maxunicode", + PyInt_FromLong(PyUnicode_GetMax())); --- python2.7-2.7.6.orig/debian/patches/test-sundry.diff +++ python2.7-2.7.6/debian/patches/test-sundry.diff @@ -0,0 +1,17 @@ +# DP: test_sundry: Don't fail on import of the profile and pstats module + +--- a/Lib/test/test_sundry.py ++++ b/Lib/test/test_sundry.py +@@ -61,7 +61,11 @@ + import os2emxpath + import pdb + import posixfile +- import pstats ++ try: ++ import pstats # separated out into the python-profiler package ++ except ImportError: ++ if test_support.verbose: ++ print "skipping profile and pstats" + import py_compile + import rexec + import sched --- python2.7-2.7.6.orig/debian/patches/tkinter-import.diff +++ python2.7-2.7.6/debian/patches/tkinter-import.diff @@ -0,0 +1,16 @@ +# DP: suggest installation of python-tk package on failing _tkinter import + +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -36,7 +36,10 @@ + if sys.platform == "win32": + # Attempt to configure Tcl/Tk without requiring PATH + import FixTk +-import _tkinter # If this fails your Python may not be configured for Tk ++try: ++ import _tkinter ++except ImportError, msg: ++ raise ImportError, str(msg) + ', please install the python-tk package' + tkinter = _tkinter # b/w compat for export + TclError = _tkinter.TclError + from types import * --- python2.7-2.7.6.orig/debian/pdb.1.in +++ python2.7-2.7.6/debian/pdb.1.in @@ -0,0 +1,16 @@ +.TH PDB@VER@ 1 +.SH NAME +pdb@VER@ \- the Python debugger +.SH SYNOPSIS +.PP +.B pdb@VER@ +.I script [...] +.SH DESCRIPTION +.PP +See /usr/lib/python@VER@/pdb.doc for more information on the use +of pdb. When the debugger is started, help is available via the +help command. +.SH SEE ALSO +python@VER@(1). Chapter 9 of the Python Library Reference +(The Python Debugger). Available in the python@VER@-doc package at +/usr/share/doc/python@VER@/html/lib/module-pdb.html. --- python2.7-2.7.6.orig/debian/pydoc.1.in +++ python2.7-2.7.6/debian/pydoc.1.in @@ -0,0 +1,53 @@ +.TH PYDOC@VER@ 1 +.SH NAME +pydoc@VER@ \- the Python documentation tool +.SH SYNOPSIS +.PP +.B pydoc@VER@ +.I name +.PP +.B pydoc@VER@ -k +.I keyword +.PP +.B pydoc@VER@ -p +.I port +.PP +.B pydoc@VER@ -g +.PP +.B pydoc@VER@ -w +.I module [...] +.SH DESCRIPTION +.PP +.B pydoc@VER@ +.I name +Show text documentation on something. +.I name +may be the name of a +Python keyword, topic, function, module, or package, or a dotted +reference to a class or function within a module or module in a +package. If +.I name +contains a '/', it is used as the path to a +Python source file to document. If name is 'keywords', 'topics', +or 'modules', a listing of these things is displayed. +.PP +.B pydoc@VER@ -k +.I keyword +Search for a keyword in the synopsis lines of all available modules. +.PP +.B pydoc@VER@ -p +.I port +Start an HTTP server on the given port on the local machine. +.PP +.B pydoc@VER@ -g +Pop up a graphical interface for finding and serving documentation. +.PP +.B pydoc@VER@ -w +.I name [...] +Write out the HTML documentation for a module to a file in the current +directory. If +.I name +contains a '/', it is treated as a filename; if +it names a directory, documentation is written for all the contents. +.SH AUTHOR +Moshe Zadka, based on "pydoc --help" --- python2.7-2.7.6.orig/debian/pygettext.1 +++ python2.7-2.7.6/debian/pygettext.1 @@ -0,0 +1,108 @@ +.TH PYGETTEXT 1 "" "pygettext 1.4" +.SH NAME +pygettext \- Python equivalent of xgettext(1) +.SH SYNOPSIS +.B pygettext +[\fIOPTIONS\fR] \fIINPUTFILE \fR... +.SH DESCRIPTION +pygettext is deprecated. The current version of xgettext supports +many languages, including Python. + +pygettext uses Python's standard tokenize module to scan Python +source code, generating .pot files identical to what GNU xgettext generates +for C and C++ code. From there, the standard GNU tools can be used. +.PP +pygettext searches only for _() by default, even though GNU xgettext +recognizes the following keywords: gettext, dgettext, dcgettext, +and gettext_noop. See the \fB\-k\fR/\fB\--keyword\fR flag below for how to +augment this. +.PP +.SH OPTIONS +.TP +\fB\-a\fR, \fB\-\-extract\-all\fR +Extract all strings. +.TP +\fB\-d\fR, \fB\-\-default\-domain\fR=\fINAME\fR +Rename the default output file from messages.pot to name.pot. +.TP +\fB\-E\fR, \fB\-\-escape\fR +Replace non-ASCII characters with octal escape sequences. +.TP +\fB\-D\fR, \fB\-\-docstrings\fR +Extract module, class, method, and function docstrings. +These do not need to be wrapped in _() markers, and in fact cannot +be for Python to consider them docstrings. (See also the \fB\-X\fR option). +.TP +\fB\-h\fR, \fB\-\-help\fR +Print this help message and exit. +.TP +\fB\-k\fR, \fB\-\-keyword\fR=\fIWORD\fR +Keywords to look for in addition to the default set, which are: _ +.IP +You can have multiple \fB\-k\fR flags on the command line. +.TP +\fB\-K\fR, \fB\-\-no\-default\-keywords\fR +Disable the default set of keywords (see above). +Any keywords explicitly added with the \fB\-k\fR/\fB\--keyword\fR option +are still recognized. +.TP +\fB\-\-no\-location\fR +Do not write filename/lineno location comments. +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +Write filename/lineno location comments indicating where each +extracted string is found in the source. These lines appear before +each msgid. The style of comments is controlled by the +\fB\-S\fR/\fB\--style\fR option. This is the default. +.TP +\fB\-o\fR, \fB\-\-output\fR=\fIFILENAME\fR +Rename the default output file from messages.pot to FILENAME. +If FILENAME is `-' then the output is sent to standard out. +.TP +\fB\-p\fR, \fB\-\-output\-dir\fR=\fIDIR\fR +Output files will be placed in directory DIR. +.TP +\fB\-S\fR, \fB\-\-style\fR=\fISTYLENAME\fR +Specify which style to use for location comments. +Two styles are supported: +.RS +.IP \(bu 4 +Solaris # File: filename, line: line-number +.IP \(bu 4 +GNU #: filename:line +.RE +.IP +The style name is case insensitive. +GNU style is the default. +.TP +\fB\-v\fR, \fB\-\-verbose\fR +Print the names of the files being processed. +.TP +\fB\-V\fR, \fB\-\-version\fR +Print the version of pygettext and exit. +.TP +\fB\-w\fR, \fB\-\-width\fR=\fICOLUMNS\fR +Set width of output to columns. +.TP +\fB\-x\fR, \fB\-\-exclude\-file\fR=\fIFILENAME\fR +Specify a file that contains a list of strings that are not be +extracted from the input files. Each string to be excluded must +appear on a line by itself in the file. +.TP +\fB\-X\fR, \fB\-\-no\-docstrings\fR=\fIFILENAME\fR +Specify a file that contains a list of files (one per line) that +should not have their docstrings extracted. This is only useful in +conjunction with the \fB\-D\fR option above. +.PP +If `INPUTFILE' is -, standard input is read. +.SH BUGS +pygettext attempts to be option and feature compatible with GNU xgettext +where ever possible. However some options are still missing or are not fully +implemented. Also, xgettext's use of command line switches with option +arguments is broken, and in these cases, pygettext just defines additional +switches. +.SH AUTHOR +pygettext is written by Barry Warsaw . +.PP +Joonas Paalasmaa put this manual page together +based on "pygettext --help". --- python2.7-2.7.6.orig/debian/pyhtml2devhelp.py +++ python2.7-2.7.6/debian/pyhtml2devhelp.py @@ -0,0 +1,222 @@ +#! /usr/bin/python + +import formatter, htmllib +import os, sys, re + +class PyHTMLParser(htmllib.HTMLParser): + pages_to_include = set(('whatsnew/index.html', 'tutorial/index.html', 'using/index.html', + 'reference/index.html', 'library/index.html', 'howto/index.html', + 'extending/index.html', 'c-api/index.html', 'install/index.html', + 'distutils/index.html')) + + def __init__(self, formatter, basedir, fn, indent, parents=set()): + htmllib.HTMLParser.__init__(self, formatter) + self.basedir = basedir + self.dir, self.fn = os.path.split(fn) + self.data = '' + self.parents = parents + self.link = {} + self.indent = indent + self.last_indent = indent - 1 + self.sub_indent = 0 + self.sub_count = 0 + self.next_link = False + + def process_link(self): + new_href = os.path.join(self.dir, self.link['href']) + text = self.link['text'] + indent = self.indent + self.sub_indent + if self.last_indent == indent: + print '%s' % (' ' * self.last_indent) + self.sub_count -= 1 + print '%s' % (' ' * indent, new_href, text) + self.sub_count += 1 + self.last_indent = self.indent + self.sub_indent + + def start_li(self, attrs): + self.sub_indent += 1 + self.next_link = True + + def end_li(self): + indent = self.indent + self.sub_indent + if self.sub_count > 0: + print '%s' % (' ' * self.last_indent) + self.sub_count -= 1 + self.last_indent -= 1 + self.sub_indent -= 1 + + def start_a(self, attrs): + self.link = {} + for attr in attrs: + self.link[attr[0]] = attr[1] + self.data = '' + + def end_a(self): + process = False + text = self.data.replace('\t', '').replace('\n', ' ').replace('&', '&').replace('<', '<').replace('>', '>') + self.link['text'] = text + # handle a tag without href attribute + try: + href = self.link['href'] + except KeyError: + return + + abs_href = os.path.join(self.basedir, href) + if abs_href in self.parents: + return + if href.startswith('..') or href.startswith('http:') \ + or href.startswith('mailto:') or href.startswith('news:'): + return + if href in ('', 'about.html', 'modindex.html', 'genindex.html', 'glossary.html', + 'search.html', 'contents.html', 'download.html', 'bugs.html', + 'license.html', 'copyright.html'): + return + + if self.link.has_key('class'): + if self.link['class'] in ('biglink'): + process = True + if self.link['class'] in ('reference external'): + if self.next_link: + process = True + next_link = False + + if process == True: + self.process_link() + if href in self.pages_to_include: + self.parse_file(os.path.join(self.dir, href)) + + def finish(self): + if self.sub_count > 0: + print '%s' % (' ' * self.last_indent) + + def handle_data(self, data): + self.data += data + + def parse_file(self, href): + # TODO basedir bestimmen + parent = os.path.join(self.basedir, self.fn) + self.parents.add(parent) + parser = PyHTMLParser(formatter.NullFormatter(), + self.basedir, href, self.indent + 1, + self.parents) + text = file(self.basedir + '/' + href).read() + parser.feed(text) + parser.finish() + parser.close() + if parent in self.parents: + self.parents.remove(parent) + +class PyIdxHTMLParser(htmllib.HTMLParser): + def __init__(self, formatter, basedir, fn, indent): + htmllib.HTMLParser.__init__(self, formatter) + self.basedir = basedir + self.dir, self.fn = os.path.split(fn) + self.data = '' + self.link = {} + self.indent = indent + self.active = False + self.indented = False + self.nolink = False + self.header = '' + self.last_letter = 'Z' + self.last_text = '' + + def process_link(self): + new_href = os.path.join(self.dir, self.link['href']) + text = self.link['text'] + if not self.active: + return + if text.startswith('['): + return + if self.link.get('rel', None) in ('prev', 'parent', 'next', 'contents', 'index'): + return + if self.indented: + text = self.last_text + ' ' + text + else: + # Save it in case we need it again + self.last_text = re.sub(' \([\w\-\.\s]+\)', '', text) + indent = self.indent + print '%s' % (' ' * indent, new_href, text) + + def start_dl(self, attrs): + if self.last_text: + # Looks like we found the second part to a command + self.indented = True + + def end_dl(self): + self.indented = False + + def start_dt(self, attrs): + self.data = '' + self.nolink = True + + def end_dt(self): + if not self.active: + return + if self.nolink == True: + # Looks like we found the first part to a command + self.last_text = re.sub(' \([\w\-\.\s]+\)', '', self.data) + self.nolink = False + + def start_h2(self, attrs): + for k, v in attrs: + if k == 'id': + self.header = v + if v == '_': + self.active = True + + def start_td(self, attrs): + self.indented = False + self.last_text = '' + + def start_table(self, attrs): + pass + + def end_table(self): + if self.header == self.last_letter: + self.active = False + + def start_a(self, attrs): + self.nolink = False + self.link = {} + for attr in attrs: + self.link[attr[0]] = attr[1] + self.data = '' + + def end_a(self): + text = self.data.replace('\t', '').replace('\n', ' ').replace('&', '&').replace('<', '<').replace('>', '>') + self.link['text'] = text + # handle a tag without href attribute + try: + href = self.link['href'] + except KeyError: + return + self.process_link() + + def handle_data(self, data): + self.data += data + +def main(): + base = sys.argv[1] + fn = sys.argv[2] + version = sys.argv[3] + + parser = PyHTMLParser(formatter.NullFormatter(), base, fn, indent=0) + print '' + print '' % (version, version) + print '' + parser.parse_file(fn) + print '' + + print '' + + fn = 'genindex-all.html' + parser = PyIdxHTMLParser(formatter.NullFormatter(), base, fn, indent=1) + text = file(base + '/' + fn).read() + parser.feed(text) + parser.close() + + print '' + print '' + +main() --- python2.7-2.7.6.orig/debian/pylogo.xpm +++ python2.7-2.7.6/debian/pylogo.xpm @@ -0,0 +1,351 @@ +/* XPM */ +static char * pylogo_xpm[] = { +"32 32 316 2", +" c None", +". c #8DB0CE", +"+ c #6396BF", +"@ c #4985B7", +"# c #4181B5", +"$ c #417EB2", +"% c #417EB1", +"& c #4D83B0", +"* c #6290B6", +"= c #94B2CA", +"- c #70A1C8", +"; c #3D83BC", +"> c #3881BD", +", c #387DB6", +"' c #387CB5", +") c #387BB3", +"! c #3779B0", +"~ c #3778AE", +"{ c #3776AB", +"] c #3776AA", +"^ c #3775A9", +"/ c #4A7FAC", +"( c #709FC5", +"_ c #3A83BE", +": c #5795C7", +"< c #94B9DB", +"[ c #73A4CE", +"} c #3D80B7", +"| c #387CB4", +"1 c #377AB2", +"2 c #377AB0", +"3 c #3777AC", +"4 c #3774A7", +"5 c #3773A5", +"6 c #3C73A5", +"7 c #4586BB", +"8 c #4489C1", +"9 c #A7C7E1", +"0 c #F7F9FD", +"a c #E1E9F1", +"b c #4C89BC", +"c c #3779AF", +"d c #3778AD", +"e c #3873A5", +"f c #4B7CA4", +"g c #3982BE", +"h c #4389C1", +"i c #A6C6E1", +"j c #F6F9FC", +"k c #D6E4F0", +"l c #4A88BB", +"m c #3773A6", +"n c #366F9F", +"o c #366E9D", +"p c #376E9C", +"q c #4A8BC0", +"r c #79A7CD", +"s c #548EBD", +"t c #387AB0", +"u c #3773A4", +"v c #366D9C", +"w c #387FBA", +"x c #387DB7", +"y c #387BB4", +"z c #3775A8", +"A c #366FA0", +"B c #4981AF", +"C c #427BAA", +"D c #3772A4", +"E c #376B97", +"F c #77A3C8", +"G c #4586BC", +"H c #3882BE", +"I c #3B76A7", +"J c #3B76A6", +"K c #366E9E", +"L c #376B98", +"M c #376B96", +"N c #5681A3", +"O c #F5EEB8", +"P c #FFED60", +"Q c #FFE85B", +"R c #FFE659", +"S c #FDE55F", +"T c #5592C4", +"U c #3A83BF", +"V c #3882BD", +"W c #387FB9", +"X c #3779AE", +"Y c #366F9E", +"Z c #366C98", +"` c #376A94", +" . c #5D85A7", +".. c #F5EDB7", +"+. c #FFEA5D", +"@. c #FFE75A", +"#. c #FFE354", +"$. c #FDDD56", +"%. c #669DC8", +"&. c #3885C3", +"*. c #3884C2", +"=. c #387EB8", +"-. c #387CB6", +";. c #377AB1", +">. c #3772A3", +",. c #366D9B", +"'. c #F5EBB5", +"). c #FFE557", +"!. c #FFE455", +"~. c #FFDF50", +"{. c #FFDB4C", +"]. c #FAD862", +"^. c #8EB4D2", +"/. c #3C86C1", +"(. c #3883C0", +"_. c #3882BF", +":. c #3881BC", +"<. c #3880BB", +"[. c #3775AA", +"}. c #F5EAB3", +"|. c #FFE051", +"1. c #FFDE4F", +"2. c #FFDA4A", +"3. c #FED446", +"4. c #F5DF9D", +"5. c #77A5CA", +"6. c #3885C2", +"7. c #387BB2", +"8. c #6B8EA8", +"9. c #F8E7A1", +"0. c #FFE153", +"a. c #FFDD4E", +"b. c #FFDB4B", +"c. c #FFD746", +"d. c #FFD645", +"e. c #FFD342", +"f. c #F6DB8D", +"g. c #508DBE", +"h. c #3771A3", +"i. c #376A95", +"j. c #3D6F97", +"k. c #C3CBC2", +"l. c #FBD964", +"m. c #FFDC4D", +"n. c #FFD544", +"o. c #FFD040", +"p. c #F9CF58", +"q. c #3F83BB", +"r. c #376B95", +"s. c #3A6C95", +"t. c #4E7BA0", +"u. c #91AABC", +"v. c #F6E4A3", +"w. c #FFDA4B", +"x. c #FFD646", +"y. c #FFD443", +"z. c #FFD241", +"A. c #FFCE3D", +"B. c #FFCC3B", +"C. c #FCC83E", +"D. c #3880BC", +"E. c #3C79AC", +"F. c #5F8DB4", +"G. c #7AA0C0", +"H. c #82A6C3", +"I. c #82A3BF", +"J. c #82A2BE", +"K. c #82A1BB", +"L. c #82A1B9", +"M. c #8BA4B5", +"N. c #C1C5AE", +"O. c #F2E19F", +"P. c #FDD74C", +"Q. c #FFD94A", +"R. c #FFD343", +"S. c #FFCE3E", +"T. c #FFCB39", +"U. c #FFC937", +"V. c #FEC636", +"W. c #3D79AB", +"X. c #9DB6C6", +"Y. c #D0CFA2", +"Z. c #EFE598", +"`. c #F8EE9B", +" + c #F8EB97", +".+ c #F8E996", +"++ c #F8E894", +"@+ c #FAE489", +"#+ c #FCDB64", +"$+ c #FFDA4D", +"%+ c #FFCF3E", +"&+ c #FFCB3A", +"*+ c #FFC734", +"=+ c #FFC532", +"-+ c #3F82B7", +";+ c #387EB9", +">+ c #9EB9D0", +",+ c #F2E287", +"'+ c #FDEB69", +")+ c #FEEC60", +"!+ c #FFEB5E", +"~+ c #FFE254", +"{+ c #FFE152", +"]+ c #FFD747", +"^+ c #FFC633", +"/+ c #FCC235", +"(+ c #578FBE", +"_+ c #6996BC", +":+ c #DED9A8", +"<+ c #FEEC62", +"[+ c #FFE658", +"}+ c #FFDF51", +"|+ c #FFDE50", +"1+ c #FFD03F", +"2+ c #FFCD3C", +"3+ c #FFC431", +"4+ c #FFBF2C", +"5+ c #FAC244", +"6+ c #85AACA", +"7+ c #A1BBD2", +"8+ c #F7E47C", +"9+ c #FFE456", +"0+ c #FFC735", +"a+ c #FFBC29", +"b+ c #F7D280", +"c+ c #9DBAD2", +"d+ c #3B7CB2", +"e+ c #ABC2D6", +"f+ c #FDEB7B", +"g+ c #FFC12E", +"h+ c #FDBD30", +"i+ c #F4DEA8", +"j+ c #5F91BA", +"k+ c #ABC1D4", +"l+ c #FDEE7E", +"m+ c #FFE253", +"n+ c #FFCC3C", +"o+ c #FFBA27", +"p+ c #FAC75B", +"q+ c #4A82B0", +"r+ c #3877AB", +"s+ c #3774A6", +"t+ c #AAC0D4", +"u+ c #FDEE7D", +"v+ c #FFEC5F", +"w+ c #FFE255", +"x+ c #FFD848", +"y+ c #FFD444", +"z+ c #FFCF3F", +"A+ c #FFBC2A", +"B+ c #FFBB28", +"C+ c #FDBA32", +"D+ c #447AA8", +"E+ c #4379A7", +"F+ c #FFE95C", +"G+ c #FFE558", +"H+ c #FFE355", +"I+ c #FED84B", +"J+ c #FCD149", +"K+ c #FBCE47", +"L+ c #FBCD46", +"M+ c #FBC840", +"N+ c #FBC63E", +"O+ c #FBC037", +"P+ c #FAC448", +"Q+ c #FDD44C", +"R+ c #FCD14E", +"S+ c #FFC836", +"T+ c #FFC22F", +"U+ c #FFC02D", +"V+ c #FFE052", +"W+ c #FFC636", +"X+ c #FFCF5C", +"Y+ c #FFD573", +"Z+ c #FFC33E", +"`+ c #FEBD2D", +" @ c #FFDB4D", +".@ c #FFD949", +"+@ c #FFD545", +"@@ c #FFD140", +"#@ c #FFCB48", +"$@ c #FFF7E4", +"%@ c #FFFCF6", +"&@ c #FFE09D", +"*@ c #FFBA2E", +"=@ c #FDBE2F", +"-@ c #FFD748", +";@ c #FFCA38", +">@ c #FFC844", +",@ c #FFF2D7", +"'@ c #FFF9EC", +")@ c #FFDB94", +"!@ c #FFB92D", +"~@ c #FAC54D", +"{@ c #FDD54E", +"]@ c #FFBD2D", +"^@ c #FFC858", +"/@ c #FFD174", +"(@ c #FFBF3E", +"_@ c #FCBD3C", +":@ c #FAD66A", +"<@ c #FECD3F", +"[@ c #FFC330", +"}@ c #FFBD2A", +"|@ c #FFB724", +"1@ c #FFB521", +"2@ c #FFB526", +"3@ c #FBC457", +"4@ c #F7E09E", +"5@ c #F8D781", +"6@ c #FAC349", +"7@ c #FCC134", +"8@ c #FEBE2C", +"9@ c #FBBE3F", +"0@ c #F7CF79", +"a@ c #F5D795", +" . + @ # $ % % & * = ", +" - ; > > , ' ) ! ~ { ] ^ / ", +" ( _ : < [ } | 1 2 ~ 3 4 5 5 6 ", +" 7 8 9 0 a b 2 c d 3 { 5 5 5 e f ", +" g h i j k l c ~ { { m 5 5 n o p ", +" > > q r s t c c d 4 5 u n v v v ", +" w x ' y 2 c d d z 5 u A v v v v ", +" B C 5 D v v v v E ", +" F G H H H x ' ) c c c d I J 5 K v v L M N O P Q R S ", +" T U H V V W ' ) c c X ~ 5 5 5 Y v v Z ` ` ...+.@.#.#.$. ", +" %.&.*.> w W =.-.;.c 3 { ^ 5 5 >.o v ,.E ` ` .'.).!.#.~.{.]. ", +"^./.(._.:.<., ' ) ;.X d [.5 5 >.K v ,.E ` ` ` .}.#.|.1.{.2.3.4.", +"5.6.(.H H x ' 7.c c 3 3 4 5 D K v v ,.` ` ` ` 8.9.0.a.b.c.d.e.f.", +"g._.> <.w ' ' | 2 3 { z 5 5 h.v v v i.` ` ` j.k.l.m.{.d.n.e.o.p.", +"q.> > :.-.' 1 c c c ] 5 5 >.v v ,.r.` ` s.t.u.v.{.w.x.y.z.A.B.C.", +"D.D.w -.' 1 c c c E.F.G.H.I.J.J.K.L.L.L.M.N.O.P.Q.c.R.S.B.T.U.V.", +"D.D.=.' ' 1 c c W.X.Y.Z.`.`.`.`.`. +.+++@+#+$+Q.d.R.%+B.&+*+=+=+", +"-+;+-.' ;.2 c c >+,+'+)+P P P !+Q R ~+{+1.{.]+d.y.%+B.&+^+=+=+/+", +"(+' ' ;.c X X _+:+<+P P P P !+R [+~+}+|+{.]+n.R.1+2+&+^+=+3+4+5+", +"6+' ) ! ~ { { 7+8+P P P P !+R 9+#.{+{.w.]+y.z.S.&+0+=+=+3+4+a+b+", +"c+d+7.! d 3 z e+f+P P P !+R 9+#.{+m.{.]+y.1+B.&+0+=+=+g+4+a+h+i+", +" j+c d 3 { 4 k+l+P P !+@.9+m+1.m.{.]+y.1+n+B.*+=+=+g+a+a+o+p+ ", +" q+r+{ s+m t+u+v+@.R w+{+}+{.x+d.y+z+n+B.0+=+=+g+A+a+B+C+ ", +" * D+E+E+ +.F+G+H+}+}+{.I+J+K+L+M+M+M+M+N+O+O+O+O+P+ ", +" ).).#.{+a.{.x+Q+R+ ", +" #.m+1.a.{.x+y.o.2+B.S+=+=+T+U+O+ ", +" 0.V+{.{.x+n.o.2+B.B.W+X+Y+Z+a+`+ ", +" @{..@+@n.@@B.B.S+^+#@$@%@&@*@=@ ", +" ].-@x.y.o.%+;@S+=+=+>@,@'@)@!@~@ ", +" {@z.z+2+U.=+=+=+T+]@^@/@(@_@ ", +" :@<@U.=+=+[@4+}@|@1@2@3@ ", +" 4@5@6@7@8@a+a+9@0@a@ "}; --- python2.7-2.7.6.orig/debian/pymindeps.py +++ python2.7-2.7.6/debian/pymindeps.py @@ -0,0 +1,175 @@ +#! /usr/bin/python + +# Matthias Klose +# Modified to only exclude module imports from a given module. + +# Copyright 2004 Toby Dickenson +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import os, sys, pprint +import modulefinder +import imp + +class mymf(modulefinder.ModuleFinder): + def __init__(self,*args,**kwargs): + self._depgraph = {} + self._types = {} + self._last_caller = None + modulefinder.ModuleFinder.__init__(self, *args, **kwargs) + + def import_hook(self, name, caller=None, fromlist=None, level=-1): + old_last_caller = self._last_caller + try: + self._last_caller = caller + return modulefinder.ModuleFinder.import_hook(self, name, caller, + fromlist, level) + finally: + self._last_caller = old_last_caller + + def import_module(self, partnam, fqname, parent): + m = modulefinder.ModuleFinder.import_module(self, + partnam, fqname, parent) + if m is not None and self._last_caller: + caller = self._last_caller.__name__ + if '.' in caller: + caller = caller[:caller.index('.')] + callee = m.__name__ + if '.' in callee: + callee = callee[:callee.index('.')] + #print "XXX last_caller", caller, "MOD", callee + #self._depgraph.setdefault(self._last_caller.__name__,{})[r.__name__] = 1 + #if caller in ('pdb', 'doctest') or callee in ('pdb', 'doctest'): + # print caller, "-->", callee + if caller != callee: + self._depgraph.setdefault(caller,{})[callee] = 1 + return m + + def find_module(self, name, path, parent=None): + if parent is not None: + # assert path is not None + fullname = parent.__name__+'.'+name + elif name == "__init__": + fullname = os.path.basename(path[0]) + else: + fullname = name + if self._last_caller: + caller = self._last_caller.__name__ + if fullname in excluded_imports.get(caller, []): + #self.msgout(3, "find_module -> Excluded", fullname) + raise ImportError, name + + if fullname in self.excludes: + #self.msgout(3, "find_module -> Excluded", fullname) + raise ImportError, name + + if path is None: + if name in sys.builtin_module_names: + return (None, None, ("", "", imp.C_BUILTIN)) + + path = self.path + return imp.find_module(name, path) + + def load_module(self, fqname, fp, pathname, file_info): + suffix, mode, type = file_info + m = modulefinder.ModuleFinder.load_module(self, fqname, + fp, pathname, file_info) + if m is not None: + self._types[m.__name__] = type + return m + + def load_package(self, fqname, pathname): + m = modulefinder.ModuleFinder.load_package(self, fqname,pathname) + if m is not None: + self._types[m.__name__] = imp.PKG_DIRECTORY + return m + +def reduce_depgraph(dg): + pass + +# guarded imports, which don't need to be included in python-minimal +excluded_imports = { + 'codecs': set(('encodings',)), + 'collections': set(('doctest', 'dummy_thread', 'cPickle')), + 'copy': set(('reprlib',)), + 'difflib': set(('doctest',)), + 'hashlib': set(('logging',)), + 'hashlib': set(('_hashlib', '_md5', '_sha', '_sha256','_sha512',)), + 'heapq': set(('doctest',)), + 'inspect': set(('compiler',)), + 'os': set(('nt', 'ntpath', 'os2', 'os2emxpath', 'mac', 'macpath', + 'riscos', 'riscospath', 'riscosenviron')), + 'optparse': set(('gettext',)), + 'pickle': set(('doctest',)), + 'platform': set(('plistlib', 'tempfile')), + #'socket': set(('_ssl', 'ssl')), + 'tempfile': set(('dummy_thread',)), + 'subprocess': set(('threading',)), + 'shutil': set(('distutils', 'tarfile', 'zipfile')), + 'sysconfig': set(('pprint', '_osx_support')), + } + +def main(argv): + # Parse command line + import getopt + try: + opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") + except getopt.error as msg: + print(msg) + return + + # Process options + debug = 1 + domods = 0 + addpath = [] + exclude = [] + for o, a in opts: + if o == '-d': + debug = debug + 1 + if o == '-m': + domods = 1 + if o == '-p': + addpath = addpath + a.split(os.pathsep) + if o == '-q': + debug = 0 + if o == '-x': + exclude.append(a) + + path = sys.path[:] + path = addpath + path + + if debug > 1: + print("version:", sys.version) + print("path:") + for item in path: + print(" ", repr(item)) + + #exclude = ['__builtin__', 'sys', 'os'] + exclude = [] + mf = mymf(path, debug, exclude) + for arg in args: + mf.run_script(arg) + + depgraph = reduce_depgraph(mf._depgraph) + + pprint.pprint({'depgraph':mf._depgraph, 'types':mf._types}) + +if __name__=='__main__': + main(sys.argv[1:]) --- python2.7-2.7.6.orig/debian/python-config.1 +++ python2.7-2.7.6/debian/python-config.1 @@ -0,0 +1,102 @@ +.TH PYTHON\-CONFIG 1 "November 27, 2011" +.SH NAME +python\-config \- output build options for python C/C++ extensions or embedding +.SH SYNOPSIS +.BI "python\-config" +[ +.BI "\-\-prefix" +] +[ +.BI "\-\-exec\-prefix" +] +[ +.BI "\-\-includes" +] +[ +.BI "\-\-libs" +] +[ +.BI "\-\-cflags" +] +[ +.BI "\-\-ldflags" +] +[ +.BI "\-\-extension\-suffix" +] +[ +.BI "\-\-configdir" +] +[ +.BI "\-\-help" +] +.SH DESCRIPTION +.B python\-config +helps compiling and linking programs, which embed the Python interpreter, or +extension modules that can be loaded dynamically (at run time) into +the interpreter. +.SH OPTIONS +.TP +.BI "\-\-cflags" +print the C compiler flags. +.TP +.BI "\-\-ldflags" +print the flags that should be passed to the linker. +.TP +.BI "\-\-includes" +similar to \fI\-\-cflags\fP but only with \-I options (path to python header files). +.TP +.BI "\-\-libs" +similar to \fI\-\-ldflags\fP but only with \-l options (used libraries). +.TP +.BI "\-\-prefix" +prints the prefix (base directory) under which python can be found. +.TP +.BI "\-\-exec\-prefix" +print the prefix used for executable program directories (such as bin, sbin, etc). +.TP +.BI "\-\-extension\-suffix" +print suffix used for extension modules (including the _d modified for debug builds). +.TP +.BI "\-\-configdir" +prints the path to the configuration directory under which the Makefile, etc. can be found). +.TP +.BI "\-\-help" +print the usage message. +.PP + +.SH EXAMPLES +To build the singe\-file c program \fIprog\fP against the python library, use +.PP +.RS +gcc $(python\-config \-\-cflags \-\-ldflags) progr.cpp \-o progr.cpp +.RE +.PP +The same in a makefile: +.PP +.RS +CFLAGS+=$(shell python\-config \-\-cflags) +.RE +.RS +LDFLAGS+=$(shell python\-config \-\-ldflags) +.RE +.RS +all: progr +.RE + +To build a dynamically loadable python module, use +.PP +.RS +gcc $(python\-config \-\-cflags \-\-ldflags) \-shared \-fPIC progr.cpp \-o progr.so +.RE + +.SH "SEE ALSO" +python (1) +.br +http://docs.python.org/extending/extending.html +.br +/usr/share/doc/python/faq/extending.html + +.SH AUTHORS +This manual page was written by Johann Felix Soden +for the Debian project (and may be used by others). --- python2.7-2.7.6.orig/debian/rules +++ python2.7-2.7.6/debian/rules @@ -0,0 +1,1368 @@ +#!/usr/bin/make -f + +unexport LANG LC_ALL LC_CTYPE LC_COLLATE LC_TIME LC_NUMERIC LC_MESSAGES +unexport CFLAGS CXXFLAGS CPPFLAGS LDFLAGS + +export SHELL = /bin/bash + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +vafilt = $(subst $(2)=,,$(filter $(2)=%,$(1))) + +DPKG_VARS := $(shell dpkg-architecture) +DEB_BUILD_ARCH ?= $(call vafilt,$(DPKG_VARS),DEB_BUILD_ARCH) +DEB_BUILD_GNU_TYPE ?= $(call vafilt,$(DPKG_VARS),DEB_BUILD_GNU_TYPE) +DEB_HOST_ARCH ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH) +DEB_HOST_ARCH_BITS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_BITS) +DEB_HOST_ARCH_ENDIAN ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_ENDIAN) +DEB_HOST_ARCH_OS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_OS) +DEB_HOST_GNU_TYPE ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_GNU_TYPE) +DEB_HOST_MULTIARCH ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_MULTIARCH) + +changelog_values := $(shell dpkg-parsechangelog \ + | awk '/^(Version|Source):/ {print $$2}') +PKGSOURCE := $(word 1, $(changelog_values)) +PKGVERSION := $(word 2, $(changelog_values)) + +on_buildd := $(shell [ -f /CurrentlyBuilding -o "$$LOGNAME" = buildd -o "$$USER" = buildd ] && echo yes) + +ifneq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS))) + WITHOUT_CHECK := yes +endif +WITHOUT_BENCH := +ifneq (,$(findstring nobench, $(DEB_BUILD_OPTIONS))) + WITHOUT_BENCH := yes +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + WITHOUT_BENCH := disabled on $(DEB_HOST_ARCH) +endif +ifeq ($(on_buildd),yes) + ifneq (,$(findstring $(DEB_HOST_ARCH), hppa mips mipsel mipsn32 mipsn32el mips64 mips64el s390)) + WITHOUT_CHECK := yes + endif +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386 kfreebsd-amd64 kfreebsd-i386)) + WITHOUT_CHECK := yes +endif +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + WITHOUT_BENCH := yes + WITHOUT_CHECK := yes +endif + +COMMA = , +ifneq (,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS)))) + NJOBS := -j $(subst parallel=,,$(filter parallel=%,$(subst $(COMMA), ,$(DEB_BUILD_OPTIONS)))) +endif + +distribution := $(shell lsb_release -is) +distrelease := $(shell lsb_release -cs) + +VER=2.7 +NVER=2.8 +PVER=python2.7 +PRIORITY=$(shell echo $(VER) | tr -d '.')0 + +PREVVER := $(shell awk '/^python/ && NR > 1 {print substr($$2,2,length($$2)-2); exit}' debian/changelog) + +# default versions are built from the python-defaults source package +# keep the definition to adjust package priorities. +DEFAULT_VERSION = yes +STATIC_PYTHON=yes + +MIN_MODS := $(shell awk '/^ / && $$2 == "module" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_EXTS := $(shell awk '/^ / && $$2 ~ /^extension/ { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_BUILTINS := $(shell awk '/^ / && $$2 == "builtin" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_PACKAGES := $(shell awk '/^ / && $$2 == "package" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_ENCODINGS := $(foreach i, \ + $(filter-out \ + big5% bz2% cp932.py cp949.py cp950.py euc_% \ + gb% iso2022% johab.py shift_jis% , \ + $(shell cd Lib/encodings && echo *.py)), \ + encodings/$(i)) \ + codecs.py stringprep.py + +with_tk := no +with_gdbm := no +with_interp := static +#with_interp := shared + +PY_INTERPRETER = /usr/bin/python$(VER) + +ifeq ($(DEFAULT_VERSION),yes) + PY_PRIO = standard + #PYSTDDEP = , python (>= $(VER)) + PY_MINPRIO = $(PY_PRIO) +else + PY_PRIO = optional + PY_MINPRIO = $(PY_PRIO) +endif +with_fpectl = yes + +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric)) + bd_qual = :any +endif +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric)) + ma_filter = cat +else + ma_filter = grep -v '^Multi-Arch:' +endif + +CC = $(DEB_HOST_GNU_TYPE)-gcc + +DPKG_CFLAGS := $(shell dpkg-buildflags --get CPPFLAGS; dpkg-buildflags --get CFLAGS) +DPKG_LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) +OPT_CFLAGS := $(filter-out -O%,$(DPKG_CFLAGS)) # default is -O3 +DEBUG_CFLAGS := $(filter-out -D_FORTIFY_SOURCE=%,$(patsubst -O%,-O0,$(DPKG_CFLAGS))) + +# on alpha, use -O2 only, use -mieee +ifeq ($(DEB_HOST_ARCH),alpha) + OPT_CFLAGS += -mieee + DEBUG_CFLAGS += -mieee + EXTRA_OPT_FLAGS += -O2 +endif +# issues with ia64 and m68k with -O3 +ifeq ($(DEB_HOST_ARCH),m68k) + EXTRA_OPT_FLAGS += -O2 +endif + +ifeq ($(DEB_HOST_ARCH_OS),linux) + ifneq (,$(findstring $(DEB_HOST_ARCH), amd64 armel armhf i386 powerpc ppc64)) + with_pgo := yes + endif +endif +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + with_pgo := +endif +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + with_pgo := +endif + +ifneq (,$(findstring $(DEB_HOST_ARCH), amd64 armel armhf i386)) + with_lto := yes +endif + +ifneq (,$(findstring noopt, $(DEB_BUILD_OPTIONS))) + OPT_CFLAGS := $(filter-out -O%, $(OPT_CFLAGS)) + EXTRA_OPT_CFLAGS = -O0 + with_pgo = + with_lto = +endif + +ifeq ($(with_lto),yes) + LTO_CFLAGS = -g -flto -fuse-linker-plugin + EXTRA_OPT_CFLAGS += $(LTO_CFLAGS) +endif + +make_build_target = $(if $(with_pgo),profile-opt) + +buildd_static := $(CURDIR)/build-static +buildd_shared := $(CURDIR)/build-shared +buildd_debug := $(CURDIR)/build-debug +buildd_shdebug := $(CURDIR)/build-shdebug + +d := debian/tmp +scriptdir = usr/share/lib/python$(VER) +scriptdir = usr/share/python$(VER) +scriptdir = usr/lib/python$(VER) + +# package names and directories +p_base := $(PVER) +p_min := $(PVER)-minimal +p_lib := lib$(PVER) +p_tk := $(PVER)-tk +p_gdbm := $(PVER)-gdbm +p_dev := $(PVER)-dev +p_exam := $(PVER)-examples +p_idle := idle-$(PVER) +p_doc := $(PVER)-doc +p_dbg := $(PVER)-dbg + +p_lbase := lib$(PVER)-stdlib +p_lmin := lib$(PVER)-minimal +p_ldev := lib$(PVER)-dev +p_ldbg := lib$(PVER)-dbg +p_ltst := lib$(PVER)-testsuite + +d_base := debian/$(p_base) +d_min := debian/$(p_min) +d_lib := debian/$(p_lib) +d_tk := debian/$(p_tk) +d_gdbm := debian/$(p_gdbm) +d_dev := debian/$(p_dev) +d_exam := debian/$(p_exam) +d_idle := debian/$(p_idle) +d_doc := debian/$(p_doc) +d_dbg := debian/$(p_dbg) + +d_lbase := debian/$(p_lbase) +d_lmin := debian/$(p_lmin) +d_ldev := debian/$(p_ldev) +d_ldbg := debian/$(p_ldbg) +d_ltst := debian/$(p_ltst) + +build-arch: stamps/stamp-build +build-indep: stamps/stamp-build-doc +build: build-arch +stamps/stamp-build: stamps/stamp-build-static stamps/stamp-mincheck \ + stamps/stamp-build-shared stamps/stamp-build-debug \ + stamps/stamp-build-shared-debug \ + stamps/stamp-check stamps/stamp-pystone stamps/stamp-pybench + touch $@ + +PROFILE_EXCLUDES = test_compiler test_distutils test_platform test_subprocess \ + test_multiprocessing test_cprofile \ + test_thread test_threaded_import test_threadedtempfile \ + test_socketserver \ + test_threading test_threading_local test_threadsignals \ + test_dbm_dumb test_dbm_ndbm test_pydoc test_sundry test_gdb \ + +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel)) + PROFILE_EXCLUDES += test_float +endif +ifneq (,$(filter $(DEB_HOST_ARCH), kfreebsd-amd64 kfreebsd-i386)) + PROFILE_EXCLUDES += test_io +endif +PROFILE_EXCLUDES += test_zipfile +PROFILE_EXCLUDES += test_xmlrpc +PROFILE_EXCLUDES += test_bsddb3 + +PROFILE_TASK = ../Lib/test/regrtest.py \ + -x $(sort $(TEST_EXCLUDES) $(PROFILE_EXCLUDES)) + +stamps/stamp-build-static: stamps/stamp-configure-static + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_static) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" \ + PROFILE_TASK='$(PROFILE_TASK)' $(make_build_target) + + : # check that things are correctly built +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + ifneq (,$(filter $(DEB_HOST_ARCH_OS), linux)) + cd $(buildd_static) && ./python -c 'from _multiprocessing import SemLock' + endif +endif + + touch stamps/stamp-build-static + +stamps/stamp-build-shared: stamps/stamp-configure-shared + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" +# : # build the shared library +# $(MAKE) $(NJOBS) -C $(buildd_shared) \ +# libpython$(VER).so + : # build a static library with PIC objects + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" \ + LIBRARY=libpython$(VER)-pic.a libpython$(VER)-pic.a + touch stamps/stamp-build-shared + +stamps/stamp-build-debug: stamps/stamp-configure-debug + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_debug) \ + EXTRA_CFLAGS="$(DEBUG_CFLAGS)" + touch stamps/stamp-build-debug + +stamps/stamp-build-shared-debug: stamps/stamp-configure-shared-debug + dh_testdir + : # build the shared debug library + $(MAKE) $(NJOBS) -C $(buildd_shdebug) \ + EXTRA_CFLAGS="$(DEBUG_CFLAGS)" + touch stamps/stamp-build-shared-debug + +common_configure_args = \ + --prefix=/usr \ + --enable-ipv6 \ + --enable-unicode=ucs4 \ + --with-dbmliborder=bdb:gdbm \ + --with-system-expat + +ifneq (,$(filter $(DEB_HOST_ARCH), avr32 or1k)) + common_configure_args += --without-ffi +else + common_configure_args += --with-system-ffi +endif + +ifeq ($(with_fpectl),yes) + common_configure_args += \ + --with-fpectl +endif + +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + common_configure_args += --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) + config_site = ac_cv_file__dev_ptmx=yes ac_cv_file__dev_ptc=yes + ifeq (,$(filter $(DEB_HOST_ARCH),arm m68k)) + ifeq ($(DEB_HOST_ARCH_ENDIAN),little) + config_site += ac_cv_little_endian_double=yes + else + config_site += ac_cv_big_endian_double=yes + endif + endif +endif + +stamps/stamp-configure-shared: stamps/stamp-patch + rm -rf $(buildd_shared) + mkdir -p $(buildd_shared) + cd $(buildd_shared) && \ + CC="$(CC)" CFLAGS="$(OPT_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + --enable-shared \ + $(common_configure_args) + + $(call __post_configure,$(buildd_shared)) + + touch stamps/stamp-configure-shared + +stamps/stamp-configure-static: stamps/stamp-patch + rm -rf $(buildd_static) + mkdir -p $(buildd_static) + cd $(buildd_static) && \ + CC="$(CC)" CFLAGS="$(OPT_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + $(common_configure_args) + + $(call __post_configure,$(buildd_static)) + + touch stamps/stamp-configure-static + +stamps/stamp-configure-debug: stamps/stamp-patch + rm -rf $(buildd_debug) + mkdir -p $(buildd_debug) + cd $(buildd_debug) && \ + CC="$(CC)" CFLAGS="$(DEBUG_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + $(common_configure_args) \ + --with-pydebug + + $(call __post_configure,$(buildd_debug)) + + touch stamps/stamp-configure-debug + +stamps/stamp-configure-shared-debug: stamps/stamp-patch + rm -rf $(buildd_shdebug) + mkdir -p $(buildd_shdebug) + cd $(buildd_shdebug) && \ + CC="$(CC)" CFLAGS="$(DEBUG_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + $(config_site) \ + ../configure \ + $(common_configure_args) \ + --enable-shared \ + --with-pydebug + + $(call __post_configure,$(buildd_shdebug)) + + touch stamps/stamp-configure-shared-debug + +define __post_configure + egrep \ + "^#($$(awk -v ORS='|' '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in)XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(1)/Modules/Setup.local + + : # unconditionally run makesetup + cd $(1) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(1)/config.c $(1)/Modules/ + + : # and fix the timestamps + $(MAKE) -C $(1) Makefile Modules/config.c + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(1)/pyconfig.h \ + > $(1)/pyconfig.h.new + touch -r $(1)/pyconfig.h $(1)/pyconfig.h.new + mv -f $(1)/pyconfig.h.new $(1)/pyconfig.h +endef + +stamps/stamp-mincheck: stamps/stamp-build-static debian/PVER-minimal.README.Debian.in +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + for m in $(MIN_MODS) $(MIN_PACKAGES) $(MIN_EXTS) $(MIN_BUILTINS); do \ + echo "import $$m"; \ + done > $(buildd_static)/minmods.py + cd $(buildd_static) && ./python ../debian/pymindeps.py minmods.py \ + > $(buildd_static)/mindeps.txt + if [ -x /usr/bin/dot ]; then \ + python debian/depgraph.py < $(buildd_static)/mindeps.txt \ + > $(buildd_static)/mindeps.dot; \ + dot -Tpng -o $(buildd_static)/mindeps.png \ + $(buildd_static)/mindeps.dot; \ + else true; fi + cd $(buildd_static) && ./python ../debian/mincheck.py \ + minmods.py mindeps.txt +endif + touch stamps/stamp-mincheck + +TEST_RESOURCES = all +ifeq ($(on_buildd),yes) + TEST_RESOURCES := $(TEST_RESOURCES),-network,-urlfetch,-bsddb +endif +TESTOPTS = -w -l -u$(TEST_RESOURCES) +TEST_EXCLUDES = +ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_codecmaps_cn test_codecmaps_hk \ + test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw \ + test_normalization test_ossaudiodev + ifneq (,$(filter $(DEB_HOST_ARCH), mips mipsel powerpc kfreebsd-i386 sparc)) + TEST_EXCLUDES += test_threading + endif + ifeq (,$(wildcard $(HOME))) + TEST_EXCLUDES += test_site + endif +endif +ifeq (,$(wildcard /dev/dsp)) + TEST_EXCLUDES += test_linuxaudiodev test_ossaudiodev +endif +ifneq (,$(filter $(DEB_HOST_ARCH), armel hppa powerpc)) + TEST_EXCLUDES += test_multiprocessing +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hppa)) + TEST_EXCLUDES += test_fork1 test_socketserver test_threading test_wait3 test_wait4 test_gdb +endif +ifneq (,$(filter $(DEB_HOST_ARCH), arm avr32)) + TEST_EXCLUDES += test_ctypes +endif +TEST_EXCLUDES += test_bsddb3 +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 m68k)) + ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_compiler + endif +endif +TEST_EXCLUDES += test_gdb +# fails on some buildds +ifneq (,$(filter $(DEB_HOST_ARCH), amd64 armel armhf mips mipsel)) + TEST_EXCLUDES += test_io +endif +ifneq (,$(filter $(DEB_HOST_ARCH), kfreebsd-amd64 kfreebsd-i386)) + TEST_EXCLUDES += test_io test_signal +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + TEST_EXCLUDES += test_io test_random test_signal test_socket test_socketserver test_ssl \ + test_threading test_subprocess +endif +ifneq (,$(filter $(DEB_HOST_ARCH), ia64)) + TEST_EXCLUDES += test_threading test_subprocess +endif +ifneq (,$(TEST_EXCLUDES)) + TESTOPTS += -x $(sort $(TEST_EXCLUDES)) + ifneq (,$(filter $(DEB_HOST_ARCH), mips mipsel)) + TESTOPTS_DEBUG := $(TESTOPTS) + else + TESTOPTS_DEBUG := $(filter-out test_gdb,$(TESTOPTS)) + endif +endif + +ifneq (,$(wildcard /usr/bin/localedef)) + SET_LOCPATH = LOCPATH=$(CURDIR)/locales +endif + +stamps/stamp-check: +ifeq ($(WITHOUT_CHECK),yes) + echo "check run disabled for this build" > $(buildd_static)/test_results +else + : # build locales needed by the testsuite + rm -rf locales + mkdir locales + if which localedef >/dev/null 2>&1; then \ + sh debian/locale-gen; \ + fi + + @echo ========== test environment ============ + @env + @echo ======================================== + ifeq (,$(findstring $(DEB_HOST_ARCH), alpha)) + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test TESTOPTS="$(TESTOPTS_DEBUG)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_debug)/run_tests + chmod 755 $(buildd_debug)/run_tests + @echo "BEGIN test debug" + -cd $(buildd_debug) && time xvfb-run -a -e xvfb-run.log ./run_tests + @echo "END test debug" + endif + + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo 'export $(SET_LOCPATH)'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" TESTOPTS="$(TESTOPTS)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_static)/run_tests + chmod 755 $(buildd_static)/run_tests + @echo "BEGIN test static" + -cd $(buildd_static) && time xvfb-run -a -e xvfb-run.log ./run_tests + @echo "END test static" + + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo 'export $(SET_LOCPATH)'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" TESTOPTS="$(TESTOPTS)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_shared)/run_tests + chmod 755 $(buildd_shared)/run_tests + @echo "BEGIN test shared" + -cd $(buildd_shared) && time xvfb-run -a -e xvfb-run.log ./run_tests + @echo "END test shared" +endif + cp -p $(buildd_static)/test_results debian/ + touch stamps/stamp-check + +stamps/stamp-pystone: +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + @echo "BEGIN pystone static" + cd $(buildd_static) && ./python ../Lib/test/pystone.py + cd $(buildd_static) && ./python ../Lib/test/pystone.py + @echo "END pystone static" + @echo "BEGIN pystone shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + @echo "END pystone shared" + @echo "BEGIN pystone debug" + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + @echo "END pystone debug" +endif + touch stamps/stamp-pystone + +#ifeq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 hppa mips mipsel m68k)) + pybench_options = -C 2 -n 5 -w 4 +#endif + +stamps/stamp-pybench: +ifeq ($(WITHOUT_BENCH),yes) + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log +else + @echo "BEGIN pybench static" + cd $(buildd_static) \ + && time ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_static) \ + && ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench static" + @echo "BEGIN pybench shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. \ + ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. \ + ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench shared" + @echo "BEGIN shared/static comparision" + $(buildd_static)/python Tools/pybench/pybench.py \ + -s $(buildd_static)/run2.pybench -c $(buildd_shared)/run2.pybench \ + | tee $(buildd_static)/pybench.log + @echo "END shared/static comparision" +endif + touch stamps/stamp-pybench + +minimal-test: + rm -rf mintest + mkdir -p mintest/lib mintest/dynlib mintest/testlib mintest/all-lib + cp -p $(buildd_static)/python mintest/ + cp -p $(foreach i,$(MIN_MODS),Lib/$(i).py) \ + mintest/lib/ + cp -a $(foreach i,$(MIN_PACKAGES),Lib/$(i)) \ + mintest/lib/ + cp -p $(wildcard $(foreach i,$(MIN_EXTS),$(buildd_static)/build/lib*/$(i).*.so)) \ + mintest/dynlib/ + cp -p Lib/unittest.py mintest/lib/ + cp -pr Lib/test mintest/lib/ + cp -pr Lib mintest/all-lib + cp -p $(buildd_static)/build/lib*/*.so mintest/all-lib/ + ( \ + echo "import sys"; \ + echo "sys.path = ["; \ + echo " '$(CURDIR)/mintest/lib',"; \ + echo " '$(CURDIR)/mintest/dynlib',"; \ + echo "]"; \ + cat Lib/test/regrtest.py; \ + ) > mintest/lib/test/mintest.py + cd mintest && ./python -E -S lib/test/mintest.py \ + -x test_codecencodings_cn test_codecencodings_hk \ + test_codecencodings_jp test_codecencodings_kr \ + test_codecencodings_tw test_codecs test_multibytecodec \ + +stamps/stamp-doc-html: + dh_testdir + $(MAKE) -C Doc html + touch stamps/stamp-doc-html + +build-doc: stamps/stamp-patch stamps/stamp-build-doc +stamps/stamp-build-doc: stamps/stamp-doc-html + touch stamps/stamp-build-doc + +control-file: + sed -e "s/@PVER@/$(PVER)/g" \ + -e "s/@VER@/$(VER)/g" \ + -e "s/@PYSTDDEP@/$(PYSTDDEP)/g" \ + -e "s/@PRIO@/$(PY_PRIO)/g" \ + -e "s/@MINPRIO@/$(PY_MINPRIO)/g" \ + -e "s/@bd_qual@/$(bd_qual)/g" \ + debian/control.in \ + | $(ma_filter) \ + > debian/control.tmp +ifeq ($(distribution),Ubuntu) + ifneq (,$(findstring ubuntu, $(PKGVERSION))) + m='Ubuntu Core Developers '; \ + sed -i "/^Maintainer:/s/\(.*\)/Maintainer: $$m\nXSBC-Original-\1/" \ + debian/control.tmp + endif +endif + [ -e debian/control ] \ + && cmp -s debian/control debian/control.tmp \ + && rm -f debian/control.tmp && exit 0; \ + mv debian/control.tmp debian/control + + + +clean: control-file + dh_testdir + dh_testroot + $(MAKE) -f debian/rules unpatch + rm -rf stamps .pc + rm -f debian/test_results + + $(MAKE) -C Doc clean + sed 's/^@/#/' Makefile.pre.in | $(MAKE) -f - srcdir=. distclean + rm -rf Lib/test/db_home + rm -rf $(buildd_static) $(buildd_shared) $(buildd_debug) $(buildd_shdebug) + find -name '*.py[co]' | xargs -r rm -f + rm -f Lib/lib2to3/*.pickle + rm -rf Lib/plat-$(DEB_HOST_MULTIARCH) + rm -rf locales + rm -rf $(d)-dbg $(d)-shdbg + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ] && [ $$f2 != debian/source.lintian-overrides ]; then \ + rm -f $$f2; \ + fi; \ + done + dh_clean + +stamps/stamp-control: + : # We have to prepare the various control files + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ]; then \ + sed -e "s/@PVER@/$(PVER)/g;s/@VER@/$(VER)/g" \ + -e "s/@PRIORITY@/$(PRIORITY)/g" \ + -e "s,@SCRIPTDIR@,/$(scriptdir),g" \ + -e "s,@INFO@,$(info_docs),g" \ + <$$f >$$f2; \ + fi; \ + done +ifeq ($(DEB_HOST_ARCH_BITS),64) + sed -i 's/\(Py_InitModule4[^@]*\)@/\1_64@/' \ + debian/lib$(PVER).symbols debian/lib$(PVER)-dbg.symbols +endif + +2to3-man: + help2man --no-info --version-string=$(VER) --no-discard-stderr \ + --name 'Python2 to Python3 converter' \ + 2to3-$(VER) > debian/2to3-$(VER).1 + +install: build-arch stamps/stamp-install +stamps/stamp-install: stamps/stamp-build control-file stamps/stamp-control + dh_testdir + dh_testroot + dh_clean -k + dh_installdirs + + : # make install into tmp and subsequently move the files into + : # their packages' directories. + install -d $(d)/usr +ifeq ($(with_interp),static) + $(MAKE) -C $(buildd_static) install prefix=$(CURDIR)/$(d)/usr +else + $(MAKE) -C $(buildd_shared) install prefix=$(CURDIR)/$(d)/usr +endif + mkdir -p $(d)/usr/include/$(DEB_HOST_MULTIARCH)/$(PVER) + mv $(d)/usr/include/$(PVER)/pyconfig.h \ + $(d)/usr/include/$(DEB_HOST_MULTIARCH)/$(PVER)/. + mv $(d)/usr/bin/python-config.sh $(d)/usr/bin/python$(VER)-config + sed -i 's/-O3/-O2/g;s/$(LTO_CFLAGS)//g;s/-fprofile-use *-fprofile-correction//g' \ + $(d)/usr/bin/python$(VER)-config + + : # fiddle around with the platform directory + mkdir -p $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/ + set -x; echo XXXXXX; \ + for i in Lib/plat-linux2/*; do \ + n=$$(basename $$i); \ + if [ ! -f $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/$$n ]; then \ + cp -p $$i $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/; \ + fi; \ + done + rm -f $(d)/$(scriptdir)/lib-dynload/*.py + cp -p $(buildd_shared)/$(shell cat $(buildd_shared)/pybuilddir.txt)/_sysconfigdata.py \ + $(d)/$(scriptdir)/. + mv $(d)/$(scriptdir)/_sysconfigdata.py \ + $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/_sysconfigdata_nd.py + sed -i 's/ -O3 / -O2 /g;s/$(LTO_CFLAGS)//g;s/-fprofile-use *-fprofile-correction//g' \ + $(d)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/_sysconfigdata_nd.py + cp -p debian/_sysconfigdata.py $(d)/$(scriptdir) + + -find $(d)/usr/lib/python$(VER) -name '*_failed*.so' + find $(d)/usr/lib/python$(VER) -name '*_failed*.so' | xargs -r rm -f + + test -f $(d)/usr/lib/python$(VER)/lib-dynload/_bsddb.so + + for i in $(d)/$(scriptdir)/lib-dynload/*.so; do \ + b=$$(basename $$i .so); \ + d=$${b}.$(DEB_HOST_MULTIARCH).so; \ + mv $$i $(d)/$(scriptdir)/lib-dynload/$$d; \ + done + + mv $(d)/usr/lib/libpython*.a $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/ + + mv $(d)/usr/lib/python$(VER)/site-packages \ + $(d)/usr/lib/python$(VER)/dist-packages + + : # remove files, which are not packaged + rm -f $(d)/usr/bin/smtpd.py + rm -rf $(d)/usr/lib/python$(VER)/ctypes/macholib + rm -f $(d)/$(scriptdir)/plat-*/regen + rm -f $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python.pc + rm -f $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python2.pc + rm -f $(d)/usr/bin/python2{,-config} + rm -f $(d)/usr/share/man/man1/python.1 + rm -f $(d)/usr/share/man/man1/python2{,-config}.1 + rm -f $(d)/$(scriptdir)/lib2to3/*.pickle + + : # cannot build it, zlib maintainer won't provide a mingw build + find $(d) -name 'wininst*.exe' | xargs -r rm -f + + : # fix some file permissions + chmod a-x $(d)/$(scriptdir)/{fractions,lib-tk/Tix}.py + + : # move manpages to new names + if [ -d $(d)/usr/man/man1 ]; then \ + mkdir -p $(d)/usr/share/man; \ + mv $(d)/usr/man/man1/* $(d)/usr/share/man/man1/; \ + rm -rf $(d)/usr/man/; \ + fi + cp -p debian/pydoc.1 $(d)/usr/share/man/man1/pydoc$(VER).1 + + : # Symlinks to /usr/bin for some tools + ln -sf ../lib/python$(VER)/pdb.py $(d)/usr/bin/pdb$(VER) + cp -p debian/pdb.1 $(d)/usr/share/man/man1/pdb$(VER).1 + + : # versioned install only + rm -f $(d)/usr/bin/python-config + + mv $(d)/usr/bin/2to3 $(d)/usr/bin/2to3-$(VER) + cp debian/2to3-$(VER).1 $(d)/usr/share/man/man1/2to3-$(VER).1 + +# : # remove the bsddb stuff +# rm -rf $(d)/$(scriptdir)/bsddb +# rm -f $(d)/$(scriptdir)/lib-dynload/_bsddb.so + + : # Remove version information from the egg-info file + mv $(d)/$(scriptdir)/lib-dynload/Python-$(VER)*.egg-info \ + $(d)/$(scriptdir)/lib-dynload/Python-$(VER).egg-info + + dh_installdirs -p$(p_lib) \ + usr/lib/$(DEB_HOST_MULTIARCH) \ + $(scriptdir)/config-$(DEB_HOST_MULTIARCH) \ + usr/share/doc + : # install the shared library + cp -p $(buildd_shared)/libpython$(VER).so.1.0 \ + $(d_lib)/usr/lib/$(DEB_HOST_MULTIARCH)/ + dh_link -p$(p_lib) \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so.1.0 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so.1 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so.1 \ + /$(scriptdir)/config-$(DEB_HOST_MULTIARCH)/libpython$(VER).so + + ln -sf $(p_base) $(d_lib)/usr/share/doc/$(p_lib) + + ln -sf libpython$(VER).so.1 $(d)/usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).so + +ifeq ($(with_interp),shared) + : # install the statically linked runtime + install -m755 $(buildd_static)/python $(d)/usr/bin/python$(VER)-static +endif + + mv $(d)/usr/bin/pydoc $(d)/usr/bin/pydoc$(VER) + cp -p Tools/i18n/pygettext.py $(d)/usr/bin/pygettext$(VER) + cp -p debian/pygettext.1 $(d)/usr/share/man/man1/pygettext$(VER).1 + + : # install the Makefile of the shared python build + sed -e '/^OPT/s,-O3,-O2,' \ + -e 's/$(LTO_CFLAGS)//g' \ + -e 's,^RUNSHARED *=.*,RUNSHARED=,' \ + -e '/BLDLIBRARY/s/-L\. //' \ + build-shared/Makefile > $(d)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)/Makefile + + : # Move the binary and the minimal libraries into $(p_lmin). + dh_installdirs -p$(p_lmin) \ + etc/$(PVER) \ + usr/bin \ + usr/include/$(PVER) \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_lmin) --sourcedir=$(d) \ + $(foreach i,$(MIN_MODS),$(scriptdir)/$(i).py) \ + $(foreach i,$(MIN_PACKAGES),$(scriptdir)/$(i)) \ + $(foreach i,$(MIN_ENCODINGS),$(scriptdir)/$(i)) \ + /$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/_sysconfigdata_nd.py \ + $(scriptdir)/site.py \ + $(shell cd $(d); for i in $(MIN_EXTS); do \ + test -e $(scriptdir)/lib-dynload/$$i.so \ + && echo $(scriptdir)/lib-dynload/$$i.so; \ + done; true) + + : # Move the binary and the minimal libraries into $(p_min). + dh_installdirs -p$(p_min) \ + usr/bin \ + usr/share/man/man1 + DH_COMPAT=2 dh_movefiles -p$(p_min) --sourcedir=$(d) \ + usr/bin/python$(VER) \ + usr/share/man/man1/python$(VER).1 + + : # Install sitecustomize.py. + cp -p debian/sitecustomize.py $(d_lmin)/etc/$(PVER)/ + dh_link -p$(p_lmin) /etc/$(PVER)/sitecustomize.py \ + /$(scriptdir)/sitecustomize.py + + : # Move the static library and the header files into $(p_ldev). +# mv $(d)/usr/share/include/python$(VER)/* $(d)/usr/include/python$(VER)/. +# rm -rf $(d)/usr/share/include + + cp $(d)/usr/bin/python$(VER)-config $(d)/usr/bin/$(DEB_HOST_MULTIARCH)-python$(VER)-config + dh_installdirs -p$(p_ldev) \ + usr/bin \ + $(scriptdir) \ + usr/include \ + usr/share/man/man1 + + DH_COMPAT=2 dh_movefiles -p$(p_ldev) --sourcedir=$(d) \ + usr/bin/$(DEB_HOST_MULTIARCH)-python$(VER)-config \ + usr/lib/python$(VER)/config-$(DEB_HOST_MULTIARCH) \ + usr/include \ + usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).{a,so} \ + usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER)*.pc + + sed 's/@subdir@/$(PVER)/;s/@header@/pyconfig.h/' \ + debian/multiarch.h.in > $(d_ldev)/usr/include/$(PVER)/pyconfig.h + + cp -p debian/python-config.1 \ + $(d_ldev)/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-python$(VER)-config.1 + +ifneq ($(DEB_HOST_MULTIARCH),$(DEB_HOST_GNU_TYPE)) + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config \ + $(d_ldev)/usr/bin/$(DEB_HOST_GNU_TYPE)-$(PVER)-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz \ + $(d_ldev)/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-$(PVER)-config.1.gz +endif + + sed -i '/^Cflags:/s,$$, -I$${includedir}/$(DEB_HOST_MULTIARCH)/python$(VER),' \ + $(d_ldev)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER).pc + + dh_link -p$(p_ldev) \ + /usr/lib/$(PVER)/config-$(DEB_HOST_MULTIARCH)/libpython$(VER).a \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER).a + + cp -p $(buildd_shared)/libpython$(VER)-pic.a \ + $(d_ldev)/usr/lib/python$(VER)/config-$(DEB_HOST_MULTIARCH)/ + + : # Move the static library and the header files into $(p_dev). + dh_installdirs -p$(p_dev) \ + usr/share/doc/python$(VER)/$(DEB_HOST_MULTIARCH) \ + usr/share/man/man1 \ + $(scriptdir) \ + $(scriptdir)/doc/html + + cp -p Misc/HISTORY Misc/README.valgrind Misc/gdbinit \ + debian/README.maintainers \ + $(d_dev)/usr/share/doc/python$(VER)/ + cp -p debian/test_results $(buildd_static)/pybench.log \ + $(d_dev)/usr/share/doc/python$(VER)/$(DEB_HOST_MULTIARCH)/ + + DH_COMPAT=2 dh_movefiles -p$(p_dev) --sourcedir=$(d) \ + usr/bin/python$(VER)-config \ + usr/lib/python$(VER)/distutils/command/wininst-*.exe + + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config $(d_dev)/usr/bin/$(PVER)-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz $(d_dev)/usr/share/man/man1/$(PVER)-config.1.gz + +ifeq ($(with_tk),yes) + : # Move the Tkinter files into $(p_tk). + dh_installdirs -p$(p_tk) \ + $(scriptdir) \ + usr/lib/python$(VER)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_tk) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/_tkinter.so +endif + +ifeq ($(with_gdbm),yes) + : # gdbm and dbm modules into $(p_gdbm). + dh_installdirs -p$(p_gdbm) \ + usr/lib/python$(VER)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_gdbm) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/gdbm.so +endif + + : # The test framework into $(p_lbase) + DH_COMPAT=2 dh_movefiles -p$(p_lbase) --sourcedir=$(d) \ + $(scriptdir)/test/{regrtest.py,test_support.py,__init__.py,pystone.py} + + : # The complete testsuite into $(p_lbase) + DH_COMPAT=2 dh_movefiles -p$(p_ltst) --sourcedir=$(d) \ + $(scriptdir)/test \ + $(scriptdir)/ctypes/test \ + $(scriptdir)/bsddb/test \ + $(scriptdir)/email/test \ + $(scriptdir)/json/tests \ + $(scriptdir)/sqlite3/test \ + $(scriptdir)/distutils/tests \ + $(scriptdir)/lib2to3/tests \ + $(scriptdir)/unittest/test \ + $(scriptdir)/lib-tk/test + +# FIXME: remove with the next new tarball + uudecode -o - debian/imghdrdata.tgz.uue | tar -C $(d_ltst)/$(scriptdir)/test -x -z -f - + + : # test_ctypes fails with test_macholib.py installed + rm -f $(d_ltst)/$(scriptdir)/ctypes/test/test_macholib.py + : # test_bdist_wininst fails, '*.exe' files are not installed + rm -f $(d_ltst)/$(scriptdir)/distutils/tests/test_bdist_wininst.py + + : # IDLE + mv $(d)/usr/bin/idle $(d)/usr/bin/idle-python$(VER) + rm -f $(d)/usr/lib/python$(VER)/idlelib/idle.bat + dh_installdirs -p$(p_idle) \ + usr/bin \ + usr/share/man/man1 + DH_COMPAT=2 dh_movefiles -p$(p_idle) --sourcedir=$(d) \ + usr/lib/python$(VER)/idlelib \ + usr/bin/idle-python$(VER) + cp -p debian/idle-$(PVER).1 $(d_idle)/usr/share/man/man1/ + +# FIXME: remove with the next new tarball + uudecode -o - debian/idle-icons.tgz.uue | tar -C $(d_idle)/$(scriptdir) -x -z -f - + + : # Move the demos and tools into $(p_exam)'s doc directory + dh_installdirs -p$(p_exam) \ + usr/share/doc/python$(VER)/examples + + cp -rp Demo Tools $(d_exam)/usr/share/doc/python$(VER)/examples/ + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Demo/sgi + : # IDLE is in its own package: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/idle + : # XXX: We don't need rgb.txt, we'll use our own: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/pynche/X + + : # XXX: Some files in upstream Demo and Tools have strange + : # exec permissions, make lintian glad: + -chmod 644 $(d_tk)/$(scriptdir)/lib-tk/Tix.py + -chmod 644 $(d)/$(scriptdir)/runpy.py + + cd $(d_exam)/usr/share/doc/python$(VER)/examples && chmod 644 \ + Demo/{classes/*.py*,comparisons/patterns} \ + Demo/{rpc/test,threads/*.py*,md5test/*} \ + Demo/pdist/{client.py,cmdfw.py,cmptree.py,cvslib.py,cvslock.py,FSProxy.py,mac.py,rcsclient.py,rcslib.py,security.py,server.py,sumtree.py} \ + Demo/scripts/{morse.py,newslist.doc} \ + Demo/sockets/{broadcast.py,ftp.py,mcast.py,radio.py} \ + Demo/tix/{bitmaps/{tix.gif,*x[pb]m*},samples/*.py} \ + Demo/tkinter/guido/{AttrDialog.py,hanoi.py,hello.py,imagedraw.py,imageview.py,listtree.py,ManPage.py,ShellWindow.py,wish.py} \ + Tools/scripts/pydocgui.pyw \ + Tools/scripts/mailerdaemon.py + + : # Replace all '#!' calls to python with $(PY_INTERPRETER) + : # and make them executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch'`; do \ + sed '1s,#!.*python[^ ]*\(.*\),#! $(PY_INTERPRETER)\1,' \ + $$i > $$i.temp; \ + if cmp --quiet $$i $$i.temp; then \ + rm -f $$i.temp; \ + else \ + mv -f $$i.temp $$i; \ + chmod 755 $$i; \ + echo "fixed interpreter: $$i"; \ + fi; \ + done + + : # Move the docs into $(p_base)'s /usr/share/doc/$(PVER) directory, + : # all other packages only have a copyright file. + dh_installdocs -p$(p_base) \ + README Misc/NEWS Misc/ACKS + ln -sf NEWS.gz $(d_base)/usr/share/doc/$(p_base)/changelog.gz + dh_installdocs --all -N$(p_base) -N$(p_dev) -N$(p_dbg) -N$(p_lib) debian/README.Debian + + : # IDLE has its own changelogs, docs... + dh_installchangelogs -p$(p_idle) Lib/idlelib/ChangeLog + dh_installdocs -p$(p_idle) Lib/idlelib/{NEWS,README,TODO,extend}.txt + + mkdir -p $(d_idle)/usr/share/applications + cp -p debian/idle.desktop \ + $(d_idle)/usr/share/applications/idle-$(PVER).desktop + + : # those packages have own README.Debian's + install -m 644 -p debian/README.$(p_base) \ + $(d_base)/usr/share/doc/$(PVER)/README.Debian + install -m 644 -p debian/README.$(p_idle) \ + $(d_idle)/usr/share/doc/$(p_idle)/README.Debian +ifeq ($(with_tk),yes) + cp -p debian/README.Tk $(d_tk)/usr/share/doc/$(p_tk)/ +endif + + : # library files into $(p_lbase) + dh_installdirs -p$(p_lbase) \ + usr/lib + dh_movefiles -p$(p_lbase) \ + usr/lib/python$(VER) + + : # The rest goes into $(p_base) + mkdir -p $(d)/usr/lib/python$(VER)/dist-packages + (cd $(d) && tar cf - .) | (cd $(d_base) && tar xpf -) + sh debian/dh_rmemptydirs -p$(p_base) + rm -f $(d_base)/usr/bin/python + + : # install egg-info for arparse + install -m 644 debian/argparse.egg-info $(d_lbase)/$(scriptdir)/ + + : # Install menu icon + dh_installdirs -p$(p_base) usr/share/pixmaps + cp -p debian/pylogo.xpm $(d_base)/usr/share/pixmaps/$(PVER).xpm + + : # generate binfmt file + mkdir -p $(d_min)/usr/share/binfmts +ifeq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + $(buildd_static)/python debian/mkbinfmt.py $(PVER) \ + > $(d_min)/usr/share/binfmts/$(PVER) +else + $(PVER) debian/mkbinfmt.py $(PVER) > $(d_min)/usr/share/binfmts/$(PVER) +endif + + : # desktop entry + mkdir -p $(d_base)/usr/share/applications + cp -p debian/$(PVER).desktop \ + $(d_base)/usr/share/applications/$(PVER).desktop + + : # remove some things + -find debian -name .cvsignore | xargs rm -f + -find debian -name '*.py[co]' | xargs rm -f + + : # remove empty directories, when all components are in place + -find debian ! -name lib-dynload -type d -empty -delete + + : # install debug package + rm -rf $(d)-dbg $(d)-shdbg + : # need some files from the shared build + $(MAKE) -C $(buildd_shdebug) install DESTDIR=$(CURDIR)/$(d)-shdbg + $(MAKE) -C $(buildd_debug) install DESTDIR=$(CURDIR)/$(d)-dbg + mv $(d)-dbg/usr/lib/libpython*.a $(d)-dbg/usr/lib/$(DEB_HOST_MULTIARCH)/ + mv $(d)-shdbg/$(scriptdir)/_sysconfigdata.py \ + $(d)-shdbg/$(scriptdir)/_sysconfigdata_d.py + + for i in $(d)-dbg/$(scriptdir)/lib-dynload/*_d.so; do \ + b=$$(basename $$i _d.so); \ + d=$${b}.$(DEB_HOST_MULTIARCH)_d.so; \ + mv $$i $(d)-dbg/$(scriptdir)/lib-dynload/$$d; \ + done + for i in $(d)-shdbg/$(scriptdir)/lib-dynload/*_d.so; do \ + b=$$(basename $$i _d.so); \ + d=$${b}.$(DEB_HOST_MULTIARCH)_d.so; \ + mv $$i $(d)-shdbg/$(scriptdir)/lib-dynload/$$d; \ + done + + dh_installdirs -p$(p_ldbg) \ + usr/bin \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload \ + $(scriptdir)/plat-$(DEB_HOST_MULTIARCH) \ + usr/include/$(PVER)_d \ + usr/include/$(DEB_HOST_MULTIARCH)/$(PVER)_d \ + usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig \ + + cp -p $(d)-shdbg/$(scriptdir)/lib-dynload/*.so \ + $(d_ldbg)/$(scriptdir)/lib-dynload/ + cp -p $(buildd_shdebug)/libpython$(VER)_d.so.1.0 \ + $(d_ldbg)/usr/lib/$(DEB_HOST_MULTIARCH)/ + dh_link -p$(p_ldbg) \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so.1.0 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so.1 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so.1 \ + /usr/lib/$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so + sed -e '/^Libs:/s,-lpython$(VER),-lpython$(VER)_d,' \ + -e '/^Cflags:/s,python$(VER),python$(VER)_d,' \ + -e '/^Cflags:/s,$$, -I$${includedir}/$(DEB_HOST_MULTIARCH)/python$(VER)_d,' \ + $(d)-dbg/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER).pc \ + > $(d_ldbg)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/python-$(VER)-dbg.pc + + : # in $(p_ldbg), prefix python-config with triplets + cp $(d)-shdbg/usr/bin/python-config.sh \ + $(d_ldbg)/usr/bin/$(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz \ + $(d_ldbg)/usr/share/man/man1/$(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config.1.gz +ifneq ($(DEB_HOST_MULTIARCH),$(DEB_HOST_GNU_TYPE)) + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config \ + $(d_ldbg)/usr/bin/$(DEB_HOST_GNU_TYPE)-$(PVER)-dbg-config + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-config.1.gz \ + $(d_ldbg)/usr/share/man/man1/$(DEB_HOST_GNU_TYPE)-$(PVER)-dbg-config.1.gz +endif + + dh_installdirs -p$(p_dbg) \ + usr/bin \ + $(scriptdir)/lib-dynload \ + usr/share/man/man1 \ + usr/share/doc/$(p_base) + + cp -p Misc/SpecialBuilds.txt $(d_dbg)/usr/share/doc/$(p_base)/ + cp -p debian/$(PVER)-dbg.README.Debian \ + $(d_dbg)/usr/share/doc/$(p_base)/README.debug + cp -p $(buildd_debug)/python $(d_dbg)/usr/bin/$(PVER)-dbg + cp -p $(d)-shdbg/usr/bin/python-config.sh \ + $(d_dbg)/usr/bin/$(PVER)-dbg-config +# cp -p $(buildd_debug)/build/lib*/*_d.so \ + $(d_dbg)/$(scriptdir)/lib-dynload/ + cp -p $(d)-shdbg/$(scriptdir)/_sysconfigdata_d.py \ + $(d_ldbg)/$(scriptdir)/plat-$(DEB_HOST_MULTIARCH)/ +ifneq ($(with_gdbm),yes) + rm -f $(d_ldbg)/$(scriptdir)/lib-dynload/gdbm.$(DEB_HOST_MULTIARCH)_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/gdbm.$(DEB_HOST_MULTIARCH).so +endif +ifneq ($(with_tk),yes) + rm -f $(d_ldbg)/$(scriptdir)/lib-dynload/_tkinter.$(DEB_HOST_MULTIARCH)_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_tkinter.$(DEB_HOST_MULTIARCH).so +endif +# rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_bsddb_d.so + + cp -a $(d)-dbg/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d \ + $(d_ldbg)/$(scriptdir)/ + ln -sf ../../$(DEB_HOST_MULTIARCH)/libpython$(VER)_d.so \ + $(d_ldbg)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d/libpython$(VER)_d.so + ln -sf libpython$(VER)_d.so \ + $(d_ldbg)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d/libpython$(VER).so + ln -sf libpython$(VER)_d.a \ + $(d_ldbg)/$(scriptdir)/config-$(DEB_HOST_MULTIARCH)_d/libpython$(VER).a + + for i in $(d_ldev)/usr/include/$(PVER)/*; do \ + i=$$(basename $$i); \ + case $$i in pyconfig.h) continue; esac; \ + ln -sf ../$(PVER)/$$i $(d_ldbg)/usr/include/$(PVER)_d/$$i; \ + done + cp -p $(buildd_debug)/pyconfig.h $(d_ldbg)/usr/include/$(DEB_HOST_MULTIARCH)/$(PVER)_d/ + sed 's/@subdir@/$(PVER)_d/;s/@header@/pyconfig.h/' \ + debian/multiarch.h.in > $(d_ldbg)/usr/include/$(PVER)_d/pyconfig.h + ln -sf $(PVER).1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg.1.gz + ln -sf $(DEB_HOST_MULTIARCH)-$(PVER)-dbg-config \ + $(d_dbg)/usr/bin/$(PVER)-dbg-config + ln -sf $(PVER)-config.1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg-config.1.gz + + for i in debian/*.overrides; do \ + b=$$(basename $$i .overrides); \ + install -D -m 644 $$i debian/$$b/usr/share/lintian/overrides/$$b; \ + done + + touch stamps/stamp-install + +# Build architecture-independent files here. +binary-indep: build-indep install stamps/stamp-control + dh_testdir -i + dh_testroot -i + + : # $(p_doc) package + dh_installdirs -p$(p_doc) \ + usr/share/doc/$(p_base) \ + usr/share/doc/$(p_doc) + dh_installdocs -p$(p_doc) + cp -a Doc/build/html $(d_doc)/usr/share/doc/$(p_base)/ + rm -f $(d_doc)/usr/share/doc/$(p_base)/html/_static/jquery.js + rm -f $(d_doc)/usr/share/doc/$(p_base)/html/_static/underscore.js + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html \ + /usr/share/doc/$(p_doc)/html \ + /usr/share/javascript/jquery/jquery.js \ + /usr/share/doc/$(p_base)/html/_static/jquery.js \ + /usr/share/javascript/underscore/underscore.js \ + /usr/share/doc/$(p_base)/html/_static/underscore.js + + : # devhelp docs + python debian/pyhtml2devhelp.py \ + $(d_doc)/usr/share/doc/$(p_base)/html index.html $(VER) \ + > $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + gzip -9v $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html /usr/share/devhelp/books/$(PVER) + + for i in $(p_ltst); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_lbase) debian/$$i/usr/share/doc/$$i; \ + done + + dh_installdebconf -i $(dh_args) + dh_installexamples -i $(dh_args) + dh_installmenu -i $(dh_args) + -dh_icons -i $(dh_args) || dh_iconcache -i $(dh_args) + dh_installchangelogs -i $(dh_args) + dh_link -i $(dh_args) + dh_compress -i $(dh_args) -X.py -X.cls -X.css -X.txt -X.json -X.js -Xobjects.inv -Xgdbinit + dh_fixperms -i $(dh_args) + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + -find $(d_doc) -name '*.txt' -perm 755 -exec chmod 644 {} \; + + dh_installdeb -i $(dh_args) + dh_gencontrol -i $(dh_args) + dh_md5sums -i $(dh_args) + dh_builddeb -i $(dh_args) + +# Build architecture-dependent files here. +binary-arch: build-arch install + dh_testdir -a + dh_testroot -a +# dh_installdebconf -a + dh_installexamples -a + dh_installmenu -a + -dh_icons -a || dh_iconcache -a +# dh_installmime -a + dh_installchangelogs -a + for i in $(p_dev) $(p_dbg); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_base) debian/$$i/usr/share/doc/$$i; \ + done + for i in $(p_lbase); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_lmin) debian/$$i/usr/share/doc/$$i; \ + done + for i in $(p_ldev) $(p_ldbg) $(p_lib); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_lbase) debian/$$i/usr/share/doc/$$i; \ + done + -find debian ! -perm -200 -print -exec chmod +w {} \; +ifneq ($(with_tk),yes) + rm -f $(d_lbase)/$(scriptdir)/lib-dynload/_tkinter.$(DEB_HOST_MULTIARCH).so +endif +ifneq ($(with_gdbm),yes) + rm -f $(d_lbase)/$(scriptdir)/lib-dynload/gdbm.$(DEB_HOST_MULTIARCH).so +endif + dh_strip -a -N$(p_dbg) -Xdebug -Xdbg --dbg-package=$(p_dbg) + cp Tools/gdb/libpython.py $(d_dbg)/usr/lib/debug/usr/bin/$(PVER)-gdb.py + ln -sf $(PVER)-gdb.py $(d_dbg)/usr/lib/debug/usr/bin/$(PVER)-dbg-gdb.py + ln -sf ../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/lib/debug/usr/lib/lib$(PVER).so.1.0-gdb.py + ln -sf ../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/lib/lib$(PVER)_d.so.1.0-gdb.py + dh_link -a + dh_compress -a -X.py + dh_fixperms -a + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + + dh_makeshlibs -p$(p_lib) -V '$(p_lib)' + dh_makeshlibs -p$(p_ldbg) -V '$(p_ldbg)' +# don't include the following symbols, found in extensions +# which either can be built as builtin or extension. + sed -ri '/^ (_check_|asdl_|fast_save_|init)/d' \ + $(d_lib)/DEBIAN/symbols $(d_ldbg)/DEBIAN/symbols + dh_shlibdeps -a + dep=`sed -n '/^shlibs:Depends/s/.*\(libc6[^,]*\).*/\1/p' $(d_min).substvars`; \ + echo "shlibs:Pre-Depends=$$dep" >> $(d_min).substvars + sed -i '/^shlibs:Depends/s/libc6[^,]*[, ]*//' $(d_min).substvars + dh_installdeb -a + dh_gencontrol -a + dh_md5sums -a + dh_builddeb -a + +# rules to patch the unpacked files in the source directory +# --------------------------------------------------------------------------- +# various rules to unpack addons and (un)apply patches. +# - patch / apply-patches +# - unpatch / reverse-patches + +patchdir = debian/patches + +glibc_version := $(shell dpkg -s locales | awk '/^Version:/ {print $$2}') +broken_utimes := $(shell dpkg --compare-versions $(glibc_version) lt 2.3.5 && echo yes || echo no) + +$(patchdir)/series: $(patchdir)/series.in + cpp -E \ + -D$(distribution) \ + $(if $(filter $(broken_utimes),yes),-DBROKEN_UTIMES) \ + $(if $(filter $(with_fpectl),yes),-DWITH_FPECTL) \ + -Darch_os_$(DEB_HOST_ARCH_OS) -Darch_$(DEB_HOST_ARCH) \ + -o - $(patchdir)/series.in \ + | egrep -v '^(#.*|$$)' > $(patchdir)/series + +patch: stamps/stamp-patch +stamps/stamp-patch: $(patchdir)/series + dh_testdir + uname -a + @echo USER=$$USER, LOGNAME=$$LOGNAME + QUILT_PATCHES=$(patchdir) quilt push -a || test $$? = 2 + rm -rf autom4te.cache configure + autoconf + mkdir -p stamps + echo ""; echo "Patches applied in this version:" > stamps/pxx + for i in $$(cat $(patchdir)/series); do \ + echo ""; echo "$$i:"; \ + sed -n 's/^# *DP: */ /p' $(patchdir)/$$i; \ + done >> stamps/pxx + mv stamps/pxx $@ + + : # don't build pgen for cross builds, adjust timestamps + touch Parser/acceler.c Parser/grammar1.c Parser/listnode.c \ + Parser/node.c Parser/parser.c Parser/parsetok.c Parser/bitset.c \ + Parser/metagrammar.c Parser/firstsets.c Parser/grammar.c \ + Parser/pgen.c + touch Objects/obmalloc.c Python/mysnprintf.c Python/pyctype.c \ + Parser/tokenizer_pgen.c Parser/printgrammar.c Parser/pgenmain.c + @sleep 1 + touch Grammar/Grammar + @sleep 1 + touch Include/graminit.h + @sleep 1 + touch Python/graminit.c + ln -sf site-packages Lib/dist-packages + +reverse-patches: unpatch +unpatch: + QUILT_PATCHES=$(patchdir) quilt pop -a -R || test $$? = 2 + rm -f stamps/stamp-patch $(patchdir)/series + rm -rf configure autom4te.cache + rm -f Lib/dist-packages + +update-patches: $(patchdir)/series + export QUILT_PATCHES=$(patchdir); \ + export QUILT_REFRESH_ARGS="--no-timestamps --no-index -pab"; \ + export QUILT_DIFF_ARGS="--no-timestamps --no-index -pab"; \ + while quilt push; do quilt refresh; done + +binary: binary-indep binary-arch + +.PHONY: control-file configure build clean binary-indep binary-arch binary install + +# Local Variables: +# mode: makefile +# end: --- python2.7-2.7.6.orig/debian/script.py +++ python2.7-2.7.6/debian/script.py @@ -0,0 +1,61 @@ +#! /usr/bin/python + +# Copyright (C) 2012 Colin Watson . +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +"""Trivial script(1) workalike, but without reading from standard input.""" + +import os +import pty +import select +import sys + +filename = sys.argv[1] +command = sys.argv[2] + +pid, master = pty.fork() +if pid == 0: # child + os.execlp("sh", "sh", "-c", command) + +# parent +with open(filename, "w") as logfile: + try: + while True: + rfds, _, _ = select.select([master], [], []) + if master in rfds: + data = os.read(master, 65536) + os.write(1, data) + logfile.write(data) + logfile.flush() + except (IOError, OSError): + pass + +pid, status = os.wait() +returncode = 0 +if os.WIFSIGNALED(status): + returncode = -os.WTERMSIG(status) +elif os.WIFEXITED(status): + returncode = os.WEXITSTATUS(status) +else: + # Should never happen + raise RuntimeError("Unknown child exit status!") +os.close(master) +sys.exit(returncode) --- python2.7-2.7.6.orig/debian/sitecustomize.py.in +++ python2.7-2.7.6/debian/sitecustomize.py.in @@ -0,0 +1,7 @@ +# install the apport exception handler if available +try: + import apport_python_hook +except ImportError: + pass +else: + apport_python_hook.install() --- python2.7-2.7.6.orig/debian/source.lintian-overrides +++ python2.7-2.7.6/debian/source.lintian-overrides @@ -0,0 +1,11 @@ +# this is conditional in the rules file +python2.7 source: debhelper-script-needs-versioned-build-depends dh_icons (>= 5.0.51~) + +# generated during the build +python2.7 source: quilt-build-dep-but-no-series-file + +# doesn't support any newer versions +python2.7 source: build-depends-on-versioned-berkeley-db + +# using the system libffi +python2.7 source: outdated-autotools-helper-file --- python2.7-2.7.6.orig/debian/source.lintian-overrides.in +++ python2.7-2.7.6/debian/source.lintian-overrides.in @@ -0,0 +1,11 @@ +# this is conditional in the rules file +@PVER@ source: debhelper-script-needs-versioned-build-depends dh_icons (>= 5.0.51~) + +# generated during the build +@PVER@ source: quilt-build-dep-but-no-series-file + +# doesn't support any newer versions +@PVER@ source: build-depends-on-versioned-berkeley-db + +# using the system libffi +@PVER@ source: outdated-autotools-helper-file --- python2.7-2.7.6.orig/debian/source/format +++ python2.7-2.7.6/debian/source/format @@ -0,0 +1 @@ +1.0 --- python2.7-2.7.6.orig/debian/tests/control +++ python2.7-2.7.6/debian/tests/control @@ -0,0 +1,19 @@ +Tests: testsuite +Depends: build-essential, python2.7-dev, libpython2.7-testsuite, python-gdbm +# test_zipfile wants to write +Restrictions: needs-root + +Tests: testsuite-dbg +Depends: build-essential, python2.7-dev, python2.7-dbg, libpython2.7-testsuite, python-gdbm-dbg +# test_zipfile wants to write +Restrictions: needs-root + +Tests: failing-tests +Depends: build-essential, python2.7-dev, libpython2.7-testsuite, python-gdbm +# test_zipfile wants to write +Restrictions: needs-root allow-stderr + +Tests: failing-tests-dbg +Depends: build-essential, python2.7-dev, python2.7-dbg, libpython2.7-testsuite, python-gdbm-dbg +# test_zipfile wants to write +Restrictions: needs-root allow-stderr --- python2.7-2.7.6.orig/debian/tests/failing-tests +++ python2.7-2.7.6/debian/tests/failing-tests @@ -0,0 +1,114 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + stop apport 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + + if status apport | grep -q start; then + echo >&2 "apport is running. needs to be disabled before running the tests" + exit 1 + fi + fi +fi +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C +arch=$(dpkg --print-architecture) + +TESTPYTHON="python2.7 -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS= + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: Issue 17752, many failures in installed location +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_gdb: not run for the optimized build +TESTEXCLUSIONS="$TESTEXCLUSIONS test_gdb" + +# test_pydoc: Issue 17773, failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_pydoc" + +# test_tools: not relevant for installed version +TESTEXCLUSIONS="$TESTEXCLUSIONS test_tools" + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# test_subprocess: Issue 17757, two failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_subprocess" + +# test_uuid: fails, but not on the buildd. need to investigate +TESTEXCLUSIONS="$TESTEXCLUSIONS test_uuid" + +if [ "$su_user" = nobody ]; then + log=/dev/null + # test_site: Issue 17758, fails to create HOME + TESTEXCLUSIONS="$TESTEXCLUSIONS test_site" +else + log=testsuite.log +fi + +# run some tests separately in it's own run. These succeed locally, +# but fail on the test setup. +SEPARATE_TESTS= +case "$arch" in + amd64) + ;; + i386) + SEPARATE_TESTS="$SEPARATE_TESTS test_io" + ;; +esac + +script=$debian_dir/script.py + +echo "Running the failing tests with the standard interpreter:" +progressions= +for tst in $TESTEXCLUSIONS; do + if [ -f "$script" ]; then + cmd="python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $tst\"" + else + cmd="$TESTPYTHON $TESTOPTS $tst" + fi + + echo "Running $tst ..." + if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd $su_user" + if su -s /bin/sh -c "$cmd" $su_user; then + progressions="$progressions $tst" + else + : + fi + else + echo "$cmd" + if eval $cmd; then + progressions="$progressions $tst" + else + : + fi + fi +done + +if [ -n "$progressions" ]; then + echo "Tests run: $TESTEXCLUSIONS" + echo "Progressions:$progressions" +fi + +exit 0 --- python2.7-2.7.6.orig/debian/tests/failing-tests-dbg +++ python2.7-2.7.6/debian/tests/failing-tests-dbg @@ -0,0 +1,99 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + stop apport 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + + if status apport | grep -q start; then + echo >&2 "apport is running. needs to be disabled before running the tests" + exit 1 + fi + fi +fi +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C + +TESTPYTHON="python2.7-dbg -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS= + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: Issue 17752, many failures in installed location +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_pydoc: Issue 17773, failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_pydoc" + +# test_tools: not relevant for installed version +TESTEXCLUSIONS="$TESTEXCLUSIONS test_tools" + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# test_subprocess: Issue 17757, two failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_subprocess" + +# test_uuid: fails, but not on the buildd. need to investigate +TESTEXCLUSIONS="$TESTEXCLUSIONS test_uuid" + +if [ "$su_user" = nobody ]; then + log=/dev/null + # test_site: Issue 17758, fails to create HOME + TESTEXCLUSIONS="$TESTEXCLUSIONS test_site" +else + log=testsuite-dbg.log +fi + +script=$debian_dir/script.py + +echo "Running the failing tests with the standard interpreter:" +progressions= +for tst in $TESTEXCLUSIONS; do + if [ -f "$script" ]; then + cmd="python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $tst\"" + else + cmd="$TESTPYTHON $TESTOPTS $tst" + fi + + echo "Running $tst ..." + if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd $su_user" + if su -s /bin/sh -c "$cmd" $su_user; then + progressions="$progressions $tst" + else + : + fi + else + echo "$cmd" + if eval $cmd; then + progressions="$progressions $tst" + else + : + fi + fi +done + +if [ -n "$progressions" ]; then + echo "Tests run: $TESTEXCLUSIONS" + echo "Progressions:$progressions" +fi + +exit 0 --- python2.7-2.7.6.orig/debian/tests/testsuite +++ python2.7-2.7.6/debian/tests/testsuite @@ -0,0 +1,104 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + stop apport 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + + if status apport | grep -q start; then + echo >&2 "apport is running. needs to be disabled before running the tests" + exit 1 + fi + fi +fi +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C +arch=$(dpkg --print-architecture) + +TESTPYTHON="python2.7 -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS="-x" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: Issue 17752, many failures in installed location +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_gdb: not run for the optimized build +TESTEXCLUSIONS="$TESTEXCLUSIONS test_gdb" + +# test_pydoc: Issue 17773, failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_pydoc" + +# test_tools: not relevant for installed version +TESTEXCLUSIONS="$TESTEXCLUSIONS test_tools" + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# test_subprocess: Issue 17757, two failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_subprocess" + +# test_uuid: fails, but not on the buildd. need to investigate +TESTEXCLUSIONS="$TESTEXCLUSIONS test_uuid" + +if [ "$su_user" = nobody ]; then + log=/dev/null + # test_site: Issue 17758, fails to create HOME + TESTEXCLUSIONS="$TESTEXCLUSIONS test_site" +else + log=testsuite.log +fi + +# run some tests separately in it's own run. These succeed locally, +# but fail on the test setup. +SEPARATE_TESTS= +case "$arch" in + amd64) + ;; + i386) + SEPARATE_TESTS="$SEPARATE_TESTS test_io" + ;; +esac + +script=$debian_dir/script.py +if [ -f "$script" ]; then + cmd1="python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS $SEPARATE_TESTS\"" + cmd2="python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $SEPARATE_TESTS\"" +else + cmd1="$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS $SEPARATE_TESTS" + cmd2="$TESTPYTHON $TESTOPTS $SEPARATE_TESTS" +fi + +echo "Running the python testsuite with the standard interpreter:" +if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd1 $su_user" + su -s /bin/sh -c "$cmd1" $su_user + if [ -n "$SEPARATE_TESTS" ]; then + echo "su -s /bin/sh -c $cmd2 $su_user" + su -s /bin/sh -c "$cmd2" $su_user + fi +else + echo "$cmd1" + eval $cmd1 + if [ -n "$SEPARATE_TESTS" ]; then + echo "$cmd2" + eval $cmd2 + fi +fi --- python2.7-2.7.6.orig/debian/tests/testsuite-dbg +++ python2.7-2.7.6/debian/tests/testsuite-dbg @@ -0,0 +1,78 @@ +#!/bin/sh + +set -e + +if [ "$(whoami)" = root ]; then + if [ -n "$SUDO_USER" ] && getent passwd "$SUDO_USER" > /dev/null; then + su_user="$SUDO_USER" + else + su_user=nobody + fi + + if [ -e /etc/default/apport ]; then + # stop apport + stop apport 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + + if status apport | grep -q start; then + echo >&2 "apport is running. needs to be disabled before running the tests" + exit 1 + fi + fi +fi +# no root access needed after this point + +debian_dir=$(dirname $(dirname $0)) + +export LOCPATH=$(pwd)/locales +sh $debian_dir/locale-gen + +export LANG=C + +TESTPYTHON="python2.7-dbg -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS="-x" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: Issue 17752, many failures in installed location +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_pydoc: Issue 17773, failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_pydoc" + +# test_tools: not relevant for installed version +TESTEXCLUSIONS="$TESTEXCLUSIONS test_tools" + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +# test_subprocess: Issue 17757, two failing tests +TESTEXCLUSIONS="$TESTEXCLUSIONS test_subprocess" + +# test_uuid: fails, but not on the buildd. need to investigate +TESTEXCLUSIONS="$TESTEXCLUSIONS test_uuid" + +if [ "$su_user" = nobody ]; then + log=/dev/null + # test_site: Issue 17758, fails to create HOME + TESTEXCLUSIONS="$TESTEXCLUSIONS test_site" +else + log=testsuite-dbg.log +fi + +script=$debian_dir/script.py +if [ -f "$script" ]; then + cmd="python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS\"" +else + cmd="$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS" +fi +echo "Running the python testsuite with the debug enabled interpreter:" +if [ "$(whoami)" = root ]; then + echo "su -s /bin/sh -c $cmd $su_user" + su -s /bin/sh -c "$cmd" $su_user +else + echo "$cmd" + eval $cmd +fi --- python2.7-2.7.6.orig/debian/watch +++ python2.7-2.7.6/debian/watch @@ -0,0 +1,3 @@ +version=3 +opts=dversionmangle=s/.*\+//,uversionmangle=s/([abcr]+[1-9])$/~$1/ \ + http://www.python.org/ftp/python/2\.7(\.\d)?/Python-(2\.7[.\dabcr]*)\.tgz