--- python2.7-2.7.11.orig/debian/2to3-2.7.1 +++ python2.7-2.7.11/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.11.orig/debian/FAQ.html +++ python2.7-2.7.11/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.11.orig/debian/PVER-dbg.README.Debian.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-dbg.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-dbg.postinst.in +++ python2.7-2.7.11/debian/PVER-dbg.postinst.in @@ -0,0 +1,19 @@ +#! /bin/sh + +set -e + +if [ "$1" = configure ]; then + files=$(dpkg -L lib@PVER@-dbg@HOST_QUAL@ | 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.11.orig/debian/PVER-dbg.prerm.in +++ python2.7-2.7.11/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@HOST_QUAL@ \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs -r rm -f >&2 + ;; + upgrade) + dpkg -L lib@PVER@-dbg@HOST_QUAL@ \ + | 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.11.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-dist.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-new.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-doc.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-examples.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-minimal.README.Debian.in +++ python2.7-2.7.11/debian/PVER-minimal.README.Debian.in @@ -0,0 +1,157 @@ +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 + calendar module + codecs module + collections module + compileall module + contextlib module + copy module + copy_reg module + datetime extension + dis module + encodings package + 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 + locale 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.11.orig/debian/PVER-minimal.postinst.in +++ python2.7-2.7.11/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@HOST_QUAL@ \ + | 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.11.orig/debian/PVER-minimal.postrm.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-minimal.preinst.in +++ python2.7-2.7.11/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.11.orig/debian/PVER-minimal.prerm.in +++ python2.7-2.7.11/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.11.orig/debian/PVER.desktop.in +++ python2.7-2.7.11/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.11.orig/debian/PVER.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/PVER.postinst.in +++ python2.7-2.7.11/debian/PVER.postinst.in @@ -0,0 +1,41 @@ +#! /bin/sh + +set -e + +case "$1" in + configure) + files=$(dpkg -L lib@PVER@-stdlib@HOST_QUAL@ | 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.11.orig/debian/PVER.prerm.in +++ python2.7-2.7.11/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.11.orig/debian/PVER.pycentral.in +++ python2.7-2.7.11/debian/PVER.pycentral.in @@ -0,0 +1,4 @@ +[@PVER@] +runtime: @PVER@ +interpreter: /usr/bin/@PVER@ +prefix: /usr/lib/@PVER@ --- python2.7-2.7.11.orig/debian/README.Debian.in +++ python2.7-2.7.11/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.11.orig/debian/README.PVER.in +++ python2.7-2.7.11/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.11.orig/debian/README.Tk +++ python2.7-2.7.11/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.11.orig/debian/README.dbm +++ python2.7-2.7.11/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.11.orig/debian/README.idle-PVER.in +++ python2.7-2.7.11/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.11.orig/debian/README.maintainers.in +++ python2.7-2.7.11/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.11.orig/debian/README.python +++ python2.7-2.7.11/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.11.orig/debian/README.source +++ python2.7-2.7.11/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.11.orig/debian/_sysconfigdata.py +++ python2.7-2.7.11/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.11.orig/debian/argparse.egg-info +++ python2.7-2.7.11/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.11.orig/debian/changelog +++ python2.7-2.7.11/debian/changelog @@ -0,0 +1,3966 @@ +python2.7 (2.7.11-5) unstable; urgency=medium + + * Update to 20160319, taken from the 2.7 release branch. + * Update symbols files. + * Don't run test_signal on alpha, hanging on the buildd. + + -- Matthias Klose Sat, 19 Mar 2016 13:14:21 +0100 + +python2.7 (2.7.11-4) unstable; urgency=medium + + * Update to 20160222, taken from the 2.7 release branch. + + -- Matthias Klose Mon, 22 Feb 2016 17:38:42 +0100 + +python2.7 (2.7.11-3) unstable; urgency=medium + + * Revert patches concerning issue #22995. + + -- Matthias Klose Mon, 11 Jan 2016 22:04:40 +0100 + +python2.7 (2.7.11-2) unstable; urgency=medium + + * Disable LTO on ppc64, ppc64el and s390x. + * Don't run the test_signal tests on alpha. + + -- Matthias Klose Wed, 09 Dec 2015 01:29:25 +0100 + +python2.7 (2.7.11-1) unstable; urgency=medium + + * Python 2.7.11 release. + * Don't run the test_cpickle test, causes other tests to fail. + See issue 25698. + * Fix building architecture independent packages only. Closes: #806868. + * Don't ship menu files anymore, just desktop files. + * d/p/fix-sslv3-test.diff: properly handle Ubuntu's openssl having OP_NO_SSLv3 + forced on by default (Marc Deslauriers). + * Update symbols files. + + -- Matthias Klose Mon, 07 Dec 2015 14:27:52 +0100 + +python2.7 (2.7.10-5) unstable; urgency=medium + + * Update to 20151010, taken from the 2.7 release branch. + * Adjust setting DH_COMPAT for dh_movefiles with updated debhelper supporting + globbing of arguments. Closes: #800301. + * pydoc: use the pager command if available. Closes: #799555. + + -- Matthias Klose Sat, 10 Oct 2015 11:11:24 +0200 + +python2.7 (2.7.10-4) unstable; urgency=medium + + * Remove byte-code for _sysconfigdata_d.py in /usr/lib/python2.7. + Closes: #793528. + * Make derivatives builds the same as the parent distro. Closes: #797667. + + -- Matthias Klose Sun, 13 Sep 2015 22:30:50 +0200 + +python2.7 (2.7.10-3) unstable; urgency=medium + + * Revert issue #24134 changes, taken from the branch. + * Add hint to install the idle package when trying to run the turtle demo. + Closes: #788621. + + -- Matthias Klose Wed, 01 Jul 2015 12:54:53 +0200 + +python2.7 (2.7.10-2) unstable; urgency=medium + + * Cherry-pick some changes from the 2.7 branch: + - Issue #24264: Fixed buffer overflow in the imageop module. + - Issue #24115: Update uses of PyObject_IsTrue(), PyObject_Not(), + PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains() + to check for and handle errors correctly. + - Issue #22095: Fixed HTTPConnection.set_tunnel with default port. The port + value in the host header was set to "None". + - Issue #4753, backport computed gotos. + * Configure --with-computed-gotos. + * Make the build reproducible (Jérémy Bobbio). Closes: #786978. + - Pass time of latest debian/changelog entry to sphinx via SPHINXOPTS. + - Do not store a timestamps when compressing devhelp. + * Pass DATE and TIME macros matching the current debian/changelog entry + when building getbuildinfo.o. + * Don't run the test_io test on sparc. + + -- Matthias Klose Mon, 01 Jun 2015 18:21:46 +0200 + +python2.7 (2.7.10-1) unstable; urgency=medium + + * Python 2.7.10 release. + + -- Matthias Klose Tue, 26 May 2015 14:47:02 +0200 + +python2.7 (2.7.10~rc1-1) unstable; urgency=medium + + * Python 2.7.10 release candidate 1. + * Re-enable running the tests, re-enable the pgo/lto build. + + -- Matthias Klose Sun, 10 May 2015 23:40:03 +0200 + +python2.7 (2.7.9-5) unstable; urgency=medium + + * Update to 20150507, taken from the 2.7 release branch. + - Issue #24134: assertRaises() and assertRaisesRegexp() checks are not + longer successful if the callable is None. + - Issues #24099, #24100, and #24101: Fix free-after-use bug in heapq's + siftup and siftdown functions. + - Backport collections.deque fixes from Python 3.5. Prevents reentrant + badness during deletion by deferring the decref until the container has + been restored to a consistent state. + - Issue #24125: Saved error's line and column numbers when an error + occured. Fixes python-docutils. Closes: #784270. + - Issue #23842, SystemError in os.minor, os.major. Closes: #782081. + + -- Matthias Klose Wed, 06 May 2015 22:47:05 +0200 + +python2.7 (2.7.9-4) unstable; urgency=medium + + * Fix installation of the optimized interpreter. Closes: #766877. + + -- Matthias Klose Wed, 29 Apr 2015 19:09:39 +0200 + +python2.7 (2.7.9-3) unstable; urgency=medium + + * Update to 20150429, taken from the 2.7 release branch. + - Issue #23629: Fix the default __sizeof__ implementation for + variable-sized objects. + - Issue #21526: Tkinter now supports new boolean type in Tcl 8.5. + - Issue #23838: linecache now clears the cache and returns an empty + result on MemoryError. + - Issue #23742: ntpath.expandvars() no longer loses unbalanced single + quotes. + - Issue #21802: The reader in BufferedRWPair now is closed even when + closing writer failed in BufferedRWPair.close(). + - Issue #23671: string.Template now allows to specify the "self" parameter + as keyword argument. string.Formatter now allows to specify the "self" + and the "format_string" parameters as keyword arguments. + - Issue #21560: An attempt to write a data of wrong type no longer cause + GzipFile corruption. + - Issue #23647: Increase imaplib's MAXLINE to accommodate modern mailbox + sizes. + - Issue #23539: If body is None, http.client.HTTPConnection.request now + sets Content-Length to 0 for PUT, POST, and PATCH headers to avoid + 411 errors from some web servers. + - Issue #23136: _strptime now uniformly handles all days in week 0, + including Dec 30 of previous year. + - Issue #23138: Fixed parsing cookies with absent keys or values in + cookiejar. + - Issue #23051: multiprocessing.Pool methods imap() and imap_unordered() + now handle exceptions raised by an iterator. + - Issue #22928: Disabled HTTP header injections in httplib. + - Issue #23615: Module tarfile now can be reloaded with imp.reload(). + - Issue #23799: Added test.test_support.start_threads() for running and + cleaning up multiple threads. + - Issue #22390: test.regrtest now emits a warning if temporary files or + directories are left after running a test. + - Issue #23583: Added tests for standard IO streams in IDLE. + - Issue #23583: Fixed writing unicode to standard output stream in IDLE. + - Issue #22853: Fixed a deadlock when use multiprocessing.Queue at import + time. + - Issue #23476: In the ssl module, enable OpenSSL's + X509_V_FLAG_TRUSTED_FIRST flag on certificate stores when it is available. + - Issue #23576: Avoid stalling in SSL reads when EOF has been reached + in the SSL layer but the underlying connection hasn't been closed. + - Issue #23504: Added an __all__ to the types module. + - Issue #23367: Fix possible overflows in the unicodedata module. + - Issue #23055: Fixed a buffer overflow in PyUnicode_FromFormatV. + - Issue #23048: Fix jumping out of an infinite while loop in the pdb. + - Issue #23458: On POSIX, the file descriptor kept open by os.urandom() is + now set to non inheritable. + - Issue #22113: struct.pack_into() now supports new buffer protocol (in + particular accepts writable memoryview). + - Issues #814253, #9179: Warnings now are raised when group references and + conditional group references are used in lookbehind assertions in regular + expressions. + - Issue #23215: Multibyte codecs with custom error handlers that ignores + errors consumed too much memory and raised SystemError or MemoryError. + - Issue #5700: io.FileIO() called flush() after closing the file. + flush() was not called in close() if closefd=False. + - Issue #21548: Fix pydoc.synopsis() and pydoc.apropos() on modules with + empty docstrings. + - Issue #22885: Fixed arbitrary code execution vulnerability in the dumbdbm + module. + - Issue #23481: Remove RC4 from the SSL module's default cipher list. + - Issue #21849: Fixed xmlrpclib serialization of non-ASCII unicode strings + in the multiprocessing module. + - Issue #21840: Fixed expanding unicode variables of form $var in + posixpath.expandvars(). Fixed all os.path implementations on + unicode-disabled builds. + - Issue #23363: Fix possible overflow in itertools.permutations. + - Issue #23364: Fix possible overflow in itertools.product. + - Issue #23365: Fixed possible integer overflow in + itertools.combinations_with_replacement. + - Issue #23366: Fixed possible integer overflow in itertools.combinations. + - Issue #23191: fnmatch functions that use caching are now threadsafe. + - Issue #18518: timeit now rejects statements which can't be compiled + outside a function or a loop (e.g. "return" or "break"). + - Issue #19996: Make :mod:`httplib` ignore headers with no name rather than + assuming the body has started. + - Issue #20188: Support Application-Layer Protocol Negotiation (ALPN) in the + ssl module. + - Issue #23248: Update ssl error codes from latest OpenSSL git master. + - Issue #23098: 64-bit dev_t is now supported in the os module. + - Issue #23063: In the disutils' check command, fix parsing of reST with + code or code-block directives. + - Issue #21356: Make ssl.RAND_egd() optional to support LibreSSL. The + availability of the function is checked during the compilation. + - Backport the context argument to ftplib.FTP_TLS. + - Issue #23111: Maximize compatibility in protocol versions of + ftplib.FTP_TLS. + - Issue #23112: Fix SimpleHTTPServer to correctly carry the query string + and fragment when it redirects to add a trailing slash. + - Issue #22585: On OpenBSD 5.6 and newer, os.urandom() now calls + getentropy(), instead of reading /dev/urandom, to get pseudo-random bytes. + - Issue #23093: In the io, module allow more operations to work on detached + streams. + - Issue #23071: Added missing names to codecs.__all__. + - Issue #23016: A warning no longer produces an AttributeError when + sys.stderr is None. + - Issue #21032. Fixed socket leak if HTTPConnection.getresponse() fails. + Original patch by Martin Panter. + - Issue #22609: Constructors and update methods of mapping classes in the + collections module now accept the self keyword argument. + - Issue #23006: Improve the documentation and indexing of dict.__missing__. + Add an entry in the language datamodel special methods section. + Revise and index its discussion in the stdtypes mapping/dict section. + Backport the code example from 3.4. + - Issue #21514: The documentation of the json module now refers to new + JSON RFC 7159 instead of obsoleted RFC 4627. + - Issue #6639: Module-level turtle functions no longer raise TclError after + closing the window. + - Issue #22314: pydoc now works when the LINES environment variable is set. + - Issue #18905: "pydoc -p 0" now outputs actually used port. + - Issue #23345: Prevent test_ssl failures with large OpenSSL patch level + values (like 0.9.8zc). + - Issue #23392: Added tests for marshal C API that works with FILE*. + - Issue #18982: Add tests for CLI of the calendar module. + - Issue #19949: The test_xpickle test now tests compatibility with installed + Python 2.7 and reports skipped tests. + - Issue #11578: Backported test for the timeit module. + - Issue #22943: bsddb tests are locale independend now. + - Issue #20577: Configuration of the max line length for the FormatParagraph + extension has been moved from the General tab of the Idle preferences + dialog to the FormatParagraph tab of the Config Extensions dialog. + - Issue #16893: Update Idle doc chapter to match current Idle and add new + information. + - Issue #23180: Rename IDLE "Windows" menu item to "Window". + - Issue #15506: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the + configure script. + - Issue #22079: PyType_Ready() now checks that statically allocated type has + no dynamically allocated bases. + * Re-apply the fix for issue #22079. This is now a warning instead of an + error. LP: #1426294. + * Fix issue #23842, SystemError in os.minor, os.major. LP: #1435242. + * When using GCC versions older than 4.9 for extension builds, automagically + mangle -fstack-protector-strong to -fstack-protector. + * debian/tests: Use init system agnostic "service" command instead of + upstart specific "stop". Also drop unnecessary "status" call right after + stopping apport. + * Refresh patches. + + -- Matthias Klose Wed, 29 Apr 2015 03:03:55 +0200 + +python2.7 (2.7.9-2) unstable; urgency=medium + + * python2.7-minimal: Make Pre-Depends mangling more robust. Closes: #779294. + * python2.7-doc: Depend on libjs-underscore. LP: #1424538. + * Remove LTO sections from the static libraries. Closes: #698395. + + -- Matthias Klose Sun, 01 Mar 2015 10:56:57 +0100 + +python2.7 (2.7.9-1) unstable; urgency=medium + + * Python 2.7.9 release. + + -- Matthias Klose Thu, 11 Dec 2014 00:38:09 +0100 + +python2.7 (2.7.9~rc1-2) unstable; urgency=medium + + * Update to 20141209, taken from the 2.7 release repository. + - Issue #22959: Remove the *check_hostname* parameter of + httplib.HTTPSConnection. The *context* parameter should be used instead. + - Issue #16043: Add a default limit for the amount of data + xmlrpclib.gzip_decode will return. This resolves CVE-2013-1753. + Closes: #742929. + - Issue #16042: CVE-2013-1752: smtplib: Limit amount of data read by + limiting the call to readline(). Closes: #742929. + - Issue #16041: In poplib, limit maximum line length read from the server + to prevent CVE-2013-1752. Closes: #742929. + - Issue #22960: Add a context argument to xmlrpclib.ServerProxy. + - Issue #22935: Allow the ssl module to be compiled if openssl + doesn't support SSL 3. + * Add locales to autopkg test dependencies as in 3.4. + * Remove Demo/scripts/newslist.* from the examples package, not + distributable, will get removed in 2.7.9~rc2 sources. See issue #12987. + * Let ensurepip always use a temporary directory for installations. + + -- Matthias Klose Tue, 09 Dec 2014 15:47:40 +0100 + +python2.7 (2.7.9~rc1-1) unstable; urgency=medium + + * Python 2.7.9 release candidate 1. + - Testsuite updates. + - Issue #16056: Rename test methods to avoid conflict. + - Issue #20351: Add examples for csv.DictReader and csv.DictWriter. + - PEP 476: verify certificates by default (#22417). + - Give urllib.urlopen a context parameter (closes #22927). + - Allow hostname to be passed to SSLContext even if OpenSSL doesn't + support SNI (closes #22921). + - Allow passing cert/ssl information to urllib2.urlopen and + httplib.HTTPSConnection (backport of issues #9003 and #22366). + * Let libpython2.7-stdlib break python-urllib3 (<< 1.9.1-3). Closes: #770157. + * Ignore the test_threading_local test failure in the Debian CI environment. + Succeeds even there when repeated. + * Don't pass default compiler search directories in the pkgconfig file. + Closes: #770935. + + -- Matthias Klose Wed, 26 Nov 2014 21:01:48 +0100 + +python2.7 (2.7.8-12) unstable; urgency=medium + + * Update to 20141118, taken from the 2.7 branch. + - Issue #12728: Different Unicode characters having the same uppercase + but different lowercase are now matched in case-insensitive regular + expressions. + - Issue #22821: Fixed fcntl() with integer argument on 64-bit big-endian + platforms. + - Issues #814253, #9179: Group references and conditional group references + now work in lookbehind assertions in regular expressions. + - Issue #22769: Fixed ttk.Treeview.tag_has() when called without arguments. + - Issue #22787: Allow the keyfile argument of SSLContext.load_cert_chain + to be None. + - Issue #22775: Fixed unpickling of Cookie.SimpleCookie with protocol 2. + - Issue #22776: Brought excluded code into the scope of a try block in + SysLogHandler.emit(). + - Issue #17381: Fixed ranges handling in case-insensitive regular + expressions. + - Issue #19329: Optimized compiling charsets in regular expressions. + - Issue #22410: Module level functions in the re module now cache compiled + locale-dependent regular expressions taking into account the locale. + - Issue #8876: distutils now falls back to copying files when hard linking + doesn't work. This allows use with special filesystems such as + VirtualBox shared folders. + - Issue #22193: Fixed integer overflow error in sys.getsizeof(). + * Backport the ensurepip patch from 3.4. + * Disable ensurepip in Debian, at least for the upcoming release. + * Fix maintainer scripts for byte-code removal. Closes: #769078. + * Allow building and testing without SSLv3 support (Kurt Roeckx). + Closes: #768611. + * Let distutils.sysconfig.get_python_inc() honor the "prefix" argument. + Closes: #769720. + + -- Matthias Klose Tue, 18 Nov 2014 11:37:13 +0100 + +python2.7 (2.7.8-11) unstable; urgency=medium + + * Update to 20141018, taken from the 2.7 branch. + - Issue #9351: Defaults set with set_defaults on an argparse subparser + are no longer ignored when also set on the parent parser. + - Issue #20421: Add a .version() method to SSL sockets exposing the actual + protocol version in use. + - Issue #22435: Fix a file descriptor leak when SocketServer bind fails. + - Issue #13664: GzipFile now supports non-ascii Unicode filenames. + - Issue #13096: Fixed segfault in CTypes POINTER handling of large + values. + - Issue #11694: Raise ConversionError in xdrlib as documented. + - Issue #10712: 2to3 has a new "asserts" fixer that replaces deprecated names + of unittest methods (e.g. failUnlessEqual -> assertEqual). + * Pass -ffat-lto-objects for LTO enabled builds with GCC 4.9. + + -- Matthias Klose Sat, 18 Oct 2014 14:14:19 +0200 + +python2.7 (2.7.8-10) unstable; urgency=medium + + * Update to 20141007, taken from the 2.7 branch. + + -- Matthias Klose Tue, 07 Oct 2014 19:42:51 +0200 + +python2.7 (2.7.8-9) unstable; urgency=medium + + * Fix refcounting error in the fix for issue #22523. Closes: #762010. + + -- Matthias Klose Thu, 02 Oct 2014 13:49:07 +0200 + +python2.7 (2.7.8-8) unstable; urgency=medium + + * Update to 20141002, taken from the 2.7 branch. + * Refresh patches. + * Apply proposed patch for issue #22523. Closes: #762010. + + -- Matthias Klose Thu, 02 Oct 2014 02:13:37 +0200 + +python2.7 (2.7.8-7) unstable; urgency=medium + + * Update to 20140909, taken from the 2.7 branch. + * debian/tests/testsuite{,-dbg}: Several tests fail with configured proxy + and disabled network test resources. Explicitly unset proxy variables. + See issue #22371. + + -- Matthias Klose Tue, 09 Sep 2014 22:02:11 +0200 + +python2.7 (2.7.8-6) unstable; urgency=medium + + * distuils: For extension builds, always pass BASECFLAGS. + + -- Matthias Klose Sat, 23 Aug 2014 22:50:19 +0200 + +python2.7 (2.7.8-5) unstable; urgency=medium + + * Build-depend on dpkg-dev (>= 1.17.11). + + -- Matthias Klose Mon, 18 Aug 2014 09:43:43 +0200 + +python2.7 (2.7.8-4) unstable; urgency=medium + + * distutils: For extension builds pass the CPPFLAGS, CFLAGS, LDFLAGS + used for the python build when these flags cannot be found in the + environment. + * Don't use the system python during the build. + * Build using autotools-dev. Closes: #756772. + * Pass AR and RANLIB for lto enabled builds. + + -- Matthias Klose Sun, 10 Aug 2014 13:45:31 +0200 + +python2.7 (2.7.8-3) unstable; urgency=medium + + * Call dpkg -L in the maintainer scripts with an architecture qualifier + for M-A: same packages. Closes: #736385. + * Apply the plat-linux2_mips patch for mips64 and mips64el. Closes: #755578. + + -- Matthias Klose Sat, 26 Jul 2014 15:32:47 +0200 + +python2.7 (2.7.8-2) unstable; urgency=medium + + * Revert the backport of issue #1856 (avoid daemon thread problems + at shutdown). Issue #21963. Apparently ceph has issues with it. + Closes: #754341. + + -- Matthias Klose Sat, 12 Jul 2014 10:19:55 +0200 + +python2.7 (2.7.8-1) unstable; urgency=medium + + * Python 2.7.8 release. + + -- Matthias Klose Fri, 04 Jul 2014 14:41:31 +0200 + +python2.7 (2.7.7-2) unstable; urgency=medium + + * Re-enable the test_pydoc, test_tools, test_subprocess and test_uuid + autopkg tests. + * In the autopkg tests, make $ADTTMP accessible to the su user. + + -- Matthias Klose Tue, 03 Jun 2014 10:13:57 +0200 + +python2.7 (2.7.7-1) unstable; urgency=medium + + * Python 2.7.7 release. + * Refresh patches. + * In the autopkg tests, set HOME to the temporary home directory after + the su call. + * Expect test failures in the distutils autopkg tests. + * Disable the test_solaris_enable_shared test. + + -- Matthias Klose Mon, 02 Jun 2014 10:53:46 +0200 + +python2.7 (2.7.7~rc1-1) unstable; urgency=medium + + * Python 2.7.7 release candidate 1. + * Run the testsuite in a temporary home directory. + + -- Matthias Klose Wed, 21 May 2014 12:15:26 +0100 + +python2.7 (2.7.6-8) unstable; urgency=medium + + * Set a temporary home directory for the build and the autopkg tests. + + -- Matthias Klose Sat, 22 Mar 2014 14:31:54 +0100 + +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.11.orig/debian/changelog.shared +++ python2.7-2.7.11/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.11.orig/debian/compat +++ python2.7-2.7.11/debian/compat @@ -0,0 +1 @@ +9 --- python2.7-2.7.11.orig/debian/control +++ python2.7-2.7.11/debian/control @@ -0,0 +1,217 @@ +Source: python2.7 +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 9), dpkg-dev (>= 1.17.11), gcc-5 (>= 5.3.1), + quilt, autoconf, autotools-dev, + 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, time, + libdb-dev (<< 1:6.0), libgdbm-dev, python:any, help2man, + 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, + hardening-wrapper +Standards-Version: 3.9.7 +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~) +Breaks: python-urllib3 (<< 1.9.1-3) +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.8-7~) +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.8-7) +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: ${misc:Pre-Depends} +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: ${misc:Pre-Depends} +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, libjs-underscore, ${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: ${misc:Pre-Depends} +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.11.orig/debian/control.in +++ python2.7-2.7.11/debian/control.in @@ -0,0 +1,217 @@ +Source: @PVER@ +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 9), @bd_dpkgdev@ @bd_gcc@ + quilt, autoconf, autotools-dev, + 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, time, + libdb-dev (<< 1:6.0), libgdbm-dev, python@bd_qual@, help2man, + xvfb, xauth +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, + @PVER@-xml, python-xml, + autoconf2.13, python-cxx-dev, + hardening-wrapper +Standards-Version: 3.9.7 +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~) +Breaks: python-urllib3 (<< 1.9.1-3) +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.8-7~) +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.8-7) +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: ${misc:Pre-Depends} +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: ${misc:Pre-Depends} +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, libjs-underscore, ${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: ${misc:Pre-Depends} +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.11.orig/debian/control.stdlib +++ python2.7-2.7.11/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.11.orig/debian/copyright +++ python2.7-2.7.11/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.11.orig/debian/depgraph.py +++ python2.7-2.7.11/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.11.orig/debian/dh_doclink +++ python2.7-2.7.11/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.11.orig/debian/idle-PVER.1.in +++ python2.7-2.7.11/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.11.orig/debian/idle-PVER.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/idle-PVER.postinst.in +++ python2.7-2.7.11/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.11.orig/debian/idle-PVER.postrm.in +++ python2.7-2.7.11/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.11.orig/debian/idle-PVER.prerm.in +++ python2.7-2.7.11/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.11.orig/debian/idle.desktop.in +++ python2.7-2.7.11/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.11.orig/debian/libPVER-dbg.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/libPVER-dbg.postinst.in +++ python2.7-2.7.11/debian/libPVER-dbg.postinst.in @@ -0,0 +1,12 @@ +#! /bin/sh + +set -e + +if [ "$1" = configure ]; then + # _sysconfigdata_d.py now found in the platform directory + rm -f /usr/lib/python2.7/_sysconfigdata_d.py[co] +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.11.orig/debian/libPVER-dbg.prerm.in +++ python2.7-2.7.11/debian/libPVER-dbg.prerm.in @@ -0,0 +1,23 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + dpkg -L lib@PVER@-dbg@HOST_QUAL@ \ + | 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.11.orig/debian/libPVER-dbg.symbols.in +++ python2.7-2.7.11/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.11.orig/debian/libPVER-dev.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/libPVER-minimal.overrides.in +++ python2.7-2.7.11/debian/libPVER-minimal.overrides.in @@ -0,0 +1 @@ +lib@PVER@-minimal binary: python-script-but-no-python-dep --- python2.7-2.7.11.orig/debian/libPVER-minimal.postinst.in +++ python2.7-2.7.11/debian/libPVER-minimal.postinst.in @@ -0,0 +1,17 @@ +#! /bin/sh + +set -e + +if [ ! -f /etc/@PVER@/sitecustomize.py ]; then + cat <<-EOF + # Empty sitecustomize.py to avoid a dangling symlink +EOF +fi + +if [ "$1" = configure ]; then + rm -f /etc/@PVER@/cert-verification.conf +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.11.orig/debian/libPVER-minimal.postrm.in +++ python2.7-2.7.11/debian/libPVER-minimal.postrm.in @@ -0,0 +1,27 @@ +#! /bin/sh + +set -e + +if [ "$1" = "remove" ]; then + pc=$(dpkg-query -f '${db:Status-Abbrev} ${binary:Package}\n' -W lib@PVER@-minimal \ + | 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 lib@PVER@-minimal \ + | 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 + rm -f /etc/@PVER@/cert-verification.conf +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.11.orig/debian/libPVER-minimal.prerm.in +++ python2.7-2.7.11/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 lib@PVER@-minimal \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + remove_bytecode lib@PVER@-minimal@HOST_QUAL@ + fi + ;; + upgrade) + remove_bytecode lib@PVER@-minimal@HOST_QUAL@ + # 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.11.orig/debian/libPVER-stdlib.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/libPVER-stdlib.prerm.in +++ python2.7-2.7.11/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 lib@PVER@-stdlib \ + | grep -v '^.n' | wc -l) + if [ "$pc" -le 1 ]; then + remove_bytecode lib@PVER@-stdlib@HOST_QUAL@ + fi + ;; + upgrade) + remove_bytecode lib@PVER@-stdlib@HOST_QUAL@ + # 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.11.orig/debian/libPVER-testsuite.overrides.in +++ python2.7-2.7.11/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.11.orig/debian/libPVER-testsuite.prerm.in +++ python2.7-2.7.11/debian/libPVER-testsuite.prerm.in @@ -0,0 +1,30 @@ +#! /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) + remove_bytecode lib@PVER@-testsuite + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.11.orig/debian/libPVER.overrides.in +++ python2.7-2.7.11/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python2.7-2.7.11.orig/debian/libPVER.symbols.in +++ python2.7-2.7.11/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.11.orig/debian/libpython.symbols.in +++ python2.7-2.7.11/debian/libpython.symbols.in @@ -0,0 +1,1348 @@ + 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@ + _PyCode_ConstantKey@Base 2.7.11 + _PyCodecInfo_GetIncrementalDecoder@Base @VER@ + _PyCodecInfo_GetIncrementalEncoder@Base @VER@ + _PyCodec_DecodeText@Base @VER@ + _PyCodec_EncodeText@Base @VER@ + _PyCodec_Lookup@Base @VER@ + _PyCodec_LookupTextEncoding@Base @VER@ + _PyComplex_FormatAdvanced@Base @VER@ + _PyDict_Contains@Base @VER@ + _PyDict_GetItemWithError@Base 2.7.11 + _PyDict_MaybeUntrack@Base @VER@ + _PyDict_NewPresized@Base @VER@ + _PyDict_Next@Base @VER@ + _PyErr_BadInternalCall@Base @VER@ + _PyErr_ReplaceException@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_Fini@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_GetSizeOf@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)initdatetime@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.11.orig/debian/locale-gen +++ python2.7-2.7.11/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__) +# if defined(__ILP32__) +# include +# else +# include +# endif +# elif defined(__aarch64__) && defined(__AARCH64EB__) +# if defined(__ILP32__) +# include +# else +# include +# endif +# elif defined(__alpha__) +# include +# elif defined(__ARM_EABI__) && defined(__ARM_PCS_VFP) +# if defined(__ARMEL__) +# include +# else +# include +# endif +# elif defined(__ARM_EABI__) && !defined(__ARM_PCS_VFP) +# if defined(__ARMEL__) +# include +# else +# include +# endif +# 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.11.orig/debian/patches/add-python-config-sh.diff +++ python2.7-2.7.11/debian/patches/add-python-config-sh.diff @@ -0,0 +1,182 @@ +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -1179,6 +1179,8 @@ python-config: $(srcdir)/Misc/python-con + # 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) +@@ -1238,6 +1240,7 @@ libainstall: all python-config + $(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:"; \ +Index: b/Misc/python-config.in +=================================================================== +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -56,3 +56,11 @@ for opt in opt_flags: + 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') +Index: b/Misc/python-config.sh.in +=================================================================== +--- /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="-lpython${VERSION}${ABIFLAGS} @LIBS@ $SYSLIBS" ++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 +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -897,6 +897,7 @@ fi + + # 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*) +@@ -957,6 +958,7 @@ if test $enable_shared = "yes"; then + + esac + else # shared is disabled ++ PY_ENABLE_SHARED=0 + case $ac_sys_system in + CYGWIN*) + BLDLIBRARY='$(LIBRARY)' +@@ -964,6 +966,7 @@ else # shared is disabled + ;; + esac + fi ++AC_SUBST(PY_ENABLE_SHARED) + + if test "$cross_compiling" = yes; then + RUNSHARED= +@@ -4723,7 +4726,7 @@ AC_MSG_RESULT($ENSUREPIP) + AC_SUBST(ENSUREPIP) + + # 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.11.orig/debian/patches/atomic-pyc-rename.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/bdist-wininst-notfound.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/bsddb-libpath.diff +++ python2.7-2.7.11/debian/patches/bsddb-libpath.diff @@ -0,0 +1,21 @@ +# DP: Don't add the bsddb multilib path, if already in the standard lib path + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -1090,7 +1090,13 @@ class PyBuildExt(build_ext): + 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.11.orig/debian/patches/build-hash.diff +++ python2.7-2.7.11/debian/patches/build-hash.diff @@ -0,0 +1,24 @@ +# DP: Always build the _md5, _sha1, _sha256 and _sha512 extension modules. + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -874,7 +874,7 @@ class PyBuildExt(build_ext): + 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 +@@ -885,7 +885,7 @@ class PyBuildExt(build_ext): + 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.11.orig/debian/patches/build-libpython.diff +++ python2.7-2.7.11/debian/patches/build-libpython.diff @@ -0,0 +1,24 @@ +# DP: Don't include object files twice in libpython. + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -426,7 +426,7 @@ LIBRARY_OBJS= \ + $(PYTHON_OBJS) \ + $(MODULE_OBJS) \ + $(SIGNAL_OBJS) \ +- $(MODOBJS) ++ $(sort $(MODOBJS)) + + ######################################################################### + # Rules +@@ -560,7 +560,7 @@ $(LIBRARY): $(LIBRARY_OBJS) + $(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.11.orig/debian/patches/cthreads.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/ctypes-arm.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/deb-locations.diff +++ python2.7-2.7.11/debian/patches/deb-locations.diff @@ -0,0 +1,73 @@ +# DP: adjust locations of directories to debian policy + +Index: b/Demo/tkinter/guido/ManPage.py +=================================================================== +--- a/Demo/tkinter/guido/ManPage.py ++++ b/Demo/tkinter/guido/ManPage.py +@@ -189,8 +189,9 @@ ManPage = ReadonlyManPage + 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': +Index: b/Demo/tkinter/guido/tkman.py +=================================================================== +--- a/Demo/tkinter/guido/tkman.py ++++ b/Demo/tkinter/guido/tkman.py +@@ -9,8 +9,8 @@ import re + 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: +Index: b/Misc/python.man +=================================================================== +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -337,7 +337,7 @@ exception). Error messages are written + 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 +Index: b/Tools/faqwiz/faqconf.py +=================================================================== +--- a/Tools/faqwiz/faqconf.py ++++ b/Tools/faqwiz/faqconf.py +@@ -21,7 +21,7 @@ OWNERNAME = "FAQ owner" + 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 +Index: b/Tools/webchecker/webchecker.py +=================================================================== +--- a/Tools/webchecker/webchecker.py ++++ b/Tools/webchecker/webchecker.py +@@ -19,7 +19,8 @@ file index.html in that directory is ret + 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.11.orig/debian/patches/deb-setup.diff +++ python2.7-2.7.11/debian/patches/deb-setup.diff @@ -0,0 +1,21 @@ +# DP: Don't include /usr/local/include and /usr/local/lib as gcc search paths + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -454,10 +454,10 @@ class PyBuildExt(build_ext): + 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.11.orig/debian/patches/debug-build.diff +++ python2.7-2.7.11/debian/patches/debug-build.diff @@ -0,0 +1,248 @@ +# 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). + +Index: b/Lib/distutils/command/build.py +=================================================================== +--- a/Lib/distutils/command/build.py ++++ b/Lib/distutils/command/build.py +@@ -91,7 +91,8 @@ class build(Command): + # '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) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -90,7 +90,7 @@ def get_python_inc(plat_specific=0, pref + # 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": +@@ -263,7 +263,7 @@ def get_makefile_filename(): + 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): +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -333,7 +333,7 @@ def get_makefile_filename(): + """Return the path of the Makefile.""" + 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") + + # Issue #22199: retain undocumented private name for compatibility + _get_makefile_filename = get_makefile_filename +@@ -465,7 +465,7 @@ def get_config_h_filename(): + 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(): +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -122,8 +122,8 @@ SCRIPTDIR= $(prefix)/lib + # 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 +@@ -137,6 +137,8 @@ DESTSHARED= $(BINLIBDEST)/lib-dynload + EXE= @EXEEXT@ + BUILDEXE= @BUILDEXEEXT@ + ++DEBUG_EXT= @DEBUG_EXT@ ++ + # Short name and location for Mac OS X Python framework + UNIVERSALSDK=@UNIVERSALSDK@ + PYTHONFRAMEWORK= @PYTHONFRAMEWORK@ +@@ -563,7 +565,7 @@ $(LIBRARY): $(LIBRARY_OBJS) + $(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) $@; \ +@@ -1190,8 +1192,8 @@ inclinstall: + $(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 +Index: b/Misc/python-config.in +=================================================================== +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -44,7 +44,7 @@ for opt in opt_flags: + print ' '.join(flags) + + elif opt in ('--libs', '--ldflags'): +- libs = ['-lpython' + pyver] ++ libs = ['-lpython' + pyver + (sys.pydebug and "_d" or "")] + libs += getvar('LIBS').split() + libs += getvar('SYSLIBS').split() + # add the prefix/lib/pythonX.Y/config dir, but only if there is no +Index: b/Python/dynload_shlib.c +=================================================================== +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -46,6 +46,10 @@ const struct filedescr _PyImport_DynLoad + {"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 +Index: b/Python/sysmodule.c +=================================================================== +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1524,6 +1524,12 @@ _PySys_Init(void) + 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; +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -759,7 +759,7 @@ AC_SUBST(LIBRARY) + AC_MSG_CHECKING(LIBRARY) + if test -z "$LIBRARY" + then +- LIBRARY='libpython$(VERSION).a' ++ LIBRARY='libpython$(VERSION)$(DEBUG_EXT).a' + fi + AC_MSG_RESULT($LIBRARY) + +@@ -905,8 +905,8 @@ if test $enable_shared = "yes"; then + 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:+:${LD_LIBRARY_PATH}} + case $ac_sys_system in + FreeBSD*) +@@ -1049,6 +1049,12 @@ else AC_MSG_RESULT(no); Py_DEBUG='false' + 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? + +@@ -1996,7 +2002,7 @@ then + esac + ;; + CYGWIN*) SO=.dll;; +- *) SO=.so;; ++ *) SO=$DEBUG_EXT.so;; + esac + else + # this might also be a termcap variable, see #610332 +Index: b/Lib/distutils/tests/test_build_ext.py +=================================================================== +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -287,8 +287,8 @@ class BuildExtTestCase(support.TempdirMa + 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 +@@ -296,8 +296,7 @@ class BuildExtTestCase(support.TempdirMa + 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) + +Index: b/Lib/distutils/tests/test_build.py +=================================================================== +--- a/Lib/distutils/tests/test_build.py ++++ b/Lib/distutils/tests/test_build.py +@@ -20,10 +20,6 @@ class BuildTestCase(support.TempdirManag + # 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 @@ class BuildTestCase(support.TempdirManag + 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.11.orig/debian/patches/disable-sem-check.diff +++ python2.7-2.7.11/debian/patches/disable-sem-check.diff @@ -0,0 +1,30 @@ +# DP: Assume working semaphores on Linux, don't rely on running kernel for the check. + +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -3922,6 +3922,11 @@ int main(void) { + [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 +@@ -3958,6 +3963,11 @@ int main(void){ + [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.11.orig/debian/patches/disable-utimes.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/distutils-install-layout.diff +++ python2.7-2.7.11/debian/patches/distutils-install-layout.diff @@ -0,0 +1,406 @@ +# 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. + +Index: b/Doc/install/index.rst +=================================================================== +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -250,6 +250,8 @@ is pure Python or contains extensions (" + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | 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) | +@@ -259,6 +261,14 @@ is pure Python or contains extensions (" + + 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 +@@ -443,6 +453,15 @@ them to go in :file:`/usr/local/lib/pyth + + /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 +@@ -694,6 +713,17 @@ Add-on Python modules might then belong + 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 +Index: b/Lib/distutils/command/install.py +=================================================================== +--- a/Lib/distutils/command/install.py ++++ b/Lib/distutils/command/install.py +@@ -47,6 +47,20 @@ INSTALL_SCHEMES = { + '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 @@ class install (Command): + + ('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 @@ class install (Command): + 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 @@ class install (Command): + 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 @@ class install (Command): + 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 @@ class install (Command): + + 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 () + +Index: b/Lib/distutils/command/install_egg_info.py +=================================================================== +--- a/Lib/distutils/command/install_egg_info.py ++++ b/Lib/distutils/command/install_egg_info.py +@@ -14,18 +14,37 @@ class install_egg_info(Command): + 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] + +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -115,6 +115,7 @@ def get_python_lib(plat_specific=0, stan + 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 @@ def get_python_lib(plat_specific=0, stan + "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") + +Index: b/Lib/site.py +=================================================================== +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -273,6 +273,13 @@ def addusersitepackages(known_paths): + + 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(): +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -16,6 +16,26 @@ _INSTALL_SCHEMES = { + '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 @@ def is_python_build(): + _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 _expand_vars(scheme, vars): + + 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(): +@@ -310,7 +333,7 @@ def get_makefile_filename(): + """Return the path of the Makefile.""" + 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") + + # Issue #22199: retain undocumented private name for compatibility + _get_makefile_filename = get_makefile_filename +@@ -442,7 +465,7 @@ def get_config_h_filename(): + 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(): +Index: b/Lib/test/test_import.py +=================================================================== +--- a/Lib/test/test_import.py ++++ b/Lib/test/test_import.py +@@ -301,7 +301,7 @@ class ImportTests(unittest.TestCase): + 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) +Index: b/Lib/test/test_site.py +=================================================================== +--- a/Lib/test/test_site.py ++++ b/Lib/test/test_site.py +@@ -247,10 +247,13 @@ class HelperFunctionsTests(unittest.Test + 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 +Index: b/Lib/test/test_sysconfig.py +=================================================================== +--- a/Lib/test/test_sysconfig.py ++++ b/Lib/test/test_sysconfig.py +@@ -239,8 +239,8 @@ class TestSysConfig(unittest.TestCase): + 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) + + @unittest.skipIf(sys.platform.startswith('win'), +Index: b/Lib/distutils/tests/test_install.py +=================================================================== +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -193,7 +193,7 @@ class InstallTestCase(support.TempdirMan + + 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): +@@ -223,7 +223,7 @@ class InstallTestCase(support.TempdirMan + + 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): +Index: b/Lib/distutils/tests/test_bdist_dumb.py +=================================================================== +--- a/Lib/distutils/tests/test_bdist_dumb.py ++++ b/Lib/distutils/tests/test_bdist_dumb.py +@@ -87,7 +87,7 @@ class BuildDumbTestCase(support.TempdirM + 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)) +Index: b/Lib/pydoc.py +=================================================================== +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -391,6 +391,7 @@ class Doc: + '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.11.orig/debian/patches/distutils-link.diff +++ python2.7-2.7.11/debian/patches/distutils-link.diff @@ -0,0 +1,20 @@ +# DP: Don't add standard library dirs to library_dirs and runtime_library_dirs. + +Index: b/Lib/distutils/unixccompiler.py +=================================================================== +--- a/Lib/distutils/unixccompiler.py ++++ b/Lib/distutils/unixccompiler.py +@@ -157,7 +157,12 @@ class UnixCCompiler(CCompiler): + 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.11.orig/debian/patches/distutils-sysconfig.diff +++ python2.7-2.7.11/debian/patches/distutils-sysconfig.diff @@ -0,0 +1,53 @@ +# DP: Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, +# DP: CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -174,10 +174,12 @@ def customize_compiler(compiler): + _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', +- 'CCSHARED', 'LDSHARED', 'SO', 'AR', +- 'ARFLAGS') ++ (cc, cxx, opt, cflags, extra_cflags, basecflags, ++ ccshared, ldshared, so_ext, ar, ar_flags, ++ configure_cppflags, configure_cflags, configure_ldflags) = \ ++ get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 'EXTRA_CFLAGS', 'BASECFLAGS', ++ 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS', ++ 'CONFIGURE_CPPFLAGS', 'CONFIGURE_CFLAGS', 'CONFIGURE_LDFLAGS') + + if 'CC' in os.environ: + newcc = os.environ['CC'] +@@ -198,13 +200,27 @@ def customize_compiler(compiler): + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ elif configure_ldflags: ++ ldshared = ldshared + ' ' + configure_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 (opt, basecflags, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] ++ elif configure_cflags: ++ cflags = ' '.join(str(x) for x in (opt, basecflags, configure_cflags, extra_cflags) if x) ++ ldshared = ldshared + ' ' + configure_cflags + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] + cflags = cflags + ' ' + os.environ['CPPFLAGS'] + ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] ++ elif configure_cppflags: ++ cpp = cpp + ' ' + configure_cppflags ++ cflags = cflags + ' ' + configure_cppflags ++ ldshared = ldshared + ' ' + configure_cppflags + if 'AR' in os.environ: + ar = os.environ['AR'] + if 'ARFLAGS' in os.environ: --- python2.7-2.7.11.orig/debian/patches/doc-nodownload.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/enable-fpectl.diff +++ python2.7-2.7.11/debian/patches/enable-fpectl.diff @@ -0,0 +1,16 @@ +# DP: Enable the build of the fpectl module. + +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -1399,6 +1399,9 @@ class PyBuildExt(build_ext): + 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.11.orig/debian/patches/enable-sqlite-loadext.diff +++ python2.7-2.7.11/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 +@@ -1200,7 +1200,7 @@ class PyBuildExt(build_ext): + 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.11.orig/debian/patches/ensurepip-disabled.diff +++ python2.7-2.7.11/debian/patches/ensurepip-disabled.diff @@ -0,0 +1,42 @@ +# DP: Disable ensurepip in Debian for now. + +--- a/Lib/ensurepip/__init__.py ++++ b/Lib/ensurepip/__init__.py +@@ -12,6 +12,21 @@ + + __all__ = ["version", "bootstrap"] + ++def _ensurepip_is_disabled_in_debian(): ++ if True: ++ print ('''\ ++ensurepip is disabled in Debian/Ubuntu for the system python. ++ ++Python modules For the system python are usually handled by dpkg and apt-get. ++ ++ apt-get install python- ++ ++Install the python-pip package to use pip itself. Using pip together ++with the system python might have unexpected results for any system installed ++module, so use it on your own risk, or make sure to only use it in virtual ++environments. ++''') ++ sys.exit(1) + + # pip currently requires ssl support, so we try to provide a nicer + # error message when that is missing (http://bugs.python.org/issue19744) +@@ -47,6 +62,7 @@ + """ + Returns a string specifying the bundled version of pip. + """ ++ _ensurepip_is_disabled_in_debian() + whl_name = 'pip' + wheel_names = glob.glob('/usr/share/python-wheels/%s-*.whl' % whl_name) + if len(wheel_names) == 1: +@@ -75,6 +91,7 @@ + + Note that calling this function will alter both sys.path and os.environ. + """ ++ _ensurepip_is_disabled_in_debian() + if altinstall and default_pip: + raise ValueError("Cannot use altinstall and default_pip together") + --- python2.7-2.7.11.orig/debian/patches/ensurepip-wheels.diff +++ python2.7-2.7.11/debian/patches/ensurepip-wheels.diff @@ -0,0 +1,145 @@ +# DP: Let ensurepip use the system wheels, not the ones from the python source. + +Index: b/Lib/ensurepip/__init__.py +=================================================================== +--- a/Lib/ensurepip/__init__.py ++++ b/Lib/ensurepip/__init__.py +@@ -1,6 +1,7 @@ + #!/usr/bin/env python2 + from __future__ import print_function + ++import glob + import os + import os.path + import pkgutil +@@ -12,13 +13,9 @@ import tempfile + __all__ = ["version", "bootstrap"] + + +-_SETUPTOOLS_VERSION = "20.3" +- +-_PIP_VERSION = "8.1.1" +- + # pip currently requires ssl support, so we try to provide a nicer + # error message when that is missing (http://bugs.python.org/issue19744) +-_MISSING_SSL_MESSAGE = ("pip {} requires SSL/TLS".format(_PIP_VERSION)) ++_MISSING_SSL_MESSAGE = ("pip requires SSL/TLS") + try: + import ssl + except ImportError: +@@ -31,8 +28,8 @@ else: + pass + + _PROJECTS = [ +- ("setuptools", _SETUPTOOLS_VERSION), +- ("pip", _PIP_VERSION), ++ "setuptools", ++ "pip", + ] + + +@@ -50,7 +47,11 @@ def version(): + """ + Returns a string specifying the bundled version of pip. + """ +- return _PIP_VERSION ++ whl_name = 'pip' ++ wheel_names = glob.glob('/usr/share/python-wheels/%s-*.whl' % whl_name) ++ if len(wheel_names) == 1: ++ return os.path.basename(wheel_names[0]).split('-')[1] ++ raise RuntimeError('missing dependency wheel %s. Installation of the python-%s-whl package is needed to use ensurepip.' % (whl_name, whl_name)) + + + def _disable_pip_configuration_settings(): +@@ -93,21 +94,53 @@ def bootstrap(root=None, upgrade=False, + # omit pip and easy_install + os.environ["ENSUREPIP_OPTIONS"] = "install" + ++ # Debian: The bundled wheels are useless to us because we must use ones ++ # crafted from source code in the archive. As we build the virtual ++ # environment, copy the wheels from the system location into the virtual ++ # environment, and place those wheels on sys.path. ++ def copy_wheels(wheels, destdir, paths): ++ for project in wheels: ++ wheel_names = glob.glob( ++ '/usr/share/python-wheels/{}-*.whl'.format(project)) ++ if len(wheel_names) == 0: ++ raise RuntimeError('missing dependency wheel %s. Installation of the python-%s-whl package is needed to use ensurepip.' % (project, project)) ++ assert len(wheel_names) == 1, wheel_names ++ wheel_name = os.path.basename(wheel_names[0]) ++ path = os.path.join('/usr/share/python-wheels', wheel_name) ++ with open(path, 'rb') as fp: ++ whl = fp.read() ++ dest = os.path.join(destdir, wheel_name) ++ with open(dest, 'wb') as fp: ++ fp.write(whl) ++ paths.append(dest) ++ ++ # check that the python-{pip,setuptools}-whl packages are installed ++ missing = [] ++ for project in reversed(_PROJECTS): ++ wheel_names = glob.glob('/usr/share/python-wheels/%s-*.whl' % project) ++ if len(wheel_names) != 1: ++ missing.append(project) ++ if missing: ++ raise RuntimeError('missing wheel(s) %s. Installation of the %s package(s) is needed to use ensurepip.' \ ++ % (', '.join([missing]), ++ ', '.join(['python-%s-whl' % m for m in missing])) \ ++ ) ++ + tmpdir = tempfile.mkdtemp() ++ ++ for project in _PROJECTS: ++ try: ++ with open('/usr/share/python-wheels/%s.dependencies' % project) as fp: ++ dependencies = [line[:-1].split()[0] for line in fp.readlines()] ++ except IOError: ++ dependencies = [] ++ copy_wheels(dependencies, tmpdir, sys.path) ++ + try: + # Put our bundled wheels into a temporary directory and construct the + # additional paths that need added to sys.path + additional_paths = [] +- for project, version in _PROJECTS: +- wheel_name = "{}-{}-py2.py3-none-any.whl".format(project, version) +- whl = pkgutil.get_data( +- "ensurepip", +- "_bundled/{}".format(wheel_name), +- ) +- with open(os.path.join(tmpdir, wheel_name), "wb") as fp: +- fp.write(whl) +- +- additional_paths.append(os.path.join(tmpdir, wheel_name)) ++ copy_wheels(_PROJECTS, tmpdir, additional_paths) + + # Construct the arguments to be passed to the pip command + args = ["install", "--no-index", "--find-links", tmpdir] +@@ -120,7 +153,7 @@ def bootstrap(root=None, upgrade=False, + if verbosity: + args += ["-" + "v" * verbosity] + +- _run_pip(args + [p[0] for p in _PROJECTS], additional_paths) ++ _run_pip(args + _PROJECTS, additional_paths) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + +@@ -137,7 +170,8 @@ def _uninstall_helper(verbosity=0): + return + + # If the pip version doesn't match the bundled one, leave it alone +- if pip.__version__ != _PIP_VERSION: ++ # Disabled for Debian, always using the version from the python3-pip package. ++ if False and pip.__version__ != _PIP_VERSION: + msg = ("ensurepip will only uninstall a matching version " + "({!r} installed, {!r} bundled)") + print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr) +@@ -151,7 +185,7 @@ def _uninstall_helper(verbosity=0): + if verbosity: + args += ["-" + "v" * verbosity] + +- _run_pip(args + [p[0] for p in reversed(_PROJECTS)]) ++ _run_pip(args + reversed(_PROJECTS)) + + + def _main(argv=None): --- python2.7-2.7.11.orig/debian/patches/ext-no-libpython-link.diff +++ python2.7-2.7.11/debian/patches/ext-no-libpython-link.diff @@ -0,0 +1,24 @@ +# DP: Don't link extensions with the shared libpython library. + +Index: b/Lib/distutils/command/build_ext.py +=================================================================== +--- a/Lib/distutils/command/build_ext.py ++++ b/Lib/distutils/command/build_ext.py +@@ -236,7 +236,7 @@ class build_ext (Command): + # 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 not sysconfig.python_build: + # building third party extensions + self.library_dirs.append(sysconfig.get_config_var('LIBDIR')) +@@ -757,7 +757,7 @@ class build_ext (Command): + 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.11.orig/debian/patches/fix-sslv3-test.diff +++ python2.7-2.7.11/debian/patches/fix-sslv3-test.diff @@ -0,0 +1,18 @@ +Description: properly handle Ubuntu's openssl having OP_NO_SSLv3 forced on by default +Author: Marc Deslauriers +Forwarded: yes, http://bugs.python.org/issue25724 + +Index: b/Lib/test/test_ssl.py +=================================================================== +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -751,7 +751,8 @@ class ContextTests(unittest.TestCase): + self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3, + ctx.options) + ctx.options = 0 +- self.assertEqual(0, ctx.options) ++ # Ubuntu has OP_NO_SSLv3 forced on by default ++ self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3) + else: + with self.assertRaises(ValueError): + ctx.options = 0 --- python2.7-2.7.11.orig/debian/patches/hg-updates.diff +++ python2.7-2.7.11/debian/patches/hg-updates.diff @@ -0,0 +1,29345 @@ +# DP: hg updates of the 2.7 release branch (until 2016-03-19). + +# hg diff -r v2.7.11 | filterdiff --exclude=.*ignore --exclude=.hg* --remove-timestamps + +diff -r 6d1b6a68f775 Doc/README.txt +--- a/Doc/README.txt ++++ b/Doc/README.txt +@@ -119,27 +119,3 @@ + + If you want to help the Documentation Team, you are always welcome. Just send + a mail to docs@python.org. +- +- +-Copyright notice +-================ +- +-The Python source is copyrighted, but you can freely use and copy it +-as long as you don't change or remove the copyright notice: +- +----------------------------------------------------------------------- +-Copyright (c) 2000-2014 Python Software Foundation. +-All rights reserved. +- +-Copyright (c) 2000 BeOpen.com. +-All rights reserved. +- +-Copyright (c) 1995-2000 Corporation for National Research Initiatives. +-All rights reserved. +- +-Copyright (c) 1991-1995 Stichting Mathematisch Centrum. +-All rights reserved. +- +-See the file "license.rst" for information on usage and redistribution +-of this file, and for a DISCLAIMER OF ALL WARRANTIES. +----------------------------------------------------------------------- +diff -r 6d1b6a68f775 Doc/bugs.rst +--- a/Doc/bugs.rst ++++ b/Doc/bugs.rst +@@ -16,7 +16,8 @@ + please submit a bug report on the :ref:`tracker `. If you + have a suggestion how to fix it, include that as well. + +-If you're short on time, you can also email your bug report to docs@python.org. ++If you're short on time, you can also email documentation bug reports to ++docs@python.org (behavioral bugs can be sent to python-list@python.org). + 'docs@' is a mailing list run by volunteers; your request will be noticed, + though it may take a while to be processed. + +diff -r 6d1b6a68f775 Doc/c-api/arg.rst +--- a/Doc/c-api/arg.rst ++++ b/Doc/c-api/arg.rst +@@ -24,7 +24,7 @@ + that matches the format unit; and the entry in [square] brackets is the type + of the C variable(s) whose address should be passed. + +-These formats allow to access an object as a contiguous chunk of memory. ++These formats allow accessing an object as a contiguous chunk of memory. + You don't have to provide raw storage for the returned unicode or bytes + area. Also, you won't have to release any memory yourself, except with the + ``es``, ``es#``, ``et`` and ``et#`` formats. +@@ -136,7 +136,8 @@ + :c:func:`PyArg_ParseTuple` will use this location as the buffer and + interpret the initial value of *\*buffer_length* as the buffer size. It + will then copy the encoded data into the buffer and NUL-terminate it. If +- the buffer is not large enough, a :exc:`ValueError` will be set. ++ the buffer is not large enough, a :exc:`TypeError` will be set. ++ Note: starting from Python 3.6 a :exc:`ValueError` will be set. + + In both cases, *\*buffer_length* is set to the length of the encoded data + without the trailing NUL byte. +diff -r 6d1b6a68f775 Doc/c-api/exceptions.rst +--- a/Doc/c-api/exceptions.rst ++++ b/Doc/c-api/exceptions.rst +@@ -404,8 +404,8 @@ + :meth:`__del__` method. + + The function is called with a single argument *obj* that identifies the context +- in which the unraisable exception occurred. The repr of *obj* will be printed in +- the warning message. ++ in which the unraisable exception occurred. If possible, ++ the repr of *obj* will be printed in the warning message. + + + .. _unicodeexceptions: +diff -r 6d1b6a68f775 Doc/c-api/intro.rst +--- a/Doc/c-api/intro.rst ++++ b/Doc/c-api/intro.rst +@@ -258,7 +258,7 @@ + if (PyObject_SetItem(target, index, item) < 0) { + Py_DECREF(index); + return -1; +- } ++ } + Py_DECREF(index); + } + return 0; +diff -r 6d1b6a68f775 Doc/c-api/structures.rst +--- a/Doc/c-api/structures.rst ++++ b/Doc/c-api/structures.rst +@@ -69,6 +69,37 @@ + expansion varies depending on the definition of :c:macro:`Py_TRACE_REFS`. + + ++.. c:macro:: Py_TYPE(o) ++ ++ This macro is used to access the :attr:`ob_type` member of a Python object. ++ It expands to:: ++ ++ (((PyObject*)(o))->ob_type) ++ ++ .. versionadded:: 2.6 ++ ++ ++.. c:macro:: Py_REFCNT(o) ++ ++ This macro is used to access the :attr:`ob_refcnt` member of a Python ++ object. ++ It expands to:: ++ ++ (((PyObject*)(o))->ob_refcnt) ++ ++ .. versionadded:: 2.6 ++ ++ ++.. c:macro:: Py_SIZE(o) ++ ++ This macro is used to access the :attr:`ob_size` member of a Python object. ++ It expands to:: ++ ++ (((PyVarObject*)(o))->ob_size) ++ ++ .. versionadded:: 2.6 ++ ++ + .. c:macro:: PyObject_HEAD_INIT(type) + + This is a macro which expands to initialization values for a new +diff -r 6d1b6a68f775 Doc/conf.py +--- a/Doc/conf.py ++++ b/Doc/conf.py +@@ -135,6 +135,14 @@ + # Get LaTeX to handle Unicode correctly + latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''} + ++ ++# Options for Epub output ++# ----------------------- ++ ++epub_author = 'Python Documentation Authors' ++epub_publisher = 'Python Software Foundation' ++ ++ + # Options for the coverage checker + # -------------------------------- + +diff -r 6d1b6a68f775 Doc/copyright.rst +--- a/Doc/copyright.rst ++++ b/Doc/copyright.rst +@@ -4,7 +4,7 @@ + + Python and this documentation is: + +-Copyright © 2001-2015 Python Software Foundation. All rights reserved. ++Copyright © 2001-2016 Python Software Foundation. All rights reserved. + + Copyright © 2000 BeOpen.com. All rights reserved. + +diff -r 6d1b6a68f775 Doc/glossary.rst +--- a/Doc/glossary.rst ++++ b/Doc/glossary.rst +@@ -346,8 +346,8 @@ + All of Python's immutable built-in objects are hashable, while no mutable + containers (such as lists or dictionaries) are. Objects which are + instances of user-defined classes are hashable by default; they all +- compare unequal (except with themselves), and their hash value is their +- :func:`id`. ++ compare unequal (except with themselves), and their hash value is derived ++ from their :func:`id`. + + IDLE + An Integrated Development Environment for Python. IDLE is a basic editor +@@ -519,7 +519,8 @@ + method resolution order + Method Resolution Order is the order in which base classes are searched + for a member during lookup. See `The Python 2.3 Method Resolution Order +- `_. ++ `_ for details of the ++ algorithm used by the Python interpreter since the 2.3 release. + + module + An object that serves as an organizational unit of Python code. Modules +diff -r 6d1b6a68f775 Doc/howto/argparse.rst +--- a/Doc/howto/argparse.rst ++++ b/Doc/howto/argparse.rst +@@ -513,7 +513,7 @@ + + * Sadly, our help output isn't very informative on the new ability our script + has acquired, but that can always be fixed by improving the documentation for +- out script (e.g. via the ``help`` keyword argument). ++ our script (e.g. via the ``help`` keyword argument). + + * That last output exposes a bug in our program. + +diff -r 6d1b6a68f775 Doc/howto/logging-cookbook.rst +--- a/Doc/howto/logging-cookbook.rst ++++ b/Doc/howto/logging-cookbook.rst +@@ -94,6 +94,61 @@ + 2005-03-23 23:47:11,673 - spam_application - INFO - + done with auxiliary_module.some_function() + ++Logging from multiple threads ++----------------------------- ++ ++Logging from multiple threads requires no special effort. The following example ++shows logging from the main (initIal) thread and another thread:: ++ ++ import logging ++ import threading ++ import time ++ ++ def worker(arg): ++ while not arg['stop']: ++ logging.debug('Hi from myfunc') ++ time.sleep(0.5) ++ ++ def main(): ++ logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s') ++ info = {'stop': False} ++ thread = threading.Thread(target=worker, args=(info,)) ++ thread.start() ++ while True: ++ try: ++ logging.debug('Hello from main') ++ time.sleep(0.75) ++ except KeyboardInterrupt: ++ info['stop'] = True ++ break ++ thread.join() ++ ++ if __name__ == '__main__': ++ main() ++ ++When run, the script should print something like the following:: ++ ++ 0 Thread-1 Hi from myfunc ++ 3 MainThread Hello from main ++ 505 Thread-1 Hi from myfunc ++ 755 MainThread Hello from main ++ 1007 Thread-1 Hi from myfunc ++ 1507 MainThread Hello from main ++ 1508 Thread-1 Hi from myfunc ++ 2010 Thread-1 Hi from myfunc ++ 2258 MainThread Hello from main ++ 2512 Thread-1 Hi from myfunc ++ 3009 MainThread Hello from main ++ 3013 Thread-1 Hi from myfunc ++ 3515 Thread-1 Hi from myfunc ++ 3761 MainThread Hello from main ++ 4017 Thread-1 Hi from myfunc ++ 4513 MainThread Hello from main ++ 4518 Thread-1 Hi from myfunc ++ ++This shows the logging output interspersed as one might expect. This approach ++works for more threads than shown here, of course. ++ + Multiple handlers and formatters + -------------------------------- + +diff -r 6d1b6a68f775 Doc/howto/pyporting.rst +--- a/Doc/howto/pyporting.rst ++++ b/Doc/howto/pyporting.rst +@@ -243,8 +243,8 @@ + binary reading). Under Python 3, binary files and text files are clearly + distinct and mutually incompatible; see the :mod:`io` module for details. + Therefore, you **must** make a decision of whether a file will be used for +-binary access (allowing to read and/or write binary data) or text access +-(allowing to read and/or write text data). You should also use :func:`io.open` ++binary access (allowing binary data to be read and/or written) or text access ++(allowing text data to be read and/or written). You should also use :func:`io.open` + for opening files instead of the built-in :func:`open` function as the :mod:`io` + module is consistent from Python 2 to 3 while the built-in :func:`open` function + is not (in Python 3 it's actually :func:`io.open`). +diff -r 6d1b6a68f775 Doc/howto/regex.rst +--- a/Doc/howto/regex.rst ++++ b/Doc/howto/regex.rst +@@ -172,7 +172,7 @@ + Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching + engine will try to repeat it as many times as possible. If later portions of the + pattern don't match, the matching engine will then back up and try again with +-few repetitions. ++fewer repetitions. + + A step-by-step example will make this more obvious. Let's consider the + expression ``a[bcd]*b``. This matches the letter ``'a'``, zero or more letters +@@ -1015,17 +1015,18 @@ + + A negative lookahead cuts through all this confusion: + +-``.*[.](?!bat$).*$`` The negative lookahead means: if the expression ``bat`` ++``.*[.](?!bat$)[^.]*$`` The negative lookahead means: if the expression ``bat`` + doesn't match at this point, try the rest of the pattern; if ``bat$`` does + match, the whole pattern will fail. The trailing ``$`` is required to ensure + that something like ``sample.batch``, where the extension only starts with +-``bat``, will be allowed. ++``bat``, will be allowed. The ``[^.]*`` makes sure that the pattern works ++when there are multiple dots in the filename. + + Excluding another filename extension is now easy; simply add it as an + alternative inside the assertion. The following pattern excludes filenames that + end in either ``bat`` or ``exe``: + +-``.*[.](?!bat$|exe$).*$`` ++``.*[.](?!bat$|exe$)[^.]*$`` + + + Modifying Strings +diff -r 6d1b6a68f775 Doc/howto/urllib2.rst +--- a/Doc/howto/urllib2.rst ++++ b/Doc/howto/urllib2.rst +@@ -499,7 +499,7 @@ + e.g. "http://example.com/" *or* an "authority" (i.e. the hostname, + optionally including the port number) e.g. "example.com" or "example.com:8080" + (the latter example includes a port number). The authority, if present, must +-NOT contain the "userinfo" component - for example "joe@password:example.com" is ++NOT contain the "userinfo" component - for example "joe:password@example.com" is + not correct. + + +diff -r 6d1b6a68f775 Doc/installing/index.rst +--- a/Doc/installing/index.rst ++++ b/Doc/installing/index.rst +@@ -82,10 +82,12 @@ + Python. + + It's also possible to specify an exact or minimum version directly on the +-command line:: ++command line. When using comparator operators such as ``>``, ``<`` or some other ++special character which get interpreted by shell, the package name and the ++version should be enclosed within double quotes:: + + python -m pip install SomePackage==1.0.4 # specific version +- python -m pip install 'SomePackage>=1.0.4' # minimum version ++ python -m pip install "SomePackage>=1.0.4" # minimum version + + Normally, if a suitable module is already installed, attempting to install + it again will have no effect. Upgrading existing modules must be requested +diff -r 6d1b6a68f775 Doc/library/base64.rst +--- a/Doc/library/base64.rst ++++ b/Doc/library/base64.rst +@@ -16,7 +16,8 @@ + encoding algorithm is not the same as the :program:`uuencode` program. + + There are two interfaces provided by this module. The modern interface supports +-encoding and decoding string objects using all three alphabets. The legacy ++encoding and decoding string objects using both base-64 alphabets defined ++in :rfc:`3548` (normal, and URL- and filesystem-safe). The legacy + interface provides for encoding and decoding to and from file-like objects as + well as strings, but only using the Base64 standard alphabet. + +@@ -25,7 +26,7 @@ + + .. function:: b64encode(s[, altchars]) + +- Encode a string use Base64. ++ Encode a string using Base64. + + *s* is the string to encode. Optional *altchars* must be a string of at least + length 2 (additional characters are ignored) which specifies an alternative +@@ -44,9 +45,10 @@ + length 2 (additional characters are ignored) which specifies the alternative + alphabet used instead of the ``+`` and ``/`` characters. + +- The decoded string is returned. A :exc:`TypeError` is raised if *s* were +- incorrectly padded or if there are non-alphabet characters present in the +- string. ++ The decoded string is returned. A :exc:`TypeError` is raised if *s* is ++ incorrectly padded. Characters that are neither ++ in the normal base-64 alphabet nor the alternative alphabet are ++ discarded prior to the padding check. + + + .. function:: standard_b64encode(s) +@@ -61,14 +63,16 @@ + + .. function:: urlsafe_b64encode(s) + +- Encode string *s* using a URL-safe alphabet, which substitutes ``-`` instead of ++ Encode string *s* using the URL- and filesystem-safe ++ alphabet, which substitutes ``-`` instead of + ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet. The result + can still contain ``=``. + + + .. function:: urlsafe_b64decode(s) + +- Decode string *s* using a URL-safe alphabet, which substitutes ``-`` instead of ++ Decode string *s* using the URL- and filesystem-safe ++ alphabet, which substitutes ``-`` instead of + ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet. + + +diff -r 6d1b6a68f775 Doc/library/binascii.rst +--- a/Doc/library/binascii.rst ++++ b/Doc/library/binascii.rst +@@ -45,8 +45,10 @@ + .. function:: b2a_base64(data) + + Convert binary data to a line of ASCII characters in base64 coding. The return +- value is the converted line, including a newline char. The length of *data* +- should be at most 57 to adhere to the base64 standard. ++ value is the converted line, including a newline char. The newline is ++ added because the original use case for this function was to feed it a ++ series of 57 byte input lines to get output lines that conform to the ++ MIME-base64 standard. Otherwise the output conforms to :rfc:`3548`. + + + .. function:: a2b_qp(string[, header]) +@@ -165,7 +167,7 @@ + .. seealso:: + + Module :mod:`base64` +- Support for base64 encoding used in MIME email messages. ++ Support for RFC compliant base64-style encoding in base 16, 32, and 64. + + Module :mod:`binhex` + Support for the binhex format used on the Macintosh. +diff -r 6d1b6a68f775 Doc/library/crypto.rst +--- a/Doc/library/crypto.rst ++++ b/Doc/library/crypto.rst +@@ -18,13 +18,3 @@ + hmac.rst + md5.rst + sha.rst +-.. index:: +- pair: AES; algorithm +- single: cryptography +- single: Kuchling, Andrew +- +-Hardcore cypherpunks will probably find the cryptographic modules written by +-A.M. Kuchling of further interest; the package contains modules for various +-encryption algorithms, most notably AES. These modules are not distributed with +-Python but available separately. See the URL http://www.pycrypto.org/ for more +-information. +diff -r 6d1b6a68f775 Doc/library/csv.rst +--- a/Doc/library/csv.rst ++++ b/Doc/library/csv.rst +@@ -112,6 +112,7 @@ + value :const:`None` is written as the empty string. While this isn't a + reversible transformation, it makes it easier to dump SQL NULL data values to + CSV files without preprocessing the data returned from a ``cursor.fetch*`` call. ++ Floats are stringified with :func:`repr` before being written. + All other non-string data are stringified with :func:`str` before being written. + + A short usage example:: +diff -r 6d1b6a68f775 Doc/library/ctypes.rst +--- a/Doc/library/ctypes.rst ++++ b/Doc/library/ctypes.rst +@@ -708,8 +708,8 @@ + >>> pi = pointer(i) + >>> + +-Pointer instances have a :attr:`contents` attribute which returns the object to +-which the pointer points, the ``i`` object above:: ++Pointer instances have a :attr:`~_Pointer.contents` attribute which ++returns the object to which the pointer points, the ``i`` object above:: + + >>> pi.contents + c_long(42) +@@ -934,7 +934,7 @@ + Callback functions + ^^^^^^^^^^^^^^^^^^ + +-:mod:`ctypes` allows to create C callable function pointers from Python callables. ++:mod:`ctypes` allows creating C callable function pointers from Python callables. + These are sometimes called *callback functions*. + + First, you must create a class for the callback function, the class knows the +@@ -1348,7 +1348,7 @@ + Loading shared libraries + ^^^^^^^^^^^^^^^^^^^^^^^^ + +-There are several ways to loaded shared libraries into the Python process. One ++There are several ways to load shared libraries into the Python process. One + way is to instantiate one of the following classes: + + +@@ -1404,7 +1404,7 @@ + ignored. + + The *use_errno* parameter, when set to True, enables a ctypes mechanism that +-allows to access the system :data:`errno` error number in a safe way. ++allows accessing the system :data:`errno` error number in a safe way. + :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno` + variable; if you call foreign functions created with ``use_errno=True`` then the + :data:`errno` value before the function call is swapped with the ctypes private +@@ -1478,7 +1478,7 @@ + Class which loads shared libraries. *dlltype* should be one of the + :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types. + +- :meth:`__getattr__` has special behavior: It allows to load a shared library by ++ :meth:`__getattr__` has special behavior: It allows loading a shared library by + accessing it as attribute of a library loader instance. The result is cached, + so repeated attribute accesses return the same library each time. + +@@ -1557,7 +1557,7 @@ + + It is possible to assign a callable Python object that is not a ctypes + type, in this case the function is assumed to return a C :c:type:`int`, and +- the callable will be called with this integer, allowing to do further ++ the callable will be called with this integer, allowing further + processing or error checking. Using this is deprecated, for more flexible + post processing or error checking use a ctypes data type as + :attr:`restype` and assign a callable to the :attr:`errcheck` attribute. +@@ -1573,7 +1573,7 @@ + + When a foreign function is called, each actual argument is passed to the + :meth:`from_param` class method of the items in the :attr:`argtypes` +- tuple, this method allows to adapt the actual argument to an object that ++ tuple, this method allows adapting the actual argument to an object that + the foreign function accepts. For example, a :class:`c_char_p` item in + the :attr:`argtypes` tuple will convert a unicode string passed as + argument into an byte string using ctypes conversion rules. +@@ -1581,7 +1581,7 @@ + New: It is now possible to put items in argtypes which are not ctypes + types, but each item must have a :meth:`from_param` method which returns a + value usable as argument (integer, string, ctypes instance). This allows +- to define adapters that can adapt custom objects as function parameters. ++ defining adapters that can adapt custom objects as function parameters. + + + .. attribute:: errcheck +@@ -1595,12 +1595,12 @@ + *result* is what the foreign function returns, as specified by the + :attr:`restype` attribute. + +- *func* is the foreign function object itself, this allows to reuse the ++ *func* is the foreign function object itself, this allows reusing the + same callable object to check or post process the results of several + functions. + + *arguments* is a tuple containing the parameters originally passed to +- the function call, this allows to specialize the behavior on the ++ the function call, this allows specializing the behavior on the + arguments used. + + The object that this function returns will be returned from the +@@ -1853,7 +1853,7 @@ + If a string is specified as first argument, the buffer is made one item larger + than the length of the string so that the last element in the array is a NUL + termination character. An integer can be passed as second argument which allows +- to specify the size of the array if the length of the string should not be used. ++ specifying the size of the array if the length of the string should not be used. + + If the first parameter is a unicode string, it is converted into an 8-bit string + according to ctypes conversion rules. +@@ -1870,7 +1870,7 @@ + If a unicode string is specified as first argument, the buffer is made one item + larger than the length of the string so that the last element in the array is a + NUL termination character. An integer can be passed as second argument which +- allows to specify the size of the array if the length of the string should not ++ allows specifying the size of the array if the length of the string should not + be used. + + If the first parameter is a 8-bit string, it is converted into an unicode string +@@ -1879,14 +1879,14 @@ + + .. function:: DllCanUnloadNow() + +- Windows only: This function is a hook which allows to implement in-process ++ Windows only: This function is a hook which allows implementing in-process + COM servers with ctypes. It is called from the DllCanUnloadNow function that + the _ctypes extension dll exports. + + + .. function:: DllGetClassObject() + +- Windows only: This function is a hook which allows to implement in-process ++ Windows only: This function is a hook which allows implementing in-process + COM servers with ctypes. It is called from the DllGetClassObject function + that the ``_ctypes`` extension dll exports. + +@@ -2432,7 +2432,7 @@ + checked, only one field can be accessed when names are repeated. + + It is possible to define the :attr:`_fields_` class variable *after* the +- class statement that defines the Structure subclass, this allows to create ++ class statement that defines the Structure subclass, this allows creating + data types that directly or indirectly reference themselves:: + + class List(Structure): +@@ -2453,7 +2453,7 @@ + + .. attribute:: _pack_ + +- An optional small integer that allows to override the alignment of ++ An optional small integer that allows overriding the alignment of + structure fields in the instance. :attr:`_pack_` must already be defined + when :attr:`_fields_` is assigned, otherwise it will have no effect. + +@@ -2465,8 +2465,8 @@ + assigned, otherwise it will have no effect. + + The fields listed in this variable must be structure or union type fields. +- :mod:`ctypes` will create descriptors in the structure type that allows to +- access the nested fields directly, without the need to create the ++ :mod:`ctypes` will create descriptors in the structure type that allow ++ accessing the nested fields directly, without the need to create the + structure or union field. + + Here is an example type (Windows):: +@@ -2512,6 +2512,56 @@ + Arrays and pointers + ^^^^^^^^^^^^^^^^^^^ + +-Not yet written - please see the sections :ref:`ctypes-pointers` and section +-:ref:`ctypes-arrays` in the tutorial. +- ++.. class:: Array(\*args) ++ ++ Abstract base class for arrays. ++ ++ The recommended way to create concrete array types is by multiplying any ++ :mod:`ctypes` data type with a positive integer. Alternatively, you can subclass ++ this type and define :attr:`_length_` and :attr:`_type_` class variables. ++ Array elements can be read and written using standard ++ subscript and slice accesses; for slice reads, the resulting object is ++ *not* itself an :class:`Array`. ++ ++ ++ .. attribute:: _length_ ++ ++ A positive integer specifying the number of elements in the array. ++ Out-of-range subscripts result in an :exc:`IndexError`. Will be ++ returned by :func:`len`. ++ ++ ++ .. attribute:: _type_ ++ ++ Specifies the type of each element in the array. ++ ++ ++ Array subclass constructors accept positional arguments, used to ++ initialize the elements in order. ++ ++ ++.. class:: _Pointer ++ ++ Private, abstract base class for pointers. ++ ++ Concrete pointer types are created by calling :func:`POINTER` with the ++ type that will be pointed to; this is done automatically by ++ :func:`pointer`. ++ ++ If a pointer points to an array, its elements can be read and ++ written using standard subscript and slice accesses. Pointer objects ++ have no size, so :func:`len` will raise :exc:`TypeError`. Negative ++ subscripts will read from the memory *before* the pointer (as in C), and ++ out-of-range subscripts will probably crash with an access violation (if ++ you're lucky). ++ ++ ++ .. attribute:: _type_ ++ ++ Specifies the type pointed to. ++ ++ .. attribute:: contents ++ ++ Returns the object to which to pointer points. Assigning to this ++ attribute changes the pointer to point to the assigned object. ++ +diff -r 6d1b6a68f775 Doc/library/datetime.rst +--- a/Doc/library/datetime.rst ++++ b/Doc/library/datetime.rst +@@ -558,7 +558,7 @@ + + .. method:: date.__format__(format) + +- Same as :meth:`.date.strftime`. This makes it possible to specify format ++ Same as :meth:`.date.strftime`. This makes it possible to specify a format + string for a :class:`.date` object when using :meth:`str.format`. + See section :ref:`strftime-strptime-behavior`. + +@@ -1058,7 +1058,7 @@ + + .. method:: datetime.__format__(format) + +- Same as :meth:`.datetime.strftime`. This makes it possible to specify format ++ Same as :meth:`.datetime.strftime`. This makes it possible to specify a format + string for a :class:`.datetime` object when using :meth:`str.format`. + See section :ref:`strftime-strptime-behavior`. + +@@ -1292,7 +1292,7 @@ + + .. method:: time.__format__(format) + +- Same as :meth:`.time.strftime`. This makes it possible to specify format string ++ Same as :meth:`.time.strftime`. This makes it possible to specify a format string + for a :class:`.time` object when using :meth:`str.format`. + See section :ref:`strftime-strptime-behavior`. + +diff -r 6d1b6a68f775 Doc/library/fileinput.rst +--- a/Doc/library/fileinput.rst ++++ b/Doc/library/fileinput.rst +@@ -60,6 +60,9 @@ + .. versionchanged:: 2.5 + Added the *mode* and *openhook* parameters. + ++ .. versionchanged:: 2.7.12 ++ The *bufsize* parameter is no longer used. ++ + The following functions use the global state created by :func:`fileinput.input`; + if there is no active state, :exc:`RuntimeError` is raised. + +@@ -143,6 +146,9 @@ + .. versionchanged:: 2.5 + Added the *mode* and *openhook* parameters. + ++ .. versionchanged:: 2.7.12 ++ The *bufsize* parameter is no longer used. ++ + **Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed + to :func:`fileinput.input` or to the :class:`FileInput` constructor, the file is + moved to a backup file and standard output is directed to the input file (if a +diff -r 6d1b6a68f775 Doc/library/inspect.rst +--- a/Doc/library/inspect.rst ++++ b/Doc/library/inspect.rst +@@ -272,7 +272,8 @@ + + .. function:: ismethod(object) + +- Return true if the object is a bound method written in Python. ++ Return true if the object is a bound or unbound method written in Python. ++ + + + .. function:: isfunction(object) +diff -r 6d1b6a68f775 Doc/library/itertools.rst +--- a/Doc/library/itertools.rst ++++ b/Doc/library/itertools.rst +@@ -695,6 +695,11 @@ + "Returns the nth item or a default value" + return next(islice(iterable, n, None), default) + ++ def all_equal(iterable): ++ "Returns True if all the elements are equal to each other" ++ g = groupby(iterable) ++ return next(g, True) and not next(g, False) ++ + def quantify(iterable, pred=bool): + "Count how many times the predicate is true" + return sum(imap(pred, iterable)) +diff -r 6d1b6a68f775 Doc/library/logging.rst +--- a/Doc/library/logging.rst ++++ b/Doc/library/logging.rst +@@ -622,7 +622,9 @@ + | Attribute name | Format | Description | + +================+=========================+===============================================+ + | args | You shouldn't need to | The tuple of arguments merged into ``msg`` to | +-| | format this yourself. | produce ``message``. | ++| | format this yourself. | produce ``message``, or a dict whose values | ++| | | are used for the merge (when there is only one| ++| | | argument, and it is a dictionary). | + +----------------+-------------------------+-----------------------------------------------+ + | asctime | ``%(asctime)s`` | Human-readable time when the | + | | | :class:`LogRecord` was created. By default | +diff -r 6d1b6a68f775 Doc/library/multiprocessing.rst +--- a/Doc/library/multiprocessing.rst ++++ b/Doc/library/multiprocessing.rst +@@ -215,7 +215,7 @@ + proxies. + + A manager returned by :func:`Manager` will support types :class:`list`, +- :class:`dict`, :class:`Namespace`, :class:`Lock`, :class:`RLock`, ++ :class:`dict`, :class:`~managers.Namespace`, :class:`Lock`, :class:`RLock`, + :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`, + :class:`Event`, :class:`~multiprocessing.Queue`, :class:`Value` and :class:`Array`. For + example, :: +@@ -261,16 +261,41 @@ + + For example:: + +- from multiprocessing import Pool ++ from multiprocessing import Pool, TimeoutError ++ import time ++ import os + + def f(x): + return x*x + + if __name__ == '__main__': + pool = Pool(processes=4) # start 4 worker processes +- result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously +- print result.get(timeout=1) # prints "100" unless your computer is *very* slow +- print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" ++ ++ # print "[0, 1, 4,..., 81]" ++ print pool.map(f, range(10)) ++ ++ # print same numbers in arbitrary order ++ for i in pool.imap_unordered(f, range(10)): ++ print i ++ ++ # evaluate "f(20)" asynchronously ++ res = pool.apply_async(f, (20,)) # runs in *only* one process ++ print res.get(timeout=1) # prints "400" ++ ++ # evaluate "os.getpid()" asynchronously ++ res = pool.apply_async(os.getpid, ()) # runs in *only* one process ++ print res.get(timeout=1) # prints the PID of that process ++ ++ # launching multiple evaluations asynchronously *may* use more processes ++ multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)] ++ print [res.get(timeout=1) for res in multiple_results] ++ ++ # make a single worker sleep for 10 secs ++ res = pool.apply_async(time.sleep, (10,)) ++ try: ++ print res.get(timeout=1) ++ except TimeoutError: ++ print "We lacked patience and got a multiprocessing.TimeoutError" + + Note that the methods of a pool should only ever be used by the + process which created it. +@@ -751,8 +776,10 @@ + If the ``freeze_support()`` line is omitted then trying to run the frozen + executable will raise :exc:`RuntimeError`. + +- If the module is being run normally by the Python interpreter then +- :func:`freeze_support` has no effect. ++ Calling ``freeze_support()`` has no effect when invoked on any operating ++ system other than Windows. In addition, if the module is being run ++ normally by the Python interpreter on Windows (the program has not been ++ frozen), then ``freeze_support()`` has no effect. + + .. function:: set_executable() + +@@ -1510,24 +1537,25 @@ + lproxy[0] = d + + +-Namespace objects +->>>>>>>>>>>>>>>>> +- +-A namespace object has no public methods, but does have writable attributes. +-Its representation shows the values of its attributes. +- +-However, when using a proxy for a namespace object, an attribute beginning with +-``'_'`` will be an attribute of the proxy and not an attribute of the referent: +- +-.. doctest:: +- +- >>> manager = multiprocessing.Manager() +- >>> Global = manager.Namespace() +- >>> Global.x = 10 +- >>> Global.y = 'hello' +- >>> Global._z = 12.3 # this is an attribute of the proxy +- >>> print Global +- Namespace(x=10, y='hello') ++.. class:: Namespace ++ ++ A type that can register with :class:`SyncManager`. ++ ++ A namespace object has no public methods, but does have writable attributes. ++ Its representation shows the values of its attributes. ++ ++ However, when using a proxy for a namespace object, an attribute beginning with ++ ``'_'`` will be an attribute of the proxy and not an attribute of the referent: ++ ++ .. doctest:: ++ ++ >>> manager = multiprocessing.Manager() ++ >>> Global = manager.Namespace() ++ >>> Global.x = 10 ++ >>> Global.y = 'hello' ++ >>> Global._z = 12.3 # this is an attribute of the proxy ++ >>> print Global ++ Namespace(x=10, y='hello') + + + Customized managers +@@ -1884,6 +1912,7 @@ + The following example demonstrates the use of a pool:: + + from multiprocessing import Pool ++ import time + + def f(x): + return x*x +@@ -1891,7 +1920,7 @@ + if __name__ == '__main__': + pool = Pool(processes=4) # start 4 worker processes + +- result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously ++ result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process + print result.get(timeout=1) # prints "100" unless your computer is *very* slow + + print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" +@@ -1901,9 +1930,8 @@ + print it.next() # prints "1" + print it.next(timeout=1) # prints "4" unless your computer is *very* slow + +- import time + result = pool.apply_async(time.sleep, (10,)) +- print result.get(timeout=1) # raises TimeoutError ++ print result.get(timeout=1) # raises multiprocessing.TimeoutError + + + .. _multiprocessing-listeners-clients: +diff -r 6d1b6a68f775 Doc/library/nis.rst +--- a/Doc/library/nis.rst ++++ b/Doc/library/nis.rst +@@ -27,7 +27,7 @@ + Note that *mapname* is first checked if it is an alias to another name. + + .. versionchanged:: 2.5 +- The *domain* argument allows to override the NIS domain used for the lookup. If ++ The *domain* argument allows overriding the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. + + +@@ -40,7 +40,7 @@ + Note that *mapname* is first checked if it is an alias to another name. + + .. versionchanged:: 2.5 +- The *domain* argument allows to override the NIS domain used for the lookup. If ++ The *domain* argument allows overriding the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. + + +@@ -49,7 +49,7 @@ + Return a list of all valid maps. + + .. versionchanged:: 2.5 +- The *domain* argument allows to override the NIS domain used for the lookup. If ++ The *domain* argument allows overriding the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. + + +diff -r 6d1b6a68f775 Doc/library/pprint.rst +--- a/Doc/library/pprint.rst ++++ b/Doc/library/pprint.rst +@@ -190,7 +190,7 @@ + the current presentation context (direct and indirect containers for *object* + that are affecting the presentation) as the keys; if an object needs to be + presented which is already represented in *context*, the third return value +- should be ``True``. Recursive calls to the :meth:`format` method should add ++ should be ``True``. Recursive calls to the :meth:`.format` method should add + additional entries for containers to this dictionary. The third argument, + *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there + is no requested limit. This argument should be passed unmodified to recursive +diff -r 6d1b6a68f775 Doc/library/pyexpat.rst +--- a/Doc/library/pyexpat.rst ++++ b/Doc/library/pyexpat.rst +@@ -595,9 +595,9 @@ + .. sectionauthor:: Fred L. Drake, Jr. + + +-Content modules are described using nested tuples. Each tuple contains four ++Content models are described using nested tuples. Each tuple contains four + values: the type, the quantifier, the name, and a tuple of children. Children +-are simply additional content module descriptions. ++are simply additional content model descriptions. + + The values of the first two fields are constants defined in the ``model`` object + of the :mod:`xml.parsers.expat` module. These constants can be collected in two +diff -r 6d1b6a68f775 Doc/library/random.rst +--- a/Doc/library/random.rst ++++ b/Doc/library/random.rst +@@ -19,7 +19,7 @@ + lognormal, negative exponential, gamma, and beta distributions. For generating + distributions of angles, the von Mises distribution is available. + +-Almost all module functions depend on the basic function :func:`random`, which ++Almost all module functions depend on the basic function :func:`.random`, which + generates a random float uniformly in the semi-open range [0.0, 1.0). Python + uses the Mersenne Twister as the core generator. It produces 53-bit precision + floats and has a period of 2\*\*19937-1. The underlying implementation in C is +@@ -36,9 +36,10 @@ + it likely that the generated sequences seen by each thread don't overlap. + + Class :class:`Random` can also be subclassed if you want to use a different +-basic generator of your own devising: in that case, override the :meth:`random`, +-:meth:`seed`, :meth:`getstate`, :meth:`setstate` and :meth:`jumpahead` methods. +-Optionally, a new generator can supply a :meth:`getrandbits` method --- this ++basic generator of your own devising: in that case, override the :meth:`~Random.random`, ++:meth:`~Random.seed`, :meth:`~Random.getstate`, :meth:`~Random.setstate` and ++:meth:`~Random.jumpahead` methods. Optionally, a new generator can supply a ++:meth:`~Random.getrandbits` method --- this + allows :meth:`randrange` to produce selections over an arbitrarily large range. + + .. versionadded:: 2.4 +@@ -158,7 +159,7 @@ + + Shuffle the sequence *x* in place. The optional argument *random* is a + 0-argument function returning a random float in [0.0, 1.0); by default, this is +- the function :func:`random`. ++ the function :func:`.random`. + + Note that for even rather small ``len(x)``, the total number of permutations of + *x* is larger than the period of most random number generators; this implies +diff -r 6d1b6a68f775 Doc/library/readline.rst +--- a/Doc/library/readline.rst ++++ b/Doc/library/readline.rst +@@ -214,6 +214,8 @@ + histfile = os.path.join(os.path.expanduser("~"), ".pyhist") + try: + readline.read_history_file(histfile) ++ # default history len is -1 (infinite), which may grow unruly ++ readline.set_history_length(1000) + except IOError: + pass + import atexit +@@ -244,5 +246,6 @@ + atexit.register(self.save_history, histfile) + + def save_history(self, histfile): ++ readline.set_history_length(1000) + readline.write_history_file(histfile) + +diff -r 6d1b6a68f775 Doc/library/sets.rst +--- a/Doc/library/sets.rst ++++ b/Doc/library/sets.rst +@@ -76,7 +76,8 @@ + +-------------------------------+------------+---------------------------------+ + | Operation | Equivalent | Result | + +===============================+============+=================================+ +-| ``len(s)`` | | cardinality of set *s* | ++| ``len(s)`` | | number of elements in set *s* | ++| | | (cardinality) | + +-------------------------------+------------+---------------------------------+ + | ``x in s`` | | test *x* for membership in *s* | + +-------------------------------+------------+---------------------------------+ +diff -r 6d1b6a68f775 Doc/library/socketserver.rst +--- a/Doc/library/socketserver.rst ++++ b/Doc/library/socketserver.rst +@@ -16,16 +16,34 @@ + + The :mod:`SocketServer` module simplifies the task of writing network servers. + +-There are four basic server classes: :class:`TCPServer` uses the Internet TCP +-protocol, which provides for continuous streams of data between the client and +-server. :class:`UDPServer` uses datagrams, which are discrete packets of +-information that may arrive out of order or be lost while in transit. The more +-infrequently used :class:`UnixStreamServer` and :class:`UnixDatagramServer` +-classes are similar, but use Unix domain sockets; they're not available on +-non-Unix platforms. For more details on network programming, consult a book +-such as +-W. Richard Steven's UNIX Network Programming or Ralph Davis's Win32 Network +-Programming. ++There are four basic concrete server classes: ++ ++ ++.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True) ++ ++ This uses the Internet TCP protocol, which provides for ++ continuous streams of data between the client and server. ++ If *bind_and_activate* is true, the constructor automatically attempts to ++ invoke :meth:`~BaseServer.server_bind` and ++ :meth:`~BaseServer.server_activate`. The other parameters are passed to ++ the :class:`BaseServer` base class. ++ ++ ++.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True) ++ ++ This uses datagrams, which are discrete packets of information that may ++ arrive out of order or be lost while in transit. The parameters are ++ the same as for :class:`TCPServer`. ++ ++ ++.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True) ++ UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True) ++ ++ These more infrequently used classes are similar to the TCP and ++ UDP classes, but use Unix domain sockets; they're not available on ++ non-Unix platforms. The parameters are the same as for ++ :class:`TCPServer`. ++ + + These four classes process requests :dfn:`synchronously`; each request must be + completed before the next request can be started. This isn't suitable if each +@@ -37,10 +55,12 @@ + + Creating a server requires several steps. First, you must create a request + handler class by subclassing the :class:`BaseRequestHandler` class and +-overriding its :meth:`handle` method; this method will process incoming ++overriding its :meth:`~BaseRequestHandler.handle` method; ++this method will process incoming + requests. Second, you must instantiate one of the server classes, passing it + the server's address and the request handler class. Then call the +-:meth:`handle_request` or :meth:`serve_forever` method of the server object to ++:meth:`~BaseServer.handle_request` or ++:meth:`~BaseServer.serve_forever` method of the server object to + process one or many requests. Finally, call :meth:`~BaseServer.server_close` + to close the socket. + +@@ -81,18 +101,33 @@ + stream server is the address family, which is simply repeated in both Unix + server classes. + +-Forking and threading versions of each type of server can be created using the +-:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes. For instance, +-a threading UDP server class is created as follows:: + +- class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass ++.. class:: ForkingMixIn ++ ThreadingMixIn + +-The mix-in class must come first, since it overrides a method defined in +-:class:`UDPServer`. Setting the various attributes also change the +-behavior of the underlying server mechanism. ++ Forking and threading versions of each type of server can be created ++ using these mix-in classes. For instance, :class:`ThreadingUDPServer` ++ is created as follows:: ++ ++ class ThreadingUDPServer(ThreadingMixIn, UDPServer): ++ pass ++ ++ The mix-in class comes first, since it overrides a method defined in ++ :class:`UDPServer`. Setting the various attributes also changes the ++ behavior of the underlying server mechanism. ++ ++ ++.. class:: ForkingTCPServer ++ ForkingUDPServer ++ ThreadingTCPServer ++ ThreadingUDPServer ++ ++ These classes are pre-defined using the mix-in classes. ++ + + To implement a service, you must derive a class from :class:`BaseRequestHandler` +-and redefine its :meth:`handle` method. You can then run various versions of ++and redefine its :meth:`~BaseRequestHandler.handle` method. ++You can then run various versions of + the service by combining one of the server classes with your request handler + class. The request handler class must be different for datagram or stream + services. This can be hidden by using the handler subclasses +@@ -114,7 +149,7 @@ + In some cases, it may be appropriate to process part of a request synchronously, + but to finish processing in a forked child depending on the request data. This + can be implemented by using a synchronous server and doing an explicit fork in +-the request handler class :meth:`handle` method. ++the request handler class :meth:`~BaseRequestHandler.handle` method. + + Another approach to handling multiple simultaneous requests in an environment + that supports neither threads nor :func:`~os.fork` (or where these are too +@@ -132,215 +167,230 @@ + Server Objects + -------------- + +-.. class:: BaseServer ++.. class:: BaseServer(server_address, RequestHandlerClass) + + This is the superclass of all Server objects in the module. It defines the + interface, given below, but does not implement most of the methods, which is +- done in subclasses. ++ done in subclasses. The two parameters are stored in the respective ++ :attr:`server_address` and :attr:`RequestHandlerClass` attributes. + + +-.. method:: BaseServer.fileno() ++ .. method:: fileno() + +- Return an integer file descriptor for the socket on which the server is +- listening. This function is most commonly passed to :func:`select.select`, to +- allow monitoring multiple servers in the same process. ++ Return an integer file descriptor for the socket on which the server is ++ listening. This function is most commonly passed to :func:`select.select`, to ++ allow monitoring multiple servers in the same process. + + +-.. method:: BaseServer.handle_request() ++ .. method:: handle_request() + +- Process a single request. This function calls the following methods in +- order: :meth:`get_request`, :meth:`verify_request`, and +- :meth:`process_request`. If the user-provided :meth:`handle` method of the +- handler class raises an exception, the server's :meth:`handle_error` method +- will be called. If no request is received within :attr:`self.timeout` +- seconds, :meth:`handle_timeout` will be called and :meth:`handle_request` +- will return. ++ Process a single request. This function calls the following methods in ++ order: :meth:`get_request`, :meth:`verify_request`, and ++ :meth:`process_request`. If the user-provided ++ :meth:`~BaseRequestHandler.handle` method of the ++ handler class raises an exception, the server's :meth:`handle_error` method ++ will be called. If no request is received within :attr:`timeout` ++ seconds, :meth:`handle_timeout` will be called and :meth:`handle_request` ++ will return. + + +-.. method:: BaseServer.serve_forever(poll_interval=0.5) ++ .. method:: serve_forever(poll_interval=0.5) + +- Handle requests until an explicit :meth:`shutdown` request. +- Poll for shutdown every *poll_interval* seconds. Ignores :attr:`self.timeout`. +- If you need to do periodic tasks, do them in another thread. ++ Handle requests until an explicit :meth:`shutdown` request. Poll for ++ shutdown every *poll_interval* seconds. ++ Ignores the :attr:`timeout` attribute. ++ If you need to do periodic tasks, do them in another thread. + + +-.. method:: BaseServer.shutdown() ++ .. method:: shutdown() + +- Tell the :meth:`serve_forever` loop to stop and wait until it does. ++ Tell the :meth:`serve_forever` loop to stop and wait until it does. + +- .. versionadded:: 2.6 ++ .. versionadded:: 2.6 + + +-.. method:: BaseServer.server_close() ++ .. method:: server_close() + +- Clean up the server. May be overridden. ++ Clean up the server. May be overridden. + +- .. versionadded:: 2.6 ++ .. versionadded:: 2.6 + + +-.. attribute:: BaseServer.address_family ++ .. attribute:: address_family + +- The family of protocols to which the server's socket belongs. +- Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`. ++ The family of protocols to which the server's socket belongs. ++ Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`. + + +-.. attribute:: BaseServer.RequestHandlerClass ++ .. attribute:: RequestHandlerClass + +- The user-provided request handler class; an instance of this class is created +- for each request. ++ The user-provided request handler class; an instance of this class is created ++ for each request. + + +-.. attribute:: BaseServer.server_address ++ .. attribute:: server_address + +- The address on which the server is listening. The format of addresses varies +- depending on the protocol family; see the documentation for the socket module +- for details. For Internet protocols, this is a tuple containing a string giving +- the address, and an integer port number: ``('127.0.0.1', 80)``, for example. ++ The address on which the server is listening. The format of addresses varies ++ depending on the protocol family; ++ see the documentation for the :mod:`socket` module ++ for details. For Internet protocols, this is a tuple containing a string giving ++ the address, and an integer port number: ``('127.0.0.1', 80)``, for example. + + +-.. attribute:: BaseServer.socket ++ .. attribute:: socket + +- The socket object on which the server will listen for incoming requests. ++ The socket object on which the server will listen for incoming requests. + + +-The server classes support the following class variables: ++ The server classes support the following class variables: + +-.. XXX should class variables be covered before instance variables, or vice versa? ++ .. XXX should class variables be covered before instance variables, or vice versa? + +-.. attribute:: BaseServer.allow_reuse_address ++ .. attribute:: allow_reuse_address + +- Whether the server will allow the reuse of an address. This defaults to +- :const:`False`, and can be set in subclasses to change the policy. ++ Whether the server will allow the reuse of an address. This defaults to ++ :const:`False`, and can be set in subclasses to change the policy. + + +-.. attribute:: BaseServer.request_queue_size ++ .. attribute:: request_queue_size + +- The size of the request queue. If it takes a long time to process a single +- request, any requests that arrive while the server is busy are placed into a +- queue, up to :attr:`request_queue_size` requests. Once the queue is full, +- further requests from clients will get a "Connection denied" error. The default +- value is usually 5, but this can be overridden by subclasses. ++ The size of the request queue. If it takes a long time to process a single ++ request, any requests that arrive while the server is busy are placed into a ++ queue, up to :attr:`request_queue_size` requests. Once the queue is full, ++ further requests from clients will get a "Connection denied" error. The default ++ value is usually 5, but this can be overridden by subclasses. + + +-.. attribute:: BaseServer.socket_type ++ .. attribute:: socket_type + +- The type of socket used by the server; :const:`socket.SOCK_STREAM` and +- :const:`socket.SOCK_DGRAM` are two common values. ++ The type of socket used by the server; :const:`socket.SOCK_STREAM` and ++ :const:`socket.SOCK_DGRAM` are two common values. + + +-.. attribute:: BaseServer.timeout ++ .. attribute:: timeout + +- Timeout duration, measured in seconds, or :const:`None` if no timeout is +- desired. If :meth:`handle_request` receives no incoming requests within the +- timeout period, the :meth:`handle_timeout` method is called. ++ Timeout duration, measured in seconds, or :const:`None` if no timeout is ++ desired. If :meth:`handle_request` receives no incoming requests within the ++ timeout period, the :meth:`handle_timeout` method is called. + + +-There are various server methods that can be overridden by subclasses of base +-server classes like :class:`TCPServer`; these methods aren't useful to external +-users of the server object. ++ There are various server methods that can be overridden by subclasses of base ++ server classes like :class:`TCPServer`; these methods aren't useful to external ++ users of the server object. + +-.. XXX should the default implementations of these be documented, or should +- it be assumed that the user will look at SocketServer.py? ++ .. XXX should the default implementations of these be documented, or should ++ it be assumed that the user will look at SocketServer.py? + +-.. method:: BaseServer.finish_request() ++ .. method:: finish_request() + +- Actually processes the request by instantiating :attr:`RequestHandlerClass` and +- calling its :meth:`handle` method. ++ Actually processes the request by instantiating :attr:`RequestHandlerClass` and ++ calling its :meth:`~BaseRequestHandler.handle` method. + + +-.. method:: BaseServer.get_request() ++ .. method:: get_request() + +- Must accept a request from the socket, and return a 2-tuple containing the *new* +- socket object to be used to communicate with the client, and the client's +- address. ++ Must accept a request from the socket, and return a 2-tuple containing the *new* ++ socket object to be used to communicate with the client, and the client's ++ address. + + +-.. method:: BaseServer.handle_error(request, client_address) ++ .. method:: handle_error(request, client_address) + +- This function is called if the :attr:`RequestHandlerClass`'s :meth:`handle` +- method raises an exception. The default action is to print the traceback to +- standard output and continue handling further requests. ++ This function is called if the :meth:`~BaseRequestHandler.handle` ++ method of a :attr:`RequestHandlerClass` instance raises ++ an exception. The default action is to print the traceback to ++ standard output and continue handling further requests. + + +-.. method:: BaseServer.handle_timeout() ++ .. method:: handle_timeout() + +- This function is called when the :attr:`timeout` attribute has been set to a +- value other than :const:`None` and the timeout period has passed with no +- requests being received. The default action for forking servers is +- to collect the status of any child processes that have exited, while +- in threading servers this method does nothing. ++ This function is called when the :attr:`timeout` attribute has been set to a ++ value other than :const:`None` and the timeout period has passed with no ++ requests being received. The default action for forking servers is ++ to collect the status of any child processes that have exited, while ++ in threading servers this method does nothing. + + +-.. method:: BaseServer.process_request(request, client_address) ++ .. method:: process_request(request, client_address) + +- Calls :meth:`finish_request` to create an instance of the +- :attr:`RequestHandlerClass`. If desired, this function can create a new process +- or thread to handle the request; the :class:`ForkingMixIn` and +- :class:`ThreadingMixIn` classes do this. ++ Calls :meth:`finish_request` to create an instance of the ++ :attr:`RequestHandlerClass`. If desired, this function can create a new process ++ or thread to handle the request; the :class:`ForkingMixIn` and ++ :class:`ThreadingMixIn` classes do this. + + +-.. Is there any point in documenting the following two functions? +- What would the purpose of overriding them be: initializing server +- instance variables, adding new network families? ++ .. Is there any point in documenting the following two functions? ++ What would the purpose of overriding them be: initializing server ++ instance variables, adding new network families? + +-.. method:: BaseServer.server_activate() ++ .. method:: server_activate() + +- Called by the server's constructor to activate the server. The default behavior +- just :meth:`listen`\ s to the server's socket. May be overridden. ++ Called by the server's constructor to activate the server. The default behavior ++ for a TCP server just invokes :meth:`~socket.socket.listen` ++ on the server's socket. May be overridden. + + +-.. method:: BaseServer.server_bind() ++ .. method:: server_bind() + +- Called by the server's constructor to bind the socket to the desired address. +- May be overridden. ++ Called by the server's constructor to bind the socket to the desired address. ++ May be overridden. + + +-.. method:: BaseServer.verify_request(request, client_address) ++ .. method:: verify_request(request, client_address) + +- Must return a Boolean value; if the value is :const:`True`, the request will be +- processed, and if it's :const:`False`, the request will be denied. This function +- can be overridden to implement access controls for a server. The default +- implementation always returns :const:`True`. ++ Must return a Boolean value; if the value is :const:`True`, the request will be ++ processed, and if it's :const:`False`, the request will be denied. This function ++ can be overridden to implement access controls for a server. The default ++ implementation always returns :const:`True`. + + +-RequestHandler Objects +----------------------- ++Request Handler Objects ++----------------------- + +-The request handler class must define a new :meth:`handle` method, and can +-override any of the following methods. A new instance is created for each +-request. ++.. class:: BaseRequestHandler + ++ This is the superclass of all request handler objects. It defines ++ the interface, given below. A concrete request handler subclass must ++ define a new :meth:`handle` method, and can override any of ++ the other methods. A new instance of the subclass is created for each ++ request. + +-.. method:: RequestHandler.finish() + +- Called after the :meth:`handle` method to perform any clean-up actions +- required. The default implementation does nothing. If :meth:`setup` +- raises an exception, this function will not be called. ++ .. method:: setup() + ++ Called before the :meth:`handle` method to perform any initialization actions ++ required. The default implementation does nothing. + +-.. method:: RequestHandler.handle() + +- This function must do all the work required to service a request. The +- default implementation does nothing. Several instance attributes are +- available to it; the request is available as :attr:`self.request`; the client +- address as :attr:`self.client_address`; and the server instance as +- :attr:`self.server`, in case it needs access to per-server information. ++ .. method:: handle() + +- The type of :attr:`self.request` is different for datagram or stream +- services. For stream services, :attr:`self.request` is a socket object; for +- datagram services, :attr:`self.request` is a pair of string and socket. +- However, this can be hidden by using the request handler subclasses +- :class:`StreamRequestHandler` or :class:`DatagramRequestHandler`, which +- override the :meth:`setup` and :meth:`finish` methods, and provide +- :attr:`self.rfile` and :attr:`self.wfile` attributes. :attr:`self.rfile` and +- :attr:`self.wfile` can be read or written, respectively, to get the request +- data or return data to the client. ++ This function must do all the work required to service a request. The ++ default implementation does nothing. Several instance attributes are ++ available to it; the request is available as :attr:`self.request`; the client ++ address as :attr:`self.client_address`; and the server instance as ++ :attr:`self.server`, in case it needs access to per-server information. + ++ The type of :attr:`self.request` is different for datagram or stream ++ services. For stream services, :attr:`self.request` is a socket object; for ++ datagram services, :attr:`self.request` is a pair of string and socket. + +-.. method:: RequestHandler.setup() + +- Called before the :meth:`handle` method to perform any initialization actions +- required. The default implementation does nothing. ++ .. method:: finish() ++ ++ Called after the :meth:`handle` method to perform any clean-up actions ++ required. The default implementation does nothing. If :meth:`setup` ++ raises an exception, this function will not be called. ++ ++ ++.. class:: StreamRequestHandler ++ DatagramRequestHandler ++ ++ These :class:`BaseRequestHandler` subclasses override the ++ :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish` ++ methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes. ++ The :attr:`self.rfile` and :attr:`self.wfile` attributes can be ++ read or written, respectively, to get the request data or return data ++ to the client. + + + Examples +@@ -355,7 +405,7 @@ + + class MyTCPHandler(SocketServer.BaseRequestHandler): + """ +- The RequestHandler class for our server. ++ The request handler class for our server. + + It is instantiated once per connection to the server, and must + override the handle() method to implement communication to the +diff -r 6d1b6a68f775 Doc/library/sqlite3.rst +--- a/Doc/library/sqlite3.rst ++++ b/Doc/library/sqlite3.rst +@@ -595,6 +595,18 @@ + + It is set for ``SELECT`` statements without any matching rows as well. + ++ .. attribute:: connection ++ ++ This read-only attribute provides the SQLite database :class:`Connection` ++ used by the :class:`Cursor` object. A :class:`Cursor` object created by ++ calling :meth:`con.cursor() ` will have a ++ :attr:`connection` attribute that refers to *con*:: ++ ++ >>> con = sqlite3.connect(":memory:") ++ >>> cur = con.cursor() ++ >>> cur.connection == con ++ True ++ + .. _sqlite3-row-objects: + + Row Objects +diff -r 6d1b6a68f775 Doc/library/stdtypes.rst +--- a/Doc/library/stdtypes.rst ++++ b/Doc/library/stdtypes.rst +@@ -963,10 +963,9 @@ + + .. method:: str.find(sub[, start[, end]]) + +- Return the lowest index in the string where substring *sub* is found, such +- that *sub* is contained in the slice ``s[start:end]``. Optional arguments +- *start* and *end* are interpreted as in slice notation. Return ``-1`` if +- *sub* is not found. ++ Return the lowest index in the string where substring *sub* is found within ++ the slice ``s[start:end]``. Optional arguments *start* and *end* are ++ interpreted as in slice notation. Return ``-1`` if *sub* is not found. + + .. note:: + +@@ -1780,7 +1779,7 @@ + + .. describe:: len(s) + +- Return the cardinality of set *s*. ++ Return the number of elements in set *s* (cardinality of *s*). + + .. describe:: x in s + +diff -r 6d1b6a68f775 Doc/library/string.rst +--- a/Doc/library/string.rst ++++ b/Doc/library/string.rst +@@ -105,8 +105,8 @@ + + .. _new-string-formatting: + +-String Formatting +------------------ ++Custom String Formatting ++------------------------ + + .. versionadded:: 2.6 + +@@ -115,7 +115,7 @@ + :meth:`str.format` method described in :pep:`3101`. The :class:`Formatter` + class in the :mod:`string` module allows you to create and customize your own + string formatting behaviors using the same implementation as the built-in +-:meth:`format` method. ++:meth:`~str.format` method. + + .. class:: Formatter + +@@ -123,9 +123,9 @@ + + .. method:: format(format_string, *args, **kwargs) + +- :meth:`format` is the primary API method. It takes a format string and ++ The primary API method. It takes a format string and + an arbitrary set of positional and keyword arguments. +- :meth:`format` is just a wrapper that calls :meth:`vformat`. ++ It is just a wrapper that calls :meth:`vformat`. + + .. method:: vformat(format_string, args, kwargs) + +@@ -293,8 +293,9 @@ + described in the next section. + + A *format_spec* field can also include nested replacement fields within it. +-These nested replacement fields can contain only a field name; conversion flags +-and format specifications are not allowed. The replacement fields within the ++These nested replacement fields may contain a field name, conversion flag ++and format specification, but deeper nesting is ++not allowed. The replacement fields within the + format_spec are substituted before the *format_spec* string is interpreted. + This allows the formatting of a value to be dynamically specified. + +@@ -332,8 +333,10 @@ + + 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 ++It is not possible to use a literal curly brace ("``{``" or "``}``") as ++the *fill* character when using the :meth:`str.format` ++method. However, it is possible to insert a curly brace ++with a nested replacement field. This limitation doesn't + affect the :func:`format` function. + + The meaning of the various alignment options is as follows: +@@ -508,8 +511,8 @@ + Format examples + ^^^^^^^^^^^^^^^ + +-This section contains examples of the new format syntax and comparison with +-the old ``%``-formatting. ++This section contains examples of the :meth:`str.format` syntax and ++comparison with the old ``%``-formatting. + + In most of the cases the syntax is similar to the old ``%``-formatting, with the + addition of the ``{}`` and with ``:`` used instead of ``%``. +diff -r 6d1b6a68f775 Doc/library/tarfile.rst +--- a/Doc/library/tarfile.rst ++++ b/Doc/library/tarfile.rst +@@ -90,7 +90,7 @@ + specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant + in combination with e.g. ``sys.stdin``, a socket file object or a tape + device. However, such a :class:`TarFile` object is limited in that it does +- not allow to be accessed randomly, see :ref:`tar-examples`. The currently ++ not allow random access, see :ref:`tar-examples`. The currently + possible modes: + + +-------------+--------------------------------------------+ +@@ -438,20 +438,29 @@ + + Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given, + ``tarinfo.size`` bytes are read from it and added to the archive. You can +- create :class:`TarInfo` objects using :meth:`gettarinfo`. ++ create :class:`TarInfo` objects directly, or by using :meth:`gettarinfo`. + + .. note:: +- + On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to + avoid irritation about the file size. + + + .. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None) + +- Create a :class:`TarInfo` object for either the file *name* or the file object +- *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify some +- of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`. +- If given, *arcname* specifies an alternative name for the file in the archive. ++ Create a :class:`TarInfo` object from the result of :func:`os.stat` or ++ equivalent on an existing file. The file is either named by *name*, or ++ specified as a file object *fileobj* with a file descriptor. If ++ given, *arcname* specifies an alternative name for the file in the ++ archive, otherwise, the name is taken from *fileobj*’s ++ :attr:`~file.name` attribute, or the *name* argument. ++ ++ You can modify some ++ of the :class:`TarInfo`’s attributes before you add it using :meth:`addfile`. ++ If the file object is not an ordinary file object positioned at the ++ beginning of the file, attributes such as :attr:`~TarInfo.size` may need ++ modifying. This is the case for objects such as :class:`~gzip.GzipFile`. ++ The :attr:`~TarInfo.name` may also be modified, in which case *arcname* ++ could be a dummy string. + + + .. method:: TarFile.close() +diff -r 6d1b6a68f775 Doc/library/tempfile.rst +--- a/Doc/library/tempfile.rst ++++ b/Doc/library/tempfile.rst +@@ -64,7 +64,8 @@ + This function operates exactly as :func:`TemporaryFile` does, except that + the file is guaranteed to have a visible name in the file system (on + Unix, the directory entry is not unlinked). That name can be retrieved +- from the :attr:`name` attribute of the file object. Whether the name can be ++ from the :attr:`name` attribute of the returned ++ file-like object. Whether the name can be + used to open the file a second time, while the named temporary file is + still open, varies across platforms (it can be so used on Unix; it cannot + on Windows NT or later). If *delete* is true (the default), the file is +diff -r 6d1b6a68f775 Doc/library/test.rst +--- a/Doc/library/test.rst ++++ b/Doc/library/test.rst +@@ -418,7 +418,7 @@ + Module and package deprecation messages are suppressed during this import + if *deprecated* is :const:`True`. + +- This function will raise :exc:`unittest.SkipTest` is the named module ++ This function will raise :exc:`unittest.SkipTest` if the named module + cannot be imported. + + Example use:: +diff -r 6d1b6a68f775 Doc/library/time.rst +--- a/Doc/library/time.rst ++++ b/Doc/library/time.rst +@@ -427,9 +427,12 @@ + + Note that unlike the C structure, the month value is a range of [1, 12], not + [0, 11]. A year value will be handled as described under :ref:`Year 2000 +- (Y2K) issues ` above. A ``-1`` argument as the daylight +- savings flag, passed to :func:`mktime` will usually result in the correct +- daylight savings state to be filled in. ++ (Y2K) issues ` above. ++ ++ In calls to :func:`mktime`, :attr:`tm_isdst` may be set to 1 when daylight ++ savings time is in effect, and 0 when it is not. A value of -1 indicates ++ that this is not known, and will usually result in the correct state being ++ filled in. + + When a tuple with an incorrect length is passed to a function expecting a + :class:`struct_time`, or having elements of the wrong type, a +diff -r 6d1b6a68f775 Doc/library/tokenize.rst +--- a/Doc/library/tokenize.rst ++++ b/Doc/library/tokenize.rst +@@ -28,7 +28,7 @@ + + The :func:`generate_tokens` generator requires one argument, *readline*, + which must be a callable object which provides the same interface as the +- :meth:`readline` method of built-in file objects (see section ++ :meth:`~file.readline` method of built-in file objects (see section + :ref:`bltin-file-objects`). Each call to the function should return one line + of input as a string. Alternately, *readline* may be a callable object that + signals completion by raising :exc:`StopIteration`. +@@ -47,11 +47,11 @@ + + .. function:: tokenize(readline[, tokeneater]) + +- The :func:`tokenize` function accepts two parameters: one representing the input +- stream, and one providing an output mechanism for :func:`tokenize`. ++ The :func:`.tokenize` function accepts two parameters: one representing the input ++ stream, and one providing an output mechanism for :func:`.tokenize`. + + The first parameter, *readline*, must be a callable object which provides the +- same interface as the :meth:`readline` method of built-in file objects (see ++ same interface as the :meth:`~file.readline` method of built-in file objects (see + section :ref:`bltin-file-objects`). Each call to the function should return one + line of input as a string. Alternately, *readline* may be a callable object that + signals completion by raising :exc:`StopIteration`. +@@ -65,7 +65,7 @@ + + All constants from the :mod:`token` module are also exported from + :mod:`tokenize`, as are two additional token type values that might be passed to +-the *tokeneater* function by :func:`tokenize`: ++the *tokeneater* function by :func:`.tokenize`: + + + .. data:: COMMENT +diff -r 6d1b6a68f775 Doc/library/traceback.rst +--- a/Doc/library/traceback.rst ++++ b/Doc/library/traceback.rst +@@ -14,29 +14,30 @@ + .. index:: object: traceback + + The module uses traceback objects --- this is the object type that is stored in +-the variables :data:`sys.exc_traceback` (deprecated) and :data:`sys.last_traceback` and +-returned as the third item from :func:`sys.exc_info`. ++the variables :data:`sys.exc_traceback` (deprecated) and ++:data:`sys.last_traceback` and returned as the third item from ++:func:`sys.exc_info`. + + The module defines the following functions: + + +-.. function:: print_tb(traceback[, limit[, file]]) ++.. function:: print_tb(tb[, limit[, file]]) + +- Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted +- or ``None``, all entries are printed. If *file* is omitted or ``None``, the +- output goes to ``sys.stderr``; otherwise it should be an open file or file-like +- object to receive the output. ++ Print up to *limit* stack trace entries from the traceback object *tb*. If ++ *limit* is omitted or ``None``, all entries are printed. If *file* is omitted ++ or ``None``, the output goes to ``sys.stderr``; otherwise it should be an ++ open file or file-like object to receive the output. + + +-.. function:: print_exception(type, value, traceback[, limit[, file]]) ++.. function:: print_exception(etype, value, tb[, limit[, file]]) + +- Print exception information and up to *limit* stack trace entries from +- *traceback* to *file*. This differs from :func:`print_tb` in the following ways: +- (1) if *traceback* is not ``None``, it prints a header ``Traceback (most recent +- call last):``; (2) it prints the exception *type* and *value* after the stack +- trace; (3) if *type* is :exc:`SyntaxError` and *value* has the appropriate +- format, it prints the line where the syntax error occurred with a caret +- indicating the approximate position of the error. ++ Print exception information and up to *limit* stack trace entries from the ++ traceback *tb* to *file*. This differs from :func:`print_tb` in the following ++ ways: (1) if *tb* is not ``None``, it prints a header ``Traceback (most ++ recent call last):``; (2) it prints the exception *etype* and *value* after ++ the stack trace; (3) if *etype* is :exc:`SyntaxError` and *value* has the ++ appropriate format, it prints the line where the syntax error occurred with a ++ caret indicating the approximate position of the error. + + + .. function:: print_exc([limit[, file]]) +@@ -49,8 +50,8 @@ + + .. function:: format_exc([limit]) + +- This is like ``print_exc(limit)`` but returns a string instead of printing to a +- file. ++ This is like ``print_exc(limit)`` but returns a string instead of printing to ++ a file. + + .. versionadded:: 2.4 + +@@ -64,21 +65,21 @@ + + .. function:: print_stack([f[, limit[, file]]]) + +- This function prints a stack trace from its invocation point. The optional *f* +- argument can be used to specify an alternate stack frame to start. The optional +- *limit* and *file* arguments have the same meaning as for ++ This function prints a stack trace from its invocation point. The optional ++ *f* argument can be used to specify an alternate stack frame to start. The ++ optional limit* and *file* arguments have the same meaning as for + :func:`print_exception`. + + +-.. function:: extract_tb(traceback[, limit]) ++.. function:: extract_tb(tb[, limit]) + + Return a list of up to *limit* "pre-processed" stack trace entries extracted +- from the traceback object *traceback*. It is useful for alternate formatting of +- stack traces. If *limit* is omitted or ``None``, all entries are extracted. A +- "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*, +- *function name*, *text*) representing the information that is usually printed +- for a stack trace. The *text* is a string with leading and trailing whitespace +- stripped; if the source is not available it is ``None``. ++ from the traceback object *tb*. It is useful for alternate formatting of ++ stack traces. If *limit* is omitted or ``None``, all entries are extracted. ++ A "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*, ++ function name*, *text*) representing the information that is usually printed ++ for a stack trace. The *text* is a string with leading and trailing ++ whitespace stripped; if the source is not available it is ``None``. + + + .. function:: extract_stack([f[, limit]]) +@@ -88,33 +89,35 @@ + arguments have the same meaning as for :func:`print_stack`. + + +-.. function:: format_list(list) ++.. function:: format_list(extracted_list) + + Given a list of tuples as returned by :func:`extract_tb` or +- :func:`extract_stack`, return a list of strings ready for printing. Each string +- in the resulting list corresponds to the item with the same index in the +- argument list. Each string ends in a newline; the strings may contain internal +- newlines as well, for those items whose source text line is not ``None``. ++ :func:`extract_stack`, return a list of strings ready for printing. Each ++ string in the resulting list corresponds to the item with the same index in ++ the argument list. Each string ends in a newline; the strings may contain ++ internal newlines as well, for those items whose source text line is not ++ ``None``. + + +-.. function:: format_exception_only(type, value) ++.. function:: format_exception_only(etype, value) + +- Format the exception part of a traceback. The arguments are the exception type +- and value such as given by ``sys.last_type`` and ``sys.last_value``. The return +- value is a list of strings, each ending in a newline. Normally, the list +- contains a single string; however, for :exc:`SyntaxError` exceptions, it +- contains several lines that (when printed) display detailed information about +- where the syntax error occurred. The message indicating which exception +- occurred is the always last string in the list. ++ Format the exception part of a traceback. The arguments are the exception ++ type, *etype* and *value* such as given by ``sys.last_type`` and ++ ``sys.last_value``. The return value is a list of strings, each ending in a ++ newline. Normally, the list contains a single string; however, for ++ :exc:`SyntaxError` exceptions, it contains several lines that (when printed) ++ display detailed information about where the syntax error occurred. The ++ message indicating which exception occurred is the always last string in the ++ list. + + +-.. function:: format_exception(type, value, tb[, limit]) ++.. function:: format_exception(etype, value, tb[, limit]) + + Format a stack trace and the exception information. The arguments have the + same meaning as the corresponding arguments to :func:`print_exception`. The +- return value is a list of strings, each ending in a newline and some containing +- internal newlines. When these lines are concatenated and printed, exactly the +- same text is printed as does :func:`print_exception`. ++ return value is a list of strings, each ending in a newline and some ++ containing internal newlines. When these lines are concatenated and printed, ++ exactly the same text is printed as does :func:`print_exception`. + + + .. function:: format_tb(tb[, limit]) +@@ -129,10 +132,10 @@ + + .. function:: tb_lineno(tb) + +- This function returns the current line number set in the traceback object. This +- function was necessary because in versions of Python prior to 2.3 when the +- :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not updated +- correctly. This function has no use in versions past 2.3. ++ This function returns the current line number set in the traceback object. ++ This function was necessary because in versions of Python prior to 2.3 when ++ the :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not ++ updated correctly. This function has no use in versions past 2.3. + + + .. _traceback-example: +diff -r 6d1b6a68f775 Doc/library/ttk.rst +--- a/Doc/library/ttk.rst ++++ b/Doc/library/ttk.rst +@@ -293,7 +293,7 @@ + :meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate` + and :meth:`Widget.state`) and those inherited from :class:`Entry` + (:meth:`Entry.bbox`, :meth:`Entry.delete`, :meth:`Entry.icursor`, +-:meth:`Entry.index`, :meth:`Entry.inset`, :meth:`Entry.selection`, ++:meth:`Entry.index`, :meth:`Entry.insert`, :meth:`Entry.selection`, + :meth:`Entry.xview`), this class has some other methods, described at + :class:`ttk.Combobox`. + +diff -r 6d1b6a68f775 Doc/library/unittest.rst +--- a/Doc/library/unittest.rst ++++ b/Doc/library/unittest.rst +@@ -147,7 +147,7 @@ + + The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you + to define instructions that will be executed before and after each test method. +-They are covered in more details in the section :ref:`organizing-tests`. ++They are covered in more detail in the section :ref:`organizing-tests`. + + The final block shows a simple way to run the tests. :func:`unittest.main` + provides a command-line interface to the test script. When run from the command +@@ -720,10 +720,12 @@ + Method called immediately after the test method has been called and the + result recorded. This is called even if the test method raised an + exception, so the implementation in subclasses may need to be particularly +- careful about checking internal state. Any exception, other than :exc:`AssertionError` +- or :exc:`SkipTest`, raised by this method will be considered an error rather than a +- test failure. This method will only be called if the :meth:`setUp` succeeds, +- regardless of the outcome of the test method. The default implementation does nothing. ++ careful about checking internal state. Any exception, other than ++ :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be ++ considered an additional error rather than a test failure (thus increasing ++ the total number of reported errors). This method will only be called if ++ the :meth:`setUp` succeeds, regardless of the outcome of the test method. ++ The default implementation does nothing. + + + .. method:: setUpClass() +@@ -783,8 +785,9 @@ + + .. _assert-methods: + +- The :class:`TestCase` class provides a number of methods to check for and +- report failures, such as: ++ The :class:`TestCase` class provides several assert methods to check for and ++ report failures. The following table lists the most commonly used methods ++ (see the tables below for more assert methods): + + +-----------------------------------------+-----------------------------+---------------+ + | Method | Checks that | New in | +@@ -1763,9 +1766,10 @@ + instead of repeatedly creating new instances. + + +-.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1) +- +- A basic test runner implementation which prints results on standard error. It ++.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, \ ++ failfast=False, buffer=False, resultclass=None) ++ ++ A basic test runner implementation which prints results on standard error. It + has a few configurable parameters, but is essentially very simple. Graphical + applications which run test suites should provide alternate implementations. + +diff -r 6d1b6a68f775 Doc/library/webbrowser.rst +--- a/Doc/library/webbrowser.rst ++++ b/Doc/library/webbrowser.rst +@@ -144,6 +144,14 @@ + +-----------------------+-----------------------------------------+-------+ + | ``'safari'`` | :class:`MacOSX('safari')` | \(3) | + +-----------------------+-----------------------------------------+-------+ ++| ``'google-chrome'`` | :class:`Chrome('google-chrome')` | \(4) | +++-----------------------+-----------------------------------------+-------+ ++| ``'chrome'`` | :class:`Chrome('chrome')` | \(4) | +++-----------------------+-----------------------------------------+-------+ ++| ``'chromium'`` | :class:`Chromium('chromium')` | \(4) | +++-----------------------+-----------------------------------------+-------+ ++| ``'chromium-browser'``| :class:`Chromium('chromium-browser')` | \(4) | +++-----------------------+-----------------------------------------+-------+ + + Notes: + +@@ -160,6 +168,9 @@ + (3) + Only on Mac OS X platform. + ++(4) ++ Support for Chrome/Chromium has been added in version 2.7.5. ++ + Here are some simple examples:: + + url = 'http://www.python.org/' +diff -r 6d1b6a68f775 Doc/library/xmlrpclib.rst +--- a/Doc/library/xmlrpclib.rst ++++ b/Doc/library/xmlrpclib.rst +@@ -564,7 +564,7 @@ + except Error as v: + print "ERROR", v + +-To access an XML-RPC server through a proxy, you need to define a custom ++To access an XML-RPC server through a HTTP proxy, you need to define a custom + transport. The following example shows how: + + .. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html +@@ -578,7 +578,7 @@ + self.proxy = proxy + def make_connection(self, host): + self.realhost = host +- h = httplib.HTTP(self.proxy) ++ h = httplib.HTTPConnection(self.proxy) + return h + def send_request(self, connection, handler, request_body): + connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) +@@ -587,7 +587,7 @@ + + p = ProxiedTransport() + p.set_proxy('proxy-server:8080') +- server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p) ++ server = xmlrpclib.ServerProxy('http://time.xmlrpc.com/RPC2', transport=p) + print server.currentTime.getCurrentTime() + + +diff -r 6d1b6a68f775 Doc/library/zlib.rst +--- a/Doc/library/zlib.rst ++++ b/Doc/library/zlib.rst +@@ -71,10 +71,12 @@ + .. function:: compressobj([level[, method[, wbits[, memlevel[, strategy]]]]]) + + Returns a compression object, to be used for compressing data streams that won't +- fit into memory at once. *level* is an integer from ``0`` to ``9`` controlling ++ fit into memory at once. *level* is an integer from ++ ``0`` to ``9`` or ``-1``, controlling + the level of compression; ``1`` is fastest and produces the least compression, + ``9`` is slowest and produces the most. ``0`` is no compression. The default +- value is ``6``. ++ value is ``-1`` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default ++ compromise between speed and compression (currently equivalent to level 6). + + *method* is the compression algorithm. Currently, the only supported value is + ``DEFLATED``. +diff -r 6d1b6a68f775 Doc/license.rst +--- a/Doc/license.rst ++++ b/Doc/license.rst +@@ -73,181 +73,189 @@ + ============================================================ + + +-.. centered:: PSF LICENSE AGREEMENT FOR PYTHON |release| ++PSF LICENSE AGREEMENT FOR PYTHON |release| ++------------------------------------------ + +-#. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and +- the Individual or Organization ("Licensee") accessing and otherwise using Python +- |release| software in source or binary form and its associated documentation. ++.. parsed-literal:: + +-#. 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 |release| alone or in any derivative +- version, provided, however, that PSF's License Agreement and PSF's notice of +- copyright, i.e., "Copyright © 2001-2015 Python Software Foundation; All Rights +- Reserved" are retained in Python |release| alone or in any derivative version +- prepared by Licensee. ++ 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and ++ the Individual or Organization ("Licensee") accessing and otherwise using Python ++ |release| software in source or binary form and its associated documentation. + +-#. In the event Licensee prepares a derivative work that is based on or +- incorporates Python |release| 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 +- |release|. ++ 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 |release| alone or in any derivative ++ version, provided, however, that PSF's License Agreement and PSF's notice of ++ copyright, i.e., "Copyright © 2001-2016 Python Software Foundation; All Rights ++ Reserved" are retained in Python |release| alone or in any derivative version ++ prepared by Licensee. + +-#. PSF is making Python |release| 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 |release| WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. ++ 3. In the event Licensee prepares a derivative work that is based on or ++ incorporates Python |release| 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 ++ |release|. + +-#. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |release| +- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF +- MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON |release|, OR ANY DERIVATIVE +- THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. ++ 4. PSF is making Python |release| 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 |release| WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +-#. This License Agreement will automatically terminate upon a material breach of +- its terms and conditions. ++ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |release| ++ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF ++ MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON |release|, OR ANY DERIVATIVE ++ THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +-#. 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. ++ 6. This License Agreement will automatically terminate upon a material breach of ++ its terms and conditions. + +-#. By copying, installing or otherwise using Python |release|, Licensee agrees +- to be bound by the terms and conditions of this License Agreement. ++ 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 |release|, Licensee agrees ++ to be bound by the terms and conditions of this License Agreement. + +-.. centered:: BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 + ++BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ++------------------------------------------- + +-.. centered:: BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 ++BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 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"). ++.. parsed-literal:: + +-#. 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. ++ 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"). + +-#. 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. ++ 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. + +-#. 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. ++ 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. + +-#. This License Agreement will automatically terminate upon a material breach of +- its terms and conditions. ++ 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. + +-#. 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. ++ 5. This License Agreement will automatically terminate upon a material breach of ++ its terms and conditions. + +-#. By copying, installing or otherwise using the software, Licensee agrees to be +- bound by the terms and conditions of this License Agreement. ++ 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. + +-.. centered:: CNRI LICENSE AGREEMENT FOR PYTHON 1.6.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. ++CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 ++--------------------------------------- + +-#. 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 © 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." ++.. parsed-literal:: + +-#. 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. ++ 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. + +-#. 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. ++ 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 © 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." + +-#. 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. ++ 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. + +-#. This License Agreement will automatically terminate upon a material breach of +- its terms and conditions. ++ 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. + +-#. 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. ++ 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. + +-#. 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. ++ 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. + +-.. centered:: ACCEPT ++ 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. + + +-.. centered:: CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 ++CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 ++-------------------------------------------------- + +-Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The +-Netherlands. All rights reserved. ++.. parsed-literal:: + +-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. ++ Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The ++ Netherlands. All rights reserved. + +-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. ++ 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 +@@ -329,18 +337,17 @@ + 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 ++ 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 ++ 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 GAI_ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN GAI_ANY WAY ++ 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. + +- + Floating point exception control + -------------------------------- + +@@ -894,4 +901,3 @@ + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu +- +diff -r 6d1b6a68f775 Doc/reference/introduction.rst +--- a/Doc/reference/introduction.rst ++++ b/Doc/reference/introduction.rst +@@ -59,7 +59,7 @@ + This implementation actually uses the CPython implementation, but is a managed + .NET application and makes .NET libraries available. It was created by Brian + Lloyd. For more information, see the `Python for .NET home page +- `_. ++ `_. + + IronPython + An alternate Python for .NET. Unlike Python.NET, this is a complete Python +diff -r 6d1b6a68f775 Doc/tools/extensions/pyspecific.py +--- a/Doc/tools/extensions/pyspecific.py ++++ b/Doc/tools/extensions/pyspecific.py +@@ -131,7 +131,7 @@ + 'assert', 'assignment', 'atom-identifiers', 'atom-literals', + 'attribute-access', 'attribute-references', 'augassign', 'binary', + 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object', +- 'bltin-null-object', 'bltin-type-objects', 'booleans', ++ 'bltin-file-objects', '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', 'exec', 'execmodel', +diff -r 6d1b6a68f775 Doc/tools/rstlint.py +--- a/Doc/tools/rstlint.py ++++ b/Doc/tools/rstlint.py +@@ -42,7 +42,7 @@ + ] + + all_directives = '(' + '|'.join(directives) + ')' +-seems_directive_re = re.compile(r'\.\. %s([^a-z:]|:(?!:))' % all_directives) ++seems_directive_re = re.compile(r'(?>>>'); + button.css(button_styles) + button.attr('title', hide_text); ++ button.data('hidden', 'false'); + jthis.prepend(button); + } + // tracebacks (.gt) contain bare text elements that need to be +@@ -37,20 +38,24 @@ + }); + + // define the behavior of the button when it's clicked +- $('.copybutton').toggle( +- function() { +- var button = $(this); ++ $('.copybutton').click(function(e){ ++ e.preventDefault(); ++ var button = $(this); ++ if (button.data('hidden') === 'false') { ++ // hide the code output + button.parent().find('.go, .gp, .gt').hide(); + button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden'); + button.css('text-decoration', 'line-through'); + button.attr('title', show_text); +- }, +- function() { +- var button = $(this); ++ button.data('hidden', 'true'); ++ } else { ++ // show the code output + button.parent().find('.go, .gp, .gt').show(); + button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible'); + button.css('text-decoration', 'none'); + button.attr('title', hide_text); +- }); ++ button.data('hidden', 'false'); ++ } ++ }); + }); + +diff -r 6d1b6a68f775 Doc/tools/susp-ignored.csv +--- a/Doc/tools/susp-ignored.csv ++++ b/Doc/tools/susp-ignored.csv +@@ -46,7 +46,7 @@ + howto/pyporting,,::,Programming Language :: Python :: 3 + howto/regex,,::, + howto/regex,,:foo,(?:foo) +-howto/urllib2,,:example,"for example ""joe@password:example.com""" ++howto/urllib2,,:password,"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]) +diff -r 6d1b6a68f775 Doc/tools/templates/download.html +--- a/Doc/tools/templates/download.html ++++ b/Doc/tools/templates/download.html +@@ -7,55 +7,96 @@ + {% endif %} + + {% block body %} +-

Download Python {{ release }} Documentation

++

{% trans %}Download Python {{ release }} Documentation{% endtrans %}

+ +-{% if last_updated %}

Last updated on: {{ last_updated }}.

{% endif %} ++{% if last_updated %} ++

{% trans %}Last updated on: {{ last_updated }}.{% endtrans %}

++{% endif %} + +-

To download an archive containing all the documents for this version of +-Python in one of various formats, follow one of links in this table. The numbers +-in the table are the size of the download files in megabytes.

++

{% trans %}To download an archive containing all the documents for ++this version of Python in one of various formats, follow one of links ++in this table. The numbers in the table are the size of the download ++files in megabytes.{% endtrans %}

+ + +- +- +- +- ++ ++ ++ + +- +- +- ++ ++ ++ + +- +- +- ++ ++ ++ + +- +- +- ++ ++ ++ ++ ++ ++ ++ ++ + +
FormatPacked as .zipPacked as .tar.bz2
PDF (US-Letter paper size)Download (ca. 8 MB)Download (ca. 8 MB)
{% trans %}Format{% endtrans %}{% trans %}Packed as .zip{% endtrans %}{% trans %}Packed as .tar.bz2{% endtrans %}
PDF (A4 paper size)Download (ca. 8 MB)Download (ca. 8 MB)
{% trans %}PDF (US-Letter paper size){% endtrans %} ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 8 MB){% endtrans %} ++ ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 8 MB){% endtrans %} ++
HTMLDownload (ca. 6 MB)Download (ca. 4 MB)
{% trans %}PDF (A4 paper size){% endtrans %} ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 8 MB){% endtrans %} ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 8 MB){% endtrans %}
Plain TextDownload (ca. 2 MB)Download (ca. 1.5 MB)
{% trans %}HTML{% endtrans %} ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 6 MB){% endtrans %} ++ ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 4 MB){% endtrans %} ++
{% trans %}Plain Text{% endtrans %} ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 2 MB){% endtrans %} ++ ++ ++ {% trans %}Download{% endtrans %} ++ {% trans %}(ca. 1.5 MB){% endtrans %} ++
+ +-

These archives contain all the content in the documentation.

++

{% trans %}These archives contain all the content in the ++documentation.{% endtrans %}

+ +-

HTML Help (.chm) files are made available in the "Windows" section +-on the Python +-download page.

++

{% trans download_page="https://www.python.org/download/releases/{{ release[:5] }}/" %}HTML Help ++(.chm) files are made available in the "Windows" section ++on the Python download page.{% endtrans %}

+ + +-

Unpacking

++

{% trans %}Unpacking{% endtrans %}

+ +-

Unix users should download the .tar.bz2 archives; these are bzipped tar +-archives and can be handled in the usual way using tar and the bzip2 +-program. The InfoZIP unzip program can be +-used to handle the ZIP archives if desired. The .tar.bz2 archives provide the +-best compression and fastest download times.

++

{% trans %}Unix users should download the .tar.bz2 archives; these ++are bzipped tar archives and can be handled in the usual way using tar ++and the bzip2 program. The InfoZIP unzip ++program can be used to handle the ZIP archives if desired. The ++.tar.bz2 archives provide the best compression and fastest download ++times.{% endtrans %}

+ +-

Windows users can use the ZIP archives since those are customary on that +-platform. These are created on Unix using the InfoZIP zip program.

++

{% trans %}Windows users can use the ZIP archives since those are ++customary on that platform. These are created on Unix using the ++InfoZIP zip program.{% endtrans %}

+ + +-

Problems

++

{% trans %}Problems{% endtrans %}

+ +-

If you have comments or suggestions for the Python documentation, please send +-email to docs@python.org.

++

{% trans %}If you have comments or suggestions for the Python ++documentation, please send email to ++docs@python.org.{% endtrans %}

+ {% endblock %} +diff -r 6d1b6a68f775 Doc/tools/templates/indexcontent.html +--- a/Doc/tools/templates/indexcontent.html ++++ b/Doc/tools/templates/indexcontent.html +@@ -1,59 +1,59 @@ + {% extends "defindex.html" %} + {% block tables %} +-

Parts of the documentation:

++

{% trans %}Parts of the documentation:{% endtrans %}

+ + +
+- +- +- +- +- +- ++ ++ ++ ++ ++ ++ + +- +- +- +- +- ++ ++ ++ ++ ++ +
+ +-

Indices and tables:

++

{% trans %}Indices and tables:{% endtrans %}

+ + +
+- +- +- ++ ++ ++ + +- +- ++ ++ +
+ +-

Meta information:

++

{% trans %}Meta information:{% endtrans %}

+ + +
+- +- ++ ++ + +- +- ++ ++ +
+ {% endblock %} +diff -r 6d1b6a68f775 Doc/tools/templates/indexsidebar.html +--- a/Doc/tools/templates/indexsidebar.html ++++ b/Doc/tools/templates/indexsidebar.html +@@ -1,17 +1,17 @@ +-

Download

+-

Download these documents

+-

Docs for other versions

++

{% trans %}Download{% endtrans %}

++

{% trans %}Download these documents{% endtrans %}

++

{% trans %}Docs for other versions{% endtrans %}

+ + +-

Other resources

++

{% trans %}Other resources{% endtrans %}

+ +diff -r 6d1b6a68f775 Doc/tools/templates/layout.html +--- a/Doc/tools/templates/layout.html ++++ b/Doc/tools/templates/layout.html +@@ -6,7 +6,7 @@ +
  • + {%- if versionswitcher is defined %} + {{ release }} +- Documentation{{ reldelim1 }} ++ {% trans %}Documentation{% endtrans %}{{ reldelim1 }} + {%- else %} + {{ shorttitle }}{{ reldelim1 }} + {%- endif %} +@@ -28,24 +28,24 @@ + {% endblock %} + {% block footer %} + + {% endblock %} + {% block sidebarsourcelink %} + {%- if show_source and has_source and sourcename %} +

    {{ _('This Page') }}

    + + {%- endif %} + {% endblock %} +diff -r 6d1b6a68f775 Doc/tutorial/introduction.rst +--- a/Doc/tutorial/introduction.rst ++++ b/Doc/tutorial/introduction.rst +@@ -357,9 +357,8 @@ + Both strings and Unicode strings support a large number of methods for + basic transformations and searching. + +- :ref:`new-string-formatting` +- Information about string formatting with :meth:`str.format` is described +- here. ++ :ref:`formatstrings` ++ Information about string formatting with :meth:`str.format`. + + :ref:`string-formatting` + The old formatting operations invoked when strings and Unicode strings are +diff -r 6d1b6a68f775 Include/code.h +--- a/Include/code.h ++++ b/Include/code.h +@@ -70,7 +70,7 @@ + /* Public interface */ + PyAPI_FUNC(PyCodeObject *) PyCode_New( + int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, +- PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *); ++ PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *); + /* same as struct above */ + + /* Creates a new empty code object with the specified source location. */ +@@ -98,6 +98,15 @@ + PyAPI_FUNC(int) _PyCode_CheckLineNumber(PyCodeObject* co, + int lasti, PyAddrPair *bounds); + ++/* Create a comparable key used to compare constants taking in account the ++ * object type. It is used to make sure types are not coerced (e.g., float and ++ * complex) _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms ++ * ++ * Return (type(obj), obj, ...): a tuple with variable size (at least 2 items) ++ * depending on the type and the value. The type is the first item to not ++ * compare bytes and str which can raise a BytesWarning exception. */ ++PyAPI_FUNC(PyObject*) _PyCode_ConstantKey(PyObject *obj); ++ + PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts, + PyObject *names, PyObject *lineno_obj); + +diff -r 6d1b6a68f775 Include/dictobject.h +--- a/Include/dictobject.h ++++ b/Include/dictobject.h +@@ -108,6 +108,7 @@ + + PyAPI_FUNC(PyObject *) PyDict_New(void); + PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key); ++PyAPI_FUNC(PyObject *) _PyDict_GetItemWithError(PyObject *mp, PyObject *key); + PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item); + PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key); + PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); +diff -r 6d1b6a68f775 Include/object.h +--- a/Include/object.h ++++ b/Include/object.h +@@ -824,6 +824,29 @@ + #define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0) + #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0) + ++/* Safely decref `op` and set `op` to `op2`. ++ * ++ * As in case of Py_CLEAR "the obvious" code can be deadly: ++ * ++ * Py_XDECREF(op); ++ * op = op2; ++ * ++ * The safe way is: ++ * ++ * Py_SETREF(op, op2); ++ * ++ * That arranges to set `op` to `op2` _before_ decref'ing, so that any code ++ * triggered as a side-effect of `op` getting torn down no longer believes ++ * `op` points to a valid object. ++ */ ++ ++#define Py_SETREF(op, op2) \ ++ do { \ ++ PyObject *_py_tmp = (PyObject *)(op); \ ++ (op) = (op2); \ ++ Py_XDECREF(_py_tmp); \ ++ } while (0) ++ + /* + These are provided as conveniences to Python runtime embedders, so that + they can have object code that is not dependent on Python compilation flags. +diff -r 6d1b6a68f775 Include/patchlevel.h +--- a/Include/patchlevel.h ++++ b/Include/patchlevel.h +@@ -27,7 +27,7 @@ + #define PY_RELEASE_SERIAL 0 + + /* Version as a string */ +-#define PY_VERSION "2.7.11" ++#define PY_VERSION "2.7.11+" + /*--end constants--*/ + + /* Subversion Revision number of this file (not of the repository). Empty +diff -r 6d1b6a68f775 Include/pyerrors.h +--- a/Include/pyerrors.h ++++ b/Include/pyerrors.h +@@ -215,7 +215,7 @@ + + /* Export the old function so that the existing API remains available: */ + PyAPI_FUNC(void) PyErr_BadInternalCall(void); +-PyAPI_FUNC(void) _PyErr_BadInternalCall(char *filename, int lineno); ++PyAPI_FUNC(void) _PyErr_BadInternalCall(const char *filename, int lineno); + /* Mask the old API with a call to the new API for code compiled under + Python 2.0: */ + #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) +diff -r 6d1b6a68f775 LICENSE +--- a/LICENSE ++++ b/LICENSE +@@ -74,8 +74,9 @@ + 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, 2014, 2015 Python Software Foundation; All Rights Reserved" +-are retained in Python alone or in any derivative version prepared by Licensee. ++2011, 2012, 2013, 2014, 2015, 2016 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 +diff -r 6d1b6a68f775 Lib/SocketServer.py +--- a/Lib/SocketServer.py ++++ b/Lib/SocketServer.py +@@ -121,11 +121,6 @@ + + # Author of the BaseServer patch: Luke Kenneth Casson Leighton + +-# XXX Warning! +-# There is a test suite for this module, but it cannot be run by the +-# standard regression test. +-# To run it manually, run Lib/test/test_socketserver.py. +- + __version__ = "0.4" + + +@@ -296,6 +291,8 @@ + except: + self.handle_error(request, client_address) + self.shutdown_request(request) ++ else: ++ self.shutdown_request(request) + + def handle_timeout(self): + """Called if no new request arrives within self.timeout. +@@ -642,7 +639,7 @@ + client address as self.client_address, and the server (in case it + needs access to per-server information) as self.server. Since a + separate instance is created for each request, the handle() method +- can define arbitrary other instance variariables. ++ can define other arbitrary instance variables. + + """ + +@@ -719,9 +716,6 @@ + + class DatagramRequestHandler(BaseRequestHandler): + +- # XXX Regrettably, I cannot get this working on Linux; +- # s.recvfrom() doesn't return a meaningful client address. +- + """Define self.rfile and self.wfile for datagram sockets.""" + + def setup(self): +diff -r 6d1b6a68f775 Lib/_strptime.py +--- a/Lib/_strptime.py ++++ b/Lib/_strptime.py +@@ -75,6 +75,8 @@ + self.__calc_date_time() + if _getlang() != self.lang: + raise ValueError("locale changed during initialization") ++ if time.tzname != self.tzname or time.daylight != self.daylight: ++ raise ValueError("timezone changed during initialization") + + def __pad(self, seq, front): + # Add '' to seq to either the front (is True), else the back. +@@ -159,15 +161,17 @@ + + def __calc_timezone(self): + # Set self.timezone by using time.tzname. +- # Do not worry about possibility of time.tzname[0] == timetzname[1] +- # and time.daylight; handle that in strptime . ++ # Do not worry about possibility of time.tzname[0] == time.tzname[1] ++ # and time.daylight; handle that in strptime. + try: + time.tzset() + except AttributeError: + pass +- no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()]) +- if time.daylight: +- has_saving = frozenset([time.tzname[1].lower()]) ++ self.tzname = time.tzname ++ self.daylight = time.daylight ++ no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()]) ++ if self.daylight: ++ has_saving = frozenset([self.tzname[1].lower()]) + else: + has_saving = frozenset() + self.timezone = (no_saving, has_saving) +@@ -296,12 +300,15 @@ + """Return a time struct based on the input string and the format string.""" + global _TimeRE_cache, _regex_cache + with _cache_lock: +- if _getlang() != _TimeRE_cache.locale_time.lang: ++ locale_time = _TimeRE_cache.locale_time ++ if (_getlang() != locale_time.lang or ++ time.tzname != locale_time.tzname or ++ time.daylight != locale_time.daylight): + _TimeRE_cache = TimeRE() + _regex_cache.clear() ++ locale_time = _TimeRE_cache.locale_time + if len(_regex_cache) > _CACHE_MAX_SIZE: + _regex_cache.clear() +- locale_time = _TimeRE_cache.locale_time + format_regex = _regex_cache.get(format) + if not format_regex: + try: +@@ -438,6 +445,10 @@ + week_starts_Mon = True if week_of_year_start == 0 else False + julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, + week_starts_Mon) ++ if julian <= 0: ++ year -= 1 ++ yday = 366 if calendar.isleap(year) else 365 ++ julian += yday + # Cannot pre-calculate datetime_date() since can change in Julian + # calculation and thus could have different value for the day of the week + # calculation. +diff -r 6d1b6a68f775 Lib/base64.py +--- a/Lib/base64.py ++++ b/Lib/base64.py +@@ -64,9 +64,10 @@ + length 2 (additional characters are ignored) which specifies the + alternative alphabet used instead of the '+' and '/' characters. + +- The decoded string is returned. A TypeError is raised if s were +- incorrectly padded or if there are non-alphabet characters present in the +- string. ++ The decoded string is returned. A TypeError is raised if s is ++ incorrectly padded. Characters that are neither in the normal base-64 ++ alphabet nor the alternative alphabet are discarded prior to the padding ++ check. + """ + if altchars is not None: + s = s.translate(string.maketrans(altchars[:2], '+/')) +@@ -87,9 +88,10 @@ + def standard_b64decode(s): + """Decode a string encoded with the standard Base64 alphabet. + +- s is the string to decode. The decoded string is returned. A TypeError +- is raised if the string is incorrectly padded or if there are non-alphabet +- characters present in the string. ++ Argument s is the string to decode. The decoded string is returned. A ++ TypeError is raised if the string is incorrectly padded. Characters that ++ are not in the standard alphabet are discarded prior to the padding ++ check. + """ + return b64decode(s) + +@@ -97,19 +99,20 @@ + _urlsafe_decode_translation = string.maketrans(b'-_', b'+/') + + def urlsafe_b64encode(s): +- """Encode a string using a url-safe Base64 alphabet. ++ """Encode a string using the URL- and filesystem-safe Base64 alphabet. + +- s is the string to encode. The encoded string is returned. The alphabet +- uses '-' instead of '+' and '_' instead of '/'. ++ Argument s is the string to encode. The encoded string is returned. The ++ alphabet uses '-' instead of '+' and '_' instead of '/'. + """ + return b64encode(s).translate(_urlsafe_encode_translation) + + def urlsafe_b64decode(s): +- """Decode a string encoded with the standard Base64 alphabet. ++ """Decode a string using the URL- and filesystem-safe Base64 alphabet. + +- s is the string to decode. The decoded string is returned. A TypeError +- is raised if the string is incorrectly padded or if there are non-alphabet +- characters present in the string. ++ Argument s is the string to decode. The decoded string is returned. A ++ TypeError is raised if the string is incorrectly padded. Characters that ++ are not in the URL-safe base-64 alphabet, and are not a plus '+' or slash ++ '/', are discarded prior to the padding check. + + The alphabet uses '-' instead of '+' and '_' instead of '/'. + """ +@@ -267,7 +270,7 @@ + a lowercase alphabet is acceptable as input. For security purposes, the + default is False. + +- The decoded string is returned. A TypeError is raised if s were ++ The decoded string is returned. A TypeError is raised if s is + incorrectly padded or if there are non-alphabet characters present in the + string. + """ +diff -r 6d1b6a68f775 Lib/collections.py +--- a/Lib/collections.py ++++ b/Lib/collections.py +@@ -1,3 +1,15 @@ ++'''This module implements specialized container datatypes providing ++alternatives to Python's general purpose built-in containers, dict, ++list, set, and tuple. ++ ++* namedtuple factory function for creating tuple subclasses with named fields ++* deque list-like container with fast appends and pops on either end ++* Counter dict subclass for counting hashable objects ++* OrderedDict dict subclass that remembers the order entries were added ++* defaultdict dict subclass that calls a factory function to supply missing values ++ ++''' ++ + __all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict'] + # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py. + # They should however be considered an integral part of collections.py. +diff -r 6d1b6a68f775 Lib/copy.py +--- a/Lib/copy.py ++++ b/Lib/copy.py +@@ -315,7 +315,7 @@ + if n > 2: + state = info[2] + else: +- state = {} ++ state = None + if n > 3: + listiter = info[3] + else: +@@ -329,7 +329,7 @@ + y = callable(*args) + memo[id(x)] = y + +- if state: ++ if state is not None: + if deep: + state = deepcopy(state, memo) + if hasattr(y, '__setstate__'): +diff -r 6d1b6a68f775 Lib/ctypes/__init__.py +--- a/Lib/ctypes/__init__.py ++++ b/Lib/ctypes/__init__.py +@@ -386,8 +386,8 @@ + return func + + class PyDLL(CDLL): +- """This class represents the Python library itself. It allows to +- access Python API functions. The GIL is not released, and ++ """This class represents the Python library itself. It allows ++ accessing Python API functions. The GIL is not released, and + Python exceptions are handled correctly. + """ + _func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI +diff -r 6d1b6a68f775 Lib/ctypes/test/test_arrays.py +--- a/Lib/ctypes/test/test_arrays.py ++++ b/Lib/ctypes/test/test_arrays.py +@@ -24,20 +24,24 @@ + self.assertEqual(len(ia), alen) + + # slot values ok? +- values = [ia[i] for i in range(len(init))] ++ values = [ia[i] for i in range(alen)] + self.assertEqual(values, init) + ++ # out-of-bounds accesses should be caught ++ with self.assertRaises(IndexError): ia[alen] ++ with self.assertRaises(IndexError): ia[-alen-1] ++ + # change the items + from operator import setitem + new_values = range(42, 42+alen) + [setitem(ia, n, new_values[n]) for n in range(alen)] +- values = [ia[i] for i in range(len(init))] ++ values = [ia[i] for i in range(alen)] + self.assertEqual(values, new_values) + + # are the items initialized to 0? + ia = int_array() +- values = [ia[i] for i in range(len(init))] +- self.assertEqual(values, [0] * len(init)) ++ values = [ia[i] for i in range(alen)] ++ self.assertEqual(values, [0] * alen) + + # Too many initializers should be caught + self.assertRaises(IndexError, int_array, *range(alen*2)) +diff -r 6d1b6a68f775 Lib/ctypes/test/test_pointers.py +--- a/Lib/ctypes/test/test_pointers.py ++++ b/Lib/ctypes/test/test_pointers.py +@@ -53,9 +53,13 @@ + # C code: + # int x = 12321; + # res = &x +- res.contents = c_int(12321) ++ x = c_int(12321) ++ res.contents = x + self.assertEqual(i.value, 54345) + ++ x.value = -99 ++ self.assertEqual(res.contents.value, -99) ++ + def test_callbacks_with_pointers(self): + # a function type receiving a pointer + PROTOTYPE = CFUNCTYPE(c_int, POINTER(c_int)) +@@ -128,9 +132,10 @@ + + def test_basic(self): + p = pointer(c_int(42)) +- # Although a pointer can be indexed, it ha no length ++ # Although a pointer can be indexed, it has no length + self.assertRaises(TypeError, len, p) + self.assertEqual(p[0], 42) ++ self.assertEqual(p[0:1], [42]) + self.assertEqual(p.contents.value, 42) + + def test_charpp(self): +diff -r 6d1b6a68f775 Lib/ctypes/test/test_values.py +--- a/Lib/ctypes/test/test_values.py ++++ b/Lib/ctypes/test/test_values.py +@@ -22,8 +22,7 @@ + ctdll = CDLL(_ctypes_test.__file__) + self.assertRaises(ValueError, c_int.in_dll, ctdll, "Undefined_Symbol") + +-@unittest.skipUnless(sys.platform == 'win32', 'Windows-specific test') +-class Win_ValuesTestCase(unittest.TestCase): ++class PythonValuesTestCase(unittest.TestCase): + """This test only works when python itself is a dll/shared library""" + + def test_optimizeflag(self): +diff -r 6d1b6a68f775 Lib/distutils/ccompiler.py +--- a/Lib/distutils/ccompiler.py ++++ b/Lib/distutils/ccompiler.py +@@ -842,8 +842,9 @@ + def library_filename(self, libname, lib_type='static', # or 'shared' + strip_dir=0, output_dir=''): + assert output_dir is not None +- if lib_type not in ("static", "shared", "dylib"): +- raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\"" ++ if lib_type not in ("static", "shared", "dylib", "xcode_stub"): ++ raise ValueError, ("""'lib_type' must be "static", "shared", """ ++ """"dylib", or "xcode_stub".""") + fmt = getattr(self, lib_type + "_lib_format") + ext = getattr(self, lib_type + "_lib_extension") + +diff -r 6d1b6a68f775 Lib/distutils/unixccompiler.py +--- a/Lib/distutils/unixccompiler.py ++++ b/Lib/distutils/unixccompiler.py +@@ -79,7 +79,9 @@ + static_lib_extension = ".a" + shared_lib_extension = ".so" + dylib_lib_extension = ".dylib" ++ xcode_stub_lib_extension = ".tbd" + static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s" ++ xcode_stub_lib_format = dylib_lib_format + if sys.platform == "cygwin": + exe_extension = ".exe" + +@@ -245,12 +247,28 @@ + def find_library_file(self, dirs, lib, debug=0): + shared_f = self.library_filename(lib, lib_type='shared') + dylib_f = self.library_filename(lib, lib_type='dylib') ++ xcode_stub_f = self.library_filename(lib, lib_type='xcode_stub') + static_f = self.library_filename(lib, lib_type='static') + + if sys.platform == 'darwin': + # On OSX users can specify an alternate SDK using + # '-isysroot', calculate the SDK root if it is specified + # (and use it further on) ++ # ++ # Note that, as of Xcode 7, Apple SDKs may contain textual stub ++ # libraries with .tbd extensions rather than the normal .dylib ++ # shared libraries installed in /. The Apple compiler tool ++ # chain handles this transparently but it can cause problems ++ # for programs that are being built with an SDK and searching ++ # for specific libraries. Callers of find_library_file need to ++ # keep in mind that the base filename of the returned SDK library ++ # file might have a different extension from that of the library ++ # file installed on the running system, for example: ++ # /Applications/Xcode.app/Contents/Developer/Platforms/ ++ # MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/ ++ # usr/lib/libedit.tbd ++ # vs ++ # /usr/lib/libedit.dylib + cflags = sysconfig.get_config_var('CFLAGS') + m = re.search(r'-isysroot\s+(\S+)', cflags) + if m is None: +@@ -264,6 +282,7 @@ + shared = os.path.join(dir, shared_f) + dylib = os.path.join(dir, dylib_f) + static = os.path.join(dir, static_f) ++ xcode_stub = os.path.join(dir, xcode_stub_f) + + if sys.platform == 'darwin' and ( + dir.startswith('/System/') or ( +@@ -272,6 +291,7 @@ + shared = os.path.join(sysroot, dir[1:], shared_f) + dylib = os.path.join(sysroot, dir[1:], dylib_f) + static = os.path.join(sysroot, dir[1:], static_f) ++ xcode_stub = os.path.join(sysroot, dir[1:], xcode_stub_f) + + # We're second-guessing the linker here, with not much hard + # data to go on: GCC seems to prefer the shared library, so I'm +@@ -279,6 +299,8 @@ + # ignoring even GCC's "-static" option. So sue me. + if os.path.exists(dylib): + return dylib ++ elif os.path.exists(xcode_stub): ++ return xcode_stub + elif os.path.exists(shared): + return shared + elif os.path.exists(static): +diff -r 6d1b6a68f775 Lib/ensurepip/__init__.py +--- a/Lib/ensurepip/__init__.py ++++ b/Lib/ensurepip/__init__.py +@@ -12,9 +12,9 @@ + __all__ = ["version", "bootstrap"] + + +-_SETUPTOOLS_VERSION = "18.2" ++_SETUPTOOLS_VERSION = "20.3" + +-_PIP_VERSION = "7.1.2" ++_PIP_VERSION = "8.1.1" + + # pip currently requires ssl support, so we try to provide a nicer + # error message when that is missing (http://bugs.python.org/issue19744) +diff -r 6d1b6a68f775 Lib/ensurepip/_bundled/pip-7.1.2-py2.py3-none-any.whl +Binary file Lib/ensurepip/_bundled/pip-7.1.2-py2.py3-none-any.whl has changed +diff -r 6d1b6a68f775 Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl +Binary file Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl has changed +diff -r 6d1b6a68f775 Lib/ensurepip/_bundled/setuptools-18.2-py2.py3-none-any.whl +Binary file Lib/ensurepip/_bundled/setuptools-18.2-py2.py3-none-any.whl has changed +diff -r 6d1b6a68f775 Lib/ensurepip/_bundled/setuptools-20.3-py2.py3-none-any.whl +Binary file Lib/ensurepip/_bundled/setuptools-20.3-py2.py3-none-any.whl has changed +diff -r 6d1b6a68f775 Lib/fileinput.py +--- a/Lib/fileinput.py ++++ b/Lib/fileinput.py +@@ -64,13 +64,6 @@ + disabled when standard input is read. XXX The current implementation + does not work for MS-DOS 8+3 filesystems. + +-Performance: this module is unfortunately one of the slower ways of +-processing large numbers of input lines. Nevertheless, a significant +-speed-up has been obtained by using readlines(bufsize) instead of +-readline(). A new keyword argument, bufsize=N, is present on the +-input() function and the FileInput() class to override the default +-buffer size. +- + XXX Possible additions: + + - optional getopt argument processing +@@ -86,6 +79,7 @@ + + _state = None + ++# No longer used + DEFAULT_BUFSIZE = 8*1024 + + def input(files=None, inplace=0, backup="", bufsize=0, +@@ -207,17 +201,14 @@ + self._files = files + self._inplace = inplace + self._backup = backup +- self._bufsize = bufsize or DEFAULT_BUFSIZE + self._savestdout = None + self._output = None + self._filename = None +- self._lineno = 0 ++ self._startlineno = 0 + self._filelineno = 0 + self._file = None + self._isstdin = False + self._backupfilename = None +- self._buffer = [] +- self._bufindex = 0 + # restrict mode argument to reading modes + if mode not in ('r', 'rU', 'U', 'rb'): + raise ValueError("FileInput opening mode must be one of " +@@ -242,22 +233,18 @@ + return self + + def next(self): +- try: +- line = self._buffer[self._bufindex] +- except IndexError: +- pass +- else: +- self._bufindex += 1 +- self._lineno += 1 +- self._filelineno += 1 +- return line +- line = self.readline() +- if not line: +- raise StopIteration +- return line ++ while 1: ++ line = self._readline() ++ if line: ++ self._filelineno += 1 ++ return line ++ if not self._file: ++ raise StopIteration ++ self.nextfile() ++ # repeat with next file + + def __getitem__(self, i): +- if i != self._lineno: ++ if i != self.lineno(): + raise RuntimeError, "accessing lines out of order" + try: + return self.next() +@@ -277,7 +264,11 @@ + output.close() + finally: + file = self._file +- self._file = 0 ++ self._file = None ++ try: ++ del self._readline # restore FileInput._readline ++ except AttributeError: ++ pass + try: + if file and not self._isstdin: + file.close() +@@ -289,75 +280,72 @@ + except OSError: pass + + self._isstdin = False +- self._buffer = [] +- self._bufindex = 0 + + def readline(self): +- try: +- line = self._buffer[self._bufindex] +- except IndexError: +- pass ++ while 1: ++ line = self._readline() ++ if line: ++ self._filelineno += 1 ++ return line ++ if not self._file: ++ return line ++ self.nextfile() ++ # repeat with next file ++ ++ def _readline(self): ++ if not self._files: ++ return "" ++ self._filename = self._files[0] ++ self._files = self._files[1:] ++ self._startlineno = self.lineno() ++ self._filelineno = 0 ++ self._file = None ++ self._isstdin = False ++ self._backupfilename = 0 ++ if self._filename == '-': ++ self._filename = '' ++ self._file = sys.stdin ++ self._isstdin = True + else: +- self._bufindex += 1 +- self._lineno += 1 +- self._filelineno += 1 +- return line +- if not self._file: +- if not self._files: +- return "" +- self._filename = self._files[0] +- self._files = self._files[1:] +- self._filelineno = 0 +- self._file = None +- self._isstdin = False +- self._backupfilename = 0 +- if self._filename == '-': +- self._filename = '' +- self._file = sys.stdin +- self._isstdin = True ++ if self._inplace: ++ self._backupfilename = ( ++ self._filename + (self._backup or os.extsep+"bak")) ++ try: os.unlink(self._backupfilename) ++ except os.error: pass ++ # The next few lines may raise IOError ++ os.rename(self._filename, self._backupfilename) ++ self._file = open(self._backupfilename, self._mode) ++ try: ++ perm = os.fstat(self._file.fileno()).st_mode ++ except OSError: ++ self._output = open(self._filename, "w") ++ else: ++ fd = os.open(self._filename, ++ os.O_CREAT | os.O_WRONLY | os.O_TRUNC, ++ perm) ++ self._output = os.fdopen(fd, "w") ++ try: ++ if hasattr(os, 'chmod'): ++ os.chmod(self._filename, perm) ++ except OSError: ++ pass ++ self._savestdout = sys.stdout ++ sys.stdout = self._output + else: +- if self._inplace: +- self._backupfilename = ( +- self._filename + (self._backup or os.extsep+"bak")) +- try: os.unlink(self._backupfilename) +- except os.error: pass +- # The next few lines may raise IOError +- os.rename(self._filename, self._backupfilename) +- self._file = open(self._backupfilename, self._mode) +- try: +- perm = os.fstat(self._file.fileno()).st_mode +- except OSError: +- self._output = open(self._filename, "w") +- else: +- fd = os.open(self._filename, +- os.O_CREAT | os.O_WRONLY | os.O_TRUNC, +- perm) +- self._output = os.fdopen(fd, "w") +- try: +- if hasattr(os, 'chmod'): +- os.chmod(self._filename, perm) +- except OSError: +- pass +- self._savestdout = sys.stdout +- sys.stdout = self._output ++ # This may raise IOError ++ if self._openhook: ++ self._file = self._openhook(self._filename, self._mode) + else: +- # This may raise IOError +- if self._openhook: +- self._file = self._openhook(self._filename, self._mode) +- else: +- self._file = open(self._filename, self._mode) +- self._buffer = self._file.readlines(self._bufsize) +- self._bufindex = 0 +- if not self._buffer: +- self.nextfile() +- # Recursive call +- return self.readline() ++ self._file = open(self._filename, self._mode) ++ ++ self._readline = self._file.readline # hide FileInput._readline ++ return self._readline() + + def filename(self): + return self._filename + + def lineno(self): +- return self._lineno ++ return self._startlineno + self._filelineno + + def filelineno(self): + return self._filelineno +diff -r 6d1b6a68f775 Lib/idlelib/CREDITS.txt +--- a/Lib/idlelib/CREDITS.txt ++++ b/Lib/idlelib/CREDITS.txt +@@ -24,7 +24,7 @@ + integration, debugger integration and persistent breakpoints). + + Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou, +-Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb, ++Jim Jewett, Martin v. Löwis, Jason Orendorff, Guilherme Polo, Josh Robb, + Nigel Rowe, Bruce Sherwood, Jeff Shute, and Weeble have submitted useful + patches. Thanks, guys! + +diff -r 6d1b6a68f775 Lib/idlelib/IOBinding.py +--- a/Lib/idlelib/IOBinding.py ++++ b/Lib/idlelib/IOBinding.py +@@ -17,6 +17,8 @@ + import tkMessageBox + from SimpleDialog import SimpleDialog + ++from idlelib.configHandler import idleConf ++ + # Try setting the locale, so that we can find out + # what encoding to use + try: +@@ -137,7 +139,6 @@ + raise LookupError, "Unknown encoding "+name + return name + +- + class IOBinding: + + def __init__(self, editwin): +@@ -567,7 +568,6 @@ + + def _io_binding(parent): # htest # + from Tkinter import Toplevel, Text +- from idlelib.configHandler import idleConf + + root = Toplevel(parent) + root.title("Test IOBinding") +@@ -578,15 +578,24 @@ + self.text = text + self.flist = None + self.text.bind("", self.open) ++ self.text.bind('', self.printer) + self.text.bind("", self.save) ++ self.text.bind("", self.saveas) ++ self.text.bind('', self.savecopy) + def get_saved(self): return 0 + def set_saved(self, flag): pass + def reset_undo(self): pass ++ def update_recent_files_list(self, filename): pass + def open(self, event): + self.text.event_generate("<>") ++ def printer(self, event): ++ self.text.event_generate("<>") + def save(self, event): + self.text.event_generate("<>") +- def update_recent_files_list(s, f): pass ++ def saveas(self, event): ++ self.text.event_generate("<>") ++ def savecopy(self, event): ++ self.text.event_generate("<>") + + text = Text(root) + text.pack() +diff -r 6d1b6a68f775 Lib/idlelib/NEWS.txt +--- a/Lib/idlelib/NEWS.txt ++++ b/Lib/idlelib/NEWS.txt +@@ -162,7 +162,7 @@ + move version to end. + + - Issue #14105: Idle debugger breakpoints no longer disappear +- when inseting or deleting lines. ++ when inserting or deleting lines. + + + What's New in IDLE 2.7.8? +diff -r 6d1b6a68f775 Lib/idlelib/README.txt +--- a/Lib/idlelib/README.txt ++++ b/Lib/idlelib/README.txt +@@ -1,6 +1,6 @@ + README.txt: an index to idlelib files and the IDLE menu. + +-IDLE is Python’s Integrated Development and Learning ++IDLE is Python's Integrated Development and Learning + Environment. The user documentation is part of the Library Reference and + is available in IDLE by selecting Help => IDLE Help. This README documents + idlelib for IDLE developers and curious users. +diff -r 6d1b6a68f775 Lib/idlelib/aboutDialog.py +--- a/Lib/idlelib/aboutDialog.py ++++ b/Lib/idlelib/aboutDialog.py +@@ -110,6 +110,7 @@ + command=self.ShowIDLECredits) + idle_credits_b.pack(side=LEFT, padx=10, pady=10) + ++ # License, et all, are of type _sitebuiltins._Printer + def ShowLicense(self): + self.display_printer_text('About - License', license) + +@@ -119,14 +120,16 @@ + def ShowPythonCredits(self): + self.display_printer_text('About - Python Credits', credits) + ++ # Encode CREDITS.txt to utf-8 for proper version of Loewis. ++ # Specify others as ascii until need utf-8, so catch errors. + def ShowIDLECredits(self): +- self.display_file_text('About - Credits', 'CREDITS.txt', 'iso-8859-1') ++ self.display_file_text('About - Credits', 'CREDITS.txt', 'utf-8') + + def ShowIDLEAbout(self): +- self.display_file_text('About - Readme', 'README.txt') ++ self.display_file_text('About - Readme', 'README.txt', 'ascii') + + def ShowIDLENEWS(self): +- self.display_file_text('About - NEWS', 'NEWS.txt') ++ self.display_file_text('About - NEWS', 'NEWS.txt', 'ascii') + + def display_printer_text(self, title, printer): + printer._Printer__setup() +diff -r 6d1b6a68f775 Lib/idlelib/help.py +--- a/Lib/idlelib/help.py ++++ b/Lib/idlelib/help.py +@@ -11,7 +11,7 @@ + Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html + (help.copy_strip)=> Lib/idlelib/help.html + +-HelpParser - Parse help.html and and render to tk Text. ++HelpParser - Parse help.html and render to tk Text. + + HelpText - Display formatted help.html. + +diff -r 6d1b6a68f775 Lib/idlelib/idle_test/htest.py +--- a/Lib/idlelib/idle_test/htest.py ++++ b/Lib/idlelib/idle_test/htest.py +@@ -192,7 +192,10 @@ + 'msg': "Test the following bindings.\n" + " to open file from dialog.\n" + "Edit the file.\n" ++ " to print the file.\n" + " to save the file.\n" ++ " to save-as another file.\n" ++ " to save-copy-as another file.\n" + "Check that changes were saved by opening the file elsewhere." + } + +diff -r 6d1b6a68f775 Lib/lib-tk/Tkinter.py +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -1335,8 +1335,9 @@ + raise TypeError("Tkinter objects don't support 'in' tests.") + def keys(self): + """Return a list of all resource names of this widget.""" +- return [x[0][1:] for x in +- self.tk.splitlist(self.tk.call(self._w, 'configure'))] ++ splitlist = self.tk.splitlist ++ return [splitlist(x)[0][1:] for x in ++ splitlist(self.tk.call(self._w, 'configure'))] + def __str__(self): + """Return the window path name of this widget.""" + return self._w +@@ -2486,7 +2487,7 @@ + self.tk.call(self._w, 'toggle') + + class Entry(Widget, XView): +- """Entry widget which allows to display simple text.""" ++ """Entry widget which allows displaying simple text.""" + def __init__(self, master=None, cnf={}, **kw): + """Construct an entry widget with the parent MASTER. + +@@ -2682,7 +2683,7 @@ + itemconfig = itemconfigure + + class Menu(Widget): +- """Menu widget which allows to display menu bars, pull-down menus and pop-up menus.""" ++ """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus.""" + def __init__(self, master=None, cnf={}, **kw): + """Construct menu widget with the parent MASTER. + +@@ -3379,16 +3380,20 @@ + destImage = PhotoImage(master=self.tk) + self.tk.call(destImage, 'copy', self.name) + return destImage +- def zoom(self,x,y=''): ++ def zoom(self, x, y=''): + """Return a new PhotoImage with the same image as this widget +- but zoom it with X and Y.""" ++ but zoom it with a factor of x in the X direction and y in the Y ++ direction. If y is not given, the default value is the same as x. ++ """ + destImage = PhotoImage(master=self.tk) + if y=='': y=x + self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) + return destImage +- def subsample(self,x,y=''): ++ def subsample(self, x, y=''): + """Return a new PhotoImage based on the same image as this widget +- but use only every Xth or Yth pixel.""" ++ but use only every Xth or Yth pixel. If y is not given, the ++ default value is the same as x. ++ """ + destImage = PhotoImage(master=self.tk) + if y=='': y=x + self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) +diff -r 6d1b6a68f775 Lib/lib-tk/test/test_tkinter/test_geometry_managers.py +--- a/Lib/lib-tk/test/test_tkinter/test_geometry_managers.py ++++ b/Lib/lib-tk/test/test_tkinter/test_geometry_managers.py +@@ -12,6 +12,8 @@ + + class PackTest(AbstractWidgetTest, unittest.TestCase): + ++ test_keys = None ++ + def create2(self): + pack = tkinter.Toplevel(self.root, name='pack') + pack.wm_geometry('300x200+0+0') +@@ -276,6 +278,8 @@ + + class PlaceTest(AbstractWidgetTest, unittest.TestCase): + ++ test_keys = None ++ + def create2(self): + t = tkinter.Toplevel(self.root, width=300, height=200, bd=0) + t.wm_geometry('300x200+0+0') +@@ -478,6 +482,8 @@ + + class GridTest(AbstractWidgetTest, unittest.TestCase): + ++ test_keys = None ++ + def tearDown(self): + cols, rows = self.root.grid_size() + for i in range(cols + 1): +diff -r 6d1b6a68f775 Lib/lib-tk/test/test_tkinter/test_widgets.py +--- a/Lib/lib-tk/test/test_tkinter/test_widgets.py ++++ b/Lib/lib-tk/test/test_tkinter/test_widgets.py +@@ -99,7 +99,7 @@ + 'background', 'borderwidth', + 'class', 'colormap', 'container', 'cursor', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', +- 'relief', 'takefocus', 'visual', 'width', ++ 'padx', 'pady', 'relief', 'takefocus', 'visual', 'width', + ) + + def create(self, **kwargs): +@@ -633,7 +633,7 @@ + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'insertbackground', 'insertborderwidth', + 'insertofftime', 'insertontime', 'insertwidth', +- 'relief', 'scrollregion', ++ 'offset', 'relief', 'scrollregion', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'state', 'takefocus', + 'xscrollcommand', 'xscrollincrement', +@@ -655,6 +655,15 @@ + widget = self.create() + self.checkBooleanParam(widget, 'confine') + ++ def test_offset(self): ++ widget = self.create() ++ self.assertEqual(widget['offset'], '0,0') ++ self.checkParams(widget, 'offset', ++ 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') ++ self.checkParam(widget, 'offset', '10,20') ++ self.checkParam(widget, 'offset', '#5,6') ++ self.checkInvalidParam(widget, 'offset', 'spam') ++ + def test_scrollregion(self): + widget = self.create() + self.checkParam(widget, 'scrollregion', '0 0 200 150') +diff -r 6d1b6a68f775 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 +@@ -189,7 +189,7 @@ + @add_standard_options(StandardTtkOptionsTests) + class LabelTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( +- 'anchor', 'background', ++ 'anchor', 'background', 'borderwidth', + 'class', 'compound', 'cursor', 'font', 'foreground', + 'image', 'justify', 'padding', 'relief', 'state', 'style', + 'takefocus', 'text', 'textvariable', +@@ -210,7 +210,8 @@ + class ButtonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'class', 'command', 'compound', 'cursor', 'default', +- 'image', 'state', 'style', 'takefocus', 'text', 'textvariable', ++ 'image', 'padding', 'state', 'style', ++ 'takefocus', 'text', 'textvariable', + 'underline', 'width', + ) + +@@ -234,7 +235,7 @@ + 'class', 'command', 'compound', 'cursor', + 'image', + 'offvalue', 'onvalue', +- 'state', 'style', ++ 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'variable', 'width', + ) +@@ -278,11 +279,146 @@ + + + @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) +-class ComboboxTest(AbstractWidgetTest, unittest.TestCase): ++class EntryTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( +- 'class', 'cursor', 'exportselection', 'height', +- 'justify', 'postcommand', 'state', 'style', +- 'takefocus', 'textvariable', 'values', 'width', ++ 'background', 'class', 'cursor', ++ 'exportselection', 'font', 'foreground', ++ 'invalidcommand', 'justify', ++ 'show', 'state', 'style', 'takefocus', 'textvariable', ++ 'validate', 'validatecommand', 'width', 'xscrollcommand', ++ ) ++ ++ def setUp(self): ++ super(EntryTest, self).setUp() ++ self.entry = self.create() ++ ++ 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.assertIsBoundingBox(self.entry.bbox(0)) ++ self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex') ++ self.assertRaises(tkinter.TclError, self.entry.bbox, None) ++ ++ ++ def test_identify(self): ++ self.entry.pack() ++ self.entry.wait_visibility() ++ self.entry.update_idletasks() ++ ++ self.assertEqual(self.entry.identify(5, 5), "textarea") ++ self.assertEqual(self.entry.identify(-1, -1), "") ++ ++ self.assertRaises(tkinter.TclError, self.entry.identify, None, 5) ++ self.assertRaises(tkinter.TclError, self.entry.identify, 5, None) ++ self.assertRaises(tkinter.TclError, self.entry.identify, 5, '') ++ ++ ++ def test_validation_options(self): ++ success = [] ++ test_invalid = lambda: success.append(True) ++ ++ self.entry['validate'] = 'none' ++ self.entry['validatecommand'] = lambda: False ++ ++ self.entry['invalidcommand'] = test_invalid ++ self.entry.validate() ++ self.assertTrue(success) ++ ++ self.entry['invalidcommand'] = '' ++ self.entry.validate() ++ self.assertEqual(len(success), 1) ++ ++ self.entry['invalidcommand'] = test_invalid ++ self.entry['validatecommand'] = lambda: True ++ self.entry.validate() ++ self.assertEqual(len(success), 1) ++ ++ self.entry['validatecommand'] = '' ++ self.entry.validate() ++ self.assertEqual(len(success), 1) ++ ++ self.entry['validatecommand'] = True ++ self.assertRaises(tkinter.TclError, self.entry.validate) ++ ++ ++ def test_validation(self): ++ validation = [] ++ def validate(to_insert): ++ if not 'a' <= to_insert.lower() <= 'z': ++ validation.append(False) ++ return False ++ validation.append(True) ++ return True ++ ++ self.entry['validate'] = 'key' ++ self.entry['validatecommand'] = self.entry.register(validate), '%S' ++ ++ self.entry.insert('end', 1) ++ self.entry.insert('end', 'a') ++ self.assertEqual(validation, [False, True]) ++ self.assertEqual(self.entry.get(), 'a') ++ ++ ++ def test_revalidation(self): ++ def validate(content): ++ for letter in content: ++ if not 'a' <= letter.lower() <= 'z': ++ return False ++ return True ++ ++ self.entry['validatecommand'] = self.entry.register(validate), '%P' ++ ++ self.entry.insert('end', 'avocado') ++ self.assertEqual(self.entry.validate(), True) ++ self.assertEqual(self.entry.state(), ()) ++ ++ self.entry.delete(0, 'end') ++ self.assertEqual(self.entry.get(), '') ++ ++ self.entry.insert('end', 'a1b') ++ self.assertEqual(self.entry.validate(), False) ++ self.assertEqual(self.entry.state(), ('invalid', )) ++ ++ self.entry.delete(1) ++ self.assertEqual(self.entry.validate(), True) ++ self.assertEqual(self.entry.state(), ()) ++ ++ ++@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) ++class ComboboxTest(EntryTest, unittest.TestCase): ++ OPTIONS = ( ++ 'background', 'class', 'cursor', 'exportselection', ++ 'font', 'foreground', 'height', 'invalidcommand', ++ 'justify', 'postcommand', 'show', 'state', 'style', ++ 'takefocus', 'textvariable', ++ 'validate', 'validatecommand', 'values', ++ 'width', 'xscrollcommand', + ) + + def setUp(self): +@@ -296,10 +432,6 @@ + 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() + self.combo.event_generate('', x=width - 5, y=5) +@@ -404,138 +536,6 @@ + + + @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() +- self.entry = self.create() +- +- 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.assertIsBoundingBox(self.entry.bbox(0)) +- self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex') +- self.assertRaises(tkinter.TclError, self.entry.bbox, None) +- +- +- def test_identify(self): +- self.entry.pack() +- self.entry.wait_visibility() +- self.entry.update_idletasks() +- +- self.assertEqual(self.entry.identify(5, 5), "textarea") +- self.assertEqual(self.entry.identify(-1, -1), "") +- +- self.assertRaises(tkinter.TclError, self.entry.identify, None, 5) +- self.assertRaises(tkinter.TclError, self.entry.identify, 5, None) +- self.assertRaises(tkinter.TclError, self.entry.identify, 5, '') +- +- +- def test_validation_options(self): +- success = [] +- test_invalid = lambda: success.append(True) +- +- self.entry['validate'] = 'none' +- self.entry['validatecommand'] = lambda: False +- +- self.entry['invalidcommand'] = test_invalid +- self.entry.validate() +- self.assertTrue(success) +- +- self.entry['invalidcommand'] = '' +- self.entry.validate() +- self.assertEqual(len(success), 1) +- +- self.entry['invalidcommand'] = test_invalid +- self.entry['validatecommand'] = lambda: True +- self.entry.validate() +- self.assertEqual(len(success), 1) +- +- self.entry['validatecommand'] = '' +- self.entry.validate() +- self.assertEqual(len(success), 1) +- +- self.entry['validatecommand'] = True +- self.assertRaises(tkinter.TclError, self.entry.validate) +- +- +- def test_validation(self): +- validation = [] +- def validate(to_insert): +- if not 'a' <= to_insert.lower() <= 'z': +- validation.append(False) +- return False +- validation.append(True) +- return True +- +- self.entry['validate'] = 'key' +- self.entry['validatecommand'] = self.entry.register(validate), '%S' +- +- self.entry.insert('end', 1) +- self.entry.insert('end', 'a') +- self.assertEqual(validation, [False, True]) +- self.assertEqual(self.entry.get(), 'a') +- +- +- def test_revalidation(self): +- def validate(content): +- for letter in content: +- if not 'a' <= letter.lower() <= 'z': +- return False +- return True +- +- self.entry['validatecommand'] = self.entry.register(validate), '%P' +- +- self.entry.insert('end', 'avocado') +- self.assertEqual(self.entry.validate(), True) +- self.assertEqual(self.entry.state(), ()) +- +- self.entry.delete(0, 'end') +- self.assertEqual(self.entry.get(), '') +- +- self.entry.insert('end', 'a1b') +- self.assertEqual(self.entry.validate(), False) +- self.assertEqual(self.entry.state(), ('invalid', )) +- +- self.entry.delete(1) +- self.assertEqual(self.entry.validate(), True) +- self.assertEqual(self.entry.state(), ()) +- +- +-@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) + class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'cursor', 'height', +@@ -675,7 +675,7 @@ + OPTIONS = ( + 'class', 'command', 'compound', 'cursor', + 'image', +- 'state', 'style', ++ 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'value', 'variable', 'width', + ) +@@ -725,7 +725,7 @@ + class MenubuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'class', 'compound', 'cursor', 'direction', +- 'image', 'menu', 'state', 'style', ++ 'image', 'menu', 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'width', + ) +@@ -903,7 +903,7 @@ + @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) + class NotebookTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( +- 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', ++ 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width', + ) + + def setUp(self): +diff -r 6d1b6a68f775 Lib/lib-tk/test/widget_tests.py +--- a/Lib/lib-tk/test/widget_tests.py ++++ b/Lib/lib-tk/test/widget_tests.py +@@ -224,6 +224,32 @@ + self.fail('Invalid bounding box: %r' % (bbox,)) + break + ++ def test_keys(self): ++ widget = self.create() ++ keys = widget.keys() ++ # XXX ++ if not isinstance(widget, Scale): ++ self.assertEqual(sorted(keys), sorted(widget.configure())) ++ for k in keys: ++ widget[k] ++ # Test if OPTIONS contains all keys ++ if test.test_support.verbose: ++ aliases = { ++ 'bd': 'borderwidth', ++ 'bg': 'background', ++ 'fg': 'foreground', ++ 'invcmd': 'invalidcommand', ++ 'vcmd': 'validatecommand', ++ } ++ keys = set(keys) ++ expected = set(self.OPTIONS) ++ for k in sorted(keys - expected): ++ if not (k in aliases and ++ aliases[k] in keys and ++ aliases[k] in expected): ++ print('%s.OPTIONS doesn\'t contain "%s"' % ++ (self.__class__.__name__, k)) ++ + + class StandardOptionsTests(object): + STANDARD_OPTIONS = ( +diff -r 6d1b6a68f775 Lib/locale.py +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -18,6 +18,10 @@ + import operator + import functools + ++# keep a copy of the builtin str type, because 'str' name is overriden ++# in globals by a function below ++_str = str ++ + try: + _unicode = unicode + except NameError: +@@ -573,7 +577,7 @@ + category may be given as one of the LC_* values. + + """ +- if locale and type(locale) is not type(""): ++ if locale and not isinstance(locale, (_str, _unicode)): + # convert to string + locale = normalize(_build_localename(locale)) + return _setlocale(category, locale) +diff -r 6d1b6a68f775 Lib/logging/__init__.py +--- a/Lib/logging/__init__.py ++++ b/Lib/logging/__init__.py +@@ -465,7 +465,15 @@ + record.message = record.getMessage() + if self.usesTime(): + record.asctime = self.formatTime(record, self.datefmt) +- s = self._fmt % record.__dict__ ++ try: ++ s = self._fmt % record.__dict__ ++ except UnicodeDecodeError as e: ++ # Issue 25664. The logger name may be Unicode. Try again ... ++ try: ++ record.name = record.name.decode('utf-8') ++ s = self._fmt % record.__dict__ ++ except UnicodeDecodeError: ++ raise e + if record.exc_info: + # Cache the traceback text to avoid converting it multiple times + # (it's constant anyway) +diff -r 6d1b6a68f775 Lib/msilib/__init__.py +--- a/Lib/msilib/__init__.py ++++ b/Lib/msilib/__init__.py +@@ -2,7 +2,11 @@ + # Copyright (C) 2005 Martin v. Löwis + # Licensed to PSF under a Contributor Agreement. + from _msi import * +-import os, string, re, sys ++import glob ++import os ++import re ++import string ++import sys + + AMD64 = "AMD64" in sys.version + Itanium = "Itanium" in sys.version +diff -r 6d1b6a68f775 Lib/platform.py +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -650,7 +650,7 @@ + csd = 'SP' + csd[13:] + + # VER_NT_SERVER = 3 +- if getattr(winver, 'product_type', None) == 3: ++ if getattr(winver, 'product', None) == 3: + release = (_WIN32_SERVER_RELEASES.get((maj, min)) or + _WIN32_SERVER_RELEASES.get((maj, None)) or + release) +diff -r 6d1b6a68f775 Lib/pydoc_data/topics.py +--- a/Lib/pydoc_data/topics.py ++++ b/Lib/pydoc_data/topics.py +@@ -1,13317 +1,81 @@ + # -*- coding: utf-8 -*- +-# Autogenerated by Sphinx on Sat Nov 21 13:35:13 2015 +-topics = {'assert': '\n' +- 'The "assert" statement\n' +- '**********************\n' +- '\n' +- 'Assert statements are a convenient way to insert debugging ' +- 'assertions\n' +- 'into a program:\n' +- '\n' +- ' assert_stmt ::= "assert" expression ["," expression]\n' +- '\n' +- 'The simple form, "assert expression", is equivalent to\n' +- '\n' +- ' if __debug__:\n' +- ' if not expression: raise AssertionError\n' +- '\n' +- 'The extended form, "assert expression1, expression2", is ' +- 'equivalent to\n' +- '\n' +- ' if __debug__:\n' +- ' if not expression1: raise AssertionError(expression2)\n' +- '\n' +- 'These equivalences assume that "__debug__" and "AssertionError" ' +- 'refer\n' +- 'to the built-in variables with those names. In the current\n' +- 'implementation, the built-in variable "__debug__" is "True" ' +- 'under\n' +- 'normal circumstances, "False" when optimization is requested ' +- '(command\n' +- 'line option -O). The current code generator emits no code for ' +- 'an\n' +- 'assert statement when optimization is requested at compile ' +- 'time. Note\n' +- 'that it is unnecessary to include the source code for the ' +- 'expression\n' +- 'that failed in the error message; it will be displayed as part ' +- 'of the\n' +- 'stack trace.\n' +- '\n' +- 'Assignments to "__debug__" are illegal. The value for the ' +- 'built-in\n' +- 'variable is determined when the interpreter starts.\n', +- 'assignment': '\n' +- 'Assignment statements\n' +- '*********************\n' +- '\n' +- 'Assignment statements are used to (re)bind names to values ' +- 'and to\n' +- 'modify 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\n' +- 'symbols.)\n' +- '\n' +- 'An assignment statement evaluates the expression list ' +- '(remember that\n' +- 'this can be a single expression or a comma-separated list, ' +- 'the latter\n' +- 'yielding a tuple) and assigns the single resulting object to ' +- 'each of\n' +- 'the target lists, from left to right.\n' +- '\n' +- 'Assignment is defined recursively depending on the form of ' +- 'the target\n' +- '(list). When a target is part of a mutable object (an ' +- 'attribute\n' +- 'reference, subscription or slicing), the mutable object ' +- 'must\n' +- 'ultimately perform the assignment and decide about its ' +- 'validity, and\n' +- 'may raise an exception if the assignment is unacceptable. ' +- 'The rules\n' +- 'observed by various types and the exceptions raised are ' +- 'given with the\n' +- 'definition of the object types (see section The standard ' +- 'type\n' +- 'hierarchy).\n' +- '\n' +- 'Assignment of an object to a target list is recursively ' +- 'defined as\n' +- 'follows.\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\n' +- ' object must be an iterable with the same number of items ' +- 'as there\n' +- ' are targets in the target list, and the items are ' +- 'assigned, from\n' +- ' left to right, to the corresponding targets.\n' +- '\n' +- 'Assignment of an object to a single target is recursively ' +- 'defined as\n' +- 'follows.\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\n' +- ' square brackets: The object must be an iterable with the ' +- 'same number\n' +- ' of 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 always\n' +- ' set as an instance attribute, creating it if necessary. ' +- 'Thus, the\n' +- ' two occurrences of "a.x" do not necessarily refer to the ' +- 'same\n' +- ' attribute: if the RHS expression refers to a class ' +- 'attribute, the\n' +- ' 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\n' +- ' reference is evaluated. It should yield a mutable ' +- 'sequence object\n' +- ' (such as a list). The assigned object should be a ' +- 'sequence object\n' +- ' of the same type. Next, the lower and upper bound ' +- 'expressions are\n' +- ' evaluated, insofar they are present; defaults are zero and ' +- 'the\n' +- " sequence's length. The bounds should evaluate to (small) " +- 'integers.\n' +- " If either bound is negative, the sequence's length is " +- 'added to it.\n' +- ' The resulting bounds are clipped to lie between zero and ' +- 'the\n' +- " sequence's length, inclusive. Finally, the sequence " +- 'object is asked\n' +- ' to replace the slice with the items of the assigned ' +- 'sequence. The\n' +- ' length of the slice may be different from the length of ' +- 'the assigned\n' +- ' sequence, thus changing the length of the target sequence, ' +- 'if the\n' +- ' object allows it.\n' +- '\n' +- '**CPython implementation detail:** In the current ' +- 'implementation, the\n' +- 'syntax for targets is taken to be the same as for ' +- 'expressions, and\n' +- 'invalid syntax is rejected during the code generation phase, ' +- 'causing\n' +- 'less detailed error messages.\n' +- '\n' +- 'WARNING: Although the definition of assignment implies that ' +- 'overlaps\n' +- 'between the left-hand side and the right-hand side are ' +- "'safe' (for\n" +- 'example "a, b = b, a" swaps two variables), overlaps ' +- '*within* the\n' +- 'collection of assigned-to variables are not safe! For ' +- 'instance, the\n' +- 'following program prints "[0, 2]":\n' +- '\n' +- ' x = [0, 1]\n' +- ' i = 0\n' +- ' i, x[i] = 1, 2\n' +- ' print x\n' +- '\n' +- '\n' +- 'Augmented assignment statements\n' +- '===============================\n' +- '\n' +- 'Augmented assignment is the combination, in a single ' +- 'statement, of a\n' +- 'binary 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\n' +- 'symbols.)\n' +- '\n' +- 'An augmented assignment evaluates the target (which, unlike ' +- 'normal\n' +- 'assignment statements, cannot be an unpacking) and the ' +- 'expression\n' +- 'list, performs the binary operation specific to the type of ' +- 'assignment\n' +- 'on the two operands, and assigns the result to the original ' +- 'target.\n' +- 'The target is only evaluated once.\n' +- '\n' +- 'An augmented assignment expression like "x += 1" can be ' +- 'rewritten as\n' +- '"x = x + 1" to achieve a similar, but not exactly equal ' +- 'effect. In the\n' +- 'augmented version, "x" is only evaluated once. Also, when ' +- 'possible,\n' +- 'the actual operation is performed *in-place*, meaning that ' +- 'rather than\n' +- 'creating a new object and assigning that to the target, the ' +- 'old object\n' +- 'is modified instead.\n' +- '\n' +- 'With the exception of assigning to tuples and multiple ' +- 'targets in a\n' +- 'single statement, the assignment done by augmented ' +- 'assignment\n' +- 'statements is handled the same way as normal assignments. ' +- 'Similarly,\n' +- 'with the exception of the possible *in-place* behavior, the ' +- 'binary\n' +- 'operation performed by augmented assignment is the same as ' +- 'the normal\n' +- 'binary operations.\n' +- '\n' +- 'For targets which are attribute references, the same caveat ' +- 'about\n' +- 'class and instance attributes applies as for regular ' +- 'assignments.\n', +- 'atom-identifiers': '\n' +- 'Identifiers (Names)\n' +- '*******************\n' +- '\n' +- 'An identifier occurring as an atom is a name. See ' +- 'section Identifiers\n' +- 'and keywords for lexical definition and section Naming ' +- 'and binding for\n' +- 'documentation of naming and binding.\n' +- '\n' +- 'When the name is bound to an object, evaluation of the ' +- 'atom yields\n' +- 'that object. When a name is not bound, an attempt to ' +- 'evaluate it\n' +- 'raises a "NameError" exception.\n' +- '\n' +- '**Private name mangling:** When an identifier that ' +- 'textually occurs in\n' +- 'a class definition begins with two or more underscore ' +- 'characters and\n' +- 'does not end in two or more underscores, it is ' +- 'considered a *private\n' +- 'name* of that class. Private names are transformed to ' +- 'a longer form\n' +- 'before code is generated for them. The transformation ' +- 'inserts the\n' +- 'class name, with leading underscores removed and a ' +- 'single underscore\n' +- 'inserted, in front of the name. For example, the ' +- 'identifier "__spam"\n' +- 'occurring in a class named "Ham" will be transformed ' +- 'to "_Ham__spam".\n' +- 'This transformation is independent of the syntactical ' +- 'context in which\n' +- 'the identifier is used. If the transformed name is ' +- 'extremely long\n' +- '(longer than 255 characters), implementation defined ' +- 'truncation may\n' +- 'happen. If the class name consists only of ' +- 'underscores, no\n' +- 'transformation is done.\n', +- 'atom-literals': '\n' +- 'Literals\n' +- '********\n' +- '\n' +- 'Python supports string literals and various numeric ' +- 'literals:\n' +- '\n' +- ' literal ::= stringliteral | integer | longinteger\n' +- ' | floatnumber | imagnumber\n' +- '\n' +- 'Evaluation of a literal yields an object of the given ' +- 'type (string,\n' +- 'integer, long integer, floating point number, complex ' +- 'number) with the\n' +- 'given value. The value may be approximated in the case ' +- 'of floating\n' +- 'point and imaginary (complex) literals. See section ' +- 'Literals for\n' +- 'details.\n' +- '\n' +- 'All literals correspond to immutable data types, and ' +- 'hence the\n' +- "object's identity is less important than its value. " +- 'Multiple\n' +- 'evaluations of literals with the same value (either the ' +- 'same\n' +- 'occurrence in the program text or a different occurrence) ' +- 'may obtain\n' +- 'the same object or a different object with the same ' +- 'value.\n', +- 'attribute-access': '\n' +- 'Customizing attribute access\n' +- '****************************\n' +- '\n' +- 'The following methods can be defined to customize the ' +- 'meaning of\n' +- 'attribute access (use of, assignment to, or deletion ' +- 'of "x.name") for\n' +- 'class instances.\n' +- '\n' +- 'object.__getattr__(self, name)\n' +- '\n' +- ' Called when an attribute lookup has not found the ' +- 'attribute in the\n' +- ' usual places (i.e. it is not an instance attribute ' +- 'nor is it found\n' +- ' in the class tree for "self"). "name" is the ' +- 'attribute name. This\n' +- ' method should return the (computed) attribute value ' +- 'or raise an\n' +- ' "AttributeError" exception.\n' +- '\n' +- ' Note that if the attribute is found through the ' +- 'normal mechanism,\n' +- ' "__getattr__()" is not called. (This is an ' +- 'intentional asymmetry\n' +- ' between "__getattr__()" and "__setattr__()".) This ' +- 'is done both for\n' +- ' efficiency reasons and because otherwise ' +- '"__getattr__()" would have\n' +- ' no way to access other attributes of the instance. ' +- 'Note that at\n' +- ' least for instance variables, you can fake total ' +- 'control by not\n' +- ' inserting any values in the instance attribute ' +- 'dictionary (but\n' +- ' instead inserting them in another object). See ' +- 'the\n' +- ' "__getattribute__()" method below for a way to ' +- 'actually get total\n' +- ' control in new-style classes.\n' +- '\n' +- 'object.__setattr__(self, name, value)\n' +- '\n' +- ' Called when an attribute assignment is attempted. ' +- 'This is called\n' +- ' instead of the normal mechanism (i.e. store the ' +- 'value in the\n' +- ' instance dictionary). *name* is the attribute ' +- 'name, *value* is the\n' +- ' value to be assigned to it.\n' +- '\n' +- ' If "__setattr__()" wants to assign to an instance ' +- 'attribute, it\n' +- ' should not simply execute "self.name = value" --- ' +- 'this would cause\n' +- ' a recursive call to itself. Instead, it should ' +- 'insert the value in\n' +- ' the dictionary of instance attributes, e.g., ' +- '"self.__dict__[name] =\n' +- ' value". For new-style classes, rather than ' +- 'accessing the instance\n' +- ' dictionary, it should call the base class method ' +- 'with the same\n' +- ' name, for example, "object.__setattr__(self, name, ' +- 'value)".\n' +- '\n' +- 'object.__delattr__(self, name)\n' +- '\n' +- ' Like "__setattr__()" but for attribute deletion ' +- 'instead of\n' +- ' assignment. This should only be implemented if ' +- '"del obj.name" is\n' +- ' meaningful for the object.\n' +- '\n' +- '\n' +- 'More attribute access for new-style classes\n' +- '===========================================\n' +- '\n' +- 'The following methods only apply to new-style ' +- 'classes.\n' +- '\n' +- 'object.__getattribute__(self, name)\n' +- '\n' +- ' Called unconditionally to implement attribute ' +- 'accesses for\n' +- ' instances of the class. If the class also defines ' +- '"__getattr__()",\n' +- ' the latter will not be called unless ' +- '"__getattribute__()" either\n' +- ' calls it explicitly or raises an "AttributeError". ' +- 'This method\n' +- ' should return the (computed) attribute value or ' +- 'raise an\n' +- ' "AttributeError" exception. In order to avoid ' +- 'infinite recursion in\n' +- ' this method, its implementation should always call ' +- 'the base class\n' +- ' method with the same name to access any attributes ' +- 'it needs, for\n' +- ' example, "object.__getattribute__(self, name)".\n' +- '\n' +- ' Note: This method may still be bypassed when ' +- 'looking up special\n' +- ' methods as the result of implicit invocation via ' +- 'language syntax\n' +- ' or built-in functions. See Special method lookup ' +- 'for new-style\n' +- ' classes.\n' +- '\n' +- '\n' +- 'Implementing Descriptors\n' +- '========================\n' +- '\n' +- 'The following methods only apply when an instance of ' +- 'the class\n' +- 'containing the method (a so-called *descriptor* class) ' +- 'appears in an\n' +- '*owner* class (the descriptor must be in either the ' +- "owner's class\n" +- 'dictionary or in the class dictionary for one of its ' +- 'parents). In the\n' +- 'examples below, "the attribute" refers to the ' +- 'attribute whose name is\n' +- "the key of the property in the owner class' " +- '"__dict__".\n' +- '\n' +- 'object.__get__(self, instance, owner)\n' +- '\n' +- ' Called to get the attribute of the owner class ' +- '(class attribute\n' +- ' access) or of an instance of that class (instance ' +- 'attribute\n' +- ' access). *owner* is always the owner class, while ' +- '*instance* is the\n' +- ' instance that the attribute was accessed through, ' +- 'or "None" when\n' +- ' the attribute is accessed through the *owner*. ' +- 'This method should\n' +- ' return the (computed) attribute value or raise an ' +- '"AttributeError"\n' +- ' exception.\n' +- '\n' +- 'object.__set__(self, instance, value)\n' +- '\n' +- ' Called to set the attribute on an instance ' +- '*instance* of the owner\n' +- ' class to a new value, *value*.\n' +- '\n' +- 'object.__delete__(self, instance)\n' +- '\n' +- ' Called to delete the attribute on an instance ' +- '*instance* of the\n' +- ' owner class.\n' +- '\n' +- '\n' +- 'Invoking Descriptors\n' +- '====================\n' +- '\n' +- 'In general, a descriptor is an object attribute with ' +- '"binding\n' +- 'behavior", one whose attribute access has been ' +- 'overridden by methods\n' +- 'in the descriptor protocol: "__get__()", "__set__()", ' +- 'and\n' +- '"__delete__()". If any of those methods are defined ' +- 'for an object, it\n' +- 'is said to be a descriptor.\n' +- '\n' +- 'The default behavior for attribute access is to get, ' +- 'set, or delete\n' +- "the attribute from an object's dictionary. For " +- 'instance, "a.x" has a\n' +- 'lookup chain starting with "a.__dict__[\'x\']", then\n' +- '"type(a).__dict__[\'x\']", and continuing through the ' +- 'base classes of\n' +- '"type(a)" excluding metaclasses.\n' +- '\n' +- 'However, if the looked-up value is an object defining ' +- 'one of the\n' +- 'descriptor methods, then Python may override the ' +- 'default behavior and\n' +- 'invoke the descriptor method instead. Where this ' +- 'occurs in the\n' +- 'precedence chain depends on which descriptor methods ' +- 'were defined and\n' +- 'how they were called. Note that descriptors are only ' +- 'invoked for new\n' +- 'style objects or classes (ones that subclass ' +- '"object()" or "type()").\n' +- '\n' +- 'The starting point for descriptor invocation is a ' +- 'binding, "a.x". How\n' +- 'the arguments are assembled depends on "a":\n' +- '\n' +- 'Direct Call\n' +- ' The simplest and least common call is when user ' +- 'code directly\n' +- ' invokes a descriptor method: "x.__get__(a)".\n' +- '\n' +- 'Instance Binding\n' +- ' If binding to a new-style object instance, "a.x" is ' +- 'transformed\n' +- ' into the call: "type(a).__dict__[\'x\'].__get__(a, ' +- 'type(a))".\n' +- '\n' +- 'Class Binding\n' +- ' If binding to a new-style class, "A.x" is ' +- 'transformed into the\n' +- ' call: "A.__dict__[\'x\'].__get__(None, A)".\n' +- '\n' +- 'Super Binding\n' +- ' If "a" is an instance of "super", then the binding ' +- '"super(B,\n' +- ' obj).m()" searches "obj.__class__.__mro__" for the ' +- 'base class "A"\n' +- ' immediately preceding "B" and then invokes the ' +- 'descriptor with the\n' +- ' call: "A.__dict__[\'m\'].__get__(obj, ' +- 'obj.__class__)".\n' +- '\n' +- 'For instance bindings, the precedence of descriptor ' +- 'invocation depends\n' +- 'on the which descriptor methods are defined. A ' +- 'descriptor can define\n' +- 'any combination of "__get__()", "__set__()" and ' +- '"__delete__()". If it\n' +- 'does not define "__get__()", then accessing the ' +- 'attribute will return\n' +- 'the descriptor object itself unless there is a value ' +- "in the object's\n" +- 'instance dictionary. If the descriptor defines ' +- '"__set__()" and/or\n' +- '"__delete__()", it is a data descriptor; if it defines ' +- 'neither, it is\n' +- 'a non-data descriptor. Normally, data descriptors ' +- 'define both\n' +- '"__get__()" and "__set__()", while non-data ' +- 'descriptors have just the\n' +- '"__get__()" method. Data descriptors with "__set__()" ' +- 'and "__get__()"\n' +- 'defined always override a redefinition in an instance ' +- 'dictionary. In\n' +- 'contrast, non-data descriptors can be overridden by ' +- 'instances.\n' +- '\n' +- 'Python methods (including "staticmethod()" and ' +- '"classmethod()") are\n' +- 'implemented as non-data descriptors. Accordingly, ' +- 'instances can\n' +- 'redefine and override methods. This allows individual ' +- 'instances to\n' +- 'acquire behaviors that differ from other instances of ' +- 'the same class.\n' +- '\n' +- 'The "property()" function is implemented as a data ' +- 'descriptor.\n' +- 'Accordingly, instances cannot override the behavior of ' +- 'a property.\n' +- '\n' +- '\n' +- '__slots__\n' +- '=========\n' +- '\n' +- 'By default, instances of both old and new-style ' +- 'classes have a\n' +- 'dictionary for attribute storage. This wastes space ' +- 'for objects\n' +- 'having very few instance variables. The space ' +- 'consumption can become\n' +- 'acute when creating large numbers of instances.\n' +- '\n' +- 'The default can be overridden by defining *__slots__* ' +- 'in a new-style\n' +- 'class definition. The *__slots__* declaration takes a ' +- 'sequence of\n' +- 'instance variables and reserves just enough space in ' +- 'each instance to\n' +- 'hold a value for each variable. Space is saved ' +- 'because *__dict__* is\n' +- 'not created for each instance.\n' +- '\n' +- '__slots__\n' +- '\n' +- ' This class variable can be assigned a string, ' +- 'iterable, or sequence\n' +- ' of strings with variable names used by instances. ' +- 'If defined in a\n' +- ' new-style class, *__slots__* reserves space for the ' +- 'declared\n' +- ' variables and prevents the automatic creation of ' +- '*__dict__* and\n' +- ' *__weakref__* for each instance.\n' +- '\n' +- ' New in version 2.2.\n' +- '\n' +- 'Notes on using *__slots__*\n' +- '\n' +- '* When inheriting from a class without *__slots__*, ' +- 'the *__dict__*\n' +- ' attribute of that class will always be accessible, ' +- 'so a *__slots__*\n' +- ' definition in the subclass is meaningless.\n' +- '\n' +- '* Without a *__dict__* variable, instances cannot be ' +- 'assigned new\n' +- ' variables not listed in the *__slots__* definition. ' +- 'Attempts to\n' +- ' assign to an unlisted variable name raises ' +- '"AttributeError". If\n' +- ' dynamic assignment of new variables is desired, then ' +- 'add\n' +- ' "\'__dict__\'" to the sequence of strings in the ' +- '*__slots__*\n' +- ' declaration.\n' +- '\n' +- ' Changed in version 2.3: Previously, adding ' +- '"\'__dict__\'" to the\n' +- ' *__slots__* declaration would not enable the ' +- 'assignment of new\n' +- ' attributes not specifically listed in the sequence ' +- 'of instance\n' +- ' variable names.\n' +- '\n' +- '* Without a *__weakref__* variable for each instance, ' +- 'classes\n' +- ' defining *__slots__* do not support weak references ' +- 'to its\n' +- ' instances. If weak reference support is needed, then ' +- 'add\n' +- ' "\'__weakref__\'" to the sequence of strings in the ' +- '*__slots__*\n' +- ' declaration.\n' +- '\n' +- ' Changed in version 2.3: Previously, adding ' +- '"\'__weakref__\'" to the\n' +- ' *__slots__* declaration would not enable support for ' +- 'weak\n' +- ' references.\n' +- '\n' +- '* *__slots__* are implemented at the class level by ' +- 'creating\n' +- ' descriptors (Implementing Descriptors) for each ' +- 'variable name. As a\n' +- ' result, class attributes cannot be used to set ' +- 'default values for\n' +- ' instance variables defined by *__slots__*; ' +- 'otherwise, the class\n' +- ' attribute would overwrite the descriptor ' +- 'assignment.\n' +- '\n' +- '* The action of a *__slots__* declaration is limited ' +- 'to the class\n' +- ' where it is defined. As a result, subclasses will ' +- 'have a *__dict__*\n' +- ' unless they also define *__slots__* (which must only ' +- 'contain names\n' +- ' of any *additional* slots).\n' +- '\n' +- '* If a class defines a slot also defined in a base ' +- 'class, the\n' +- ' instance variable defined by the base class slot is ' +- 'inaccessible\n' +- ' (except by retrieving its descriptor directly from ' +- 'the base class).\n' +- ' This renders the meaning of the program undefined. ' +- 'In the future, a\n' +- ' check may be added to prevent this.\n' +- '\n' +- '* Nonempty *__slots__* does not work for classes ' +- 'derived from\n' +- ' "variable-length" built-in types such as "long", ' +- '"str" and "tuple".\n' +- '\n' +- '* Any non-string iterable may be assigned to ' +- '*__slots__*. Mappings\n' +- ' may also be used; however, in the future, special ' +- 'meaning may be\n' +- ' assigned to the values corresponding to each key.\n' +- '\n' +- '* *__class__* assignment works only if both classes ' +- 'have the same\n' +- ' *__slots__*.\n' +- '\n' +- ' Changed in version 2.6: Previously, *__class__* ' +- 'assignment raised an\n' +- ' error if either new or old class had *__slots__*.\n', +- 'attribute-references': '\n' +- 'Attribute references\n' +- '********************\n' +- '\n' +- 'An attribute reference is a primary followed by a ' +- 'period and a name:\n' +- '\n' +- ' attributeref ::= primary "." identifier\n' +- '\n' +- 'The primary must evaluate to an object of a type ' +- 'that supports\n' +- 'attribute references, e.g., a module, list, or an ' +- 'instance. This\n' +- 'object is then asked to produce the attribute ' +- 'whose name is the\n' +- 'identifier. If this attribute is not available, ' +- 'the exception\n' +- '"AttributeError" is raised. Otherwise, the type ' +- 'and value of the\n' +- 'object produced is determined by the object. ' +- 'Multiple evaluations of\n' +- 'the same attribute reference may yield different ' +- 'objects.\n', +- 'augassign': '\n' +- 'Augmented assignment statements\n' +- '*******************************\n' +- '\n' +- 'Augmented assignment is the combination, in a single ' +- 'statement, of a\n' +- 'binary 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\n' +- 'symbols.)\n' +- '\n' +- 'An augmented assignment evaluates the target (which, unlike ' +- 'normal\n' +- 'assignment statements, cannot be an unpacking) and the ' +- 'expression\n' +- 'list, performs the binary operation specific to the type of ' +- 'assignment\n' +- 'on the two operands, and assigns the result to the original ' +- 'target.\n' +- 'The target is only evaluated once.\n' +- '\n' +- 'An augmented assignment expression like "x += 1" can be ' +- 'rewritten as\n' +- '"x = x + 1" to achieve a similar, but not exactly equal ' +- 'effect. In the\n' +- 'augmented version, "x" is only evaluated once. Also, when ' +- 'possible,\n' +- 'the actual operation is performed *in-place*, meaning that ' +- 'rather than\n' +- 'creating a new object and assigning that to the target, the ' +- 'old object\n' +- 'is modified instead.\n' +- '\n' +- 'With the exception of assigning to tuples and multiple ' +- 'targets in a\n' +- 'single statement, the assignment done by augmented ' +- 'assignment\n' +- 'statements is handled the same way as normal assignments. ' +- 'Similarly,\n' +- 'with the exception of the possible *in-place* behavior, the ' +- 'binary\n' +- 'operation performed by augmented assignment is the same as ' +- 'the normal\n' +- 'binary operations.\n' +- '\n' +- 'For targets which are attribute references, the same caveat ' +- 'about\n' +- 'class and instance attributes applies as for regular ' +- 'assignments.\n', +- 'binary': '\n' +- 'Binary arithmetic operations\n' +- '****************************\n' +- '\n' +- 'The binary arithmetic operations have the conventional priority\n' +- 'levels. Note that some of these operations also apply to ' +- 'certain non-\n' +- 'numeric types. Apart from the power operator, there are only ' +- 'two\n' +- 'levels, one for multiplicative operators and one for additive\n' +- 'operators:\n' +- '\n' +- ' m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | ' +- 'm_expr "/" u_expr\n' +- ' | m_expr "%" u_expr\n' +- ' a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n' +- '\n' +- 'The "*" (multiplication) operator yields the product of its ' +- 'arguments.\n' +- 'The arguments must either both be numbers, or one argument must ' +- 'be an\n' +- 'integer (plain or long) and the other must be a sequence. In ' +- 'the\n' +- 'former case, the numbers are converted to a common type and ' +- 'then\n' +- 'multiplied together. In the latter case, sequence repetition ' +- 'is\n' +- 'performed; a negative repetition factor yields an empty ' +- 'sequence.\n' +- '\n' +- 'The "/" (division) and "//" (floor division) operators yield ' +- 'the\n' +- 'quotient of their arguments. The numeric arguments are first\n' +- 'converted to a common type. Plain or long integer division ' +- 'yields an\n' +- 'integer of the same type; the result is that of mathematical ' +- 'division\n' +- "with the 'floor' function applied to the result. Division by " +- 'zero\n' +- 'raises the "ZeroDivisionError" exception.\n' +- '\n' +- 'The "%" (modulo) operator yields the remainder from the division ' +- 'of\n' +- 'the first argument by the second. The numeric arguments are ' +- 'first\n' +- 'converted to a common type. A zero right argument raises the\n' +- '"ZeroDivisionError" exception. The arguments may be floating ' +- 'point\n' +- 'numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals ' +- '"4*0.7 +\n' +- '0.34".) The modulo operator always yields a result with the ' +- 'same sign\n' +- 'as its second operand (or zero); the absolute value of the ' +- 'result is\n' +- 'strictly smaller than the absolute value of the second operand ' +- '[2].\n' +- '\n' +- 'The integer division and modulo operators are connected by the\n' +- 'following identity: "x == (x/y)*y + (x%y)". Integer division ' +- 'and\n' +- 'modulo are also connected with the built-in function ' +- '"divmod()":\n' +- '"divmod(x, y) == (x/y, x%y)". These identities don\'t hold for\n' +- 'floating point numbers; there similar identities hold ' +- 'approximately\n' +- 'where "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" ' +- '[3].\n' +- '\n' +- 'In addition to performing the modulo operation on numbers, the ' +- '"%"\n' +- 'operator is also overloaded by string and unicode objects to ' +- 'perform\n' +- 'string formatting (also known as interpolation). The syntax for ' +- 'string\n' +- 'formatting is described in the Python Library Reference, ' +- 'section\n' +- 'String Formatting Operations.\n' +- '\n' +- 'Deprecated since version 2.3: The floor division operator, the ' +- 'modulo\n' +- 'operator, and the "divmod()" function are no longer defined for\n' +- 'complex numbers. Instead, convert to a floating point number ' +- 'using\n' +- 'the "abs()" function if appropriate.\n' +- '\n' +- 'The "+" (addition) operator yields the sum of its arguments. ' +- 'The\n' +- 'arguments must either both be numbers or both sequences of the ' +- 'same\n' +- 'type. In the former case, the numbers are converted to a common ' +- 'type\n' +- 'and then added together. In the latter case, the sequences are\n' +- 'concatenated.\n' +- '\n' +- 'The "-" (subtraction) operator yields the difference of its ' +- 'arguments.\n' +- 'The numeric arguments are first converted to a common type.\n', +- 'bitwise': '\n' +- 'Binary bitwise operations\n' +- '*************************\n' +- '\n' +- 'Each of the three bitwise operations has a different priority ' +- 'level:\n' +- '\n' +- ' and_expr ::= shift_expr | and_expr "&" shift_expr\n' +- ' xor_expr ::= and_expr | xor_expr "^" and_expr\n' +- ' or_expr ::= xor_expr | or_expr "|" xor_expr\n' +- '\n' +- 'The "&" operator yields the bitwise AND of its arguments, which ' +- 'must\n' +- 'be plain or long integers. The arguments are converted to a ' +- 'common\n' +- 'type.\n' +- '\n' +- 'The "^" operator yields the bitwise XOR (exclusive OR) of its\n' +- 'arguments, which must be plain or long integers. The arguments ' +- 'are\n' +- 'converted to a common type.\n' +- '\n' +- 'The "|" operator yields the bitwise (inclusive) OR of its ' +- 'arguments,\n' +- 'which must be plain or long integers. The arguments are ' +- 'converted to\n' +- 'a common type.\n', +- 'bltin-code-objects': '\n' +- 'Code Objects\n' +- '************\n' +- '\n' +- 'Code objects are used by the implementation to ' +- 'represent "pseudo-\n' +- 'compiled" executable Python code such as a function ' +- 'body. They differ\n' +- "from function objects because they don't contain a " +- 'reference to their\n' +- 'global execution environment. Code objects are ' +- 'returned by the built-\n' +- 'in "compile()" function and can be extracted from ' +- 'function objects\n' +- 'through their "func_code" attribute. See also the ' +- '"code" module.\n' +- '\n' +- 'A code object can be executed or evaluated by ' +- 'passing it (instead of a\n' +- 'source string) to the "exec" statement or the ' +- 'built-in "eval()"\n' +- 'function.\n' +- '\n' +- 'See The standard type hierarchy for more ' +- 'information.\n', +- 'bltin-ellipsis-object': '\n' +- 'The Ellipsis Object\n' +- '*******************\n' +- '\n' +- 'This object is used by extended slice notation ' +- '(see Slicings). It\n' +- 'supports no special operations. There is exactly ' +- 'one ellipsis object,\n' +- 'named "Ellipsis" (a built-in name).\n' +- '\n' +- 'It is written as "Ellipsis". When in a ' +- 'subscript, it can also be\n' +- 'written as "...", for example "seq[...]".\n', +- 'bltin-null-object': '\n' +- 'The Null Object\n' +- '***************\n' +- '\n' +- "This object is returned by functions that don't " +- 'explicitly return a\n' +- 'value. It supports no special operations. There is ' +- 'exactly one null\n' +- 'object, named "None" (a built-in name).\n' +- '\n' +- 'It is written as "None".\n', +- 'bltin-type-objects': '\n' +- 'Type Objects\n' +- '************\n' +- '\n' +- 'Type objects represent the various object types. An ' +- "object's type is\n" +- 'accessed by the built-in function "type()". There ' +- 'are no special\n' +- 'operations on types. The standard module "types" ' +- 'defines names for\n' +- 'all standard built-in types.\n' +- '\n' +- 'Types are written like this: "".\n', +- 'booleans': '\n' +- 'Boolean operations\n' +- '******************\n' +- '\n' +- ' or_test ::= and_test | or_test "or" and_test\n' +- ' and_test ::= not_test | and_test "and" not_test\n' +- ' not_test ::= comparison | "not" not_test\n' +- '\n' +- 'In the context of Boolean operations, and also when ' +- 'expressions are\n' +- 'used by control flow statements, the following values are ' +- 'interpreted\n' +- 'as false: "False", "None", numeric zero of all types, and ' +- 'empty\n' +- 'strings and containers (including strings, tuples, lists,\n' +- 'dictionaries, sets and frozensets). All other values are ' +- 'interpreted\n' +- 'as true. (See the "__nonzero__()" special method for a way to ' +- 'change\n' +- 'this.)\n' +- '\n' +- 'The operator "not" yields "True" if its argument is false, ' +- '"False"\n' +- 'otherwise.\n' +- '\n' +- 'The expression "x and y" first evaluates *x*; if *x* is false, ' +- 'its\n' +- 'value is returned; otherwise, *y* is evaluated and the ' +- 'resulting value\n' +- 'is returned.\n' +- '\n' +- 'The expression "x or y" first evaluates *x*; if *x* is true, ' +- 'its value\n' +- 'is returned; otherwise, *y* is evaluated and the resulting ' +- 'value is\n' +- 'returned.\n' +- '\n' +- '(Note that neither "and" nor "or" restrict the value and type ' +- 'they\n' +- 'return to "False" and "True", but rather return the last ' +- 'evaluated\n' +- 'argument. This is sometimes useful, e.g., if "s" is a string ' +- 'that\n' +- 'should be replaced by a default value if it is empty, the ' +- 'expression\n' +- '"s or \'foo\'" yields the desired value. Because "not" has to ' +- 'invent a\n' +- 'value anyway, it does not bother to return a value of the same ' +- 'type as\n' +- 'its argument, so e.g., "not \'foo\'" yields "False", not ' +- '"\'\'".)\n', +- 'break': '\n' +- 'The "break" statement\n' +- '*********************\n' +- '\n' +- ' break_stmt ::= "break"\n' +- '\n' +- '"break" may only occur syntactically nested in a "for" or ' +- '"while"\n' +- 'loop, but not nested in a function or class definition within ' +- 'that\n' +- 'loop.\n' +- '\n' +- 'It terminates the nearest enclosing loop, skipping the optional ' +- '"else"\n' +- 'clause if the loop has one.\n' +- '\n' +- 'If a "for" loop is terminated by "break", the loop control ' +- 'target\n' +- 'keeps its current value.\n' +- '\n' +- 'When "break" passes control out of a "try" statement with a ' +- '"finally"\n' +- 'clause, that "finally" clause is executed before really leaving ' +- 'the\n' +- 'loop.\n', +- 'callable-types': '\n' +- 'Emulating callable objects\n' +- '**************************\n' +- '\n' +- 'object.__call__(self[, args...])\n' +- '\n' +- ' Called when the instance is "called" as a function; ' +- 'if this method\n' +- ' is defined, "x(arg1, arg2, ...)" is a shorthand for\n' +- ' "x.__call__(arg1, arg2, ...)".\n', +- 'calls': '\n' +- 'Calls\n' +- '*****\n' +- '\n' +- 'A call calls a callable object (e.g., a *function*) with a ' +- 'possibly\n' +- 'empty series of *arguments*:\n' +- '\n' +- ' call ::= primary "(" [argument_list [","]\n' +- ' | expression genexpr_for] ")"\n' +- ' argument_list ::= positional_arguments ["," ' +- 'keyword_arguments]\n' +- ' ["," "*" expression] ["," ' +- 'keyword_arguments]\n' +- ' ["," "**" expression]\n' +- ' | keyword_arguments ["," "*" expression]\n' +- ' ["," "**" expression]\n' +- ' | "*" expression ["," keyword_arguments] ' +- '["," "**" expression]\n' +- ' | "**" expression\n' +- ' positional_arguments ::= expression ("," expression)*\n' +- ' keyword_arguments ::= keyword_item ("," keyword_item)*\n' +- ' keyword_item ::= identifier "=" expression\n' +- '\n' +- 'A trailing comma may be present after the positional and keyword\n' +- 'arguments but does not affect the semantics.\n' +- '\n' +- 'The primary must evaluate to a callable object (user-defined\n' +- 'functions, built-in functions, methods of built-in objects, ' +- 'class\n' +- 'objects, methods of class instances, and certain class instances\n' +- 'themselves are callable; extensions may define additional ' +- 'callable\n' +- 'object types). All argument expressions are evaluated before the ' +- 'call\n' +- 'is attempted. Please refer to section Function definitions for ' +- 'the\n' +- 'syntax of formal *parameter* lists.\n' +- '\n' +- 'If keyword arguments are present, they are first converted to\n' +- 'positional arguments, as follows. First, a list of unfilled ' +- 'slots is\n' +- 'created for the formal parameters. If there are N positional\n' +- 'arguments, they are placed in the first N slots. Next, for each\n' +- 'keyword argument, the identifier is used to determine the\n' +- 'corresponding slot (if the identifier is the same as the first ' +- 'formal\n' +- 'parameter name, the first slot is used, and so on). If the slot ' +- 'is\n' +- 'already filled, a "TypeError" exception is raised. Otherwise, ' +- 'the\n' +- 'value of the argument is placed in the slot, filling it (even if ' +- 'the\n' +- 'expression is "None", it fills the slot). When all arguments ' +- 'have\n' +- 'been processed, the slots that are still unfilled are filled with ' +- 'the\n' +- 'corresponding default value from the function definition. ' +- '(Default\n' +- 'values are calculated, once, when the function is defined; thus, ' +- 'a\n' +- 'mutable object such as a list or dictionary used as default value ' +- 'will\n' +- "be shared by all calls that don't specify an argument value for " +- 'the\n' +- 'corresponding slot; this should usually be avoided.) If there ' +- 'are any\n' +- 'unfilled slots for which no default value is specified, a ' +- '"TypeError"\n' +- 'exception is raised. Otherwise, the list of filled slots is used ' +- 'as\n' +- 'the argument list for the call.\n' +- '\n' +- '**CPython implementation detail:** An implementation may provide\n' +- 'built-in functions whose positional parameters do not have names, ' +- 'even\n' +- "if they are 'named' for the purpose of documentation, and which\n" +- 'therefore cannot be supplied by keyword. In CPython, this is the ' +- 'case\n' +- 'for functions implemented in C that use "PyArg_ParseTuple()" to ' +- 'parse\n' +- 'their arguments.\n' +- '\n' +- 'If there are more positional arguments than there are formal ' +- 'parameter\n' +- 'slots, a "TypeError" exception is raised, unless a formal ' +- 'parameter\n' +- 'using the syntax "*identifier" is present; in this case, that ' +- 'formal\n' +- 'parameter receives a tuple containing the excess positional ' +- 'arguments\n' +- '(or an empty tuple if there were no excess positional ' +- 'arguments).\n' +- '\n' +- 'If any keyword argument does not correspond to a formal ' +- 'parameter\n' +- 'name, a "TypeError" exception is raised, unless a formal ' +- 'parameter\n' +- 'using the syntax "**identifier" is present; in this case, that ' +- 'formal\n' +- 'parameter receives a dictionary containing the excess keyword\n' +- 'arguments (using the keywords as keys and the argument values as\n' +- 'corresponding values), or a (new) empty dictionary if there were ' +- 'no\n' +- 'excess keyword arguments.\n' +- '\n' +- 'If the syntax "*expression" appears in the function call, ' +- '"expression"\n' +- 'must evaluate to an iterable. Elements from this iterable are ' +- 'treated\n' +- 'as if they were additional positional arguments; if there are\n' +- 'positional arguments *x1*, ..., *xN*, and "expression" evaluates ' +- 'to a\n' +- 'sequence *y1*, ..., *yM*, this is equivalent to a call with M+N\n' +- 'positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n' +- '\n' +- 'A consequence of this is that although the "*expression" syntax ' +- 'may\n' +- 'appear *after* some keyword arguments, it is processed *before* ' +- 'the\n' +- 'keyword arguments (and the "**expression" argument, if any -- ' +- 'see\n' +- 'below). So:\n' +- '\n' +- ' >>> def f(a, b):\n' +- ' ... print a, b\n' +- ' ...\n' +- ' >>> f(b=1, *(2,))\n' +- ' 2 1\n' +- ' >>> f(a=1, *(2,))\n' +- ' Traceback (most recent call last):\n' +- ' File "", line 1, in ?\n' +- " TypeError: f() got multiple values for keyword argument 'a'\n" +- ' >>> f(1, *(2,))\n' +- ' 1 2\n' +- '\n' +- 'It is unusual for both keyword arguments and the "*expression" ' +- 'syntax\n' +- 'to be used in the same call, so in practice this confusion does ' +- 'not\n' +- 'arise.\n' +- '\n' +- 'If the syntax "**expression" appears in the function call,\n' +- '"expression" must evaluate to a mapping, the contents of which ' +- 'are\n' +- 'treated as additional keyword arguments. In the case of a ' +- 'keyword\n' +- 'appearing in both "expression" and as an explicit keyword ' +- 'argument, a\n' +- '"TypeError" exception is raised.\n' +- '\n' +- 'Formal parameters using the syntax "*identifier" or ' +- '"**identifier"\n' +- 'cannot be used as positional argument slots or as keyword ' +- 'argument\n' +- 'names. Formal parameters using the syntax "(sublist)" cannot be ' +- 'used\n' +- 'as keyword argument names; the outermost sublist corresponds to ' +- 'a\n' +- 'single unnamed argument slot, and the argument value is assigned ' +- 'to\n' +- 'the sublist using the usual tuple assignment rules after all ' +- 'other\n' +- 'parameter processing is done.\n' +- '\n' +- 'A call always returns some value, possibly "None", unless it ' +- 'raises an\n' +- 'exception. How this value is computed depends on the type of ' +- 'the\n' +- 'callable object.\n' +- '\n' +- 'If it is---\n' +- '\n' +- 'a user-defined function:\n' +- ' The code block for the function is executed, passing it the\n' +- ' argument list. The first thing the code block will do is bind ' +- 'the\n' +- ' formal parameters to the arguments; this is described in ' +- 'section\n' +- ' Function definitions. When the code block executes a ' +- '"return"\n' +- ' statement, this specifies the return value of the function ' +- 'call.\n' +- '\n' +- 'a built-in function or method:\n' +- ' The result is up to the interpreter; see Built-in Functions ' +- 'for the\n' +- ' descriptions of built-in functions and methods.\n' +- '\n' +- 'a class object:\n' +- ' A new instance of that class is returned.\n' +- '\n' +- 'a class instance method:\n' +- ' The corresponding user-defined function is called, with an ' +- 'argument\n' +- ' list that is one longer than the argument list of the call: ' +- 'the\n' +- ' instance becomes the first argument.\n' +- '\n' +- 'a class instance:\n' +- ' The class must define a "__call__()" method; the effect is ' +- 'then the\n' +- ' same as if that method was called.\n', +- 'class': '\n' +- 'Class definitions\n' +- '*****************\n' +- '\n' +- 'A class definition defines a class object (see section The ' +- 'standard\n' +- 'type hierarchy):\n' +- '\n' +- ' classdef ::= "class" classname [inheritance] ":" suite\n' +- ' inheritance ::= "(" [expression_list] ")"\n' +- ' classname ::= identifier\n' +- '\n' +- 'A class definition is an executable statement. It first ' +- 'evaluates the\n' +- 'inheritance list, if present. Each item in the inheritance list\n' +- 'should evaluate to a class object or class type which allows\n' +- "subclassing. The class's suite is then executed in a new " +- 'execution\n' +- 'frame (see section Naming and binding), using a newly created ' +- 'local\n' +- 'namespace and the original global namespace. (Usually, the suite\n' +- "contains only function definitions.) When the class's suite " +- 'finishes\n' +- 'execution, its execution frame is discarded but its local ' +- 'namespace is\n' +- 'saved. [4] A class object is then created using the inheritance ' +- 'list\n' +- 'for the base classes and the saved local namespace for the ' +- 'attribute\n' +- 'dictionary. The class name is bound to this class object in the\n' +- 'original local namespace.\n' +- '\n' +- "**Programmer's note:** Variables defined in the class definition " +- 'are\n' +- 'class variables; they are shared by all instances. To create ' +- 'instance\n' +- 'variables, they can be set in a method with "self.name = value". ' +- 'Both\n' +- 'class and instance variables are accessible through the notation\n' +- '""self.name"", and an instance variable hides a class variable ' +- 'with\n' +- 'the same name when accessed in this way. Class variables can be ' +- 'used\n' +- 'as defaults for instance variables, but using mutable values ' +- 'there can\n' +- 'lead to unexpected results. For *new-style class*es, descriptors ' +- 'can\n' +- 'be used to create instance variables with different ' +- 'implementation\n' +- 'details.\n' +- '\n' +- 'Class definitions, like function definitions, may be wrapped by ' +- 'one or\n' +- 'more *decorator* expressions. The evaluation rules for the ' +- 'decorator\n' +- 'expressions are the same as for functions. The result must be a ' +- 'class\n' +- 'object, which is then bound to the class name.\n' +- '\n' +- '-[ Footnotes ]-\n' +- '\n' +- '[1] The exception is propagated to the invocation stack unless\n' +- ' there is a "finally" clause which happens to raise another\n' +- ' exception. That new exception causes the old one to be lost.\n' +- '\n' +- '[2] Currently, control "flows off the end" except in the case of\n' +- ' an exception or the execution of a "return", "continue", or\n' +- ' "break" statement.\n' +- '\n' +- '[3] A string literal appearing as the first statement in the\n' +- ' function body is transformed into the function\'s "__doc__"\n' +- " attribute and therefore the function's *docstring*.\n" +- '\n' +- '[4] A string literal appearing as the first statement in the ' +- 'class\n' +- ' body is transformed into the namespace\'s "__doc__" item and\n' +- " therefore the class's *docstring*.\n", +- 'comparisons': '\n' +- 'Comparisons\n' +- '***********\n' +- '\n' +- 'Unlike C, all comparison operations in Python have the same ' +- 'priority,\n' +- 'which is lower than that of any arithmetic, shifting or ' +- 'bitwise\n' +- 'operation. Also unlike C, expressions like "a < b < c" ' +- 'have the\n' +- 'interpretation that is conventional in mathematics:\n' +- '\n' +- ' comparison ::= or_expr ( comp_operator or_expr )*\n' +- ' comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" ' +- '| "!="\n' +- ' | "is" ["not"] | ["not"] "in"\n' +- '\n' +- 'Comparisons yield boolean values: "True" or "False".\n' +- '\n' +- 'Comparisons can be chained arbitrarily, e.g., "x < y <= z" ' +- 'is\n' +- 'equivalent to "x < y and y <= z", except that "y" is ' +- 'evaluated only\n' +- 'once (but in both cases "z" is not evaluated at all when "x ' +- '< y" is\n' +- 'found to be false).\n' +- '\n' +- 'Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions ' +- 'and *op1*,\n' +- '*op2*, ..., *opN* are comparison operators, then "a op1 b ' +- 'op2 c ... y\n' +- 'opN z" is equivalent to "a op1 b and b op2 c and ... y opN ' +- 'z", except\n' +- 'that each expression is evaluated at most once.\n' +- '\n' +- 'Note that "a op1 b op2 c" doesn\'t imply any kind of ' +- 'comparison between\n' +- '*a* and *c*, so that, e.g., "x < y > z" is perfectly legal ' +- '(though\n' +- 'perhaps not pretty).\n' +- '\n' +- 'The forms "<>" and "!=" are equivalent; for consistency ' +- 'with C, "!="\n' +- 'is preferred; where "!=" is mentioned below "<>" is also ' +- 'accepted.\n' +- 'The "<>" spelling is considered obsolescent.\n' +- '\n' +- 'The operators "<", ">", "==", ">=", "<=", and "!=" compare ' +- 'the values\n' +- 'of two objects. The objects need not have the same type. ' +- 'If both are\n' +- 'numbers, they are converted to a common type. Otherwise, ' +- 'objects of\n' +- 'different types *always* compare unequal, and are ordered ' +- 'consistently\n' +- 'but arbitrarily. You can control comparison behavior of ' +- 'objects of\n' +- 'non-built-in types by defining a "__cmp__" method or rich ' +- 'comparison\n' +- 'methods like "__gt__", described in section Special method ' +- 'names.\n' +- '\n' +- '(This unusual definition of comparison was used to simplify ' +- 'the\n' +- 'definition of operations like sorting and the "in" and "not ' +- 'in"\n' +- 'operators. In the future, the comparison rules for objects ' +- 'of\n' +- 'different types are likely to change.)\n' +- '\n' +- 'Comparison of objects of the same type depends on the ' +- 'type:\n' +- '\n' +- '* Numbers are compared arithmetically.\n' +- '\n' +- '* Strings are compared lexicographically using the numeric\n' +- ' equivalents (the result of the built-in function "ord()") ' +- 'of their\n' +- ' characters. Unicode and 8-bit strings are fully ' +- 'interoperable in\n' +- ' this behavior. [4]\n' +- '\n' +- '* Tuples and lists are compared lexicographically using ' +- 'comparison\n' +- ' of corresponding elements. This means that to compare ' +- 'equal, each\n' +- ' element must compare equal and the two sequences must be ' +- 'of the same\n' +- ' type and have the same length.\n' +- '\n' +- ' If not equal, the sequences are ordered the same as their ' +- 'first\n' +- ' differing elements. For example, "cmp([1,2,x], [1,2,y])" ' +- 'returns\n' +- ' the same as "cmp(x,y)". If the corresponding element ' +- 'does not\n' +- ' exist, the shorter sequence is ordered first (for ' +- 'example, "[1,2] <\n' +- ' [1,2,3]").\n' +- '\n' +- '* Mappings (dictionaries) compare equal if and only if ' +- 'their sorted\n' +- ' (key, value) lists compare equal. [5] Outcomes other than ' +- 'equality\n' +- ' are resolved consistently, but are not otherwise defined. ' +- '[6]\n' +- '\n' +- '* Most other objects of built-in types compare unequal ' +- 'unless they\n' +- ' are the same object; the choice whether one object is ' +- 'considered\n' +- ' smaller or larger than another one is made arbitrarily ' +- 'but\n' +- ' consistently within one execution of a program.\n' +- '\n' +- 'The operators "in" and "not in" test for collection ' +- 'membership. "x in\n' +- 's" evaluates to true if *x* is a member of the collection ' +- '*s*, and\n' +- 'false otherwise. "x not in s" returns the negation of "x ' +- 'in s". The\n' +- 'collection membership test has traditionally been bound to ' +- 'sequences;\n' +- 'an object is a member of a collection if the collection is ' +- 'a sequence\n' +- 'and contains an element equal to that object. However, it ' +- 'make sense\n' +- 'for many other object types to support membership tests ' +- 'without being\n' +- 'a sequence. In particular, dictionaries (for keys) and ' +- 'sets support\n' +- 'membership testing.\n' +- '\n' +- 'For the list and tuple types, "x in y" is true if and only ' +- 'if there\n' +- 'exists an index *i* such that "x == y[i]" is true.\n' +- '\n' +- 'For the Unicode and string types, "x in y" is true if and ' +- 'only if *x*\n' +- 'is a substring of *y*. An equivalent test is "y.find(x) != ' +- '-1".\n' +- 'Note, *x* and *y* need not be the same type; consequently, ' +- '"u\'ab\' in\n' +- '\'abc\'" will return "True". Empty strings are always ' +- 'considered to be a\n' +- 'substring of any other string, so """ in "abc"" will return ' +- '"True".\n' +- '\n' +- 'Changed in version 2.3: Previously, *x* was required to be ' +- 'a string of\n' +- 'length "1".\n' +- '\n' +- 'For user-defined classes which define the "__contains__()" ' +- 'method, "x\n' +- 'in y" is true if and only if "y.__contains__(x)" is true.\n' +- '\n' +- 'For user-defined classes which do not define ' +- '"__contains__()" but do\n' +- 'define "__iter__()", "x in y" is true if some value "z" ' +- 'with "x == z"\n' +- 'is produced while iterating over "y". If an exception is ' +- 'raised\n' +- 'during the iteration, it is as if "in" raised that ' +- 'exception.\n' +- '\n' +- 'Lastly, the old-style iteration protocol is tried: if a ' +- 'class defines\n' +- '"__getitem__()", "x in y" is true if and only if there is a ' +- 'non-\n' +- 'negative integer index *i* such that "x == y[i]", and all ' +- 'lower\n' +- 'integer indices do not raise "IndexError" exception. (If ' +- 'any other\n' +- 'exception is raised, it is as if "in" raised that ' +- 'exception).\n' +- '\n' +- 'The operator "not in" is defined to have the inverse true ' +- 'value of\n' +- '"in".\n' +- '\n' +- 'The operators "is" and "is not" test for object identity: ' +- '"x is y" is\n' +- 'true if and only if *x* and *y* are the same object. "x is ' +- 'not y"\n' +- 'yields the inverse truth value. [7]\n', +- 'compound': '\n' +- 'Compound statements\n' +- '*******************\n' +- '\n' +- 'Compound statements contain (groups of) other statements; they ' +- 'affect\n' +- 'or control the execution of those other statements in some ' +- 'way. In\n' +- 'general, compound statements span multiple lines, although in ' +- 'simple\n' +- 'incarnations a whole compound statement may be contained in ' +- 'one line.\n' +- '\n' +- 'The "if", "while" and "for" statements implement traditional ' +- 'control\n' +- 'flow constructs. "try" specifies exception handlers and/or ' +- 'cleanup\n' +- 'code for a group of statements. Function and class ' +- 'definitions are\n' +- 'also syntactically compound statements.\n' +- '\n' +- "Compound statements consist of one or more 'clauses.' A " +- 'clause\n' +- "consists of a header and a 'suite.' The clause headers of a\n" +- 'particular compound statement are all at the same indentation ' +- 'level.\n' +- 'Each clause header begins with a uniquely identifying keyword ' +- 'and ends\n' +- 'with a colon. A suite is a group of statements controlled by ' +- 'a\n' +- 'clause. A suite can be one or more semicolon-separated ' +- 'simple\n' +- 'statements on the same line as the header, following the ' +- "header's\n" +- 'colon, or it can be one or more indented statements on ' +- 'subsequent\n' +- 'lines. Only the latter form of suite can contain nested ' +- 'compound\n' +- 'statements; the following is illegal, mostly because it ' +- "wouldn't be\n" +- 'clear to which "if" clause a following "else" clause would ' +- 'belong:\n' +- '\n' +- ' if test1: if test2: print x\n' +- '\n' +- 'Also note that the semicolon binds tighter than the colon in ' +- 'this\n' +- 'context, so that in the following example, either all or none ' +- 'of the\n' +- '"print" statements are executed:\n' +- '\n' +- ' if x < y < z: print x; print y; print z\n' +- '\n' +- 'Summarizing:\n' +- '\n' +- ' compound_stmt ::= if_stmt\n' +- ' | while_stmt\n' +- ' | for_stmt\n' +- ' | try_stmt\n' +- ' | with_stmt\n' +- ' | funcdef\n' +- ' | classdef\n' +- ' | decorated\n' +- ' suite ::= stmt_list NEWLINE | NEWLINE INDENT ' +- 'statement+ DEDENT\n' +- ' statement ::= stmt_list NEWLINE | compound_stmt\n' +- ' stmt_list ::= simple_stmt (";" simple_stmt)* [";"]\n' +- '\n' +- 'Note that statements always end in a "NEWLINE" possibly ' +- 'followed by a\n' +- '"DEDENT". Also note that optional continuation clauses always ' +- 'begin\n' +- 'with a keyword that cannot start a statement, thus there are ' +- 'no\n' +- 'ambiguities (the \'dangling "else"\' problem is solved in ' +- 'Python by\n' +- 'requiring nested "if" statements to be indented).\n' +- '\n' +- 'The formatting of the grammar rules in the following sections ' +- 'places\n' +- 'each clause on a separate line for clarity.\n' +- '\n' +- '\n' +- 'The "if" statement\n' +- '==================\n' +- '\n' +- 'The "if" statement is used for conditional execution:\n' +- '\n' +- ' if_stmt ::= "if" expression ":" suite\n' +- ' ( "elif" expression ":" suite )*\n' +- ' ["else" ":" suite]\n' +- '\n' +- 'It selects exactly one of the suites by evaluating the ' +- 'expressions one\n' +- 'by one until one is found to be true (see section Boolean ' +- 'operations\n' +- 'for the definition of true and false); then that suite is ' +- 'executed\n' +- '(and no other part of the "if" statement is executed or ' +- 'evaluated).\n' +- 'If all expressions are false, the suite of the "else" clause, ' +- 'if\n' +- 'present, is executed.\n' +- '\n' +- '\n' +- 'The "while" statement\n' +- '=====================\n' +- '\n' +- 'The "while" statement is used for repeated execution as long ' +- 'as an\n' +- 'expression is true:\n' +- '\n' +- ' while_stmt ::= "while" expression ":" suite\n' +- ' ["else" ":" suite]\n' +- '\n' +- 'This repeatedly tests the expression and, if it is true, ' +- 'executes the\n' +- 'first suite; if the expression is false (which may be the ' +- 'first time\n' +- 'it is tested) the suite of the "else" clause, if present, is ' +- 'executed\n' +- 'and the loop terminates.\n' +- '\n' +- 'A "break" statement executed in the first suite terminates the ' +- 'loop\n' +- 'without executing the "else" clause\'s suite. A "continue" ' +- 'statement\n' +- 'executed in the first suite skips the rest of the suite and ' +- 'goes back\n' +- 'to testing the expression.\n' +- '\n' +- '\n' +- 'The "for" statement\n' +- '===================\n' +- '\n' +- 'The "for" statement is used to iterate over the elements of a ' +- 'sequence\n' +- '(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' +- '\n' +- 'The expression list is evaluated once; it should yield an ' +- 'iterable\n' +- 'object. An iterator is created for the result of the\n' +- '"expression_list". The suite is then executed once for each ' +- 'item\n' +- 'provided by the iterator, in the order of ascending indices. ' +- 'Each\n' +- 'item in turn is assigned to the target list using the standard ' +- 'rules\n' +- 'for assignments, and then the suite is executed. When the ' +- 'items are\n' +- 'exhausted (which is immediately when the sequence is empty), ' +- 'the suite\n' +- 'in the "else" clause, if present, is executed, and the loop\n' +- 'terminates.\n' +- '\n' +- 'A "break" statement executed in the first suite terminates the ' +- 'loop\n' +- 'without executing the "else" clause\'s suite. A "continue" ' +- 'statement\n' +- 'executed in the first suite skips the rest of the suite and ' +- 'continues\n' +- 'with the next item, or with the "else" clause if there was no ' +- 'next\n' +- 'item.\n' +- '\n' +- 'The suite may assign to the variable(s) in the target list; ' +- 'this does\n' +- 'not affect the next item assigned to it.\n' +- '\n' +- 'The target list is not deleted when the loop is finished, but ' +- 'if the\n' +- 'sequence is empty, it will not have been assigned to at all by ' +- 'the\n' +- 'loop. Hint: the built-in function "range()" returns a ' +- 'sequence of\n' +- 'integers suitable to emulate the effect of Pascal\'s "for i := ' +- 'a to b\n' +- 'do"; e.g., "range(3)" returns the list "[0, 1, 2]".\n' +- '\n' +- 'Note: There is a subtlety when the sequence is being modified ' +- 'by the\n' +- ' loop (this can only occur for mutable sequences, i.e. ' +- 'lists). An\n' +- ' internal counter is used to keep track of which item is used ' +- 'next,\n' +- ' and this is incremented on each iteration. When this ' +- 'counter has\n' +- ' reached the length of the sequence the loop terminates. ' +- 'This means\n' +- ' that if the suite deletes the current (or a previous) item ' +- 'from the\n' +- ' sequence, the next item will be skipped (since it gets the ' +- 'index of\n' +- ' the 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' +- '\n' +- '\n' +- 'The "try" statement\n' +- '===================\n' +- '\n' +- 'The "try" statement specifies exception handlers and/or ' +- 'cleanup code\n' +- 'for a group of statements:\n' +- '\n' +- ' try_stmt ::= try1_stmt | try2_stmt\n' +- ' try1_stmt ::= "try" ":" suite\n' +- ' ("except" [expression [("as" | ",") ' +- 'identifier]] ":" suite)+\n' +- ' ["else" ":" suite]\n' +- ' ["finally" ":" suite]\n' +- ' try2_stmt ::= "try" ":" suite\n' +- ' "finally" ":" suite\n' +- '\n' +- 'Changed in version 2.5: In previous versions of Python,\n' +- '"try"..."except"..."finally" did not work. "try"..."except" ' +- 'had to be\n' +- 'nested in "try"..."finally".\n' +- '\n' +- 'The "except" clause(s) specify one or more exception handlers. ' +- 'When no\n' +- 'exception occurs in the "try" clause, no exception handler is\n' +- 'executed. When an exception occurs in the "try" suite, a ' +- 'search for an\n' +- 'exception handler is started. This search inspects the except ' +- 'clauses\n' +- 'in turn until one is found that matches the exception. An ' +- 'expression-\n' +- 'less except clause, if present, must be last; it matches any\n' +- 'exception. For an except clause with an expression, that ' +- 'expression\n' +- 'is evaluated, and the clause matches the exception if the ' +- 'resulting\n' +- 'object is "compatible" with the exception. An object is ' +- 'compatible\n' +- 'with an exception if it is the class or a base class of the ' +- 'exception\n' +- 'object, or a tuple containing an item compatible with the ' +- 'exception.\n' +- '\n' +- 'If no except clause matches the exception, the search for an ' +- 'exception\n' +- 'handler continues in the surrounding code and on the ' +- 'invocation stack.\n' +- '[1]\n' +- '\n' +- 'If the evaluation of an expression in the header of an except ' +- 'clause\n' +- 'raises an exception, the original search for a handler is ' +- 'canceled and\n' +- 'a search starts for the new exception in the surrounding code ' +- 'and on\n' +- 'the call stack (it is treated as if the entire "try" statement ' +- 'raised\n' +- 'the exception).\n' +- '\n' +- 'When a matching except clause is found, the exception is ' +- 'assigned to\n' +- 'the target specified in that except clause, if present, and ' +- 'the except\n' +- "clause's suite is executed. All except clauses must have an\n" +- 'executable block. When the end of this block is reached, ' +- 'execution\n' +- 'continues normally after the entire try statement. (This ' +- 'means that\n' +- 'if two nested handlers exist for the same exception, and the ' +- 'exception\n' +- 'occurs in the try clause of the inner handler, the outer ' +- 'handler will\n' +- 'not handle the exception.)\n' +- '\n' +- "Before an except clause's suite is executed, details about " +- 'the\n' +- 'exception 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\n' +- 'standard type hierarchy) identifying the point in the program ' +- 'where\n' +- 'the exception occurred. These details are also available ' +- 'through the\n' +- '"sys.exc_info()" function, which returns a tuple "(exc_type,\n' +- 'exc_value, exc_traceback)". Use of the corresponding ' +- 'variables is\n' +- 'deprecated in favor of this function, since their use is ' +- 'unsafe in a\n' +- 'threaded program. As of Python 1.5, the variables are ' +- 'restored to\n' +- 'their previous values (before the call) when returning from a ' +- 'function\n' +- 'that handled an exception.\n' +- '\n' +- 'The optional "else" clause is executed if and when control ' +- 'flows off\n' +- 'the end of the "try" clause. [2] Exceptions in the "else" ' +- 'clause are\n' +- 'not handled by the preceding "except" clauses.\n' +- '\n' +- 'If "finally" is present, it specifies a \'cleanup\' handler. ' +- 'The "try"\n' +- 'clause is executed, including any "except" and "else" ' +- 'clauses. If an\n' +- 'exception occurs in any of the clauses and is not handled, ' +- 'the\n' +- 'exception is temporarily saved. The "finally" clause is ' +- 'executed. If\n' +- 'there is a saved exception, it is re-raised at the end of the\n' +- '"finally" clause. If the "finally" clause raises another ' +- 'exception or\n' +- 'executes a "return" or "break" statement, the saved exception ' +- 'is\n' +- 'discarded:\n' +- '\n' +- ' >>> def f():\n' +- ' ... try:\n' +- ' ... 1/0\n' +- ' ... finally:\n' +- ' ... return 42\n' +- ' ...\n' +- ' >>> f()\n' +- ' 42\n' +- '\n' +- 'The exception information is not available to the program ' +- 'during\n' +- 'execution of the "finally" clause.\n' +- '\n' +- 'When a "return", "break" or "continue" statement is executed ' +- 'in the\n' +- '"try" suite of a "try"..."finally" statement, the "finally" ' +- 'clause is\n' +- 'also executed \'on the way out.\' A "continue" statement is ' +- 'illegal in\n' +- 'the "finally" clause. (The reason is a problem with the ' +- 'current\n' +- 'implementation --- this restriction may be lifted in the ' +- 'future).\n' +- '\n' +- 'The return value of a function is determined by the last ' +- '"return"\n' +- 'statement executed. Since the "finally" clause always ' +- 'executes, a\n' +- '"return" statement executed in the "finally" clause will ' +- 'always be the\n' +- 'last one executed:\n' +- '\n' +- ' >>> def foo():\n' +- ' ... try:\n' +- " ... return 'try'\n" +- ' ... finally:\n' +- " ... return 'finally'\n" +- ' ...\n' +- ' >>> foo()\n' +- " 'finally'\n" +- '\n' +- 'Additional information on exceptions can be found in section\n' +- 'Exceptions, and information on using the "raise" statement to ' +- 'generate\n' +- 'exceptions may be found in section The raise statement.\n' +- '\n' +- '\n' +- 'The "with" statement\n' +- '====================\n' +- '\n' +- 'New in version 2.5.\n' +- '\n' +- 'The "with" statement is used to wrap the execution of a block ' +- 'with\n' +- 'methods defined by a context manager (see section With ' +- 'Statement\n' +- 'Context Managers). This allows common ' +- '"try"..."except"..."finally"\n' +- 'usage patterns to be encapsulated for convenient reuse.\n' +- '\n' +- ' with_stmt ::= "with" with_item ("," with_item)* ":" suite\n' +- ' with_item ::= expression ["as" target]\n' +- '\n' +- 'The execution of the "with" statement with one "item" proceeds ' +- 'as\n' +- 'follows:\n' +- '\n' +- '1. The context expression (the expression given in the ' +- '"with_item")\n' +- ' is evaluated to obtain a context manager.\n' +- '\n' +- '2. The context manager\'s "__exit__()" is loaded for later ' +- 'use.\n' +- '\n' +- '3. The context manager\'s "__enter__()" method is invoked.\n' +- '\n' +- '4. 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 be\n' +- ' 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' +- '\n' +- '5. The suite is executed.\n' +- '\n' +- '6. 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, three\n' +- ' "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 ' +- 'reraised.\n' +- ' If the return value was true, the exception is suppressed, ' +- 'and\n' +- ' execution continues with the statement following the ' +- '"with"\n' +- ' 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' +- '\n' +- 'With more than one item, the context managers are processed as ' +- 'if\n' +- 'multiple "with" statements were nested:\n' +- '\n' +- ' with A() as a, B() as b:\n' +- ' suite\n' +- '\n' +- 'is equivalent to\n' +- '\n' +- ' with A() as a:\n' +- ' with B() as b:\n' +- ' suite\n' +- '\n' +- 'Note: In Python 2.5, the "with" statement is only allowed when ' +- 'the\n' +- ' "with_statement" feature has been enabled. It is always ' +- 'enabled in\n' +- ' Python 2.6.\n' +- '\n' +- 'Changed in version 2.7: Support for multiple context ' +- 'expressions.\n' +- '\n' +- 'See also: **PEP 0343** - The "with" statement\n' +- '\n' +- ' The specification, background, and examples for the ' +- 'Python "with"\n' +- ' statement.\n' +- '\n' +- '\n' +- 'Function definitions\n' +- '====================\n' +- '\n' +- 'A function definition defines a user-defined function object ' +- '(see\n' +- 'section 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' +- '\n' +- 'A function definition is an executable statement. Its ' +- 'execution binds\n' +- 'the function name in the current local namespace to a function ' +- 'object\n' +- '(a wrapper around the executable code for the function). ' +- 'This\n' +- 'function object contains a reference to the current global ' +- 'namespace\n' +- 'as the global namespace to be used when the function is ' +- 'called.\n' +- '\n' +- 'The function definition does not execute the function body; ' +- 'this gets\n' +- 'executed only when the function is called. [3]\n' +- '\n' +- 'A function definition may be wrapped by one or more ' +- '*decorator*\n' +- 'expressions. Decorator expressions are evaluated when the ' +- 'function is\n' +- 'defined, in the scope that contains the function definition. ' +- 'The\n' +- 'result must be a callable, which is invoked with the function ' +- 'object\n' +- 'as the only argument. The returned value is bound to the ' +- 'function name\n' +- 'instead of the function object. Multiple decorators are ' +- 'applied in\n' +- 'nested fashion. For example, the following code:\n' +- '\n' +- ' @f1(arg)\n' +- ' @f2\n' +- ' def func(): pass\n' +- '\n' +- 'is equivalent to:\n' +- '\n' +- ' def func(): pass\n' +- ' func = f1(arg)(f2(func))\n' +- '\n' +- 'When one or more top-level *parameters* have the form ' +- '*parameter* "="\n' +- '*expression*, the function is said to have "default parameter ' +- 'values."\n' +- 'For a parameter with a default value, the corresponding ' +- '*argument* may\n' +- "be omitted from a call, in which case the parameter's default " +- 'value is\n' +- 'substituted. If a parameter has a default value, all ' +- 'following\n' +- 'parameters must also have a default value --- this is a ' +- 'syntactic\n' +- 'restriction that is not expressed by the grammar.\n' +- '\n' +- '**Default parameter values are evaluated when the function ' +- 'definition\n' +- 'is executed.** This means that the expression is evaluated ' +- 'once, when\n' +- 'the function is defined, and that the same "pre-computed" ' +- 'value is\n' +- 'used for each call. This is especially important to ' +- 'understand when a\n' +- 'default parameter is a mutable object, such as a list or a ' +- 'dictionary:\n' +- 'if the function modifies the object (e.g. by appending an item ' +- 'to a\n' +- 'list), the default value is in effect modified. This is ' +- 'generally not\n' +- 'what was intended. A way around this is to use "None" as ' +- 'the\n' +- 'default, 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' +- '\n' +- 'Function call semantics are described in more detail in ' +- 'section Calls.\n' +- 'A function call always assigns values to all parameters ' +- 'mentioned in\n' +- 'the parameter list, either from position arguments, from ' +- 'keyword\n' +- 'arguments, or from default values. If the form ' +- '""*identifier"" is\n' +- 'present, it is initialized to a tuple receiving any excess ' +- 'positional\n' +- 'parameters, defaulting to the empty tuple. If the form\n' +- '""**identifier"" is present, it is initialized to a new ' +- 'dictionary\n' +- 'receiving any excess keyword arguments, defaulting to a new ' +- 'empty\n' +- 'dictionary.\n' +- '\n' +- 'It is also possible to create anonymous functions (functions ' +- 'not bound\n' +- 'to a name), for immediate use in expressions. This uses ' +- 'lambda\n' +- 'expressions, described in section Lambdas. Note that the ' +- 'lambda\n' +- 'expression is merely a shorthand for a simplified function ' +- 'definition;\n' +- 'a function defined in a ""def"" statement can be passed around ' +- 'or\n' +- 'assigned to another name just like a function defined by a ' +- 'lambda\n' +- 'expression. The ""def"" form is actually more powerful since ' +- 'it\n' +- 'allows the execution of multiple statements.\n' +- '\n' +- "**Programmer's note:** Functions are first-class objects. A " +- '""def""\n' +- 'form executed inside a function definition defines a local ' +- 'function\n' +- 'that can be returned or passed around. Free variables used in ' +- 'the\n' +- 'nested function can access the local variables of the ' +- 'function\n' +- 'containing the def. See section Naming and binding for ' +- 'details.\n' +- '\n' +- '\n' +- 'Class definitions\n' +- '=================\n' +- '\n' +- 'A class definition defines a class object (see section The ' +- 'standard\n' +- 'type hierarchy):\n' +- '\n' +- ' classdef ::= "class" classname [inheritance] ":" suite\n' +- ' inheritance ::= "(" [expression_list] ")"\n' +- ' classname ::= identifier\n' +- '\n' +- 'A class definition is an executable statement. It first ' +- 'evaluates the\n' +- 'inheritance list, if present. Each item in the inheritance ' +- 'list\n' +- 'should evaluate to a class object or class type which allows\n' +- "subclassing. The class's suite is then executed in a new " +- 'execution\n' +- 'frame (see section Naming and binding), using a newly created ' +- 'local\n' +- 'namespace and the original global namespace. (Usually, the ' +- 'suite\n' +- "contains only function definitions.) When the class's suite " +- 'finishes\n' +- 'execution, its execution frame is discarded but its local ' +- 'namespace is\n' +- 'saved. [4] A class object is then created using the ' +- 'inheritance list\n' +- 'for the base classes and the saved local namespace for the ' +- 'attribute\n' +- 'dictionary. The class name is bound to this class object in ' +- 'the\n' +- 'original local namespace.\n' +- '\n' +- "**Programmer's note:** Variables defined in the class " +- 'definition are\n' +- 'class variables; they are shared by all instances. To create ' +- 'instance\n' +- 'variables, they can be set in a method with "self.name = ' +- 'value". Both\n' +- 'class and instance variables are accessible through the ' +- 'notation\n' +- '""self.name"", and an instance variable hides a class variable ' +- 'with\n' +- 'the same name when accessed in this way. Class variables can ' +- 'be used\n' +- 'as defaults for instance variables, but using mutable values ' +- 'there can\n' +- 'lead to unexpected results. For *new-style class*es, ' +- 'descriptors can\n' +- 'be used to create instance variables with different ' +- 'implementation\n' +- 'details.\n' +- '\n' +- 'Class definitions, like function definitions, may be wrapped ' +- 'by one or\n' +- 'more *decorator* expressions. The evaluation rules for the ' +- 'decorator\n' +- 'expressions are the same as for functions. The result must be ' +- 'a class\n' +- 'object, which is then bound to the class name.\n' +- '\n' +- '-[ Footnotes ]-\n' +- '\n' +- '[1] The exception is propagated to the invocation stack ' +- 'unless\n' +- ' there is a "finally" clause which happens to raise ' +- 'another\n' +- ' exception. That new exception causes the old one to be ' +- 'lost.\n' +- '\n' +- '[2] Currently, control "flows off the end" except in the case ' +- 'of\n' +- ' an exception or the execution of a "return", "continue", ' +- 'or\n' +- ' "break" statement.\n' +- '\n' +- '[3] A string literal appearing as the first statement in the\n' +- " function body is transformed into the function's " +- '"__doc__"\n' +- " attribute and therefore the function's *docstring*.\n" +- '\n' +- '[4] A string literal appearing as the first statement in the ' +- 'class\n' +- ' body is transformed into the namespace\'s "__doc__" item ' +- 'and\n' +- " therefore the class's *docstring*.\n", +- 'context-managers': '\n' +- 'With Statement Context Managers\n' +- '*******************************\n' +- '\n' +- 'New in version 2.5.\n' +- '\n' +- 'A *context manager* is an object that defines the ' +- 'runtime context to\n' +- 'be established when executing a "with" statement. The ' +- 'context manager\n' +- 'handles the entry into, and the exit from, the desired ' +- 'runtime context\n' +- 'for the execution of the block of code. Context ' +- 'managers are normally\n' +- 'invoked using the "with" statement (described in ' +- 'section The with\n' +- 'statement), but can also be used by directly invoking ' +- 'their methods.\n' +- '\n' +- 'Typical uses of context managers include saving and ' +- 'restoring various\n' +- 'kinds of global state, locking and unlocking ' +- 'resources, closing opened\n' +- 'files, etc.\n' +- '\n' +- 'For more information on context managers, see Context ' +- 'Manager Types.\n' +- '\n' +- 'object.__enter__(self)\n' +- '\n' +- ' Enter the runtime context related to this object. ' +- 'The "with"\n' +- " statement will bind this method's return value to " +- 'the target(s)\n' +- ' specified in the "as" clause of the statement, if ' +- 'any.\n' +- '\n' +- 'object.__exit__(self, exc_type, exc_value, traceback)\n' +- '\n' +- ' Exit the runtime context related to this object. ' +- 'The parameters\n' +- ' describe the exception that caused the context to ' +- 'be exited. If the\n' +- ' context was exited without an exception, all three ' +- 'arguments will\n' +- ' be "None".\n' +- '\n' +- ' If an exception is supplied, and the method wishes ' +- 'to suppress the\n' +- ' exception (i.e., prevent it from being propagated), ' +- 'it should\n' +- ' return a true value. Otherwise, the exception will ' +- 'be processed\n' +- ' normally upon exit from this method.\n' +- '\n' +- ' Note that "__exit__()" methods should not reraise ' +- 'the passed-in\n' +- " exception; this is the caller's responsibility.\n" +- '\n' +- 'See also: **PEP 0343** - The "with" statement\n' +- '\n' +- ' The specification, background, and examples for ' +- 'the Python "with"\n' +- ' statement.\n', +- 'continue': '\n' +- 'The "continue" statement\n' +- '************************\n' +- '\n' +- ' continue_stmt ::= "continue"\n' +- '\n' +- '"continue" may only occur syntactically nested in a "for" or ' +- '"while"\n' +- 'loop, but not nested in a function or class definition or ' +- '"finally"\n' +- 'clause within that loop. It continues with the next cycle of ' +- 'the\n' +- 'nearest enclosing loop.\n' +- '\n' +- 'When "continue" passes control out of a "try" statement with ' +- 'a\n' +- '"finally" clause, that "finally" clause is executed before ' +- 'really\n' +- 'starting the next loop cycle.\n', +- 'conversions': '\n' +- 'Arithmetic conversions\n' +- '**********************\n' +- '\n' +- 'When a description of an arithmetic operator below uses the ' +- 'phrase\n' +- '"the numeric arguments are converted to a common type," the ' +- 'arguments\n' +- 'are coerced using the coercion rules listed at Coercion ' +- 'rules. If\n' +- 'both arguments are standard numeric types, the following ' +- 'coercions are\n' +- 'applied:\n' +- '\n' +- '* If either argument is a complex number, the other is ' +- 'converted to\n' +- ' complex;\n' +- '\n' +- '* otherwise, if either argument is a floating point number, ' +- 'the\n' +- ' other is converted to floating point;\n' +- '\n' +- '* otherwise, if either argument is a long integer, the ' +- 'other is\n' +- ' converted to long integer;\n' +- '\n' +- '* otherwise, both must be plain integers and no conversion ' +- 'is\n' +- ' necessary.\n' +- '\n' +- 'Some additional rules apply for certain operators (e.g., a ' +- 'string left\n' +- "argument to the '%' operator). Extensions can define their " +- 'own\n' +- 'coercions.\n', +- 'customization': '\n' +- 'Basic customization\n' +- '*******************\n' +- '\n' +- 'object.__new__(cls[, ...])\n' +- '\n' +- ' Called to create a new instance of class *cls*. ' +- '"__new__()" is a\n' +- ' static method (special-cased so you need not declare ' +- 'it as such)\n' +- ' that takes the class of which an instance was ' +- 'requested as its\n' +- ' first argument. The remaining arguments are those ' +- 'passed to the\n' +- ' object constructor expression (the call to the ' +- 'class). The return\n' +- ' value of "__new__()" should be the new object instance ' +- '(usually an\n' +- ' instance of *cls*).\n' +- '\n' +- ' Typical implementations create a new instance of the ' +- 'class by\n' +- ' invoking the superclass\'s "__new__()" method using\n' +- ' "super(currentclass, cls).__new__(cls[, ...])" with ' +- 'appropriate\n' +- ' arguments and then modifying the newly-created ' +- 'instance as\n' +- ' necessary before returning it.\n' +- '\n' +- ' If "__new__()" returns an instance of *cls*, then the ' +- 'new\n' +- ' instance\'s "__init__()" method will be invoked like\n' +- ' "__init__(self[, ...])", where *self* is the new ' +- 'instance and the\n' +- ' remaining arguments are the same as were passed to ' +- '"__new__()".\n' +- '\n' +- ' If "__new__()" does not return an instance of *cls*, ' +- 'then the new\n' +- ' instance\'s "__init__()" method will not be invoked.\n' +- '\n' +- ' "__new__()" is intended mainly to allow subclasses of ' +- 'immutable\n' +- ' types (like int, str, or tuple) to customize instance ' +- 'creation. It\n' +- ' is also commonly overridden in custom metaclasses in ' +- 'order to\n' +- ' customize class creation.\n' +- '\n' +- 'object.__init__(self[, ...])\n' +- '\n' +- ' Called after the instance has been created (by ' +- '"__new__()"), but\n' +- ' before it is returned to the caller. The arguments ' +- 'are those\n' +- ' passed to the class constructor expression. If a base ' +- 'class has an\n' +- ' "__init__()" method, the derived class\'s "__init__()" ' +- 'method, if\n' +- ' any, must explicitly call it to ensure proper ' +- 'initialization of the\n' +- ' base class part of the instance; for example:\n' +- ' "BaseClass.__init__(self, [args...])".\n' +- '\n' +- ' Because "__new__()" and "__init__()" work together in ' +- 'constructing\n' +- ' objects ("__new__()" to create it, and "__init__()" to ' +- 'customise\n' +- ' it), no non-"None" value may be returned by ' +- '"__init__()"; doing so\n' +- ' will cause a "TypeError" to be raised at runtime.\n' +- '\n' +- 'object.__del__(self)\n' +- '\n' +- ' Called when the instance is about to be destroyed. ' +- 'This is also\n' +- ' called a destructor. If a base class has a ' +- '"__del__()" method, the\n' +- ' derived class\'s "__del__()" method, if any, must ' +- 'explicitly call it\n' +- ' to ensure proper deletion of the base class part of ' +- 'the instance.\n' +- ' Note that it is possible (though not recommended!) for ' +- 'the\n' +- ' "__del__()" method to postpone destruction of the ' +- 'instance by\n' +- ' creating a new reference to it. It may then be called ' +- 'at a later\n' +- ' time when this new reference is deleted. It is not ' +- 'guaranteed that\n' +- ' "__del__()" methods are called for objects that still ' +- 'exist when\n' +- ' the interpreter exits.\n' +- '\n' +- ' Note: "del x" doesn\'t directly call "x.__del__()" --- ' +- 'the former\n' +- ' decrements the reference count for "x" by one, and ' +- 'the latter is\n' +- ' only called when "x"\'s reference count reaches ' +- 'zero. Some common\n' +- ' situations that may prevent the reference count of ' +- 'an object from\n' +- ' going to zero include: circular references between ' +- 'objects (e.g.,\n' +- ' a doubly-linked list or a tree data structure with ' +- 'parent and\n' +- ' child pointers); a reference to the object on the ' +- 'stack frame of\n' +- ' a function that caught an exception (the traceback ' +- 'stored in\n' +- ' "sys.exc_traceback" keeps the stack frame alive); or ' +- 'a reference\n' +- ' to the object on the stack frame that raised an ' +- 'unhandled\n' +- ' exception in interactive mode (the traceback stored ' +- 'in\n' +- ' "sys.last_traceback" keeps the stack frame alive). ' +- 'The first\n' +- ' situation can only be remedied by explicitly ' +- 'breaking the cycles;\n' +- ' the latter two situations can be resolved by storing ' +- '"None" in\n' +- ' "sys.exc_traceback" or "sys.last_traceback". ' +- 'Circular references\n' +- ' which are garbage are detected when the option cycle ' +- 'detector is\n' +- " enabled (it's on by default), but can only be " +- 'cleaned up if there\n' +- ' are no Python-level "__del__()" methods involved. ' +- 'Refer to the\n' +- ' documentation for the "gc" module for more ' +- 'information about how\n' +- ' "__del__()" methods are handled by the cycle ' +- 'detector,\n' +- ' particularly the description of the "garbage" ' +- 'value.\n' +- '\n' +- ' Warning: Due to the precarious circumstances under ' +- 'which\n' +- ' "__del__()" methods are invoked, exceptions that ' +- 'occur during\n' +- ' their execution are ignored, and a warning is ' +- 'printed to\n' +- ' "sys.stderr" instead. Also, when "__del__()" is ' +- 'invoked in\n' +- ' response to a module being deleted (e.g., when ' +- 'execution of the\n' +- ' program is done), other globals referenced by the ' +- '"__del__()"\n' +- ' method may already have been deleted or in the ' +- 'process of being\n' +- ' torn down (e.g. the import machinery shutting ' +- 'down). For this\n' +- ' reason, "__del__()" methods should do the absolute ' +- 'minimum needed\n' +- ' to maintain external invariants. Starting with ' +- 'version 1.5,\n' +- ' Python guarantees that globals whose name begins ' +- 'with a single\n' +- ' underscore are deleted from their module before ' +- 'other globals are\n' +- ' deleted; if no other references to such globals ' +- 'exist, this may\n' +- ' help in assuring that imported modules are still ' +- 'available at the\n' +- ' time when the "__del__()" method is called.\n' +- '\n' +- ' See also the "-R" command-line option.\n' +- '\n' +- 'object.__repr__(self)\n' +- '\n' +- ' Called by the "repr()" built-in function and by string ' +- 'conversions\n' +- ' (reverse quotes) to compute the "official" string ' +- 'representation of\n' +- ' an object. If at all possible, this should look like ' +- 'a valid\n' +- ' Python expression that could be used to recreate an ' +- 'object with the\n' +- ' same value (given an appropriate environment). If ' +- 'this is not\n' +- ' possible, a string of the form "<...some useful ' +- 'description...>"\n' +- ' should be returned. The return value must be a string ' +- 'object. If a\n' +- ' class defines "__repr__()" but not "__str__()", then ' +- '"__repr__()"\n' +- ' is also used when an "informal" string representation ' +- 'of instances\n' +- ' of that class is required.\n' +- '\n' +- ' This is typically used for debugging, so it is ' +- 'important that the\n' +- ' representation is information-rich and unambiguous.\n' +- '\n' +- 'object.__str__(self)\n' +- '\n' +- ' Called by the "str()" built-in function and by the ' +- '"print"\n' +- ' statement to compute the "informal" string ' +- 'representation of an\n' +- ' object. This differs from "__repr__()" in that it ' +- 'does not have to\n' +- ' be a valid Python expression: a more convenient or ' +- 'concise\n' +- ' representation may be used instead. The return value ' +- 'must be a\n' +- ' string object.\n' +- '\n' +- 'object.__lt__(self, other)\n' +- 'object.__le__(self, other)\n' +- 'object.__eq__(self, other)\n' +- 'object.__ne__(self, other)\n' +- 'object.__gt__(self, other)\n' +- 'object.__ge__(self, other)\n' +- '\n' +- ' New in version 2.1.\n' +- '\n' +- ' These are the so-called "rich comparison" methods, and ' +- 'are called\n' +- ' for comparison operators in preference to "__cmp__()" ' +- 'below. The\n' +- ' correspondence between operator symbols and method ' +- 'names is as\n' +- ' follows: "xy" call ' +- '"x.__ne__(y)",\n' +- ' "x>y" calls "x.__gt__(y)", and "x>=y" calls ' +- '"x.__ge__(y)".\n' +- '\n' +- ' A rich comparison method may return the singleton ' +- '"NotImplemented"\n' +- ' if it does not implement the operation for a given ' +- 'pair of\n' +- ' arguments. By convention, "False" and "True" are ' +- 'returned for a\n' +- ' successful comparison. However, these methods can ' +- 'return any value,\n' +- ' so if the comparison operator is used in a Boolean ' +- 'context (e.g.,\n' +- ' in the condition of an "if" statement), Python will ' +- 'call "bool()"\n' +- ' on the value to determine if the result is true or ' +- 'false.\n' +- '\n' +- ' There are no implied relationships among the ' +- 'comparison operators.\n' +- ' The truth of "x==y" does not imply that "x!=y" is ' +- 'false.\n' +- ' Accordingly, when defining "__eq__()", one should also ' +- 'define\n' +- ' "__ne__()" so that the operators will behave as ' +- 'expected. See the\n' +- ' paragraph on "__hash__()" for some important notes on ' +- 'creating\n' +- ' *hashable* objects which support custom comparison ' +- 'operations and\n' +- ' are usable as dictionary keys.\n' +- '\n' +- ' There are no swapped-argument versions of these ' +- 'methods (to be used\n' +- ' when the left argument does not support the operation ' +- 'but the right\n' +- ' argument does); rather, "__lt__()" and "__gt__()" are ' +- "each other's\n" +- ' reflection, "__le__()" and "__ge__()" are each ' +- "other's reflection,\n" +- ' and "__eq__()" and "__ne__()" are their own ' +- 'reflection.\n' +- '\n' +- ' Arguments to rich comparison methods are never ' +- 'coerced.\n' +- '\n' +- ' To automatically generate ordering operations from a ' +- 'single root\n' +- ' operation, see "functools.total_ordering()".\n' +- '\n' +- 'object.__cmp__(self, other)\n' +- '\n' +- ' Called by comparison operations if rich comparison ' +- '(see above) is\n' +- ' not defined. Should return a negative integer if ' +- '"self < other",\n' +- ' zero if "self == other", a positive integer if "self > ' +- 'other". If\n' +- ' no "__cmp__()", "__eq__()" or "__ne__()" operation is ' +- 'defined,\n' +- ' class instances are compared by object identity ' +- '("address"). See\n' +- ' also the description of "__hash__()" for some ' +- 'important notes on\n' +- ' creating *hashable* objects which support custom ' +- 'comparison\n' +- ' operations and are usable as dictionary keys. (Note: ' +- 'the\n' +- ' restriction that exceptions are not propagated by ' +- '"__cmp__()" has\n' +- ' been removed since Python 1.5.)\n' +- '\n' +- 'object.__rcmp__(self, other)\n' +- '\n' +- ' Changed in version 2.1: No longer supported.\n' +- '\n' +- 'object.__hash__(self)\n' +- '\n' +- ' Called by built-in function "hash()" and for ' +- 'operations on members\n' +- ' of hashed collections including "set", "frozenset", ' +- 'and "dict".\n' +- ' "__hash__()" should return an integer. The only ' +- 'required property\n' +- ' is that objects which compare equal have the same hash ' +- 'value; it is\n' +- ' advised to somehow mix together (e.g. using exclusive ' +- 'or) the hash\n' +- ' values for the components of the object that also play ' +- 'a part in\n' +- ' comparison of objects.\n' +- '\n' +- ' If a class does not define a "__cmp__()" or "__eq__()" ' +- 'method it\n' +- ' should not define a "__hash__()" operation either; if ' +- 'it defines\n' +- ' "__cmp__()" or "__eq__()" but not "__hash__()", its ' +- 'instances will\n' +- ' not be usable in hashed collections. If a class ' +- 'defines mutable\n' +- ' objects and implements a "__cmp__()" or "__eq__()" ' +- 'method, it\n' +- ' should not implement "__hash__()", since hashable ' +- 'collection\n' +- " implementations require that a object's hash value is " +- 'immutable (if\n' +- " the object's hash value changes, it will be in the " +- 'wrong hash\n' +- ' bucket).\n' +- '\n' +- ' User-defined classes have "__cmp__()" and "__hash__()" ' +- 'methods by\n' +- ' default; with them, all objects compare unequal ' +- '(except with\n' +- ' themselves) and "x.__hash__()" returns a result ' +- 'derived from\n' +- ' "id(x)".\n' +- '\n' +- ' Classes which inherit a "__hash__()" method from a ' +- 'parent class but\n' +- ' change the meaning of "__cmp__()" or "__eq__()" such ' +- 'that the hash\n' +- ' value returned is no longer appropriate (e.g. by ' +- 'switching to a\n' +- ' value-based concept of equality instead of the default ' +- 'identity\n' +- ' based equality) can explicitly flag themselves as ' +- 'being unhashable\n' +- ' by setting "__hash__ = None" in the class definition. ' +- 'Doing so\n' +- ' means that not only will instances of the class raise ' +- 'an\n' +- ' appropriate "TypeError" when a program attempts to ' +- 'retrieve their\n' +- ' hash value, but they will also be correctly identified ' +- 'as\n' +- ' unhashable when checking "isinstance(obj, ' +- 'collections.Hashable)"\n' +- ' (unlike classes which define their own "__hash__()" to ' +- 'explicitly\n' +- ' raise "TypeError").\n' +- '\n' +- ' Changed in version 2.5: "__hash__()" may now also ' +- 'return a long\n' +- ' integer object; the 32-bit integer is then derived ' +- 'from the hash of\n' +- ' that object.\n' +- '\n' +- ' Changed in version 2.6: "__hash__" may now be set to ' +- '"None" to\n' +- ' explicitly flag instances of a class as unhashable.\n' +- '\n' +- 'object.__nonzero__(self)\n' +- '\n' +- ' Called to implement truth value testing and the ' +- 'built-in operation\n' +- ' "bool()"; should return "False" or "True", or their ' +- 'integer\n' +- ' equivalents "0" or "1". When this method is not ' +- 'defined,\n' +- ' "__len__()" is called, if it is defined, and the ' +- 'object is\n' +- ' considered true if its result is nonzero. If a class ' +- 'defines\n' +- ' neither "__len__()" nor "__nonzero__()", all its ' +- 'instances are\n' +- ' considered true.\n' +- '\n' +- 'object.__unicode__(self)\n' +- '\n' +- ' Called to implement "unicode()" built-in; should ' +- 'return a Unicode\n' +- ' object. When this method is not defined, string ' +- 'conversion is\n' +- ' attempted, and the result of string conversion is ' +- 'converted to\n' +- ' Unicode using the system default encoding.\n', +- 'debugger': '\n' +- '"pdb" --- The Python Debugger\n' +- '*****************************\n' +- '\n' +- '**Source code:** Lib/pdb.py\n' +- '\n' +- '======================================================================\n' +- '\n' +- 'The module "pdb" defines an interactive source code debugger ' +- 'for\n' +- 'Python programs. It supports setting (conditional) ' +- 'breakpoints and\n' +- 'single stepping at the source line level, inspection of stack ' +- 'frames,\n' +- 'source code listing, and evaluation of arbitrary Python code ' +- 'in the\n' +- 'context of any stack frame. It also supports post-mortem ' +- 'debugging\n' +- 'and can be called under program control.\n' +- '\n' +- 'The debugger is extensible --- it is actually defined as the ' +- 'class\n' +- '"Pdb". This is currently undocumented but easily understood by ' +- 'reading\n' +- 'the source. The extension interface uses the modules "bdb" ' +- 'and "cmd".\n' +- '\n' +- 'The debugger\'s prompt is "(Pdb)". Typical usage to run a ' +- 'program under\n' +- 'control of the debugger is:\n' +- '\n' +- ' >>> import pdb\n' +- ' >>> import mymodule\n' +- " >>> pdb.run('mymodule.test()')\n" +- ' > (0)?()\n' +- ' (Pdb) continue\n' +- ' > (1)?()\n' +- ' (Pdb) continue\n' +- " NameError: 'spam'\n" +- ' > (1)?()\n' +- ' (Pdb)\n' +- '\n' +- '"pdb.py" can also be invoked as a script to debug other ' +- 'scripts. For\n' +- 'example:\n' +- '\n' +- ' python -m pdb myscript.py\n' +- '\n' +- 'When invoked as a script, pdb will automatically enter ' +- 'post-mortem\n' +- 'debugging if the program being debugged exits abnormally. ' +- 'After post-\n' +- 'mortem debugging (or after normal exit of the program), pdb ' +- 'will\n' +- "restart the program. Automatic restarting preserves pdb's " +- 'state (such\n' +- 'as breakpoints) and in most cases is more useful than quitting ' +- 'the\n' +- "debugger upon program's exit.\n" +- '\n' +- 'New in version 2.4: Restarting post-mortem behavior added.\n' +- '\n' +- 'The typical usage to break into the debugger from a running ' +- 'program is\n' +- 'to insert\n' +- '\n' +- ' import pdb; pdb.set_trace()\n' +- '\n' +- 'at the location you want to break into the debugger. You can ' +- 'then\n' +- 'step through the code following this statement, and continue ' +- 'running\n' +- 'without the debugger using the "c" command.\n' +- '\n' +- 'The typical usage to inspect a crashed program is:\n' +- '\n' +- ' >>> import pdb\n' +- ' >>> import mymodule\n' +- ' >>> mymodule.test()\n' +- ' Traceback (most recent call last):\n' +- ' File "", line 1, in ?\n' +- ' File "./mymodule.py", line 4, in test\n' +- ' test2()\n' +- ' File "./mymodule.py", line 3, in test2\n' +- ' print spam\n' +- ' NameError: spam\n' +- ' >>> pdb.pm()\n' +- ' > ./mymodule.py(3)test2()\n' +- ' -> print spam\n' +- ' (Pdb)\n' +- '\n' +- 'The module defines the following functions; each enters the ' +- 'debugger\n' +- 'in a slightly different way:\n' +- '\n' +- 'pdb.run(statement[, globals[, locals]])\n' +- '\n' +- ' Execute the *statement* (given as a string) under debugger ' +- 'control.\n' +- ' The debugger prompt appears before any code is executed; ' +- 'you can\n' +- ' set breakpoints and type "continue", or you can step ' +- 'through the\n' +- ' statement using "step" or "next" (all these commands are ' +- 'explained\n' +- ' below). The optional *globals* and *locals* arguments ' +- 'specify the\n' +- ' environment in which the code is executed; by default the\n' +- ' dictionary of the module "__main__" is used. (See the ' +- 'explanation\n' +- ' of the "exec" statement or the "eval()" built-in ' +- 'function.)\n' +- '\n' +- 'pdb.runeval(expression[, globals[, locals]])\n' +- '\n' +- ' Evaluate the *expression* (given as a string) under ' +- 'debugger\n' +- ' control. When "runeval()" returns, it returns the value of ' +- 'the\n' +- ' expression. Otherwise this function is similar to ' +- '"run()".\n' +- '\n' +- 'pdb.runcall(function[, argument, ...])\n' +- '\n' +- ' Call the *function* (a function or method object, not a ' +- 'string)\n' +- ' with the given arguments. When "runcall()" returns, it ' +- 'returns\n' +- ' whatever the function call returned. The debugger prompt ' +- 'appears\n' +- ' as soon as the function is entered.\n' +- '\n' +- 'pdb.set_trace()\n' +- '\n' +- ' Enter the debugger at the calling stack frame. This is ' +- 'useful to\n' +- ' hard-code a breakpoint at a given point in a program, even ' +- 'if the\n' +- ' code is not otherwise being debugged (e.g. when an ' +- 'assertion\n' +- ' fails).\n' +- '\n' +- 'pdb.post_mortem([traceback])\n' +- '\n' +- ' Enter post-mortem debugging of the given *traceback* ' +- 'object. If no\n' +- ' *traceback* is given, it uses the one of the exception that ' +- 'is\n' +- ' currently being handled (an exception must be being handled ' +- 'if the\n' +- ' default is to be used).\n' +- '\n' +- 'pdb.pm()\n' +- '\n' +- ' Enter post-mortem debugging of the traceback found in\n' +- ' "sys.last_traceback".\n' +- '\n' +- 'The "run*" functions and "set_trace()" are aliases for ' +- 'instantiating\n' +- 'the "Pdb" class and calling the method of the same name. If ' +- 'you want\n' +- 'to access further features, you have to do this yourself:\n' +- '\n' +- "class class pdb.Pdb(completekey='tab', stdin=None, " +- 'stdout=None, skip=None)\n' +- '\n' +- ' "Pdb" is the debugger class.\n' +- '\n' +- ' The *completekey*, *stdin* and *stdout* arguments are ' +- 'passed to the\n' +- ' underlying "cmd.Cmd" class; see the description there.\n' +- '\n' +- ' The *skip* argument, if given, must be an iterable of ' +- 'glob-style\n' +- ' module name patterns. The debugger will not step into ' +- 'frames that\n' +- ' originate in a module that matches one of these patterns. ' +- '[1]\n' +- '\n' +- ' Example call to enable tracing with *skip*:\n' +- '\n' +- " import pdb; pdb.Pdb(skip=['django.*']).set_trace()\n" +- '\n' +- ' New in version 2.7: The *skip* argument.\n' +- '\n' +- ' run(statement[, globals[, locals]])\n' +- ' runeval(expression[, globals[, locals]])\n' +- ' runcall(function[, argument, ...])\n' +- ' set_trace()\n' +- '\n' +- ' See the documentation for the functions explained ' +- 'above.\n', +- 'del': '\n' +- 'The "del" statement\n' +- '*******************\n' +- '\n' +- ' del_stmt ::= "del" target_list\n' +- '\n' +- 'Deletion is recursively defined very similar to the way assignment ' +- 'is\n' +- 'defined. Rather than spelling it out in full details, here are ' +- 'some\n' +- 'hints.\n' +- '\n' +- 'Deletion of a target list recursively deletes each target, from ' +- 'left\n' +- 'to right.\n' +- '\n' +- 'Deletion of a name removes the binding of that name from the local ' +- 'or\n' +- 'global namespace, depending on whether the name occurs in a ' +- '"global"\n' +- 'statement in the same code block. If the name is unbound, a\n' +- '"NameError" exception will be raised.\n' +- '\n' +- 'It is illegal to delete a name from the local namespace if it ' +- 'occurs\n' +- 'as a free variable in a nested block.\n' +- '\n' +- 'Deletion of attribute references, subscriptions and slicings is ' +- 'passed\n' +- 'to the primary object involved; deletion of a slicing is in ' +- 'general\n' +- 'equivalent to assignment of an empty slice of the right type (but ' +- 'even\n' +- 'this is determined by the sliced object).\n', +- 'dict': '\n' +- 'Dictionary displays\n' +- '*******************\n' +- '\n' +- 'A dictionary display is a possibly empty series of key/datum ' +- 'pairs\n' +- 'enclosed in curly braces:\n' +- '\n' +- ' dict_display ::= "{" [key_datum_list | ' +- 'dict_comprehension] "}"\n' +- ' key_datum_list ::= key_datum ("," key_datum)* [","]\n' +- ' key_datum ::= expression ":" expression\n' +- ' dict_comprehension ::= expression ":" expression comp_for\n' +- '\n' +- 'A dictionary display yields a new dictionary object.\n' +- '\n' +- 'If a comma-separated sequence of key/datum pairs is given, they ' +- 'are\n' +- 'evaluated from left to right to define the entries of the ' +- 'dictionary:\n' +- 'each key object is used as a key into the dictionary to store the\n' +- 'corresponding datum. This means that you can specify the same ' +- 'key\n' +- "multiple times in the key/datum list, and the final dictionary's " +- 'value\n' +- 'for that key will be the last one given.\n' +- '\n' +- 'A dict comprehension, in contrast to list and set comprehensions,\n' +- 'needs two expressions separated with a colon followed by the ' +- 'usual\n' +- '"for" and "if" clauses. When the comprehension is run, the ' +- 'resulting\n' +- 'key and value elements are inserted in the new dictionary in the ' +- 'order\n' +- 'they are produced.\n' +- '\n' +- 'Restrictions on the types of the key values are listed earlier in\n' +- 'section The standard type hierarchy. (To summarize, the key type\n' +- 'should be *hashable*, which excludes all mutable objects.) ' +- 'Clashes\n' +- 'between duplicate keys are not detected; the last datum ' +- '(textually\n' +- 'rightmost in the display) stored for a given key value prevails.\n', +- 'dynamic-features': '\n' +- 'Interaction with dynamic features\n' +- '*********************************\n' +- '\n' +- 'There are several cases where Python statements are ' +- 'illegal when used\n' +- 'in conjunction with nested scopes that contain free ' +- 'variables.\n' +- '\n' +- 'If a variable is referenced in an enclosing scope, it ' +- 'is illegal to\n' +- 'delete the name. An error will be reported at compile ' +- 'time.\n' +- '\n' +- 'If the wild card form of import --- "import *" --- is ' +- 'used in a\n' +- 'function and the function contains or is a nested ' +- 'block with free\n' +- 'variables, the compiler will raise a "SyntaxError".\n' +- '\n' +- 'If "exec" is used in a function and the function ' +- 'contains or is a\n' +- 'nested block with free variables, the compiler will ' +- 'raise a\n' +- '"SyntaxError" unless the exec explicitly specifies the ' +- 'local namespace\n' +- 'for the "exec". (In other words, "exec obj" would be ' +- 'illegal, but\n' +- '"exec obj in ns" would be legal.)\n' +- '\n' +- 'The "eval()", "execfile()", and "input()" functions ' +- 'and the "exec"\n' +- 'statement do not have access to the full environment ' +- 'for resolving\n' +- 'names. Names may be resolved in the local and global ' +- 'namespaces of\n' +- 'the caller. Free variables are not resolved in the ' +- 'nearest enclosing\n' +- 'namespace, but in the global namespace. [1] The "exec" ' +- 'statement and\n' +- 'the "eval()" and "execfile()" functions have optional ' +- 'arguments to\n' +- 'override the global and local namespace. If only one ' +- 'namespace is\n' +- 'specified, it is used for both.\n', +- 'else': '\n' +- 'The "if" statement\n' +- '******************\n' +- '\n' +- 'The "if" statement is used for conditional execution:\n' +- '\n' +- ' if_stmt ::= "if" expression ":" suite\n' +- ' ( "elif" expression ":" suite )*\n' +- ' ["else" ":" suite]\n' +- '\n' +- 'It selects exactly one of the suites by evaluating the expressions ' +- 'one\n' +- 'by one until one is found to be true (see section Boolean ' +- 'operations\n' +- 'for the definition of true and false); then that suite is ' +- 'executed\n' +- '(and no other part of the "if" statement is executed or ' +- 'evaluated).\n' +- 'If all expressions are false, the suite of the "else" clause, if\n' +- 'present, is executed.\n', +- 'exceptions': '\n' +- 'Exceptions\n' +- '**********\n' +- '\n' +- 'Exceptions are a means of breaking out of the normal flow of ' +- 'control\n' +- 'of a code block in order to handle errors or other ' +- 'exceptional\n' +- 'conditions. An exception is *raised* at the point where the ' +- 'error is\n' +- 'detected; it may be *handled* by the surrounding code block ' +- 'or by any\n' +- 'code block that directly or indirectly invoked the code ' +- 'block where\n' +- 'the error occurred.\n' +- '\n' +- 'The Python interpreter raises an exception when it detects a ' +- 'run-time\n' +- 'error (such as division by zero). A Python program can ' +- 'also\n' +- 'explicitly raise an exception with the "raise" statement. ' +- 'Exception\n' +- 'handlers are specified with the "try" ... "except" ' +- 'statement. The\n' +- '"finally" clause of such a statement can be used to specify ' +- 'cleanup\n' +- 'code which does not handle the exception, but is executed ' +- 'whether an\n' +- 'exception occurred or not in the preceding code.\n' +- '\n' +- 'Python uses the "termination" model of error handling: an ' +- 'exception\n' +- 'handler can find out what happened and continue execution at ' +- 'an outer\n' +- 'level, but it cannot repair the cause of the error and retry ' +- 'the\n' +- 'failing operation (except by re-entering the offending piece ' +- 'of code\n' +- 'from the top).\n' +- '\n' +- 'When an exception is not handled at all, the interpreter ' +- 'terminates\n' +- 'execution of the program, or returns to its interactive main ' +- 'loop. In\n' +- 'either case, it prints a stack backtrace, except when the ' +- 'exception is\n' +- '"SystemExit".\n' +- '\n' +- 'Exceptions are identified by class instances. The "except" ' +- 'clause is\n' +- 'selected depending on the class of the instance: it must ' +- 'reference the\n' +- 'class of the instance or a base class thereof. The instance ' +- 'can be\n' +- 'received by the handler and can carry additional information ' +- 'about the\n' +- 'exceptional condition.\n' +- '\n' +- 'Exceptions can also be identified by strings, in which case ' +- 'the\n' +- '"except" clause is selected by object identity. An ' +- 'arbitrary value\n' +- 'can be raised along with the identifying string which can be ' +- 'passed to\n' +- 'the handler.\n' +- '\n' +- 'Note: 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' +- '\n' +- 'See also the description of the "try" statement in section ' +- 'The try\n' +- 'statement and "raise" statement in section The raise ' +- 'statement.\n' +- '\n' +- '-[ Footnotes ]-\n' +- '\n' +- '[1] This limitation occurs because the code that is executed ' +- 'by\n' +- ' these operations is not available at the time the module ' +- 'is\n' +- ' compiled.\n', +- 'exec': '\n' +- 'The "exec" statement\n' +- '********************\n' +- '\n' +- ' exec_stmt ::= "exec" or_expr ["in" expression ["," ' +- 'expression]]\n' +- '\n' +- 'This statement supports dynamic execution of Python code. The ' +- 'first\n' +- 'expression should evaluate to either a Unicode string, a ' +- '*Latin-1*\n' +- 'encoded string, an open file object, a code object, or a tuple. ' +- 'If it\n' +- 'is a string, the string is parsed as a suite of Python statements\n' +- 'which is then executed (unless a syntax error occurs). [1] If it ' +- 'is an\n' +- 'open file, the file is parsed until EOF and executed. If it is a ' +- 'code\n' +- 'object, it is simply executed. For the interpretation of a tuple, ' +- 'see\n' +- "below. In all cases, the code that's executed is expected to be " +- 'valid\n' +- 'as file input (see section File input). Be aware that the ' +- '"return"\n' +- 'and "yield" statements may not be used outside of function ' +- 'definitions\n' +- 'even within the context of code passed to the "exec" statement.\n' +- '\n' +- 'In all cases, if the optional parts are omitted, the code is ' +- 'executed\n' +- 'in the current scope. If only the first expression after "in" is\n' +- 'specified, it should be a dictionary, which will be used for both ' +- 'the\n' +- 'global and the local variables. If two expressions are given, ' +- 'they\n' +- 'are used for the global and local variables, respectively. If\n' +- 'provided, *locals* can be any mapping object. Remember that at ' +- 'module\n' +- 'level, globals and locals are the same dictionary. If two ' +- 'separate\n' +- 'objects are given as *globals* and *locals*, the code will be ' +- 'executed\n' +- 'as if it were embedded in a class definition.\n' +- '\n' +- 'The first expression may also be a tuple of length 2 or 3. In ' +- 'this\n' +- 'case, the optional parts must be omitted. The form "exec(expr,\n' +- 'globals)" is equivalent to "exec expr in globals", while the form\n' +- '"exec(expr, globals, locals)" is equivalent to "exec expr in ' +- 'globals,\n' +- 'locals". The tuple form of "exec" provides compatibility with ' +- 'Python\n' +- '3, where "exec" is a function rather than a statement.\n' +- '\n' +- 'Changed in version 2.4: Formerly, *locals* was required to be a\n' +- 'dictionary.\n' +- '\n' +- 'As a side effect, an implementation may insert additional keys ' +- 'into\n' +- 'the dictionaries given besides those corresponding to variable ' +- 'names\n' +- 'set by the executed code. For example, the current implementation ' +- 'may\n' +- 'add a reference to the dictionary of the built-in module ' +- '"__builtin__"\n' +- 'under the key "__builtins__" (!).\n' +- '\n' +- "**Programmer's hints:** dynamic evaluation of expressions is " +- 'supported\n' +- 'by the built-in function "eval()". The built-in functions ' +- '"globals()"\n' +- 'and "locals()" return the current global and local dictionary,\n' +- 'respectively, which may be useful to pass around for use by ' +- '"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': '\n' +- 'Execution model\n' +- '***************\n' +- '\n' +- '\n' +- 'Naming and binding\n' +- '==================\n' +- '\n' +- '*Names* refer to objects. Names are introduced by name ' +- 'binding\n' +- 'operations. Each occurrence of a name in the program text ' +- 'refers to\n' +- 'the *binding* of that name established in the innermost ' +- 'function block\n' +- 'containing the use.\n' +- '\n' +- 'A *block* is a piece of Python program text that is executed ' +- 'as a\n' +- 'unit. The following are blocks: a module, a function body, ' +- 'and a class\n' +- 'definition. Each command typed interactively is a block. A ' +- 'script\n' +- 'file (a file given as standard input to the interpreter or ' +- 'specified\n' +- 'on the interpreter command line the first argument) is a code ' +- 'block.\n' +- 'A script command (a command specified on the interpreter ' +- 'command line\n' +- "with the '**-c**' option) is a code block. The file read by " +- 'the\n' +- 'built-in function "execfile()" is a code block. The string ' +- 'argument\n' +- 'passed to the built-in function "eval()" and to the "exec" ' +- 'statement\n' +- 'is a code block. The expression read and evaluated by the ' +- 'built-in\n' +- 'function "input()" is a code block.\n' +- '\n' +- 'A code block is executed in an *execution frame*. A frame ' +- 'contains\n' +- 'some administrative information (used for debugging) and ' +- 'determines\n' +- "where and how execution continues after the code block's " +- 'execution has\n' +- 'completed.\n' +- '\n' +- 'A *scope* defines the visibility of a name within a block. ' +- 'If a local\n' +- 'variable is defined in a block, its scope includes that ' +- 'block. If the\n' +- 'definition occurs in a function block, the scope extends to ' +- 'any blocks\n' +- 'contained within the defining one, unless a contained block ' +- 'introduces\n' +- 'a different binding for the name. The scope of names defined ' +- 'in a\n' +- 'class block is limited to the class block; it does not extend ' +- 'to the\n' +- 'code blocks of methods -- this includes generator expressions ' +- 'since\n' +- 'they are implemented using a function scope. This means that ' +- 'the\n' +- 'following will fail:\n' +- '\n' +- ' class A:\n' +- ' a = 42\n' +- ' b = list(a + i for i in range(10))\n' +- '\n' +- 'When a name is used in a code block, it is resolved using the ' +- 'nearest\n' +- 'enclosing scope. The set of all such scopes visible to a ' +- 'code block\n' +- "is called the block's *environment*.\n" +- '\n' +- 'If a name is bound in a block, it is a local variable of that ' +- 'block.\n' +- 'If a name is bound at the module level, it is a global ' +- 'variable. (The\n' +- 'variables of the module code block are local and global.) If ' +- 'a\n' +- 'variable is used in a code block but not defined there, it is ' +- 'a *free\n' +- 'variable*.\n' +- '\n' +- 'When a name is not found at all, a "NameError" exception is ' +- 'raised.\n' +- 'If the name refers to a local variable that has not been ' +- 'bound, a\n' +- '"UnboundLocalError" exception is raised. "UnboundLocalError" ' +- 'is a\n' +- 'subclass of "NameError".\n' +- '\n' +- 'The following constructs bind names: formal parameters to ' +- 'functions,\n' +- '"import" statements, class and function definitions (these ' +- 'bind the\n' +- 'class or function name in the defining block), and targets ' +- 'that are\n' +- 'identifiers if occurring in an assignment, "for" loop header, ' +- 'in the\n' +- 'second position of an "except" clause header or after "as" in ' +- 'a "with"\n' +- 'statement. The "import" statement of the form "from ... ' +- 'import *"\n' +- 'binds all names defined in the imported module, except those ' +- 'beginning\n' +- 'with an underscore. This form may only be used at the module ' +- 'level.\n' +- '\n' +- 'A target occurring in a "del" statement is also considered ' +- 'bound for\n' +- 'this purpose (though the actual semantics are to unbind the ' +- 'name). It\n' +- 'is illegal to unbind a name that is referenced by an ' +- 'enclosing scope;\n' +- 'the compiler will report a "SyntaxError".\n' +- '\n' +- 'Each assignment or import statement occurs within a block ' +- 'defined by a\n' +- 'class or function definition or at the module level (the ' +- 'top-level\n' +- 'code block).\n' +- '\n' +- 'If a name binding operation occurs anywhere within a code ' +- 'block, all\n' +- 'uses of the name within the block are treated as references ' +- 'to the\n' +- 'current block. This can lead to errors when a name is used ' +- 'within a\n' +- 'block before it is bound. This rule is subtle. Python lacks\n' +- 'declarations and allows name binding operations to occur ' +- 'anywhere\n' +- 'within a code block. The local variables of a code block can ' +- 'be\n' +- 'determined by scanning the entire text of the block for name ' +- 'binding\n' +- 'operations.\n' +- '\n' +- 'If the global statement occurs within a block, all uses of ' +- 'the name\n' +- 'specified in the statement refer to the binding of that name ' +- 'in the\n' +- 'top-level namespace. Names are resolved in the top-level ' +- 'namespace by\n' +- 'searching the global namespace, i.e. the namespace of the ' +- 'module\n' +- 'containing the code block, and the builtins namespace, the ' +- 'namespace\n' +- 'of the module "__builtin__". The global namespace is ' +- 'searched first.\n' +- 'If the name is not found there, the builtins namespace is ' +- 'searched.\n' +- 'The global statement must precede all uses of the name.\n' +- '\n' +- 'The builtins namespace associated with the execution of a ' +- 'code block\n' +- 'is actually found by looking up the name "__builtins__" in ' +- 'its global\n' +- 'namespace; this should be a dictionary or a module (in the ' +- 'latter case\n' +- "the module's dictionary is used). By default, when in the " +- '"__main__"\n' +- 'module, "__builtins__" is the built-in module "__builtin__" ' +- '(note: no\n' +- '\'s\'); when in any other module, "__builtins__" is an alias ' +- 'for the\n' +- 'dictionary of the "__builtin__" module itself. ' +- '"__builtins__" can be\n' +- 'set to a user-created dictionary to create a weak form of ' +- 'restricted\n' +- 'execution.\n' +- '\n' +- '**CPython implementation detail:** Users should not touch\n' +- '"__builtins__"; it is strictly an implementation detail. ' +- 'Users\n' +- 'wanting to override values in the builtins namespace should ' +- '"import"\n' +- 'the "__builtin__" (no \'s\') module and modify its ' +- 'attributes\n' +- 'appropriately.\n' +- '\n' +- 'The namespace for a module is automatically created the first ' +- 'time a\n' +- 'module is imported. The main module for a script is always ' +- 'called\n' +- '"__main__".\n' +- '\n' +- 'The "global" statement has the same scope as a name binding ' +- 'operation\n' +- 'in the same block. If the nearest enclosing scope for a free ' +- 'variable\n' +- 'contains a global statement, the free variable is treated as ' +- 'a global.\n' +- '\n' +- 'A class definition is an executable statement that may use ' +- 'and define\n' +- 'names. These references follow the normal rules for name ' +- 'resolution.\n' +- 'The namespace of the class definition becomes the attribute ' +- 'dictionary\n' +- 'of the class. Names defined at the class scope are not ' +- 'visible in\n' +- 'methods.\n' +- '\n' +- '\n' +- 'Interaction with dynamic features\n' +- '---------------------------------\n' +- '\n' +- 'There are several cases where Python statements are illegal ' +- 'when used\n' +- 'in conjunction with nested scopes that contain free ' +- 'variables.\n' +- '\n' +- 'If a variable is referenced in an enclosing scope, it is ' +- 'illegal to\n' +- 'delete the name. An error will be reported at compile time.\n' +- '\n' +- 'If the wild card form of import --- "import *" --- is used in ' +- 'a\n' +- 'function and the function contains or is a nested block with ' +- 'free\n' +- 'variables, the compiler will raise a "SyntaxError".\n' +- '\n' +- 'If "exec" is used in a function and the function contains or ' +- 'is a\n' +- 'nested block with free variables, the compiler will raise a\n' +- '"SyntaxError" unless the exec explicitly specifies the local ' +- 'namespace\n' +- 'for the "exec". (In other words, "exec obj" would be ' +- 'illegal, but\n' +- '"exec obj in ns" would be legal.)\n' +- '\n' +- 'The "eval()", "execfile()", and "input()" functions and the ' +- '"exec"\n' +- 'statement do not have access to the full environment for ' +- 'resolving\n' +- 'names. Names may be resolved in the local and global ' +- 'namespaces of\n' +- 'the caller. Free variables are not resolved in the nearest ' +- 'enclosing\n' +- 'namespace, but in the global namespace. [1] The "exec" ' +- 'statement and\n' +- 'the "eval()" and "execfile()" functions have optional ' +- 'arguments to\n' +- 'override the global and local namespace. If only one ' +- 'namespace is\n' +- 'specified, it is used for both.\n' +- '\n' +- '\n' +- 'Exceptions\n' +- '==========\n' +- '\n' +- 'Exceptions are a means of breaking out of the normal flow of ' +- 'control\n' +- 'of a code block in order to handle errors or other ' +- 'exceptional\n' +- 'conditions. An exception is *raised* at the point where the ' +- 'error is\n' +- 'detected; it may be *handled* by the surrounding code block ' +- 'or by any\n' +- 'code block that directly or indirectly invoked the code block ' +- 'where\n' +- 'the error occurred.\n' +- '\n' +- 'The Python interpreter raises an exception when it detects a ' +- 'run-time\n' +- 'error (such as division by zero). A Python program can also\n' +- 'explicitly raise an exception with the "raise" statement. ' +- 'Exception\n' +- 'handlers are specified with the "try" ... "except" ' +- 'statement. The\n' +- '"finally" clause of such a statement can be used to specify ' +- 'cleanup\n' +- 'code which does not handle the exception, but is executed ' +- 'whether an\n' +- 'exception occurred or not in the preceding code.\n' +- '\n' +- 'Python uses the "termination" model of error handling: an ' +- 'exception\n' +- 'handler can find out what happened and continue execution at ' +- 'an outer\n' +- 'level, but it cannot repair the cause of the error and retry ' +- 'the\n' +- 'failing operation (except by re-entering the offending piece ' +- 'of code\n' +- 'from the top).\n' +- '\n' +- 'When an exception is not handled at all, the interpreter ' +- 'terminates\n' +- 'execution of the program, or returns to its interactive main ' +- 'loop. In\n' +- 'either case, it prints a stack backtrace, except when the ' +- 'exception is\n' +- '"SystemExit".\n' +- '\n' +- 'Exceptions are identified by class instances. The "except" ' +- 'clause is\n' +- 'selected depending on the class of the instance: it must ' +- 'reference the\n' +- 'class of the instance or a base class thereof. The instance ' +- 'can be\n' +- 'received by the handler and can carry additional information ' +- 'about the\n' +- 'exceptional condition.\n' +- '\n' +- 'Exceptions can also be identified by strings, in which case ' +- 'the\n' +- '"except" clause is selected by object identity. An arbitrary ' +- 'value\n' +- 'can be raised along with the identifying string which can be ' +- 'passed to\n' +- 'the handler.\n' +- '\n' +- 'Note: 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' +- '\n' +- 'See also the description of the "try" statement in section ' +- 'The try\n' +- 'statement and "raise" statement in section The raise ' +- 'statement.\n' +- '\n' +- '-[ Footnotes ]-\n' +- '\n' +- '[1] This limitation occurs because the code that is executed ' +- 'by\n' +- ' these operations is not available at the time the module ' +- 'is\n' +- ' compiled.\n', +- 'exprlists': '\n' +- 'Expression lists\n' +- '****************\n' +- '\n' +- ' expression_list ::= expression ( "," expression )* [","]\n' +- '\n' +- 'An expression list containing at least one comma yields a ' +- 'tuple. The\n' +- 'length of the tuple is the number of expressions in the ' +- 'list. The\n' +- 'expressions are evaluated from left to right.\n' +- '\n' +- 'The 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\n' +- "without a trailing comma doesn't create a tuple, but rather " +- 'yields the\n' +- 'value of that expression. (To create an empty tuple, use an ' +- 'empty pair\n' +- 'of parentheses: "()".)\n', +- 'floating': '\n' +- 'Floating point literals\n' +- '***********************\n' +- '\n' +- 'Floating point literals are described by the following ' +- 'lexical\n' +- 'definitions:\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' +- '\n' +- 'Note that the integer and exponent parts of floating point ' +- 'numbers can\n' +- 'look like octal integers, but are interpreted using radix 10. ' +- 'For\n' +- 'example, "077e010" is legal, and denotes the same number as ' +- '"77e10".\n' +- 'The allowed range of floating point literals is ' +- 'implementation-\n' +- 'dependent. Some examples of floating point literals:\n' +- '\n' +- ' 3.14 10. .001 1e100 3.14e-10 0e0\n' +- '\n' +- 'Note that numeric literals do not include a sign; a phrase ' +- 'like "-1"\n' +- 'is actually an expression composed of the unary operator "-" ' +- 'and the\n' +- 'literal "1".\n', +- 'for': '\n' +- 'The "for" statement\n' +- '*******************\n' +- '\n' +- 'The "for" statement is used to iterate over the elements of a ' +- 'sequence\n' +- '(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' +- '\n' +- 'The expression list is evaluated once; it should yield an iterable\n' +- 'object. An iterator is created for the result of the\n' +- '"expression_list". The suite is then executed once for each item\n' +- 'provided by the iterator, in the order of ascending indices. Each\n' +- 'item in turn is assigned to the target list using the standard ' +- 'rules\n' +- 'for assignments, and then the suite is executed. When the items ' +- 'are\n' +- 'exhausted (which is immediately when the sequence is empty), the ' +- 'suite\n' +- 'in the "else" clause, if present, is executed, and the loop\n' +- 'terminates.\n' +- '\n' +- 'A "break" statement executed in the first suite terminates the ' +- 'loop\n' +- 'without executing the "else" clause\'s suite. A "continue" ' +- 'statement\n' +- 'executed in the first suite skips the rest of the suite and ' +- 'continues\n' +- 'with the next item, or with the "else" clause if there was no next\n' +- 'item.\n' +- '\n' +- 'The suite may assign to the variable(s) in the target list; this ' +- 'does\n' +- 'not affect the next item assigned to it.\n' +- '\n' +- 'The target list is not deleted when the loop is finished, but if ' +- 'the\n' +- 'sequence is empty, it will not have been assigned to at all by the\n' +- 'loop. Hint: the built-in function "range()" returns a sequence of\n' +- 'integers suitable to emulate the effect of Pascal\'s "for i := a to ' +- 'b\n' +- 'do"; e.g., "range(3)" returns the list "[0, 1, 2]".\n' +- '\n' +- 'Note: There is a subtlety when the sequence is being modified by ' +- 'the\n' +- ' loop (this can only occur for mutable sequences, i.e. lists). An\n' +- ' internal counter is used to keep track of which item is used ' +- 'next,\n' +- ' and this is incremented on each iteration. When this counter ' +- 'has\n' +- ' reached the length of the sequence the loop terminates. This ' +- 'means\n' +- ' that if the suite deletes the current (or a previous) item from ' +- 'the\n' +- ' sequence, the next item will be skipped (since it gets the index ' +- 'of\n' +- ' the 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': '\n' +- 'Format String Syntax\n' +- '********************\n' +- '\n' +- 'The "str.format()" method and the "Formatter" class share ' +- 'the same\n' +- 'syntax for format strings (although in the case of ' +- '"Formatter",\n' +- 'subclasses can define their own format string syntax).\n' +- '\n' +- 'Format strings contain "replacement fields" surrounded by ' +- 'curly braces\n' +- '"{}". Anything that is not contained in braces is ' +- 'considered literal\n' +- 'text, which is copied unchanged to the output. If you ' +- 'need to include\n' +- 'a brace character in the literal text, it can be escaped ' +- 'by doubling:\n' +- '"{{" and "}}".\n' +- '\n' +- 'The 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' +- '\n' +- 'In less formal terms, the replacement field can start ' +- 'with a\n' +- '*field_name* that specifies the object whose value is to ' +- 'be formatted\n' +- 'and inserted into the output instead of the replacement ' +- 'field. The\n' +- '*field_name* is optionally followed by a *conversion* ' +- 'field, which is\n' +- 'preceded by an exclamation point "\'!\'", and a ' +- '*format_spec*, which is\n' +- 'preceded by a colon "\':\'". These specify a non-default ' +- 'format for the\n' +- 'replacement value.\n' +- '\n' +- 'See also the Format Specification Mini-Language section.\n' +- '\n' +- 'The *field_name* itself begins with an *arg_name* that is ' +- 'either a\n' +- "number or a keyword. If it's a number, it refers to a " +- 'positional\n' +- "argument, and if it's a keyword, it refers to a named " +- 'keyword\n' +- 'argument. 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\n' +- 'numbers 0, 1, 2, ... will be automatically inserted in ' +- 'that order.\n' +- 'Because *arg_name* is not quote-delimited, it is not ' +- 'possible to\n' +- 'specify arbitrary dictionary keys (e.g., the strings ' +- '"\'10\'" or\n' +- '"\':-]\'") within a format string. The *arg_name* can be ' +- 'followed by any\n' +- 'number of index or attribute expressions. An expression ' +- 'of the form\n' +- '"\'.name\'" selects the named attribute using ' +- '"getattr()", while an\n' +- 'expression of the form "\'[index]\'" does an index lookup ' +- 'using\n' +- '"__getitem__()".\n' +- '\n' +- 'Changed in version 2.7: The positional argument ' +- 'specifiers can be\n' +- 'omitted, so "\'{} {}\'" is equivalent to "\'{0} {1}\'".\n' +- '\n' +- 'Some 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" +- '\n' +- 'The *conversion* field causes a type coercion before ' +- 'formatting.\n' +- 'Normally, the job of formatting a value is done by the ' +- '"__format__()"\n' +- 'method of the value itself. However, in some cases it is ' +- 'desirable to\n' +- 'force a type to be formatted as a string, overriding its ' +- 'own\n' +- 'definition of formatting. By converting the value to a ' +- 'string before\n' +- 'calling "__format__()", the normal formatting logic is ' +- 'bypassed.\n' +- '\n' +- 'Two conversion flags are currently supported: "\'!s\'" ' +- 'which calls\n' +- '"str()" on the value, and "\'!r\'" which calls "repr()".\n' +- '\n' +- 'Some 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' +- '\n' +- 'The *format_spec* field contains a specification of how ' +- 'the value\n' +- 'should be presented, including such details as field ' +- 'width, alignment,\n' +- 'padding, decimal precision and so on. Each value type ' +- 'can define its\n' +- 'own "formatting mini-language" or interpretation of the ' +- '*format_spec*.\n' +- '\n' +- 'Most built-in types support a common formatting ' +- 'mini-language, which\n' +- 'is described in the next section.\n' +- '\n' +- 'A *format_spec* field can also include nested replacement ' +- 'fields\n' +- 'within it. These nested replacement fields can contain ' +- 'only a field\n' +- 'name; conversion flags and format specifications are not ' +- 'allowed. The\n' +- 'replacement fields within the format_spec are substituted ' +- 'before the\n' +- '*format_spec* string is interpreted. This allows the ' +- 'formatting of a\n' +- 'value to be dynamically specified.\n' +- '\n' +- 'See the Format examples section for some examples.\n' +- '\n' +- '\n' +- 'Format Specification Mini-Language\n' +- '==================================\n' +- '\n' +- '"Format specifications" are used within replacement ' +- 'fields contained\n' +- 'within a format string to define how individual values ' +- 'are presented\n' +- '(see Format String Syntax). They can also be passed ' +- 'directly to the\n' +- 'built-in "format()" function. Each formattable type may ' +- 'define how\n' +- 'the format specification is to be interpreted.\n' +- '\n' +- 'Most built-in types implement the following options for ' +- 'format\n' +- 'specifications, although some of the formatting options ' +- 'are only\n' +- 'supported by the numeric types.\n' +- '\n' +- 'A general convention is that an empty format string ' +- '("""") produces\n' +- 'the same result as if you had called "str()" on the ' +- 'value. A non-empty\n' +- 'format string typically modifies the result.\n' +- '\n' +- 'The 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' +- '\n' +- 'If a valid *align* value is specified, it can be preceded ' +- 'by a *fill*\n' +- 'character that can be any character and defaults to a ' +- 'space if\n' +- 'omitted. Note that it is not possible to use "{" and "}" ' +- 'as *fill*\n' +- 'char while using the "str.format()" method; this ' +- 'limitation however\n' +- 'doesn\'t affect the "format()" function.\n' +- '\n' +- 'The 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' +- '\n' +- 'Note that unless a minimum field width is defined, the ' +- 'field width\n' +- 'will always be the same size as the data to fill it, so ' +- 'that the\n' +- 'alignment option has no meaning in this case.\n' +- '\n' +- 'The *sign* option is only valid for number types, and can ' +- 'be one of\n' +- 'the 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' +- '\n' +- 'The "\'#\'" option is only valid for integers, and only ' +- 'for binary,\n' +- 'octal, or hexadecimal output. If present, it specifies ' +- 'that the\n' +- 'output will be prefixed by "\'0b\'", "\'0o\'", or ' +- '"\'0x\'", respectively.\n' +- '\n' +- 'The "\',\'" option signals the use of a comma for a ' +- 'thousands separator.\n' +- 'For a locale aware separator, use the "\'n\'" integer ' +- 'presentation type\n' +- 'instead.\n' +- '\n' +- 'Changed in version 2.7: Added the "\',\'" option (see ' +- 'also **PEP 378**).\n' +- '\n' +- '*width* is a decimal integer defining the minimum field ' +- 'width. If not\n' +- 'specified, then the field width will be determined by the ' +- 'content.\n' +- '\n' +- 'Preceding the *width* field by a zero ("\'0\'") character ' +- 'enables sign-\n' +- 'aware zero-padding for numeric types. This is equivalent ' +- 'to a *fill*\n' +- 'character of "\'0\'" with an *alignment* type of ' +- '"\'=\'".\n' +- '\n' +- 'The *precision* is a decimal number indicating how many ' +- 'digits should\n' +- 'be displayed after the decimal point for a floating point ' +- 'value\n' +- 'formatted with "\'f\'" and "\'F\'", or before and after ' +- 'the decimal point\n' +- 'for a floating point value formatted with "\'g\'" or ' +- '"\'G\'". For non-\n' +- 'number types the field indicates the maximum field size - ' +- 'in other\n' +- 'words, how many characters will be used from the field ' +- 'content. The\n' +- '*precision* is not allowed for integer values.\n' +- '\n' +- 'Finally, the *type* determines how the data should be ' +- 'presented.\n' +- '\n' +- 'The 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' +- '\n' +- 'The 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 the |\n' +- ' | | current locale setting to insert the ' +- 'appropriate number |\n' +- ' | | separator ' +- 'characters. |\n' +- ' ' +- '+-----------+------------------------------------------------------------+\n' +- ' | None | The same as ' +- '"\'d\'". |\n' +- ' ' +- '+-----------+------------------------------------------------------------+\n' +- '\n' +- 'In addition to the above presentation types, integers can ' +- 'be formatted\n' +- 'with the floating point presentation types listed below ' +- '(except "\'n\'"\n' +- 'and None). When doing so, "float()" is used to convert ' +- 'the integer to\n' +- 'a floating point number before formatting.\n' +- '\n' +- 'The available presentation types for floating point and ' +- 'decimal values\n' +- 'are:\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 "p-1" |\n' +- ' | | would have exponent "exp". Then if "-4 ' +- '<= exp < p", the |\n' +- ' | | number is formatted with presentation ' +- 'type "\'f\'" and |\n' +- ' | | precision "p-1-exp". Otherwise, the ' +- 'number is formatted |\n' +- ' | | with presentation type "\'e\'" and ' +- 'precision "p-1". In both |\n' +- ' | | cases insignificant trailing zeros are ' +- 'removed from the |\n' +- ' | | significand, and the decimal point is ' +- 'also removed if |\n' +- ' | | there are no remaining digits following ' +- 'it. Positive and |\n' +- ' | | negative infinity, positive and negative ' +- 'zero, and nans, |\n' +- ' | | are formatted as "inf", "-inf", "0", ' +- '"-0" and "nan" |\n' +- ' | | respectively, regardless of the ' +- 'precision. A precision of |\n' +- ' | | "0" is treated as equivalent to a ' +- 'precision of "1". The |\n' +- ' | | default precision is ' +- '"6". |\n' +- ' ' +- '+-----------+------------------------------------------------------------+\n' +- ' | "\'G\'" | General format. Same as "\'g\'" except ' +- 'switches to "\'E\'" if |\n' +- ' | | the number gets too large. The ' +- 'representations of infinity |\n' +- ' | | and NaN are uppercased, ' +- 'too. |\n' +- ' ' +- '+-----------+------------------------------------------------------------+\n' +- ' | "\'n\'" | Number. This is the same as "\'g\'", ' +- 'except that it uses the |\n' +- ' | | current locale setting to insert the ' +- 'appropriate number |\n' +- ' | | 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' +- '\n' +- 'Format examples\n' +- '===============\n' +- '\n' +- 'This section contains examples of the new format syntax ' +- 'and comparison\n' +- 'with the old "%"-formatting.\n' +- '\n' +- 'In most of the cases the syntax is similar to the old ' +- '"%"-formatting,\n' +- 'with the addition of the "{}" and with ":" used instead ' +- 'of "%". For\n' +- 'example, "\'%03.2f\'" can be translated to ' +- '"\'{:03.2f}\'".\n' +- '\n' +- 'The new format syntax also supports new and different ' +- 'options, shown\n' +- 'in the follow examples.\n' +- '\n' +- 'Accessing 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" +- '\n' +- 'Accessing 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" +- '\n' +- "Accessing 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" +- '\n' +- "Accessing arguments' items:\n" +- '\n' +- ' >>> coord = (3, 5)\n' +- " >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)\n" +- " 'X: 3; Y: 5'\n" +- '\n' +- 'Replacing "%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' +- '\n' +- 'Aligning 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" +- '\n' +- 'Replacing "%+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" +- '\n' +- 'Replacing "%x" and "%o" and converting the value to ' +- 'different bases:\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" +- '\n' +- 'Using the comma as a thousands separator:\n' +- '\n' +- " >>> '{:,}'.format(1234567890)\n" +- " '1,234,567,890'\n" +- '\n' +- 'Expressing a percentage:\n' +- '\n' +- ' >>> points = 19.5\n' +- ' >>> total = 22\n' +- " >>> 'Correct answers: {:.2%}'.format(points/total)\n" +- " 'Correct answers: 88.64%'\n" +- '\n' +- 'Using 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" +- '\n' +- 'Nesting 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': '\n' +- 'Function definitions\n' +- '********************\n' +- '\n' +- 'A function definition defines a user-defined function object ' +- '(see\n' +- 'section 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' +- '\n' +- 'A function definition is an executable statement. Its ' +- 'execution binds\n' +- 'the function name in the current local namespace to a function ' +- 'object\n' +- '(a wrapper around the executable code for the function). ' +- 'This\n' +- 'function object contains a reference to the current global ' +- 'namespace\n' +- 'as the global namespace to be used when the function is ' +- 'called.\n' +- '\n' +- 'The function definition does not execute the function body; ' +- 'this gets\n' +- 'executed only when the function is called. [3]\n' +- '\n' +- 'A function definition may be wrapped by one or more ' +- '*decorator*\n' +- 'expressions. Decorator expressions are evaluated when the ' +- 'function is\n' +- 'defined, in the scope that contains the function definition. ' +- 'The\n' +- 'result must be a callable, which is invoked with the function ' +- 'object\n' +- 'as the only argument. The returned value is bound to the ' +- 'function name\n' +- 'instead of the function object. Multiple decorators are ' +- 'applied in\n' +- 'nested fashion. For example, the following code:\n' +- '\n' +- ' @f1(arg)\n' +- ' @f2\n' +- ' def func(): pass\n' +- '\n' +- 'is equivalent to:\n' +- '\n' +- ' def func(): pass\n' +- ' func = f1(arg)(f2(func))\n' +- '\n' +- 'When one or more top-level *parameters* have the form ' +- '*parameter* "="\n' +- '*expression*, the function is said to have "default parameter ' +- 'values."\n' +- 'For a parameter with a default value, the corresponding ' +- '*argument* may\n' +- "be omitted from a call, in which case the parameter's default " +- 'value is\n' +- 'substituted. If a parameter has a default value, all ' +- 'following\n' +- 'parameters must also have a default value --- this is a ' +- 'syntactic\n' +- 'restriction that is not expressed by the grammar.\n' +- '\n' +- '**Default parameter values are evaluated when the function ' +- 'definition\n' +- 'is executed.** This means that the expression is evaluated ' +- 'once, when\n' +- 'the function is defined, and that the same "pre-computed" ' +- 'value is\n' +- 'used for each call. This is especially important to ' +- 'understand when a\n' +- 'default parameter is a mutable object, such as a list or a ' +- 'dictionary:\n' +- 'if the function modifies the object (e.g. by appending an item ' +- 'to a\n' +- 'list), the default value is in effect modified. This is ' +- 'generally not\n' +- 'what was intended. A way around this is to use "None" as ' +- 'the\n' +- 'default, 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' +- '\n' +- 'Function call semantics are described in more detail in ' +- 'section Calls.\n' +- 'A function call always assigns values to all parameters ' +- 'mentioned in\n' +- 'the parameter list, either from position arguments, from ' +- 'keyword\n' +- 'arguments, or from default values. If the form ' +- '""*identifier"" is\n' +- 'present, it is initialized to a tuple receiving any excess ' +- 'positional\n' +- 'parameters, defaulting to the empty tuple. If the form\n' +- '""**identifier"" is present, it is initialized to a new ' +- 'dictionary\n' +- 'receiving any excess keyword arguments, defaulting to a new ' +- 'empty\n' +- 'dictionary.\n' +- '\n' +- 'It is also possible to create anonymous functions (functions ' +- 'not bound\n' +- 'to a name), for immediate use in expressions. This uses ' +- 'lambda\n' +- 'expressions, described in section Lambdas. Note that the ' +- 'lambda\n' +- 'expression is merely a shorthand for a simplified function ' +- 'definition;\n' +- 'a function defined in a ""def"" statement can be passed around ' +- 'or\n' +- 'assigned to another name just like a function defined by a ' +- 'lambda\n' +- 'expression. The ""def"" form is actually more powerful since ' +- 'it\n' +- 'allows the execution of multiple statements.\n' +- '\n' +- "**Programmer's note:** Functions are first-class objects. A " +- '""def""\n' +- 'form executed inside a function definition defines a local ' +- 'function\n' +- 'that can be returned or passed around. Free variables used in ' +- 'the\n' +- 'nested function can access the local variables of the ' +- 'function\n' +- 'containing the def. See section Naming and binding for ' +- 'details.\n', +- 'global': '\n' +- 'The "global" statement\n' +- '**********************\n' +- '\n' +- ' global_stmt ::= "global" identifier ("," identifier)*\n' +- '\n' +- 'The "global" statement is a declaration which holds for the ' +- 'entire\n' +- 'current code block. It means that the listed identifiers are to ' +- 'be\n' +- 'interpreted as globals. It would be impossible to assign to a ' +- 'global\n' +- 'variable without "global", although free variables may refer to\n' +- 'globals without being declared global.\n' +- '\n' +- 'Names listed in a "global" statement must not be used in the ' +- 'same code\n' +- 'block textually preceding that "global" statement.\n' +- '\n' +- 'Names listed in a "global" statement must not be defined as ' +- 'formal\n' +- 'parameters or in a "for" loop control target, "class" ' +- 'definition,\n' +- 'function definition, or "import" statement.\n' +- '\n' +- '**CPython implementation detail:** The current implementation ' +- 'does not\n' +- 'enforce the latter two restrictions, but programs should not ' +- 'abuse\n' +- 'this freedom, as future implementations may enforce them or ' +- 'silently\n' +- 'change the meaning of the program.\n' +- '\n' +- '**Programmer\'s note:** the "global" is a directive to the ' +- 'parser. It\n' +- 'applies only to code parsed at the same time as the "global"\n' +- 'statement. In particular, a "global" statement contained in an ' +- '"exec"\n' +- 'statement does not affect the code block *containing* the ' +- '"exec"\n' +- 'statement, and code contained in an "exec" statement is ' +- 'unaffected by\n' +- '"global" statements in the code containing the "exec" ' +- 'statement. The\n' +- 'same applies to the "eval()", "execfile()" and "compile()" ' +- 'functions.\n', +- 'id-classes': '\n' +- 'Reserved classes of identifiers\n' +- '*******************************\n' +- '\n' +- 'Certain classes of identifiers (besides keywords) have ' +- 'special\n' +- 'meanings. These classes are identified by the patterns of ' +- 'leading and\n' +- 'trailing 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 the\n' +- ' last evaluation; it is stored in the "__builtin__" ' +- 'module. When\n' +- ' not in interactive mode, "_" has no special meaning and ' +- 'is not\n' +- ' 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 and\n' +- ' elsewhere. More will likely be defined in future ' +- 'versions of\n' +- ' Python. *Any* use of "__*__" names, in any context, that ' +- 'does not\n' +- ' follow explicitly documented use, is subject to breakage ' +- 'without\n' +- ' 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', +- 'identifiers': '\n' +- 'Identifiers and keywords\n' +- '************************\n' +- '\n' +- 'Identifiers (also referred to as *names*) are described by ' +- 'the\n' +- 'following lexical definitions:\n' +- '\n' +- ' identifier ::= (letter|"_") (letter | digit | "_")*\n' +- ' letter ::= lowercase | uppercase\n' +- ' lowercase ::= "a"..."z"\n' +- ' uppercase ::= "A"..."Z"\n' +- ' digit ::= "0"..."9"\n' +- '\n' +- 'Identifiers are unlimited in length. Case is significant.\n' +- '\n' +- '\n' +- 'Keywords\n' +- '========\n' +- '\n' +- 'The following identifiers are used as reserved words, or ' +- '*keywords* of\n' +- 'the language, and cannot be used as ordinary identifiers. ' +- 'They must\n' +- 'be spelled exactly as written here:\n' +- '\n' +- ' and del from not while\n' +- ' as elif global or with\n' +- ' assert else if pass yield\n' +- ' break except import print\n' +- ' class exec in raise\n' +- ' continue finally is return\n' +- ' def for lambda try\n' +- '\n' +- 'Changed in version 2.4: "None" became a constant and is now ' +- 'recognized\n' +- 'by the compiler as a name for the built-in object "None". ' +- 'Although it\n' +- 'is not a keyword, you cannot assign a different object to ' +- 'it.\n' +- '\n' +- 'Changed in version 2.5: Using "as" and "with" as ' +- 'identifiers triggers\n' +- 'a warning. To use them as keywords, enable the ' +- '"with_statement"\n' +- 'future feature .\n' +- '\n' +- 'Changed in version 2.6: "as" and "with" are full keywords.\n' +- '\n' +- '\n' +- 'Reserved classes of identifiers\n' +- '===============================\n' +- '\n' +- 'Certain classes of identifiers (besides keywords) have ' +- 'special\n' +- 'meanings. These classes are identified by the patterns of ' +- 'leading and\n' +- 'trailing 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 the\n' +- ' last evaluation; it is stored in the "__builtin__" ' +- 'module. When\n' +- ' not in interactive mode, "_" has no special meaning and ' +- 'is not\n' +- ' 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 and\n' +- ' elsewhere. More will likely be defined in future ' +- 'versions of\n' +- ' Python. *Any* use of "__*__" names, in any context, ' +- 'that does not\n' +- ' follow explicitly documented use, is subject to breakage ' +- 'without\n' +- ' 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', +- 'if': '\n' +- 'The "if" statement\n' +- '******************\n' +- '\n' +- 'The "if" statement is used for conditional execution:\n' +- '\n' +- ' if_stmt ::= "if" expression ":" suite\n' +- ' ( "elif" expression ":" suite )*\n' +- ' ["else" ":" suite]\n' +- '\n' +- 'It selects exactly one of the suites by evaluating the expressions ' +- 'one\n' +- 'by one until one is found to be true (see section Boolean ' +- 'operations\n' +- 'for the definition of true and false); then that suite is executed\n' +- '(and no other part of the "if" statement is executed or evaluated).\n' +- 'If all expressions are false, the suite of the "else" clause, if\n' +- 'present, is executed.\n', +- 'imaginary': '\n' +- 'Imaginary literals\n' +- '******************\n' +- '\n' +- 'Imaginary literals are described by the following lexical ' +- 'definitions:\n' +- '\n' +- ' imagnumber ::= (floatnumber | intpart) ("j" | "J")\n' +- '\n' +- 'An imaginary literal yields a complex number with a real part ' +- 'of 0.0.\n' +- 'Complex numbers are represented as a pair of floating point ' +- 'numbers\n' +- 'and have the same restrictions on their range. To create a ' +- 'complex\n' +- 'number with a nonzero real part, add a floating point number ' +- 'to it,\n' +- 'e.g., "(3+4j)". Some examples of imaginary literals:\n' +- '\n' +- ' 3.14j 10.j 10j .001j 1e100j 3.14e-10j\n', +- 'import': '\n' +- 'The "import" statement\n' +- '**********************\n' +- '\n' +- ' import_stmt ::= "import" module ["as" name] ( "," module ' +- '["as" name] )*\n' +- ' | "from" relative_module "import" identifier ' +- '["as" name]\n' +- ' ( "," identifier ["as" name] )*\n' +- ' | "from" relative_module "import" "(" ' +- 'identifier ["as" name]\n' +- ' ( "," identifier ["as" name] )* [","] ")"\n' +- ' | "from" module "import" "*"\n' +- ' module ::= (identifier ".")* identifier\n' +- ' relative_module ::= "."* module | "."+\n' +- ' name ::= identifier\n' +- '\n' +- 'Import statements are executed in two steps: (1) find a module, ' +- 'and\n' +- 'initialize it if necessary; (2) define a name or names in the ' +- 'local\n' +- 'namespace (of the scope where the "import" statement occurs). ' +- 'The\n' +- 'statement comes in two forms differing on whether it uses the ' +- '"from"\n' +- 'keyword. The first form (without "from") repeats these steps for ' +- 'each\n' +- 'identifier in the list. The form with "from" performs step (1) ' +- 'once,\n' +- 'and then performs step (2) repeatedly.\n' +- '\n' +- 'To understand how step (1) occurs, one must first understand ' +- 'how\n' +- 'Python handles hierarchical naming of modules. To help organize\n' +- 'modules and provide a hierarchy in naming, Python has a concept ' +- 'of\n' +- 'packages. A package can contain other packages and modules ' +- 'while\n' +- 'modules cannot contain other modules or packages. From a file ' +- 'system\n' +- 'perspective, packages are directories and modules are files.\n' +- '\n' +- 'Once the name of the module is known (unless otherwise ' +- 'specified, the\n' +- 'term "module" will refer to both packages and modules), ' +- 'searching for\n' +- 'the module or package can begin. The first place checked is\n' +- '"sys.modules", the cache of all modules that have been imported\n' +- 'previously. If the module is found there then it is used in step ' +- '(2)\n' +- 'of import.\n' +- '\n' +- 'If the module is not found in the cache, then "sys.meta_path" ' +- 'is\n' +- 'searched (the specification for "sys.meta_path" can be found in ' +- '**PEP\n' +- '302**). The object is a list of *finder* objects which are ' +- 'queried in\n' +- 'order as to whether they know how to load the module by calling ' +- 'their\n' +- '"find_module()" method with the name of the module. If the ' +- 'module\n' +- 'happens to be contained within a package (as denoted by the ' +- 'existence\n' +- 'of a dot in the name), then a second argument to "find_module()" ' +- 'is\n' +- 'given as the value of the "__path__" attribute from the parent ' +- 'package\n' +- '(everything up to the last dot in the name of the module being\n' +- 'imported). If a finder can find the module it returns a ' +- '*loader*\n' +- '(discussed later) or returns "None".\n' +- '\n' +- 'If none of the finders on "sys.meta_path" are able to find the ' +- 'module\n' +- 'then some implicitly defined finders are queried. ' +- 'Implementations of\n' +- 'Python vary in what implicit meta path finders are defined. The ' +- 'one\n' +- 'they all do define, though, is one that handles ' +- '"sys.path_hooks",\n' +- '"sys.path_importer_cache", and "sys.path".\n' +- '\n' +- 'The implicit finder searches for the requested module in the ' +- '"paths"\n' +- 'specified in one of two places ("paths" do not have to be file ' +- 'system\n' +- 'paths). If the module being imported is supposed to be ' +- 'contained\n' +- 'within a package then the second argument passed to ' +- '"find_module()",\n' +- '"__path__" on the parent package, is used as the source of ' +- 'paths. If\n' +- 'the module is not contained in a package then "sys.path" is used ' +- 'as\n' +- 'the source of paths.\n' +- '\n' +- 'Once the source of paths is chosen it is iterated over to find ' +- 'a\n' +- 'finder that can handle that path. The dict at\n' +- '"sys.path_importer_cache" caches finders for paths and is ' +- 'checked for\n' +- 'a finder. If the path does not have a finder cached then\n' +- '"sys.path_hooks" is searched by calling each object in the list ' +- 'with a\n' +- 'single argument of the path, returning a finder or raises\n' +- '"ImportError". If a finder is returned then it is cached in\n' +- '"sys.path_importer_cache" and then used for that path entry. If ' +- 'no\n' +- 'finder can be found but the path exists then a value of "None" ' +- 'is\n' +- 'stored in "sys.path_importer_cache" to signify that an implicit, ' +- 'file-\n' +- 'based finder that handles modules stored as individual files ' +- 'should be\n' +- 'used for that path. If the path does not exist then a finder ' +- 'which\n' +- 'always returns "None" is placed in the cache for the path.\n' +- '\n' +- 'If no finder can find the module then "ImportError" is raised.\n' +- 'Otherwise some finder returned a loader whose "load_module()" ' +- 'method\n' +- 'is called with the name of the module to load (see **PEP 302** ' +- 'for the\n' +- 'original definition of loaders). A loader has several ' +- 'responsibilities\n' +- 'to perform on a module it loads. First, if the module already ' +- 'exists\n' +- 'in "sys.modules" (a possibility if the loader is called outside ' +- 'of the\n' +- 'import machinery) then it is to use that module for ' +- 'initialization and\n' +- 'not a new module. But if the module does not exist in ' +- '"sys.modules"\n' +- 'then it is to be added to that dict before initialization ' +- 'begins. If\n' +- 'an error occurs during loading of the module and it was added ' +- 'to\n' +- '"sys.modules" it is to be removed from the dict. If an error ' +- 'occurs\n' +- 'but the module was already in "sys.modules" it is left in the ' +- 'dict.\n' +- '\n' +- 'The loader must set several attributes on the module. "__name__" ' +- 'is to\n' +- 'be set to the name of the module. "__file__" is to be the "path" ' +- 'to\n' +- 'the file unless the module is built-in (and thus listed in\n' +- '"sys.builtin_module_names") in which case the attribute is not ' +- 'set. If\n' +- 'what is being imported is a package then "__path__" is to be set ' +- 'to a\n' +- 'list of paths to be searched when looking for modules and ' +- 'packages\n' +- 'contained within the package being imported. "__package__" is ' +- 'optional\n' +- 'but should be set to the name of package that contains the ' +- 'module or\n' +- 'package (the empty string is used for module not contained in a\n' +- 'package). "__loader__" is also optional but should be set to ' +- 'the\n' +- 'loader object that is loading the module.\n' +- '\n' +- 'If an error occurs during loading then the loader raises ' +- '"ImportError"\n' +- 'if some other exception is not already being propagated. ' +- 'Otherwise the\n' +- 'loader returns the module that was loaded and initialized.\n' +- '\n' +- 'When step (1) finishes without raising an exception, step (2) ' +- 'can\n' +- 'begin.\n' +- '\n' +- 'The first form of "import" statement binds the module name in ' +- 'the\n' +- 'local namespace to the module object, and then goes on to import ' +- 'the\n' +- 'next identifier, if any. If the module name is followed by ' +- '"as", the\n' +- 'name following "as" is used as the local name for the module.\n' +- '\n' +- 'The "from" form does not bind the module name: it goes through ' +- 'the\n' +- 'list of identifiers, looks each one of them up in the module ' +- 'found in\n' +- 'step (1), and binds the name in the local namespace to the ' +- 'object thus\n' +- 'found. As with the first form of "import", an alternate local ' +- 'name\n' +- 'can be supplied by specifying ""as" localname". If a name is ' +- 'not\n' +- 'found, "ImportError" is raised. If the list of identifiers is\n' +- 'replaced by a star ("\'*\'"), all public names defined in the ' +- 'module are\n' +- 'bound in the local namespace of the "import" statement..\n' +- '\n' +- 'The *public names* defined by a module are determined by ' +- 'checking the\n' +- 'module\'s namespace for a variable named "__all__"; if defined, ' +- 'it must\n' +- 'be a sequence of strings which are names defined or imported by ' +- 'that\n' +- 'module. The names given in "__all__" are all considered public ' +- 'and\n' +- 'are required to exist. If "__all__" is not defined, the set of ' +- 'public\n' +- "names includes all names found in the module's namespace which " +- 'do not\n' +- 'begin with an underscore character ("\'_\'"). "__all__" should ' +- 'contain\n' +- 'the entire public API. It is intended to avoid accidentally ' +- 'exporting\n' +- 'items that are not part of the API (such as library modules ' +- 'which were\n' +- 'imported and used within the module).\n' +- '\n' +- 'The "from" form with "*" may only occur in a module scope. If ' +- 'the\n' +- 'wild card form of import --- "import *" --- is used in a ' +- 'function and\n' +- 'the function contains or is a nested block with free variables, ' +- 'the\n' +- 'compiler will raise a "SyntaxError".\n' +- '\n' +- 'When specifying what module to import you do not have to specify ' +- 'the\n' +- 'absolute name of the module. When a module or package is ' +- 'contained\n' +- 'within another package it is possible to make a relative import ' +- 'within\n' +- 'the same top package without having to mention the package name. ' +- 'By\n' +- 'using leading dots in the specified module or package after ' +- '"from" you\n' +- 'can specify how high to traverse up the current package ' +- 'hierarchy\n' +- 'without specifying exact names. One leading dot means the ' +- 'current\n' +- 'package where the module making the import exists. Two dots ' +- 'means up\n' +- 'one package level. Three dots is up two levels, etc. So if you ' +- 'execute\n' +- '"from . import mod" from a module in the "pkg" package then you ' +- 'will\n' +- 'end up importing "pkg.mod". If you execute "from ..subpkg2 ' +- 'import mod"\n' +- 'from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". ' +- 'The\n' +- 'specification for relative imports is contained within **PEP ' +- '328**.\n' +- '\n' +- '"importlib.import_module()" is provided to support applications ' +- 'that\n' +- 'determine which modules need to be loaded dynamically.\n' +- '\n' +- '\n' +- 'Future statements\n' +- '=================\n' +- '\n' +- 'A *future statement* is a directive to the compiler that a ' +- 'particular\n' +- 'module should be compiled using syntax or semantics that will ' +- 'be\n' +- 'available in a specified future release of Python. The future\n' +- 'statement is intended to ease migration to future versions of ' +- 'Python\n' +- 'that introduce incompatible changes to the language. It allows ' +- 'use of\n' +- 'the new features on a per-module basis before the release in ' +- 'which the\n' +- 'feature becomes standard.\n' +- '\n' +- ' future_statement ::= "from" "__future__" "import" feature ' +- '["as" name]\n' +- ' ("," feature ["as" name])*\n' +- ' | "from" "__future__" "import" "(" ' +- 'feature ["as" name]\n' +- ' ("," feature ["as" name])* [","] ")"\n' +- ' feature ::= identifier\n' +- ' name ::= identifier\n' +- '\n' +- 'A future statement must appear near the top of the module. The ' +- 'only\n' +- 'lines that can appear before a future statement are:\n' +- '\n' +- '* the module docstring (if any),\n' +- '\n' +- '* comments,\n' +- '\n' +- '* blank lines, and\n' +- '\n' +- '* other future statements.\n' +- '\n' +- 'The features recognized by Python 2.6 are "unicode_literals",\n' +- '"print_function", "absolute_import", "division", "generators",\n' +- '"nested_scopes" and "with_statement". "generators", ' +- '"with_statement",\n' +- '"nested_scopes" are redundant in Python version 2.6 and above ' +- 'because\n' +- 'they are always enabled.\n' +- '\n' +- 'A future statement is recognized and treated specially at ' +- 'compile\n' +- 'time: Changes to the semantics of core constructs are often\n' +- 'implemented by generating different code. It may even be the ' +- 'case\n' +- 'that a new feature introduces new incompatible syntax (such as a ' +- 'new\n' +- 'reserved word), in which case the compiler may need to parse ' +- 'the\n' +- 'module differently. Such decisions cannot be pushed off until\n' +- 'runtime.\n' +- '\n' +- 'For any given release, the compiler knows which feature names ' +- 'have\n' +- 'been defined, and raises a compile-time error if a future ' +- 'statement\n' +- 'contains a feature not known to it.\n' +- '\n' +- 'The direct runtime semantics are the same as for any import ' +- 'statement:\n' +- 'there is a standard module "__future__", described later, and it ' +- 'will\n' +- 'be imported in the usual way at the time the future statement ' +- 'is\n' +- 'executed.\n' +- '\n' +- 'The interesting runtime semantics depend on the specific ' +- 'feature\n' +- 'enabled by the future statement.\n' +- '\n' +- 'Note that there is nothing special about the statement:\n' +- '\n' +- ' import __future__ [as name]\n' +- '\n' +- "That is not a future statement; it's an ordinary import " +- 'statement with\n' +- 'no special semantics or syntax restrictions.\n' +- '\n' +- 'Code compiled by an "exec" statement or calls to the built-in\n' +- 'functions "compile()" and "execfile()" that occur in a module ' +- '"M"\n' +- 'containing a future statement will, by default, use the new ' +- 'syntax or\n' +- 'semantics associated with the future statement. This can, ' +- 'starting\n' +- 'with Python 2.2 be controlled by optional arguments to ' +- '"compile()" ---\n' +- 'see the documentation of that function for details.\n' +- '\n' +- 'A future statement typed at an interactive interpreter prompt ' +- 'will\n' +- 'take effect for the rest of the interpreter session. If an\n' +- 'interpreter is started with the "-i" option, is passed a script ' +- 'name\n' +- 'to execute, and the script includes a future statement, it will ' +- 'be in\n' +- 'effect in the interactive session started after the script is\n' +- 'executed.\n' +- '\n' +- 'See also: **PEP 236** - Back to the __future__\n' +- '\n' +- ' The original proposal for the __future__ mechanism.\n', +- 'in': '\n' +- 'Comparisons\n' +- '***********\n' +- '\n' +- 'Unlike C, all comparison operations in Python have the same ' +- 'priority,\n' +- 'which is lower than that of any arithmetic, shifting or bitwise\n' +- 'operation. Also unlike C, expressions like "a < b < c" have the\n' +- 'interpretation that is conventional in mathematics:\n' +- '\n' +- ' comparison ::= or_expr ( comp_operator or_expr )*\n' +- ' comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="\n' +- ' | "is" ["not"] | ["not"] "in"\n' +- '\n' +- 'Comparisons yield boolean values: "True" or "False".\n' +- '\n' +- 'Comparisons can be chained arbitrarily, e.g., "x < y <= z" is\n' +- 'equivalent to "x < y and y <= z", except that "y" is evaluated only\n' +- 'once (but in both cases "z" is not evaluated at all when "x < y" is\n' +- 'found to be false).\n' +- '\n' +- 'Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and ' +- '*op1*,\n' +- '*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... ' +- 'y\n' +- 'opN z" is equivalent to "a op1 b and b op2 c and ... y opN z", ' +- 'except\n' +- 'that each expression is evaluated at most once.\n' +- '\n' +- 'Note that "a op1 b op2 c" doesn\'t imply any kind of comparison ' +- 'between\n' +- '*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\n' +- 'perhaps not pretty).\n' +- '\n' +- 'The forms "<>" and "!=" are equivalent; for consistency with C, ' +- '"!="\n' +- 'is preferred; where "!=" is mentioned below "<>" is also accepted.\n' +- 'The "<>" spelling is considered obsolescent.\n' +- '\n' +- 'The operators "<", ">", "==", ">=", "<=", and "!=" compare the ' +- 'values\n' +- 'of two objects. The objects need not have the same type. If both ' +- 'are\n' +- 'numbers, they are converted to a common type. Otherwise, objects ' +- 'of\n' +- 'different types *always* compare unequal, and are ordered ' +- 'consistently\n' +- 'but arbitrarily. You can control comparison behavior of objects of\n' +- 'non-built-in types by defining a "__cmp__" method or rich ' +- 'comparison\n' +- 'methods like "__gt__", described in section Special method names.\n' +- '\n' +- '(This unusual definition of comparison was used to simplify the\n' +- 'definition of operations like sorting and the "in" and "not in"\n' +- 'operators. In the future, the comparison rules for objects of\n' +- 'different types are likely to change.)\n' +- '\n' +- 'Comparison of objects of the same type depends on the type:\n' +- '\n' +- '* Numbers are compared arithmetically.\n' +- '\n' +- '* Strings are compared lexicographically using the numeric\n' +- ' equivalents (the result of the built-in function "ord()") of ' +- 'their\n' +- ' characters. Unicode and 8-bit strings are fully interoperable in\n' +- ' this behavior. [4]\n' +- '\n' +- '* Tuples and lists are compared lexicographically using comparison\n' +- ' of corresponding elements. This means that to compare equal, ' +- 'each\n' +- ' element must compare equal and the two sequences must be of the ' +- 'same\n' +- ' type and have the same length.\n' +- '\n' +- ' If not equal, the sequences are ordered the same as their first\n' +- ' differing elements. For example, "cmp([1,2,x], [1,2,y])" returns\n' +- ' the same as "cmp(x,y)". If the corresponding element does not\n' +- ' exist, the shorter sequence is ordered first (for example, "[1,2] ' +- '<\n' +- ' [1,2,3]").\n' +- '\n' +- '* Mappings (dictionaries) compare equal if and only if their sorted\n' +- ' (key, value) lists compare equal. [5] Outcomes other than ' +- 'equality\n' +- ' are resolved consistently, but are not otherwise defined. [6]\n' +- '\n' +- '* Most other objects of built-in types compare unequal unless they\n' +- ' are the same object; the choice whether one object is considered\n' +- ' smaller or larger than another one is made arbitrarily but\n' +- ' consistently within one execution of a program.\n' +- '\n' +- 'The operators "in" and "not in" test for collection membership. "x ' +- 'in\n' +- 's" evaluates to true if *x* is a member of the collection *s*, and\n' +- 'false otherwise. "x not in s" returns the negation of "x in s". ' +- 'The\n' +- 'collection membership test has traditionally been bound to ' +- 'sequences;\n' +- 'an object is a member of a collection if the collection is a ' +- 'sequence\n' +- 'and contains an element equal to that object. However, it make ' +- 'sense\n' +- 'for many other object types to support membership tests without ' +- 'being\n' +- 'a sequence. In particular, dictionaries (for keys) and sets ' +- 'support\n' +- 'membership testing.\n' +- '\n' +- 'For the list and tuple types, "x in y" is true if and only if there\n' +- 'exists an index *i* such that "x == y[i]" is true.\n' +- '\n' +- 'For the Unicode and string types, "x in y" is true if and only if ' +- '*x*\n' +- 'is a substring of *y*. An equivalent test is "y.find(x) != -1".\n' +- 'Note, *x* and *y* need not be the same type; consequently, "u\'ab\' ' +- 'in\n' +- '\'abc\'" will return "True". Empty strings are always considered to ' +- 'be a\n' +- 'substring of any other string, so """ in "abc"" will return "True".\n' +- '\n' +- 'Changed in version 2.3: Previously, *x* was required to be a string ' +- 'of\n' +- 'length "1".\n' +- '\n' +- 'For user-defined classes which define the "__contains__()" method, ' +- '"x\n' +- 'in y" is true if and only if "y.__contains__(x)" is true.\n' +- '\n' +- 'For user-defined classes which do not define "__contains__()" but ' +- 'do\n' +- 'define "__iter__()", "x in y" is true if some value "z" with "x == ' +- 'z"\n' +- 'is produced while iterating over "y". If an exception is raised\n' +- 'during the iteration, it is as if "in" raised that exception.\n' +- '\n' +- 'Lastly, the old-style iteration protocol is tried: if a class ' +- 'defines\n' +- '"__getitem__()", "x in y" is true if and only if there is a non-\n' +- 'negative integer index *i* such that "x == y[i]", and all lower\n' +- 'integer indices do not raise "IndexError" exception. (If any other\n' +- 'exception is raised, it is as if "in" raised that exception).\n' +- '\n' +- 'The operator "not in" is defined to have the inverse true value of\n' +- '"in".\n' +- '\n' +- 'The operators "is" and "is not" test for object identity: "x is y" ' +- 'is\n' +- 'true if and only if *x* and *y* are the same object. "x is not y"\n' +- 'yields the inverse truth value. [7]\n', +- 'integers': '\n' +- 'Integer and long integer literals\n' +- '*********************************\n' +- '\n' +- 'Integer and long integer literals are described by the ' +- 'following\n' +- 'lexical definitions:\n' +- '\n' +- ' longinteger ::= integer ("l" | "L")\n' +- ' integer ::= decimalinteger | octinteger | hexinteger ' +- '| bininteger\n' +- ' decimalinteger ::= nonzerodigit digit* | "0"\n' +- ' octinteger ::= "0" ("o" | "O") octdigit+ | "0" ' +- 'octdigit+\n' +- ' hexinteger ::= "0" ("x" | "X") hexdigit+\n' +- ' bininteger ::= "0" ("b" | "B") bindigit+\n' +- ' nonzerodigit ::= "1"..."9"\n' +- ' octdigit ::= "0"..."7"\n' +- ' bindigit ::= "0" | "1"\n' +- ' hexdigit ::= digit | "a"..."f" | "A"..."F"\n' +- '\n' +- 'Although both lower case "\'l\'" and upper case "\'L\'" are ' +- 'allowed as\n' +- 'suffix for long integers, it is strongly recommended to always ' +- 'use\n' +- '"\'L\'", since the letter "\'l\'" looks too much like the ' +- 'digit "\'1\'".\n' +- '\n' +- 'Plain integer literals that are above the largest ' +- 'representable plain\n' +- 'integer (e.g., 2147483647 when using 32-bit arithmetic) are ' +- 'accepted\n' +- 'as if they were long integers instead. [1] There is no limit ' +- 'for long\n' +- 'integer literals apart from what can be stored in available ' +- 'memory.\n' +- '\n' +- 'Some examples of plain integer literals (first row) and long ' +- 'integer\n' +- 'literals (second and third rows):\n' +- '\n' +- ' 7 2147483647 0177\n' +- ' 3L 79228162514264337593543950336L 0377L ' +- '0x100000000L\n' +- ' 79228162514264337593543950336 0xdeadbeef\n', +- 'lambda': '\n' +- 'Lambdas\n' +- '*******\n' +- '\n' +- ' lambda_expr ::= "lambda" [parameter_list]: expression\n' +- ' old_lambda_expr ::= "lambda" [parameter_list]: ' +- 'old_expression\n' +- '\n' +- 'Lambda expressions (sometimes called lambda forms) have the ' +- 'same\n' +- 'syntactic position as expressions. They are a shorthand to ' +- 'create\n' +- 'anonymous functions; the expression "lambda arguments: ' +- 'expression"\n' +- 'yields a function object. The unnamed object behaves like a ' +- 'function\n' +- 'object defined with\n' +- '\n' +- ' def name(arguments):\n' +- ' return expression\n' +- '\n' +- 'See section Function definitions for the syntax of parameter ' +- 'lists.\n' +- 'Note that functions created with lambda expressions cannot ' +- 'contain\n' +- 'statements.\n', +- 'lists': '\n' +- 'List displays\n' +- '*************\n' +- '\n' +- 'A list display is a possibly empty series of expressions enclosed ' +- 'in\n' +- 'square brackets:\n' +- '\n' +- ' list_display ::= "[" [expression_list | ' +- 'list_comprehension] "]"\n' +- ' list_comprehension ::= expression list_for\n' +- ' list_for ::= "for" target_list "in" ' +- 'old_expression_list [list_iter]\n' +- ' old_expression_list ::= old_expression [("," old_expression)+ ' +- '[","]]\n' +- ' old_expression ::= or_test | old_lambda_expr\n' +- ' list_iter ::= list_for | list_if\n' +- ' list_if ::= "if" old_expression [list_iter]\n' +- '\n' +- 'A list display yields a new list object. Its contents are ' +- 'specified\n' +- 'by providing either a list of expressions or a list ' +- 'comprehension.\n' +- 'When a comma-separated list of expressions is supplied, its ' +- 'elements\n' +- 'are evaluated from left to right and placed into the list object ' +- 'in\n' +- 'that order. When a list comprehension is supplied, it consists ' +- 'of a\n' +- 'single expression followed by at least one "for" clause and zero ' +- 'or\n' +- 'more "for" or "if" clauses. In this case, the elements of the ' +- 'new\n' +- 'list are those that would be produced by considering each of the ' +- '"for"\n' +- 'or "if" clauses a block, nesting from left to right, and ' +- 'evaluating\n' +- 'the expression to produce a list element each time the innermost ' +- 'block\n' +- 'is reached [1].\n', +- 'naming': '\n' +- 'Naming and binding\n' +- '******************\n' +- '\n' +- '*Names* refer to objects. Names are introduced by name binding\n' +- 'operations. Each occurrence of a name in the program text refers ' +- 'to\n' +- 'the *binding* of that name established in the innermost function ' +- 'block\n' +- 'containing the use.\n' +- '\n' +- 'A *block* is a piece of Python program text that is executed as ' +- 'a\n' +- 'unit. The following are blocks: a module, a function body, and a ' +- 'class\n' +- 'definition. Each command typed interactively is a block. A ' +- 'script\n' +- 'file (a file given as standard input to the interpreter or ' +- 'specified\n' +- 'on the interpreter command line the first argument) is a code ' +- 'block.\n' +- 'A script command (a command specified on the interpreter command ' +- 'line\n' +- "with the '**-c**' option) is a code block. The file read by " +- 'the\n' +- 'built-in function "execfile()" is a code block. The string ' +- 'argument\n' +- 'passed to the built-in function "eval()" and to the "exec" ' +- 'statement\n' +- 'is a code block. The expression read and evaluated by the ' +- 'built-in\n' +- 'function "input()" is a code block.\n' +- '\n' +- 'A code block is executed in an *execution frame*. A frame ' +- 'contains\n' +- 'some administrative information (used for debugging) and ' +- 'determines\n' +- "where and how execution continues after the code block's " +- 'execution has\n' +- 'completed.\n' +- '\n' +- 'A *scope* defines the visibility of a name within a block. If a ' +- 'local\n' +- 'variable is defined in a block, its scope includes that block. ' +- 'If the\n' +- 'definition occurs in a function block, the scope extends to any ' +- 'blocks\n' +- 'contained within the defining one, unless a contained block ' +- 'introduces\n' +- 'a different binding for the name. The scope of names defined in ' +- 'a\n' +- 'class block is limited to the class block; it does not extend to ' +- 'the\n' +- 'code blocks of methods -- this includes generator expressions ' +- 'since\n' +- 'they are implemented using a function scope. This means that ' +- 'the\n' +- 'following will fail:\n' +- '\n' +- ' class A:\n' +- ' a = 42\n' +- ' b = list(a + i for i in range(10))\n' +- '\n' +- 'When a name is used in a code block, it is resolved using the ' +- 'nearest\n' +- 'enclosing scope. The set of all such scopes visible to a code ' +- 'block\n' +- "is called the block's *environment*.\n" +- '\n' +- 'If a name is bound in a block, it is a local variable of that ' +- 'block.\n' +- 'If a name is bound at the module level, it is a global ' +- 'variable. (The\n' +- 'variables of the module code block are local and global.) If a\n' +- 'variable is used in a code block but not defined there, it is a ' +- '*free\n' +- 'variable*.\n' +- '\n' +- 'When a name is not found at all, a "NameError" exception is ' +- 'raised.\n' +- 'If the name refers to a local variable that has not been bound, ' +- 'a\n' +- '"UnboundLocalError" exception is raised. "UnboundLocalError" is ' +- 'a\n' +- 'subclass of "NameError".\n' +- '\n' +- 'The following constructs bind names: formal parameters to ' +- 'functions,\n' +- '"import" statements, class and function definitions (these bind ' +- 'the\n' +- 'class or function name in the defining block), and targets that ' +- 'are\n' +- 'identifiers if occurring in an assignment, "for" loop header, in ' +- 'the\n' +- 'second position of an "except" clause header or after "as" in a ' +- '"with"\n' +- 'statement. The "import" statement of the form "from ... import ' +- '*"\n' +- 'binds all names defined in the imported module, except those ' +- 'beginning\n' +- 'with an underscore. This form may only be used at the module ' +- 'level.\n' +- '\n' +- 'A target occurring in a "del" statement is also considered bound ' +- 'for\n' +- 'this purpose (though the actual semantics are to unbind the ' +- 'name). It\n' +- 'is illegal to unbind a name that is referenced by an enclosing ' +- 'scope;\n' +- 'the compiler will report a "SyntaxError".\n' +- '\n' +- 'Each assignment or import statement occurs within a block ' +- 'defined by a\n' +- 'class or function definition or at the module level (the ' +- 'top-level\n' +- 'code block).\n' +- '\n' +- 'If a name binding operation occurs anywhere within a code block, ' +- 'all\n' +- 'uses of the name within the block are treated as references to ' +- 'the\n' +- 'current block. This can lead to errors when a name is used ' +- 'within a\n' +- 'block before it is bound. This rule is subtle. Python lacks\n' +- 'declarations and allows name binding operations to occur ' +- 'anywhere\n' +- 'within a code block. The local variables of a code block can ' +- 'be\n' +- 'determined by scanning the entire text of the block for name ' +- 'binding\n' +- 'operations.\n' +- '\n' +- 'If the global statement occurs within a block, all uses of the ' +- 'name\n' +- 'specified in the statement refer to the binding of that name in ' +- 'the\n' +- 'top-level namespace. Names are resolved in the top-level ' +- 'namespace by\n' +- 'searching the global namespace, i.e. the namespace of the ' +- 'module\n' +- 'containing the code block, and the builtins namespace, the ' +- 'namespace\n' +- 'of the module "__builtin__". The global namespace is searched ' +- 'first.\n' +- 'If the name is not found there, the builtins namespace is ' +- 'searched.\n' +- 'The global statement must precede all uses of the name.\n' +- '\n' +- 'The builtins namespace associated with the execution of a code ' +- 'block\n' +- 'is actually found by looking up the name "__builtins__" in its ' +- 'global\n' +- 'namespace; this should be a dictionary or a module (in the ' +- 'latter case\n' +- "the module's dictionary is used). By default, when in the " +- '"__main__"\n' +- 'module, "__builtins__" is the built-in module "__builtin__" ' +- '(note: no\n' +- '\'s\'); when in any other module, "__builtins__" is an alias for ' +- 'the\n' +- 'dictionary of the "__builtin__" module itself. "__builtins__" ' +- 'can be\n' +- 'set to a user-created dictionary to create a weak form of ' +- 'restricted\n' +- 'execution.\n' +- '\n' +- '**CPython implementation detail:** Users should not touch\n' +- '"__builtins__"; it is strictly an implementation detail. Users\n' +- 'wanting to override values in the builtins namespace should ' +- '"import"\n' +- 'the "__builtin__" (no \'s\') module and modify its attributes\n' +- 'appropriately.\n' +- '\n' +- 'The namespace for a module is automatically created the first ' +- 'time a\n' +- 'module is imported. The main module for a script is always ' +- 'called\n' +- '"__main__".\n' +- '\n' +- 'The "global" statement has the same scope as a name binding ' +- 'operation\n' +- 'in the same block. If the nearest enclosing scope for a free ' +- 'variable\n' +- 'contains a global statement, the free variable is treated as a ' +- 'global.\n' +- '\n' +- 'A class definition is an executable statement that may use and ' +- 'define\n' +- 'names. These references follow the normal rules for name ' +- 'resolution.\n' +- 'The namespace of the class definition becomes the attribute ' +- 'dictionary\n' +- 'of the class. Names defined at the class scope are not visible ' +- 'in\n' +- 'methods.\n' +- '\n' +- '\n' +- 'Interaction with dynamic features\n' +- '=================================\n' +- '\n' +- 'There are several cases where Python statements are illegal when ' +- 'used\n' +- 'in conjunction with nested scopes that contain free variables.\n' +- '\n' +- 'If a variable is referenced in an enclosing scope, it is illegal ' +- 'to\n' +- 'delete the name. An error will be reported at compile time.\n' +- '\n' +- 'If the wild card form of import --- "import *" --- is used in a\n' +- 'function and the function contains or is a nested block with ' +- 'free\n' +- 'variables, the compiler will raise a "SyntaxError".\n' +- '\n' +- 'If "exec" is used in a function and the function contains or is ' +- 'a\n' +- 'nested block with free variables, the compiler will raise a\n' +- '"SyntaxError" unless the exec explicitly specifies the local ' +- 'namespace\n' +- 'for the "exec". (In other words, "exec obj" would be illegal, ' +- 'but\n' +- '"exec obj in ns" would be legal.)\n' +- '\n' +- 'The "eval()", "execfile()", and "input()" functions and the ' +- '"exec"\n' +- 'statement do not have access to the full environment for ' +- 'resolving\n' +- 'names. Names may be resolved in the local and global namespaces ' +- 'of\n' +- 'the caller. Free variables are not resolved in the nearest ' +- 'enclosing\n' +- 'namespace, but in the global namespace. [1] The "exec" statement ' +- 'and\n' +- 'the "eval()" and "execfile()" functions have optional arguments ' +- 'to\n' +- 'override the global and local namespace. If only one namespace ' +- 'is\n' +- 'specified, it is used for both.\n', +- 'numbers': '\n' +- 'Numeric literals\n' +- '****************\n' +- '\n' +- 'There are four types of numeric literals: plain integers, long\n' +- 'integers, floating point numbers, and imaginary numbers. There ' +- 'are no\n' +- 'complex literals (complex numbers can be formed by adding a ' +- 'real\n' +- 'number and an imaginary number).\n' +- '\n' +- 'Note that numeric literals do not include a sign; a phrase like ' +- '"-1"\n' +- 'is actually an expression composed of the unary operator ' +- '\'"-"\' and the\n' +- 'literal "1".\n', +- 'numeric-types': '\n' +- 'Emulating numeric types\n' +- '***********************\n' +- '\n' +- 'The following methods can be defined to emulate numeric ' +- 'objects.\n' +- 'Methods corresponding to operations that are not ' +- 'supported by the\n' +- 'particular kind of number implemented (e.g., bitwise ' +- 'operations for\n' +- 'non-integral numbers) should be left undefined.\n' +- '\n' +- 'object.__add__(self, other)\n' +- 'object.__sub__(self, other)\n' +- 'object.__mul__(self, other)\n' +- 'object.__floordiv__(self, other)\n' +- 'object.__mod__(self, other)\n' +- 'object.__divmod__(self, other)\n' +- 'object.__pow__(self, other[, modulo])\n' +- 'object.__lshift__(self, other)\n' +- 'object.__rshift__(self, other)\n' +- 'object.__and__(self, other)\n' +- 'object.__xor__(self, other)\n' +- 'object.__or__(self, other)\n' +- '\n' +- ' These methods are called to implement the binary ' +- 'arithmetic\n' +- ' operations ("+", "-", "*", "//", "%", "divmod()", ' +- '"pow()", "**",\n' +- ' "<<", ">>", "&", "^", "|"). For instance, to evaluate ' +- 'the\n' +- ' expression "x + y", where *x* is an instance of a ' +- 'class that has an\n' +- ' "__add__()" method, "x.__add__(y)" is called. The ' +- '"__divmod__()"\n' +- ' method should be the equivalent to using ' +- '"__floordiv__()" and\n' +- ' "__mod__()"; it should not be related to ' +- '"__truediv__()" (described\n' +- ' below). Note that "__pow__()" should be defined to ' +- 'accept an\n' +- ' optional third argument if the ternary version of the ' +- 'built-in\n' +- ' "pow()" function is to be supported.\n' +- '\n' +- ' If one of those methods does not support the operation ' +- 'with the\n' +- ' supplied arguments, it should return ' +- '"NotImplemented".\n' +- '\n' +- 'object.__div__(self, other)\n' +- 'object.__truediv__(self, other)\n' +- '\n' +- ' The division operator ("/") is implemented by these ' +- 'methods. The\n' +- ' "__truediv__()" method is used when ' +- '"__future__.division" is in\n' +- ' effect, otherwise "__div__()" is used. If only one of ' +- 'these two\n' +- ' methods is defined, the object will not support ' +- 'division in the\n' +- ' alternate context; "TypeError" will be raised ' +- 'instead.\n' +- '\n' +- 'object.__radd__(self, other)\n' +- 'object.__rsub__(self, other)\n' +- 'object.__rmul__(self, other)\n' +- 'object.__rdiv__(self, other)\n' +- 'object.__rtruediv__(self, other)\n' +- 'object.__rfloordiv__(self, other)\n' +- 'object.__rmod__(self, other)\n' +- 'object.__rdivmod__(self, other)\n' +- 'object.__rpow__(self, other)\n' +- 'object.__rlshift__(self, other)\n' +- 'object.__rrshift__(self, other)\n' +- 'object.__rand__(self, other)\n' +- 'object.__rxor__(self, other)\n' +- 'object.__ror__(self, other)\n' +- '\n' +- ' These methods are called to implement the binary ' +- 'arithmetic\n' +- ' operations ("+", "-", "*", "/", "%", "divmod()", ' +- '"pow()", "**",\n' +- ' "<<", ">>", "&", "^", "|") with reflected (swapped) ' +- 'operands.\n' +- ' These functions are only called if the left operand ' +- 'does not\n' +- ' support the corresponding operation and the operands ' +- 'are of\n' +- ' different types. [2] For instance, to evaluate the ' +- 'expression "x -\n' +- ' y", where *y* is an instance of a class that has an ' +- '"__rsub__()"\n' +- ' method, "y.__rsub__(x)" is called if "x.__sub__(y)" ' +- 'returns\n' +- ' *NotImplemented*.\n' +- '\n' +- ' Note that ternary "pow()" will not try calling ' +- '"__rpow__()" (the\n' +- ' coercion rules would become too complicated).\n' +- '\n' +- " Note: If the right operand's type is a subclass of the " +- 'left\n' +- " operand's type and that subclass provides the " +- 'reflected method\n' +- ' for the operation, this method will be called before ' +- 'the left\n' +- " operand's non-reflected method. This behavior " +- 'allows subclasses\n' +- " to override their ancestors' operations.\n" +- '\n' +- 'object.__iadd__(self, other)\n' +- 'object.__isub__(self, other)\n' +- 'object.__imul__(self, other)\n' +- 'object.__idiv__(self, other)\n' +- 'object.__itruediv__(self, other)\n' +- 'object.__ifloordiv__(self, other)\n' +- 'object.__imod__(self, other)\n' +- 'object.__ipow__(self, other[, modulo])\n' +- 'object.__ilshift__(self, other)\n' +- 'object.__irshift__(self, other)\n' +- 'object.__iand__(self, other)\n' +- 'object.__ixor__(self, other)\n' +- 'object.__ior__(self, other)\n' +- '\n' +- ' These methods are called to implement the augmented ' +- 'arithmetic\n' +- ' assignments ("+=", "-=", "*=", "/=", "//=", "%=", ' +- '"**=", "<<=",\n' +- ' ">>=", "&=", "^=", "|="). These methods should ' +- 'attempt to do the\n' +- ' operation in-place (modifying *self*) and return the ' +- 'result (which\n' +- ' could be, but does not have to be, *self*). If a ' +- 'specific method\n' +- ' is not defined, the augmented assignment falls back to ' +- 'the normal\n' +- ' methods. For instance, to execute the statement "x += ' +- 'y", where\n' +- ' *x* is an instance of a class that has an "__iadd__()" ' +- 'method,\n' +- ' "x.__iadd__(y)" is called. If *x* is an instance of a ' +- 'class that\n' +- ' does not define a "__iadd__()" method, "x.__add__(y)" ' +- 'and\n' +- ' "y.__radd__(x)" are considered, as with the evaluation ' +- 'of "x + y".\n' +- '\n' +- 'object.__neg__(self)\n' +- 'object.__pos__(self)\n' +- 'object.__abs__(self)\n' +- 'object.__invert__(self)\n' +- '\n' +- ' Called to implement the unary arithmetic operations ' +- '("-", "+",\n' +- ' "abs()" and "~").\n' +- '\n' +- 'object.__complex__(self)\n' +- 'object.__int__(self)\n' +- 'object.__long__(self)\n' +- 'object.__float__(self)\n' +- '\n' +- ' Called to implement the built-in functions ' +- '"complex()", "int()",\n' +- ' "long()", and "float()". Should return a value of the ' +- 'appropriate\n' +- ' type.\n' +- '\n' +- 'object.__oct__(self)\n' +- 'object.__hex__(self)\n' +- '\n' +- ' Called to implement the built-in functions "oct()" and ' +- '"hex()".\n' +- ' Should return a string value.\n' +- '\n' +- 'object.__index__(self)\n' +- '\n' +- ' Called to implement "operator.index()". Also called ' +- 'whenever\n' +- ' Python needs an integer object (such as in slicing). ' +- 'Must return\n' +- ' an integer (int or long).\n' +- '\n' +- ' New in version 2.5.\n' +- '\n' +- 'object.__coerce__(self, other)\n' +- '\n' +- ' Called to implement "mixed-mode" numeric arithmetic. ' +- 'Should either\n' +- ' return a 2-tuple containing *self* and *other* ' +- 'converted to a\n' +- ' common numeric type, or "None" if conversion is ' +- 'impossible. When\n' +- ' the common type would be the type of "other", it is ' +- 'sufficient to\n' +- ' return "None", since the interpreter will also ask the ' +- 'other object\n' +- ' to attempt a coercion (but sometimes, if the ' +- 'implementation of the\n' +- ' other type cannot be changed, it is useful to do the ' +- 'conversion to\n' +- ' the other type here). A return value of ' +- '"NotImplemented" is\n' +- ' equivalent to returning "None".\n', +- 'objects': '\n' +- 'Objects, values and types\n' +- '*************************\n' +- '\n' +- "*Objects* are Python's abstraction for data. All data in a " +- 'Python\n' +- 'program is represented by objects or by relations between ' +- 'objects. (In\n' +- "a sense, and in conformance to Von Neumann's model of a " +- '"stored\n' +- 'program computer," code is also represented by objects.)\n' +- '\n' +- "Every object has an identity, a type and a value. An object's\n" +- '*identity* never changes once it has been created; you may ' +- 'think of it\n' +- 'as the object\'s address in memory. The \'"is"\' operator ' +- 'compares the\n' +- 'identity of two objects; the "id()" function returns an ' +- 'integer\n' +- 'representing its identity (currently implemented as its ' +- 'address). An\n' +- "object's *type* is also unchangeable. [1] An object's type " +- 'determines\n' +- 'the operations that the object supports (e.g., "does it have a\n' +- 'length?") and also defines the possible values for objects of ' +- 'that\n' +- 'type. The "type()" function returns an object\'s type (which ' +- 'is an\n' +- 'object itself). The *value* of some objects can change. ' +- 'Objects\n' +- 'whose value can change are said to be *mutable*; objects whose ' +- 'value\n' +- 'is unchangeable once they are created are called *immutable*. ' +- '(The\n' +- 'value of an immutable container object that contains a ' +- 'reference to a\n' +- "mutable object can change when the latter's value is changed; " +- 'however\n' +- 'the container is still considered immutable, because the ' +- 'collection of\n' +- 'objects it contains cannot be changed. So, immutability is ' +- 'not\n' +- 'strictly the same as having an unchangeable value, it is more ' +- 'subtle.)\n' +- "An object's mutability is determined by its type; for " +- 'instance,\n' +- 'numbers, strings and tuples are immutable, while dictionaries ' +- 'and\n' +- 'lists are mutable.\n' +- '\n' +- 'Objects are never explicitly destroyed; however, when they ' +- 'become\n' +- 'unreachable they may be garbage-collected. An implementation ' +- 'is\n' +- 'allowed to postpone garbage collection or omit it altogether ' +- '--- it is\n' +- 'a matter of implementation quality how garbage collection is\n' +- 'implemented, as long as no objects are collected that are ' +- 'still\n' +- 'reachable.\n' +- '\n' +- '**CPython implementation detail:** CPython currently uses a ' +- 'reference-\n' +- 'counting scheme with (optional) delayed detection of cyclically ' +- 'linked\n' +- 'garbage, which collects most objects as soon as they become\n' +- 'unreachable, but is not guaranteed to collect garbage ' +- 'containing\n' +- 'circular references. See the documentation of the "gc" module ' +- 'for\n' +- 'information on controlling the collection of cyclic garbage. ' +- 'Other\n' +- 'implementations act differently and CPython may change. Do not ' +- 'depend\n' +- 'on immediate finalization of objects when they become ' +- 'unreachable (ex:\n' +- 'always close files).\n' +- '\n' +- "Note that the use of the implementation's tracing or debugging\n" +- 'facilities may keep objects alive that would normally be ' +- 'collectable.\n' +- 'Also note that catching an exception with a ' +- '\'"try"..."except"\'\n' +- 'statement may keep objects alive.\n' +- '\n' +- 'Some objects contain references to "external" resources such as ' +- 'open\n' +- 'files or windows. It is understood that these resources are ' +- 'freed\n' +- 'when the object is garbage-collected, but since garbage ' +- 'collection is\n' +- 'not guaranteed to happen, such objects also provide an explicit ' +- 'way to\n' +- 'release the external resource, usually a "close()" method. ' +- 'Programs\n' +- 'are strongly recommended to explicitly close such objects. ' +- 'The\n' +- '\'"try"..."finally"\' statement provides a convenient way to do ' +- 'this.\n' +- '\n' +- 'Some objects contain references to other objects; these are ' +- 'called\n' +- '*containers*. Examples of containers are tuples, lists and\n' +- "dictionaries. The references are part of a container's value. " +- 'In\n' +- 'most cases, when we talk about the value of a container, we ' +- 'imply the\n' +- 'values, not the identities of the contained objects; however, ' +- 'when we\n' +- 'talk about the mutability of a container, only the identities ' +- 'of the\n' +- 'immediately contained objects are implied. So, if an ' +- 'immutable\n' +- 'container (like a tuple) contains a reference to a mutable ' +- 'object, its\n' +- 'value changes if that mutable object is changed.\n' +- '\n' +- 'Types affect almost all aspects of object behavior. Even the\n' +- 'importance of object identity is affected in some sense: for ' +- 'immutable\n' +- 'types, operations that compute new values may actually return ' +- 'a\n' +- 'reference to any existing object with the same type and value, ' +- 'while\n' +- 'for mutable objects this is not allowed. E.g., after "a = 1; b ' +- '= 1",\n' +- '"a" and "b" may or may not refer to the same object with the ' +- 'value\n' +- 'one, depending on the implementation, but after "c = []; d = ' +- '[]", "c"\n' +- 'and "d" are guaranteed to refer to two different, unique, ' +- 'newly\n' +- 'created empty lists. (Note that "c = d = []" assigns the same ' +- 'object\n' +- 'to both "c" and "d".)\n', +- 'operator-summary': '\n' +- 'Operator precedence\n' +- '*******************\n' +- '\n' +- 'The following table summarizes the operator ' +- 'precedences in Python,\n' +- 'from lowest precedence (least binding) to highest ' +- 'precedence (most\n' +- 'binding). Operators in the same box have the same ' +- 'precedence. Unless\n' +- 'the syntax is explicitly given, operators are binary. ' +- 'Operators in\n' +- 'the same box group left to right (except for ' +- 'comparisons, including\n' +- 'tests, which all have the same precedence and chain ' +- 'from left to right\n' +- '--- see section Comparisons --- and exponentiation, ' +- 'which groups from\n' +- '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...]", "{key: | ' +- 'Binding or tuple display, list |\n' +- '| 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"\n' +- ' the control variables of each "for" it contains ' +- 'into the\n' +- ' containing scope. However, this behavior is ' +- 'deprecated, and\n' +- ' relying on it will not work in Python 3.\n' +- '\n' +- '[2] While "abs(x%y) < abs(y)" is true mathematically, ' +- 'for floats\n' +- ' it 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", which\n' +- ' is numerically exactly equal to "1e100". The ' +- 'function\n' +- ' "math.fmod()" returns a result whose sign matches ' +- 'the sign of the\n' +- ' first argument instead, and so returns "-1e-100" ' +- 'in this case.\n' +- ' Which approach is more appropriate depends on the ' +- '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" due to\n' +- ' rounding. In such cases, Python returns the ' +- 'latter result, in\n' +- ' order to preserve that "divmod(x,y)[0] * y + x % ' +- 'y" be very close\n' +- ' to "x".\n' +- '\n' +- '[4] While comparisons between unicode strings make ' +- 'sense at the\n' +- ' byte level, they may be counter-intuitive to ' +- 'users. For example,\n' +- ' the 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\n' +- ' constructing lists or sorting.\n' +- '\n' +- '[6] Earlier versions of Python used lexicographic ' +- 'comparison of\n' +- ' the 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\n' +- ' dynamic nature of descriptors, you may notice ' +- 'seemingly unusual\n' +- ' behaviour in certain uses of the "is" operator, ' +- 'like those\n' +- ' involving comparisons between instance methods, or ' +- 'constants.\n' +- ' Check their 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\n' +- ' or bitwise unary operator on its right, that is, ' +- '"2**-1" is "0.5".\n', +- 'pass': '\n' +- 'The "pass" statement\n' +- '********************\n' +- '\n' +- ' pass_stmt ::= "pass"\n' +- '\n' +- '"pass" is a null operation --- when it is executed, nothing ' +- 'happens.\n' +- 'It is useful as a placeholder when a statement is required\n' +- 'syntactically, 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': '\n' +- 'The power operator\n' +- '******************\n' +- '\n' +- 'The power operator binds more tightly than unary operators on ' +- 'its\n' +- 'left; it binds less tightly than unary operators on its right. ' +- 'The\n' +- 'syntax is:\n' +- '\n' +- ' power ::= primary ["**" u_expr]\n' +- '\n' +- 'Thus, in an unparenthesized sequence of power and unary ' +- 'operators, the\n' +- 'operators are evaluated from right to left (this does not ' +- 'constrain\n' +- 'the evaluation order for the operands): "-1**2" results in "-1".\n' +- '\n' +- 'The power operator has the same semantics as the built-in ' +- '"pow()"\n' +- 'function, when called with two arguments: it yields its left ' +- 'argument\n' +- 'raised to the power of its right argument. The numeric arguments ' +- 'are\n' +- 'first converted to a common type. The result type is that of ' +- 'the\n' +- 'arguments after coercion.\n' +- '\n' +- 'With mixed operand types, the coercion rules for binary ' +- 'arithmetic\n' +- 'operators apply. For int and long int operands, the result has ' +- 'the\n' +- 'same type as the operands (after coercion) unless the second ' +- 'argument\n' +- 'is negative; in that case, all arguments are converted to float ' +- 'and a\n' +- 'float result is delivered. For example, "10**2" returns "100", ' +- 'but\n' +- '"10**-2" returns "0.01". (This last feature was added in Python ' +- '2.2.\n' +- 'In Python 2.1 and before, if both arguments were of integer types ' +- 'and\n' +- 'the second argument was negative, an exception was raised).\n' +- '\n' +- 'Raising "0.0" to a negative power results in a ' +- '"ZeroDivisionError".\n' +- 'Raising a negative number to a fractional power results in a\n' +- '"ValueError".\n', +- 'print': '\n' +- 'The "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\n' +- 'object to standard output (see below). If an object is not a ' +- 'string,\n' +- 'it is first converted to a string using the rules for string\n' +- 'conversions. The (resulting or original) string is then ' +- 'written. A\n' +- 'space is written before each object is (converted and) written, ' +- 'unless\n' +- 'the output system believes it is positioned at the beginning of ' +- 'a\n' +- 'line. This is the case (1) when no characters have yet been ' +- 'written\n' +- 'to standard output, (2) when the last character written to ' +- 'standard\n' +- 'output is a whitespace character except "\' \'", or (3) when the ' +- 'last\n' +- 'write operation on standard output was not a "print" statement. ' +- '(In\n' +- 'some cases it may be functional to write an empty string to ' +- 'standard\n' +- 'output for this reason.)\n' +- '\n' +- 'Note: Objects which act like file objects but which are not the\n' +- ' built-in file objects often do not properly emulate this aspect ' +- 'of\n' +- " the file object's behavior, so it is best not to rely on this.\n" +- '\n' +- 'A "\'\\n\'" character is written at the end, unless the "print" ' +- 'statement\n' +- 'ends with a comma. This is the only action if the statement ' +- 'contains\n' +- 'just the keyword "print".\n' +- '\n' +- 'Standard output is defined as the file object named "stdout" in ' +- 'the\n' +- 'built-in module "sys". If no such object exists, or if it does ' +- 'not\n' +- 'have a "write()" method, a "RuntimeError" exception is raised.\n' +- '\n' +- '"print" also has an extended form, defined by the second portion ' +- 'of\n' +- 'the 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 ' +- 'that has\n' +- 'a "write()" method as described above. With this extended form, ' +- 'the\n' +- 'subsequent expressions are printed to this file object. If the ' +- 'first\n' +- 'expression evaluates to "None", then "sys.stdout" is used as the ' +- 'file\n' +- 'for output.\n', +- 'raise': '\n' +- 'The "raise" statement\n' +- '*********************\n' +- '\n' +- ' raise_stmt ::= "raise" [expression ["," expression ["," ' +- 'expression]]]\n' +- '\n' +- 'If no expressions are present, "raise" re-raises the last ' +- 'exception\n' +- 'that was active in the current scope. If no exception is active ' +- 'in\n' +- 'the current scope, a "TypeError" exception is raised indicating ' +- 'that\n' +- 'this is an error (if running under IDLE, a "Queue.Empty" ' +- 'exception is\n' +- 'raised instead).\n' +- '\n' +- 'Otherwise, "raise" evaluates the expressions to get three ' +- 'objects,\n' +- 'using "None" as the value of omitted expressions. The first two\n' +- 'objects are used to determine the *type* and *value* of the ' +- 'exception.\n' +- '\n' +- 'If the first object is an instance, the type of the exception is ' +- 'the\n' +- 'class of the instance, the instance itself is the value, and the\n' +- 'second object must be "None".\n' +- '\n' +- 'If the first object is a class, it becomes the type of the ' +- 'exception.\n' +- 'The second object is used to determine the exception value: If it ' +- 'is\n' +- 'an instance of the class, the instance becomes the exception ' +- 'value. If\n' +- 'the second object is a tuple, it is used as the argument list for ' +- 'the\n' +- 'class constructor; if it is "None", an empty argument list is ' +- 'used,\n' +- 'and any other object is treated as a single argument to the\n' +- 'constructor. The instance so created by calling the constructor ' +- 'is\n' +- 'used as the exception value.\n' +- '\n' +- 'If a third object is present and not "None", it must be a ' +- 'traceback\n' +- 'object (see section The standard type hierarchy), and it is\n' +- 'substituted instead of the current location as the place where ' +- 'the\n' +- 'exception occurred. If the third object is present and not a\n' +- 'traceback object or "None", a "TypeError" exception is raised. ' +- 'The\n' +- 'three-expression form of "raise" is useful to re-raise an ' +- 'exception\n' +- 'transparently in an except clause, but "raise" with no ' +- 'expressions\n' +- 'should be preferred if the exception to be re-raised was the ' +- 'most\n' +- 'recently active exception in the current scope.\n' +- '\n' +- 'Additional information on exceptions can be found in section\n' +- 'Exceptions, and information about handling exceptions is in ' +- 'section\n' +- 'The try statement.\n', +- 'return': '\n' +- 'The "return" statement\n' +- '**********************\n' +- '\n' +- ' return_stmt ::= "return" [expression_list]\n' +- '\n' +- '"return" may only occur syntactically nested in a function ' +- 'definition,\n' +- 'not within a nested class definition.\n' +- '\n' +- 'If an expression list is present, it is evaluated, else "None" ' +- 'is\n' +- 'substituted.\n' +- '\n' +- '"return" leaves the current function call with the expression ' +- 'list (or\n' +- '"None") as return value.\n' +- '\n' +- 'When "return" passes control out of a "try" statement with a ' +- '"finally"\n' +- 'clause, that "finally" clause is executed before really leaving ' +- 'the\n' +- 'function.\n' +- '\n' +- 'In a generator function, the "return" statement is not allowed ' +- 'to\n' +- 'include an "expression_list". In that context, a bare "return"\n' +- 'indicates that the generator is done and will cause ' +- '"StopIteration" to\n' +- 'be raised.\n', +- 'sequence-types': '\n' +- 'Emulating container types\n' +- '*************************\n' +- '\n' +- 'The following methods can be defined to implement ' +- 'container objects.\n' +- 'Containers usually are sequences (such as lists or ' +- 'tuples) or mappings\n' +- '(like dictionaries), but can represent other containers ' +- 'as well. The\n' +- 'first set of methods is used either to emulate a ' +- 'sequence or to\n' +- 'emulate a mapping; the difference is that for a ' +- 'sequence, the\n' +- 'allowable keys should be the integers *k* for which "0 ' +- '<= k < N" where\n' +- '*N* is the length of the sequence, or slice objects, ' +- 'which define a\n' +- 'range of items. (For backwards compatibility, the ' +- 'method\n' +- '"__getslice__()" (see below) can also be defined to ' +- 'handle simple, but\n' +- 'not extended slices.) It is also recommended that ' +- 'mappings provide the\n' +- 'methods "keys()", "values()", "items()", "has_key()", ' +- '"get()",\n' +- '"clear()", "setdefault()", "iterkeys()", ' +- '"itervalues()",\n' +- '"iteritems()", "pop()", "popitem()", "copy()", and ' +- '"update()" behaving\n' +- "similar to those for Python's standard dictionary " +- 'objects. The\n' +- '"UserDict" module provides a "DictMixin" class to help ' +- 'create those\n' +- 'methods from a base set of "__getitem__()", ' +- '"__setitem__()",\n' +- '"__delitem__()", and "keys()". Mutable sequences should ' +- 'provide\n' +- 'methods "append()", "count()", "index()", "extend()", ' +- '"insert()",\n' +- '"pop()", "remove()", "reverse()" and "sort()", like ' +- 'Python standard\n' +- 'list objects. Finally, sequence types should implement ' +- 'addition\n' +- '(meaning concatenation) and multiplication (meaning ' +- 'repetition) by\n' +- 'defining the methods "__add__()", "__radd__()", ' +- '"__iadd__()",\n' +- '"__mul__()", "__rmul__()" and "__imul__()" described ' +- 'below; they\n' +- 'should not define "__coerce__()" or other numerical ' +- 'operators. It is\n' +- 'recommended that both mappings and sequences implement ' +- 'the\n' +- '"__contains__()" method to allow efficient use of the ' +- '"in" operator;\n' +- 'for mappings, "in" should be equivalent of "has_key()"; ' +- 'for sequences,\n' +- 'it should search through the values. It is further ' +- 'recommended that\n' +- 'both mappings and sequences implement the "__iter__()" ' +- 'method to allow\n' +- 'efficient iteration through the container; for mappings, ' +- '"__iter__()"\n' +- 'should be the same as "iterkeys()"; for sequences, it ' +- 'should iterate\n' +- 'through the values.\n' +- '\n' +- 'object.__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 that\n' +- ' doesn\'t define a "__nonzero__()" method and whose ' +- '"__len__()"\n' +- ' method returns zero is considered to be false in a ' +- 'Boolean context.\n' +- '\n' +- 'object.__getitem__(self, key)\n' +- '\n' +- ' Called to implement evaluation of "self[key]". For ' +- 'sequence types,\n' +- ' the accepted keys should be integers and slice ' +- 'objects. Note that\n' +- ' the special interpretation of negative indexes (if ' +- 'the class wishes\n' +- ' to emulate a sequence type) is up to the ' +- '"__getitem__()" method. If\n' +- ' *key* is of an inappropriate type, "TypeError" may be ' +- 'raised; if of\n' +- ' a value outside the set of indexes for the sequence ' +- '(after any\n' +- ' special interpretation of negative values), ' +- '"IndexError" should be\n' +- ' raised. For mapping types, if *key* is missing (not ' +- 'in the\n' +- ' container), "KeyError" 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' +- '\n' +- 'object.__missing__(self, key)\n' +- '\n' +- ' Called by "dict"."__getitem__()" to implement ' +- '"self[key]" for dict\n' +- ' subclasses when key is not in the dictionary.\n' +- '\n' +- 'object.__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' +- '\n' +- 'object.__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__()" method.\n' +- '\n' +- 'object.__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' +- '\n' +- 'object.__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 ' +- '"reversed()"\n' +- ' built-in will fall back to using the sequence ' +- 'protocol ("__len__()"\n' +- ' and "__getitem__()"). Objects that support the ' +- 'sequence protocol\n' +- ' should only provide "__reversed__()" if they can ' +- 'provide an\n' +- ' implementation that is more efficient than the one ' +- 'provided by\n' +- ' "reversed()".\n' +- '\n' +- ' New in version 2.6.\n' +- '\n' +- 'The membership test operators ("in" and "not in") are ' +- 'normally\n' +- 'implemented as an iteration through a sequence. ' +- 'However, container\n' +- 'objects can supply the following special method with a ' +- 'more efficient\n' +- 'implementation, which also does not require the object ' +- 'be a sequence.\n' +- '\n' +- 'object.__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 test\n' +- ' first tries iteration via "__iter__()", then the old ' +- 'sequence\n' +- ' iteration protocol via "__getitem__()", see this ' +- 'section in the\n' +- ' language reference.\n', +- 'shifting': '\n' +- 'Shifting operations\n' +- '*******************\n' +- '\n' +- 'The shifting operations have lower priority than the ' +- 'arithmetic\n' +- 'operations:\n' +- '\n' +- ' shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n' +- '\n' +- 'These operators accept plain or long integers as arguments. ' +- 'The\n' +- 'arguments are converted to a common type. They shift the ' +- 'first\n' +- 'argument to the left or right by the number of bits given by ' +- 'the\n' +- 'second argument.\n' +- '\n' +- 'A right shift by *n* bits is defined as division by "pow(2, ' +- 'n)". A\n' +- 'left shift by *n* bits is defined as multiplication with ' +- '"pow(2, n)".\n' +- 'Negative shift counts raise a "ValueError" exception.\n' +- '\n' +- 'Note: In the current implementation, the right-hand operand ' +- 'is\n' +- ' required to be at most "sys.maxsize". If the right-hand ' +- 'operand is\n' +- ' larger than "sys.maxsize" an "OverflowError" exception is ' +- 'raised.\n', +- 'slicings': '\n' +- 'Slicings\n' +- '********\n' +- '\n' +- 'A slicing selects a range of items in a sequence object (e.g., ' +- 'a\n' +- 'string, tuple or list). Slicings may be used as expressions ' +- 'or as\n' +- 'targets in assignment or "del" statements. The syntax for a ' +- 'slicing:\n' +- '\n' +- ' slicing ::= simple_slicing | extended_slicing\n' +- ' simple_slicing ::= primary "[" short_slice "]"\n' +- ' extended_slicing ::= primary "[" slice_list "]"\n' +- ' slice_list ::= slice_item ("," slice_item)* [","]\n' +- ' slice_item ::= expression | proper_slice | ellipsis\n' +- ' proper_slice ::= short_slice | long_slice\n' +- ' short_slice ::= [lower_bound] ":" [upper_bound]\n' +- ' long_slice ::= short_slice ":" [stride]\n' +- ' lower_bound ::= expression\n' +- ' upper_bound ::= expression\n' +- ' stride ::= expression\n' +- ' ellipsis ::= "..."\n' +- '\n' +- 'There is ambiguity in the formal syntax here: anything that ' +- 'looks like\n' +- 'an expression list also looks like a slice list, so any ' +- 'subscription\n' +- 'can be interpreted as a slicing. Rather than further ' +- 'complicating the\n' +- 'syntax, this is disambiguated by defining that in this case ' +- 'the\n' +- 'interpretation as a subscription takes priority over the\n' +- 'interpretation as a slicing (this is the case if the slice ' +- 'list\n' +- 'contains no proper slice nor ellipses). Similarly, when the ' +- 'slice\n' +- 'list has exactly one short slice and no trailing comma, the\n' +- 'interpretation as a simple slicing takes priority over that as ' +- 'an\n' +- 'extended slicing.\n' +- '\n' +- 'The semantics for a simple slicing are as follows. The ' +- 'primary must\n' +- 'evaluate to a sequence object. The lower and upper bound ' +- 'expressions,\n' +- 'if present, must evaluate to plain integers; defaults are zero ' +- 'and the\n' +- '"sys.maxint", respectively. If either bound is negative, the\n' +- "sequence's length is added to it. The slicing now selects all " +- 'items\n' +- 'with index *k* such that "i <= k < j" where *i* and *j* are ' +- 'the\n' +- 'specified lower and upper bounds. This may be an empty ' +- 'sequence. It\n' +- 'is not an error if *i* or *j* lie outside the range of valid ' +- 'indexes\n' +- "(such items don't exist so they aren't selected).\n" +- '\n' +- 'The semantics for an extended slicing are as follows. The ' +- 'primary\n' +- 'must evaluate to a mapping object, and it is indexed with a ' +- 'key that\n' +- 'is constructed from the slice list, as follows. If the slice ' +- 'list\n' +- 'contains at least one comma, the key is a tuple containing ' +- 'the\n' +- 'conversion of the slice items; otherwise, the conversion of ' +- 'the lone\n' +- 'slice item is the key. The conversion of a slice item that is ' +- 'an\n' +- 'expression is that expression. The conversion of an ellipsis ' +- 'slice\n' +- 'item is the built-in "Ellipsis" object. The conversion of a ' +- 'proper\n' +- 'slice is a slice object (see section The standard type ' +- 'hierarchy)\n' +- 'whose "start", "stop" and "step" attributes are the values of ' +- 'the\n' +- 'expressions given as lower bound, upper bound and stride,\n' +- 'respectively, substituting "None" for missing expressions.\n', +- 'specialattrs': '\n' +- 'Special Attributes\n' +- '******************\n' +- '\n' +- 'The implementation adds a few special read-only attributes ' +- 'to several\n' +- 'object types, where they are relevant. Some of these are ' +- 'not reported\n' +- 'by the "dir()" built-in function.\n' +- '\n' +- 'object.__dict__\n' +- '\n' +- ' A dictionary or other mapping object used to store an ' +- "object's\n" +- ' (writable) attributes.\n' +- '\n' +- 'object.__methods__\n' +- '\n' +- ' Deprecated since version 2.2: Use the built-in function ' +- '"dir()" to\n' +- " get a list of an object's attributes. This attribute is " +- 'no longer\n' +- ' available.\n' +- '\n' +- 'object.__members__\n' +- '\n' +- ' Deprecated since version 2.2: Use the built-in function ' +- '"dir()" to\n' +- " get a list of an object's attributes. This attribute is " +- 'no longer\n' +- ' available.\n' +- '\n' +- 'instance.__class__\n' +- '\n' +- ' The class to which a class instance belongs.\n' +- '\n' +- 'class.__bases__\n' +- '\n' +- ' The tuple of base classes of a class object.\n' +- '\n' +- 'class.__name__\n' +- '\n' +- ' The name of the class or type.\n' +- '\n' +- 'The following attributes are only supported by *new-style ' +- 'class*es.\n' +- '\n' +- 'class.__mro__\n' +- '\n' +- ' This attribute is a tuple of classes that are ' +- 'considered when\n' +- ' looking for base classes during method resolution.\n' +- '\n' +- 'class.mro()\n' +- '\n' +- ' This method can be overridden by a metaclass to ' +- 'customize the\n' +- ' method resolution order for its instances. It is ' +- 'called at class\n' +- ' instantiation, and its result is stored in "__mro__".\n' +- '\n' +- 'class.__subclasses__()\n' +- '\n' +- ' Each new-style class keeps a list of weak references to ' +- 'its\n' +- ' immediate subclasses. This method returns a list of ' +- 'all those\n' +- ' references still alive. Example:\n' +- '\n' +- ' >>> int.__subclasses__()\n' +- " []\n" +- '\n' +- '-[ Footnotes ]-\n' +- '\n' +- '[1] Additional information on these special methods may be ' +- 'found\n' +- ' in the Python Reference Manual (Basic customization).\n' +- '\n' +- '[2] As a consequence, the list "[1, 2]" is considered ' +- 'equal to\n' +- ' "[1.0, 2.0]", and similarly for tuples.\n' +- '\n' +- "[3] They must have since the parser can't tell the type of " +- 'the\n' +- ' operands.\n' +- '\n' +- '[4] Cased characters are those with general category ' +- 'property\n' +- ' being one of "Lu" (Letter, uppercase), "Ll" (Letter, ' +- 'lowercase),\n' +- ' or "Lt" (Letter, titlecase).\n' +- '\n' +- '[5] To format only a tuple you should therefore provide a\n' +- ' singleton tuple whose only element is the tuple to be ' +- 'formatted.\n' +- '\n' +- '[6] The advantage of leaving the newline on is that ' +- 'returning an\n' +- ' empty string is then an unambiguous EOF indication. ' +- 'It is also\n' +- ' possible (in cases where it might matter, for example, ' +- 'if you want\n' +- ' to make an exact copy of a file while scanning its ' +- 'lines) to tell\n' +- ' whether the last line of a file ended in a newline or ' +- 'not (yes\n' +- ' this happens!).\n', +- 'specialnames': '\n' +- 'Special method names\n' +- '********************\n' +- '\n' +- 'A class can implement certain operations that are invoked ' +- 'by special\n' +- 'syntax (such as arithmetic operations or subscripting and ' +- 'slicing) by\n' +- "defining methods with special names. This is Python's " +- 'approach to\n' +- '*operator overloading*, allowing classes to define their ' +- 'own behavior\n' +- 'with respect to language operators. For instance, if a ' +- 'class defines\n' +- 'a method named "__getitem__()", and "x" is an instance of ' +- 'this class,\n' +- 'then "x[i]" is roughly equivalent to "x.__getitem__(i)" ' +- 'for old-style\n' +- 'classes and "type(x).__getitem__(x, i)" for new-style ' +- 'classes. Except\n' +- 'where mentioned, attempts to execute an operation raise an ' +- 'exception\n' +- 'when no appropriate method is defined (typically ' +- '"AttributeError" or\n' +- '"TypeError").\n' +- '\n' +- 'When implementing a class that emulates any built-in type, ' +- 'it is\n' +- 'important that the emulation only be implemented to the ' +- 'degree that it\n' +- 'makes sense for the object being modelled. For example, ' +- 'some\n' +- 'sequences may work well with retrieval of individual ' +- 'elements, but\n' +- 'extracting a slice may not make sense. (One example of ' +- 'this is the\n' +- '"NodeList" interface in the W3C\'s Document Object ' +- 'Model.)\n' +- '\n' +- '\n' +- 'Basic customization\n' +- '===================\n' +- '\n' +- 'object.__new__(cls[, ...])\n' +- '\n' +- ' Called to create a new instance of class *cls*. ' +- '"__new__()" is a\n' +- ' static method (special-cased so you need not declare it ' +- 'as such)\n' +- ' that takes the class of which an instance was requested ' +- 'as its\n' +- ' first argument. The remaining arguments are those ' +- 'passed to the\n' +- ' object constructor expression (the call to the class). ' +- 'The return\n' +- ' value of "__new__()" should be the new object instance ' +- '(usually an\n' +- ' instance of *cls*).\n' +- '\n' +- ' Typical implementations create a new instance of the ' +- 'class by\n' +- ' invoking the superclass\'s "__new__()" method using\n' +- ' "super(currentclass, cls).__new__(cls[, ...])" with ' +- 'appropriate\n' +- ' arguments and then modifying the newly-created instance ' +- 'as\n' +- ' necessary before returning it.\n' +- '\n' +- ' If "__new__()" returns an instance of *cls*, then the ' +- 'new\n' +- ' instance\'s "__init__()" method will be invoked like\n' +- ' "__init__(self[, ...])", where *self* is the new ' +- 'instance and the\n' +- ' remaining arguments are the same as were passed to ' +- '"__new__()".\n' +- '\n' +- ' If "__new__()" does not return an instance of *cls*, ' +- 'then the new\n' +- ' instance\'s "__init__()" method will not be invoked.\n' +- '\n' +- ' "__new__()" is intended mainly to allow subclasses of ' +- 'immutable\n' +- ' types (like int, str, or tuple) to customize instance ' +- 'creation. It\n' +- ' is also commonly overridden in custom metaclasses in ' +- 'order to\n' +- ' customize class creation.\n' +- '\n' +- 'object.__init__(self[, ...])\n' +- '\n' +- ' Called after the instance has been created (by ' +- '"__new__()"), but\n' +- ' before it is returned to the caller. The arguments are ' +- 'those\n' +- ' passed to the class constructor expression. If a base ' +- 'class has an\n' +- ' "__init__()" method, the derived class\'s "__init__()" ' +- 'method, if\n' +- ' any, must explicitly call it to ensure proper ' +- 'initialization of the\n' +- ' base class part of the instance; for example:\n' +- ' "BaseClass.__init__(self, [args...])".\n' +- '\n' +- ' Because "__new__()" and "__init__()" work together in ' +- 'constructing\n' +- ' objects ("__new__()" to create it, and "__init__()" to ' +- 'customise\n' +- ' it), no non-"None" value may be returned by ' +- '"__init__()"; doing so\n' +- ' will cause a "TypeError" to be raised at runtime.\n' +- '\n' +- 'object.__del__(self)\n' +- '\n' +- ' Called when the instance is about to be destroyed. ' +- 'This is also\n' +- ' called a destructor. If a base class has a "__del__()" ' +- 'method, the\n' +- ' derived class\'s "__del__()" method, if any, must ' +- 'explicitly call it\n' +- ' to ensure proper deletion of the base class part of the ' +- 'instance.\n' +- ' Note that it is possible (though not recommended!) for ' +- 'the\n' +- ' "__del__()" method to postpone destruction of the ' +- 'instance by\n' +- ' creating a new reference to it. It may then be called ' +- 'at a later\n' +- ' time when this new reference is deleted. It is not ' +- 'guaranteed that\n' +- ' "__del__()" methods are called for objects that still ' +- 'exist when\n' +- ' the interpreter exits.\n' +- '\n' +- ' Note: "del x" doesn\'t directly call "x.__del__()" --- ' +- 'the former\n' +- ' decrements the reference count for "x" by one, and ' +- 'the latter is\n' +- ' only called when "x"\'s reference count reaches ' +- 'zero. Some common\n' +- ' situations that may prevent the reference count of an ' +- 'object from\n' +- ' going to zero include: circular references between ' +- 'objects (e.g.,\n' +- ' a doubly-linked list or a tree data structure with ' +- 'parent and\n' +- ' child pointers); a reference to the object on the ' +- 'stack frame of\n' +- ' a function that caught an exception (the traceback ' +- 'stored in\n' +- ' "sys.exc_traceback" keeps the stack frame alive); or ' +- 'a reference\n' +- ' to the object on the stack frame that raised an ' +- 'unhandled\n' +- ' exception in interactive mode (the traceback stored ' +- 'in\n' +- ' "sys.last_traceback" keeps the stack frame alive). ' +- 'The first\n' +- ' situation can only be remedied by explicitly breaking ' +- 'the cycles;\n' +- ' the latter two situations can be resolved by storing ' +- '"None" in\n' +- ' "sys.exc_traceback" or "sys.last_traceback". ' +- 'Circular references\n' +- ' which are garbage are detected when the option cycle ' +- 'detector is\n' +- " enabled (it's on by default), but can only be cleaned " +- 'up if there\n' +- ' are no Python-level "__del__()" methods involved. ' +- 'Refer to the\n' +- ' documentation for the "gc" module for more ' +- 'information about how\n' +- ' "__del__()" methods are handled by the cycle ' +- 'detector,\n' +- ' particularly the description of the "garbage" value.\n' +- '\n' +- ' Warning: Due to the precarious circumstances under ' +- 'which\n' +- ' "__del__()" methods are invoked, exceptions that ' +- 'occur during\n' +- ' their execution are ignored, and a warning is printed ' +- 'to\n' +- ' "sys.stderr" instead. Also, when "__del__()" is ' +- 'invoked in\n' +- ' response to a module being deleted (e.g., when ' +- 'execution of the\n' +- ' program is done), other globals referenced by the ' +- '"__del__()"\n' +- ' method may already have been deleted or in the ' +- 'process of being\n' +- ' torn down (e.g. the import machinery shutting down). ' +- 'For this\n' +- ' reason, "__del__()" methods should do the absolute ' +- 'minimum needed\n' +- ' to maintain external invariants. Starting with ' +- 'version 1.5,\n' +- ' Python guarantees that globals whose name begins with ' +- 'a single\n' +- ' underscore are deleted from their module before other ' +- 'globals are\n' +- ' deleted; if no other references to such globals ' +- 'exist, this may\n' +- ' help in assuring that imported modules are still ' +- 'available at the\n' +- ' time when the "__del__()" method is called.\n' +- '\n' +- ' See also the "-R" command-line option.\n' +- '\n' +- 'object.__repr__(self)\n' +- '\n' +- ' Called by the "repr()" built-in function and by string ' +- 'conversions\n' +- ' (reverse quotes) to compute the "official" string ' +- 'representation of\n' +- ' an object. If at all possible, this should look like a ' +- 'valid\n' +- ' Python expression that could be used to recreate an ' +- 'object with the\n' +- ' same value (given an appropriate environment). If this ' +- 'is not\n' +- ' possible, a string of the form "<...some useful ' +- 'description...>"\n' +- ' should be returned. The return value must be a string ' +- 'object. If a\n' +- ' class defines "__repr__()" but not "__str__()", then ' +- '"__repr__()"\n' +- ' is also used when an "informal" string representation ' +- 'of instances\n' +- ' of that class is required.\n' +- '\n' +- ' This is typically used for debugging, so it is ' +- 'important that the\n' +- ' representation is information-rich and unambiguous.\n' +- '\n' +- 'object.__str__(self)\n' +- '\n' +- ' Called by the "str()" built-in function and by the ' +- '"print"\n' +- ' statement to compute the "informal" string ' +- 'representation of an\n' +- ' object. This differs from "__repr__()" in that it does ' +- 'not have to\n' +- ' be a valid Python expression: a more convenient or ' +- 'concise\n' +- ' representation may be used instead. The return value ' +- 'must be a\n' +- ' string object.\n' +- '\n' +- 'object.__lt__(self, other)\n' +- 'object.__le__(self, other)\n' +- 'object.__eq__(self, other)\n' +- 'object.__ne__(self, other)\n' +- 'object.__gt__(self, other)\n' +- 'object.__ge__(self, other)\n' +- '\n' +- ' New in version 2.1.\n' +- '\n' +- ' These are the so-called "rich comparison" methods, and ' +- 'are called\n' +- ' for comparison operators in preference to "__cmp__()" ' +- 'below. The\n' +- ' correspondence between operator symbols and method ' +- 'names is as\n' +- ' follows: "xy" call ' +- '"x.__ne__(y)",\n' +- ' "x>y" calls "x.__gt__(y)", and "x>=y" calls ' +- '"x.__ge__(y)".\n' +- '\n' +- ' A rich comparison method may return the singleton ' +- '"NotImplemented"\n' +- ' if it does not implement the operation for a given pair ' +- 'of\n' +- ' arguments. By convention, "False" and "True" are ' +- 'returned for a\n' +- ' successful comparison. However, these methods can ' +- 'return any value,\n' +- ' so if the comparison operator is used in a Boolean ' +- 'context (e.g.,\n' +- ' in the condition of an "if" statement), Python will ' +- 'call "bool()"\n' +- ' on the value to determine if the result is true or ' +- 'false.\n' +- '\n' +- ' There are no implied relationships among the comparison ' +- 'operators.\n' +- ' The truth of "x==y" does not imply that "x!=y" is ' +- 'false.\n' +- ' Accordingly, when defining "__eq__()", one should also ' +- 'define\n' +- ' "__ne__()" so that the operators will behave as ' +- 'expected. See the\n' +- ' paragraph on "__hash__()" for some important notes on ' +- 'creating\n' +- ' *hashable* objects which support custom comparison ' +- 'operations and\n' +- ' are usable as dictionary keys.\n' +- '\n' +- ' There are no swapped-argument versions of these methods ' +- '(to be used\n' +- ' when the left argument does not support the operation ' +- 'but the right\n' +- ' argument does); rather, "__lt__()" and "__gt__()" are ' +- "each other's\n" +- ' reflection, "__le__()" and "__ge__()" are each other\'s ' +- 'reflection,\n' +- ' and "__eq__()" and "__ne__()" are their own ' +- 'reflection.\n' +- '\n' +- ' Arguments to rich comparison methods are never ' +- 'coerced.\n' +- '\n' +- ' To automatically generate ordering operations from a ' +- 'single root\n' +- ' operation, see "functools.total_ordering()".\n' +- '\n' +- 'object.__cmp__(self, other)\n' +- '\n' +- ' Called by comparison operations if rich comparison (see ' +- 'above) is\n' +- ' not defined. Should return a negative integer if "self ' +- '< other",\n' +- ' zero if "self == other", a positive integer if "self > ' +- 'other". If\n' +- ' no "__cmp__()", "__eq__()" or "__ne__()" operation is ' +- 'defined,\n' +- ' class instances are compared by object identity ' +- '("address"). See\n' +- ' also the description of "__hash__()" for some important ' +- 'notes on\n' +- ' creating *hashable* objects which support custom ' +- 'comparison\n' +- ' operations and are usable as dictionary keys. (Note: ' +- 'the\n' +- ' restriction that exceptions are not propagated by ' +- '"__cmp__()" has\n' +- ' been removed since Python 1.5.)\n' +- '\n' +- 'object.__rcmp__(self, other)\n' +- '\n' +- ' Changed in version 2.1: No longer supported.\n' +- '\n' +- 'object.__hash__(self)\n' +- '\n' +- ' Called by built-in function "hash()" and for operations ' +- 'on members\n' +- ' of hashed collections including "set", "frozenset", and ' +- '"dict".\n' +- ' "__hash__()" should return an integer. The only ' +- 'required property\n' +- ' is that objects which compare equal have the same hash ' +- 'value; it is\n' +- ' advised to somehow mix together (e.g. using exclusive ' +- 'or) the hash\n' +- ' values for the components of the object that also play ' +- 'a part in\n' +- ' comparison of objects.\n' +- '\n' +- ' If a class does not define a "__cmp__()" or "__eq__()" ' +- 'method it\n' +- ' should not define a "__hash__()" operation either; if ' +- 'it defines\n' +- ' "__cmp__()" or "__eq__()" but not "__hash__()", its ' +- 'instances will\n' +- ' not be usable in hashed collections. If a class ' +- 'defines mutable\n' +- ' objects and implements a "__cmp__()" or "__eq__()" ' +- 'method, it\n' +- ' should not implement "__hash__()", since hashable ' +- 'collection\n' +- " implementations require that a object's hash value is " +- 'immutable (if\n' +- " the object's hash value changes, it will be in the " +- 'wrong hash\n' +- ' bucket).\n' +- '\n' +- ' User-defined classes have "__cmp__()" and "__hash__()" ' +- 'methods by\n' +- ' default; with them, all objects compare unequal (except ' +- 'with\n' +- ' themselves) and "x.__hash__()" returns a result derived ' +- 'from\n' +- ' "id(x)".\n' +- '\n' +- ' Classes which inherit a "__hash__()" method from a ' +- 'parent class but\n' +- ' change the meaning of "__cmp__()" or "__eq__()" such ' +- 'that the hash\n' +- ' value returned is no longer appropriate (e.g. by ' +- 'switching to a\n' +- ' value-based concept of equality instead of the default ' +- 'identity\n' +- ' based equality) can explicitly flag themselves as being ' +- 'unhashable\n' +- ' by setting "__hash__ = None" in the class definition. ' +- 'Doing so\n' +- ' means that not only will instances of the class raise ' +- 'an\n' +- ' appropriate "TypeError" when a program attempts to ' +- 'retrieve their\n' +- ' hash value, but they will also be correctly identified ' +- 'as\n' +- ' unhashable when checking "isinstance(obj, ' +- 'collections.Hashable)"\n' +- ' (unlike classes which define their own "__hash__()" to ' +- 'explicitly\n' +- ' raise "TypeError").\n' +- '\n' +- ' Changed in version 2.5: "__hash__()" may now also ' +- 'return a long\n' +- ' integer object; the 32-bit integer is then derived from ' +- 'the hash of\n' +- ' that object.\n' +- '\n' +- ' Changed in version 2.6: "__hash__" may now be set to ' +- '"None" to\n' +- ' explicitly flag instances of a class as unhashable.\n' +- '\n' +- 'object.__nonzero__(self)\n' +- '\n' +- ' Called to implement truth value testing and the ' +- 'built-in operation\n' +- ' "bool()"; should return "False" or "True", or their ' +- 'integer\n' +- ' equivalents "0" or "1". When this method is not ' +- 'defined,\n' +- ' "__len__()" is called, if it is defined, and the object ' +- 'is\n' +- ' considered true if its result is nonzero. If a class ' +- 'defines\n' +- ' neither "__len__()" nor "__nonzero__()", all its ' +- 'instances are\n' +- ' considered true.\n' +- '\n' +- 'object.__unicode__(self)\n' +- '\n' +- ' Called to implement "unicode()" built-in; should return ' +- 'a Unicode\n' +- ' object. When this method is not defined, string ' +- 'conversion is\n' +- ' attempted, and the result of string conversion is ' +- 'converted to\n' +- ' Unicode using the system default encoding.\n' +- '\n' +- '\n' +- 'Customizing attribute access\n' +- '============================\n' +- '\n' +- 'The following methods can be defined to customize the ' +- 'meaning of\n' +- 'attribute access (use of, assignment to, or deletion of ' +- '"x.name") for\n' +- 'class instances.\n' +- '\n' +- 'object.__getattr__(self, name)\n' +- '\n' +- ' Called when an attribute lookup has not found the ' +- 'attribute in the\n' +- ' usual places (i.e. it is not an instance attribute nor ' +- 'is it found\n' +- ' in the class tree for "self"). "name" is the attribute ' +- 'name. This\n' +- ' method should return the (computed) attribute value or ' +- 'raise an\n' +- ' "AttributeError" exception.\n' +- '\n' +- ' Note that if the attribute is found through the normal ' +- 'mechanism,\n' +- ' "__getattr__()" is not called. (This is an intentional ' +- 'asymmetry\n' +- ' between "__getattr__()" and "__setattr__()".) This is ' +- 'done both for\n' +- ' efficiency reasons and because otherwise ' +- '"__getattr__()" would have\n' +- ' no way to access other attributes of the instance. ' +- 'Note that at\n' +- ' least for instance variables, you can fake total ' +- 'control by not\n' +- ' inserting any values in the instance attribute ' +- 'dictionary (but\n' +- ' instead inserting them in another object). See the\n' +- ' "__getattribute__()" method below for a way to actually ' +- 'get total\n' +- ' control in new-style classes.\n' +- '\n' +- 'object.__setattr__(self, name, value)\n' +- '\n' +- ' Called when an attribute assignment is attempted. This ' +- 'is called\n' +- ' instead of the normal mechanism (i.e. store the value ' +- 'in the\n' +- ' instance dictionary). *name* is the attribute name, ' +- '*value* is the\n' +- ' value to be assigned to it.\n' +- '\n' +- ' If "__setattr__()" wants to assign to an instance ' +- 'attribute, it\n' +- ' should not simply execute "self.name = value" --- this ' +- 'would cause\n' +- ' a recursive call to itself. Instead, it should insert ' +- 'the value in\n' +- ' the dictionary of instance attributes, e.g., ' +- '"self.__dict__[name] =\n' +- ' value". For new-style classes, rather than accessing ' +- 'the instance\n' +- ' dictionary, it should call the base class method with ' +- 'the same\n' +- ' name, for example, "object.__setattr__(self, name, ' +- 'value)".\n' +- '\n' +- 'object.__delattr__(self, name)\n' +- '\n' +- ' Like "__setattr__()" but for attribute deletion instead ' +- 'of\n' +- ' assignment. This should only be implemented if "del ' +- 'obj.name" is\n' +- ' meaningful for the object.\n' +- '\n' +- '\n' +- 'More attribute access for new-style classes\n' +- '-------------------------------------------\n' +- '\n' +- 'The following methods only apply to new-style classes.\n' +- '\n' +- 'object.__getattribute__(self, name)\n' +- '\n' +- ' Called unconditionally to implement attribute accesses ' +- 'for\n' +- ' instances of the class. If the class also defines ' +- '"__getattr__()",\n' +- ' the latter will not be called unless ' +- '"__getattribute__()" either\n' +- ' calls it explicitly or raises an "AttributeError". This ' +- 'method\n' +- ' should return the (computed) attribute value or raise ' +- 'an\n' +- ' "AttributeError" exception. In order to avoid infinite ' +- 'recursion in\n' +- ' this method, its implementation should always call the ' +- 'base class\n' +- ' method with the same name to access any attributes it ' +- 'needs, for\n' +- ' example, "object.__getattribute__(self, name)".\n' +- '\n' +- ' Note: This method may still be bypassed when looking up ' +- 'special\n' +- ' methods as the result of implicit invocation via ' +- 'language syntax\n' +- ' or built-in functions. See Special method lookup for ' +- 'new-style\n' +- ' classes.\n' +- '\n' +- '\n' +- 'Implementing Descriptors\n' +- '------------------------\n' +- '\n' +- 'The following methods only apply when an instance of the ' +- 'class\n' +- 'containing the method (a so-called *descriptor* class) ' +- 'appears in an\n' +- '*owner* class (the descriptor must be in either the ' +- "owner's class\n" +- 'dictionary or in the class dictionary for one of its ' +- 'parents). In the\n' +- 'examples below, "the attribute" refers to the attribute ' +- 'whose name is\n' +- 'the key of the property in the owner class\' "__dict__".\n' +- '\n' +- 'object.__get__(self, instance, owner)\n' +- '\n' +- ' Called to get the attribute of the owner class (class ' +- 'attribute\n' +- ' access) or of an instance of that class (instance ' +- 'attribute\n' +- ' access). *owner* is always the owner class, while ' +- '*instance* is the\n' +- ' instance that the attribute was accessed through, or ' +- '"None" when\n' +- ' the attribute is accessed through the *owner*. This ' +- 'method should\n' +- ' return the (computed) attribute value or raise an ' +- '"AttributeError"\n' +- ' exception.\n' +- '\n' +- 'object.__set__(self, instance, value)\n' +- '\n' +- ' Called to set the attribute on an instance *instance* ' +- 'of the owner\n' +- ' class to a new value, *value*.\n' +- '\n' +- 'object.__delete__(self, instance)\n' +- '\n' +- ' Called to delete the attribute on an instance ' +- '*instance* of the\n' +- ' owner class.\n' +- '\n' +- '\n' +- 'Invoking Descriptors\n' +- '--------------------\n' +- '\n' +- 'In general, a descriptor is an object attribute with ' +- '"binding\n' +- 'behavior", one whose attribute access has been overridden ' +- 'by methods\n' +- 'in the descriptor protocol: "__get__()", "__set__()", ' +- 'and\n' +- '"__delete__()". If any of those methods are defined for an ' +- 'object, it\n' +- 'is said to be a descriptor.\n' +- '\n' +- 'The default behavior for attribute access is to get, set, ' +- 'or delete\n' +- "the attribute from an object's dictionary. For instance, " +- '"a.x" has a\n' +- 'lookup chain starting with "a.__dict__[\'x\']", then\n' +- '"type(a).__dict__[\'x\']", and continuing through the base ' +- 'classes of\n' +- '"type(a)" excluding metaclasses.\n' +- '\n' +- 'However, if the looked-up value is an object defining one ' +- 'of the\n' +- 'descriptor methods, then Python may override the default ' +- 'behavior and\n' +- 'invoke the descriptor method instead. Where this occurs ' +- 'in the\n' +- 'precedence chain depends on which descriptor methods were ' +- 'defined and\n' +- 'how they were called. Note that descriptors are only ' +- 'invoked for new\n' +- 'style objects or classes (ones that subclass "object()" or ' +- '"type()").\n' +- '\n' +- 'The starting point for descriptor invocation is a binding, ' +- '"a.x". How\n' +- 'the arguments are assembled depends on "a":\n' +- '\n' +- 'Direct Call\n' +- ' The simplest and least common call is when user code ' +- 'directly\n' +- ' invokes a descriptor method: "x.__get__(a)".\n' +- '\n' +- 'Instance Binding\n' +- ' If binding to a new-style object instance, "a.x" is ' +- 'transformed\n' +- ' into the call: "type(a).__dict__[\'x\'].__get__(a, ' +- 'type(a))".\n' +- '\n' +- 'Class Binding\n' +- ' If binding to a new-style class, "A.x" is transformed ' +- 'into the\n' +- ' call: "A.__dict__[\'x\'].__get__(None, A)".\n' +- '\n' +- 'Super Binding\n' +- ' If "a" is an instance of "super", then the binding ' +- '"super(B,\n' +- ' obj).m()" searches "obj.__class__.__mro__" for the base ' +- 'class "A"\n' +- ' immediately preceding "B" and then invokes the ' +- 'descriptor with the\n' +- ' call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n' +- '\n' +- 'For instance bindings, the precedence of descriptor ' +- 'invocation depends\n' +- 'on the which descriptor methods are defined. A descriptor ' +- 'can define\n' +- 'any combination of "__get__()", "__set__()" and ' +- '"__delete__()". If it\n' +- 'does not define "__get__()", then accessing the attribute ' +- 'will return\n' +- 'the descriptor object itself unless there is a value in ' +- "the object's\n" +- 'instance dictionary. If the descriptor defines ' +- '"__set__()" and/or\n' +- '"__delete__()", it is a data descriptor; if it defines ' +- 'neither, it is\n' +- 'a non-data descriptor. Normally, data descriptors define ' +- 'both\n' +- '"__get__()" and "__set__()", while non-data descriptors ' +- 'have just the\n' +- '"__get__()" method. Data descriptors with "__set__()" and ' +- '"__get__()"\n' +- 'defined always override a redefinition in an instance ' +- 'dictionary. In\n' +- 'contrast, non-data descriptors can be overridden by ' +- 'instances.\n' +- '\n' +- 'Python methods (including "staticmethod()" and ' +- '"classmethod()") are\n' +- 'implemented as non-data descriptors. Accordingly, ' +- 'instances can\n' +- 'redefine and override methods. This allows individual ' +- 'instances to\n' +- 'acquire behaviors that differ from other instances of the ' +- 'same class.\n' +- '\n' +- 'The "property()" function is implemented as a data ' +- 'descriptor.\n' +- 'Accordingly, instances cannot override the behavior of a ' +- 'property.\n' +- '\n' +- '\n' +- '__slots__\n' +- '---------\n' +- '\n' +- 'By default, instances of both old and new-style classes ' +- 'have a\n' +- 'dictionary for attribute storage. This wastes space for ' +- 'objects\n' +- 'having very few instance variables. The space consumption ' +- 'can become\n' +- 'acute when creating large numbers of instances.\n' +- '\n' +- 'The default can be overridden by defining *__slots__* in a ' +- 'new-style\n' +- 'class definition. The *__slots__* declaration takes a ' +- 'sequence of\n' +- 'instance variables and reserves just enough space in each ' +- 'instance to\n' +- 'hold a value for each variable. Space is saved because ' +- '*__dict__* is\n' +- 'not created for each instance.\n' +- '\n' +- '__slots__\n' +- '\n' +- ' This class variable can be assigned a string, iterable, ' +- 'or sequence\n' +- ' of strings with variable names used by instances. If ' +- 'defined in a\n' +- ' new-style class, *__slots__* reserves space for the ' +- 'declared\n' +- ' variables and prevents the automatic creation of ' +- '*__dict__* and\n' +- ' *__weakref__* for each instance.\n' +- '\n' +- ' New in version 2.2.\n' +- '\n' +- 'Notes on using *__slots__*\n' +- '\n' +- '* When inheriting from a class without *__slots__*, the ' +- '*__dict__*\n' +- ' attribute of that class will always be accessible, so a ' +- '*__slots__*\n' +- ' definition in the subclass is meaningless.\n' +- '\n' +- '* Without a *__dict__* variable, instances cannot be ' +- 'assigned new\n' +- ' variables not listed in the *__slots__* definition. ' +- 'Attempts to\n' +- ' assign to an unlisted variable name raises ' +- '"AttributeError". If\n' +- ' dynamic assignment of new variables is desired, then ' +- 'add\n' +- ' "\'__dict__\'" to the sequence of strings in the ' +- '*__slots__*\n' +- ' declaration.\n' +- '\n' +- ' Changed in version 2.3: Previously, adding ' +- '"\'__dict__\'" to the\n' +- ' *__slots__* declaration would not enable the assignment ' +- 'of new\n' +- ' attributes not specifically listed in the sequence of ' +- 'instance\n' +- ' variable names.\n' +- '\n' +- '* Without a *__weakref__* variable for each instance, ' +- 'classes\n' +- ' defining *__slots__* do not support weak references to ' +- 'its\n' +- ' instances. If weak reference support is needed, then ' +- 'add\n' +- ' "\'__weakref__\'" to the sequence of strings in the ' +- '*__slots__*\n' +- ' declaration.\n' +- '\n' +- ' Changed in version 2.3: Previously, adding ' +- '"\'__weakref__\'" to the\n' +- ' *__slots__* declaration would not enable support for ' +- 'weak\n' +- ' references.\n' +- '\n' +- '* *__slots__* are implemented at the class level by ' +- 'creating\n' +- ' descriptors (Implementing Descriptors) for each variable ' +- 'name. As a\n' +- ' result, class attributes cannot be used to set default ' +- 'values for\n' +- ' instance variables defined by *__slots__*; otherwise, ' +- 'the class\n' +- ' attribute would overwrite the descriptor assignment.\n' +- '\n' +- '* The action of a *__slots__* declaration is limited to ' +- 'the class\n' +- ' where it is defined. As a result, subclasses will have ' +- 'a *__dict__*\n' +- ' unless they also define *__slots__* (which must only ' +- 'contain names\n' +- ' of any *additional* slots).\n' +- '\n' +- '* If a class defines a slot also defined in a base class, ' +- 'the\n' +- ' instance variable defined by the base class slot is ' +- 'inaccessible\n' +- ' (except by retrieving its descriptor directly from the ' +- 'base class).\n' +- ' This renders the meaning of the program undefined. In ' +- 'the future, a\n' +- ' check may be added to prevent this.\n' +- '\n' +- '* Nonempty *__slots__* does not work for classes derived ' +- 'from\n' +- ' "variable-length" built-in types such as "long", "str" ' +- 'and "tuple".\n' +- '\n' +- '* Any non-string iterable may be assigned to *__slots__*. ' +- 'Mappings\n' +- ' may also be used; however, in the future, special ' +- 'meaning may be\n' +- ' assigned to the values corresponding to each key.\n' +- '\n' +- '* *__class__* assignment works only if both classes have ' +- 'the same\n' +- ' *__slots__*.\n' +- '\n' +- ' Changed in version 2.6: Previously, *__class__* ' +- 'assignment raised an\n' +- ' error if either new or old class had *__slots__*.\n' +- '\n' +- '\n' +- 'Customizing class creation\n' +- '==========================\n' +- '\n' +- 'By default, new-style classes are constructed using ' +- '"type()". A class\n' +- 'definition is read into a separate namespace and the value ' +- 'of class\n' +- 'name is bound to the result of "type(name, bases, dict)".\n' +- '\n' +- 'When the class definition is read, if *__metaclass__* is ' +- 'defined then\n' +- 'the callable assigned to it will be called instead of ' +- '"type()". This\n' +- 'allows classes or functions to be written which monitor or ' +- 'alter the\n' +- 'class creation process:\n' +- '\n' +- '* Modifying the class dictionary prior to the class being ' +- 'created.\n' +- '\n' +- '* Returning an instance of another class -- essentially ' +- 'performing\n' +- ' the role of a factory function.\n' +- '\n' +- "These steps will have to be performed in the metaclass's " +- '"__new__()"\n' +- 'method -- "type.__new__()" can then be called from this ' +- 'method to\n' +- 'create a class with different properties. This example ' +- 'adds a new\n' +- 'element to the class dictionary before creating the ' +- 'class:\n' +- '\n' +- ' class metacls(type):\n' +- ' def __new__(mcs, name, bases, dict):\n' +- " dict['foo'] = 'metacls was here'\n" +- ' return type.__new__(mcs, name, bases, dict)\n' +- '\n' +- 'You can of course also override other class methods (or ' +- 'add new\n' +- 'methods); for example defining a custom "__call__()" ' +- 'method in the\n' +- 'metaclass allows custom behavior when the class is called, ' +- 'e.g. not\n' +- 'always creating a new instance.\n' +- '\n' +- '__metaclass__\n' +- '\n' +- ' This variable can be any callable accepting arguments ' +- 'for "name",\n' +- ' "bases", and "dict". Upon class creation, the callable ' +- 'is used\n' +- ' instead of the built-in "type()".\n' +- '\n' +- ' New in version 2.2.\n' +- '\n' +- 'The appropriate metaclass is determined by the following ' +- 'precedence\n' +- 'rules:\n' +- '\n' +- '* If "dict[\'__metaclass__\']" exists, it is used.\n' +- '\n' +- '* Otherwise, if there is at least one base class, its ' +- 'metaclass is\n' +- ' used (this looks for a *__class__* attribute first and ' +- 'if not found,\n' +- ' uses its type).\n' +- '\n' +- '* Otherwise, if a global variable named __metaclass__ ' +- 'exists, it is\n' +- ' used.\n' +- '\n' +- '* Otherwise, the old-style, classic metaclass ' +- '(types.ClassType) is\n' +- ' used.\n' +- '\n' +- 'The potential uses for metaclasses are boundless. Some ' +- 'ideas that have\n' +- 'been explored including logging, interface checking, ' +- 'automatic\n' +- 'delegation, automatic property creation, proxies, ' +- 'frameworks, and\n' +- 'automatic resource locking/synchronization.\n' +- '\n' +- '\n' +- 'Customizing instance and subclass checks\n' +- '========================================\n' +- '\n' +- 'New in version 2.6.\n' +- '\n' +- 'The following methods are used to override the default ' +- 'behavior of the\n' +- '"isinstance()" and "issubclass()" built-in functions.\n' +- '\n' +- 'In particular, the metaclass "abc.ABCMeta" implements ' +- 'these methods in\n' +- 'order to allow the addition of Abstract Base Classes ' +- '(ABCs) as\n' +- '"virtual base classes" to any class or type (including ' +- 'built-in\n' +- 'types), including other ABCs.\n' +- '\n' +- 'class.__instancecheck__(self, instance)\n' +- '\n' +- ' Return true if *instance* should be considered a ' +- '(direct or\n' +- ' indirect) instance of *class*. If defined, called to ' +- 'implement\n' +- ' "isinstance(instance, class)".\n' +- '\n' +- 'class.__subclasscheck__(self, subclass)\n' +- '\n' +- ' Return true if *subclass* should be considered a ' +- '(direct or\n' +- ' indirect) subclass of *class*. If defined, called to ' +- 'implement\n' +- ' "issubclass(subclass, class)".\n' +- '\n' +- 'Note that these methods are looked up on the type ' +- '(metaclass) of a\n' +- 'class. They cannot be defined as class methods in the ' +- 'actual class.\n' +- 'This is consistent with the lookup of special methods that ' +- 'are called\n' +- 'on instances, only in this case the instance is itself a ' +- 'class.\n' +- '\n' +- 'See also: **PEP 3119** - Introducing Abstract Base ' +- 'Classes\n' +- '\n' +- ' Includes the specification for customizing ' +- '"isinstance()" and\n' +- ' "issubclass()" behavior through "__instancecheck__()" ' +- 'and\n' +- ' "__subclasscheck__()", with motivation for this ' +- 'functionality in\n' +- ' the context of adding Abstract Base Classes (see the ' +- '"abc"\n' +- ' module) to the language.\n' +- '\n' +- '\n' +- 'Emulating callable objects\n' +- '==========================\n' +- '\n' +- 'object.__call__(self[, args...])\n' +- '\n' +- ' Called when the instance is "called" as a function; if ' +- 'this method\n' +- ' is defined, "x(arg1, arg2, ...)" is a shorthand for\n' +- ' "x.__call__(arg1, arg2, ...)".\n' +- '\n' +- '\n' +- 'Emulating container types\n' +- '=========================\n' +- '\n' +- 'The following methods can be defined to implement ' +- 'container objects.\n' +- 'Containers usually are sequences (such as lists or tuples) ' +- 'or mappings\n' +- '(like dictionaries), but can represent other containers as ' +- 'well. The\n' +- 'first set of methods is used either to emulate a sequence ' +- 'or to\n' +- 'emulate a mapping; the difference is that for a sequence, ' +- 'the\n' +- 'allowable keys should be the integers *k* for which "0 <= ' +- 'k < N" where\n' +- '*N* is the length of the sequence, or slice objects, which ' +- 'define a\n' +- 'range of items. (For backwards compatibility, the method\n' +- '"__getslice__()" (see below) can also be defined to handle ' +- 'simple, but\n' +- 'not extended slices.) It is also recommended that mappings ' +- 'provide the\n' +- 'methods "keys()", "values()", "items()", "has_key()", ' +- '"get()",\n' +- '"clear()", "setdefault()", "iterkeys()", "itervalues()",\n' +- '"iteritems()", "pop()", "popitem()", "copy()", and ' +- '"update()" behaving\n' +- "similar to those for Python's standard dictionary " +- 'objects. The\n' +- '"UserDict" module provides a "DictMixin" class to help ' +- 'create those\n' +- 'methods from a base set of "__getitem__()", ' +- '"__setitem__()",\n' +- '"__delitem__()", and "keys()". Mutable sequences should ' +- 'provide\n' +- 'methods "append()", "count()", "index()", "extend()", ' +- '"insert()",\n' +- '"pop()", "remove()", "reverse()" and "sort()", like Python ' +- 'standard\n' +- 'list objects. Finally, sequence types should implement ' +- 'addition\n' +- '(meaning concatenation) and multiplication (meaning ' +- 'repetition) by\n' +- 'defining the methods "__add__()", "__radd__()", ' +- '"__iadd__()",\n' +- '"__mul__()", "__rmul__()" and "__imul__()" described ' +- 'below; they\n' +- 'should not define "__coerce__()" or other numerical ' +- 'operators. It is\n' +- 'recommended that both mappings and sequences implement ' +- 'the\n' +- '"__contains__()" method to allow efficient use of the "in" ' +- 'operator;\n' +- 'for mappings, "in" should be equivalent of "has_key()"; ' +- 'for sequences,\n' +- 'it should search through the values. It is further ' +- 'recommended that\n' +- 'both mappings and sequences implement the "__iter__()" ' +- 'method to allow\n' +- 'efficient iteration through the container; for mappings, ' +- '"__iter__()"\n' +- 'should be the same as "iterkeys()"; for sequences, it ' +- 'should iterate\n' +- 'through the values.\n' +- '\n' +- 'object.__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 that\n' +- ' doesn\'t define a "__nonzero__()" method and whose ' +- '"__len__()"\n' +- ' method returns zero is considered to be false in a ' +- 'Boolean context.\n' +- '\n' +- 'object.__getitem__(self, key)\n' +- '\n' +- ' Called to implement evaluation of "self[key]". For ' +- 'sequence types,\n' +- ' the accepted keys should be integers and slice ' +- 'objects. Note that\n' +- ' the special interpretation of negative indexes (if the ' +- 'class wishes\n' +- ' to emulate a sequence type) is up to the ' +- '"__getitem__()" method. If\n' +- ' *key* is of an inappropriate type, "TypeError" may be ' +- 'raised; if of\n' +- ' a value outside the set of indexes for the sequence ' +- '(after any\n' +- ' special interpretation of negative values), ' +- '"IndexError" should be\n' +- ' raised. For mapping types, if *key* is missing (not in ' +- 'the\n' +- ' container), "KeyError" 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' +- '\n' +- 'object.__missing__(self, key)\n' +- '\n' +- ' Called by "dict"."__getitem__()" to implement ' +- '"self[key]" for dict\n' +- ' subclasses when key is not in the dictionary.\n' +- '\n' +- 'object.__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' +- '\n' +- 'object.__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__()" method.\n' +- '\n' +- 'object.__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' +- '\n' +- 'object.__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 ' +- '"reversed()"\n' +- ' built-in will fall back to using the sequence protocol ' +- '("__len__()"\n' +- ' and "__getitem__()"). Objects that support the ' +- 'sequence protocol\n' +- ' should only provide "__reversed__()" if they can ' +- 'provide an\n' +- ' implementation that is more efficient than the one ' +- 'provided by\n' +- ' "reversed()".\n' +- '\n' +- ' New in version 2.6.\n' +- '\n' +- 'The membership test operators ("in" and "not in") are ' +- 'normally\n' +- 'implemented as an iteration through a sequence. However, ' +- 'container\n' +- 'objects can supply the following special method with a ' +- 'more efficient\n' +- 'implementation, which also does not require the object be ' +- 'a sequence.\n' +- '\n' +- 'object.__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 test\n' +- ' first tries iteration via "__iter__()", then the old ' +- 'sequence\n' +- ' iteration protocol via "__getitem__()", see this ' +- 'section in the\n' +- ' language reference.\n' +- '\n' +- '\n' +- 'Additional methods for emulation of sequence types\n' +- '==================================================\n' +- '\n' +- 'The following optional methods can be defined to further ' +- 'emulate\n' +- 'sequence objects. Immutable sequences methods should at ' +- 'most only\n' +- 'define "__getslice__()"; mutable sequences might define ' +- 'all three\n' +- 'methods.\n' +- '\n' +- 'object.__getslice__(self, i, j)\n' +- '\n' +- ' Deprecated since version 2.0: Support slice objects as ' +- 'parameters\n' +- ' to the "__getitem__()" method. (However, built-in types ' +- 'in CPython\n' +- ' currently still implement "__getslice__()". Therefore, ' +- 'you have to\n' +- ' override it in derived classes when implementing ' +- 'slicing.)\n' +- '\n' +- ' Called to implement evaluation of "self[i:j]". The ' +- 'returned object\n' +- ' should be of the same type as *self*. Note that ' +- 'missing *i* or *j*\n' +- ' in the slice expression are replaced by zero or ' +- '"sys.maxsize",\n' +- ' respectively. If negative indexes are used in the ' +- 'slice, the\n' +- ' length of the sequence is added to that index. If the ' +- 'instance does\n' +- ' not implement the "__len__()" method, an ' +- '"AttributeError" is\n' +- ' raised. No guarantee is made that indexes adjusted this ' +- 'way are not\n' +- ' still negative. Indexes which are greater than the ' +- 'length of the\n' +- ' sequence are not modified. If no "__getslice__()" is ' +- 'found, a slice\n' +- ' object is created instead, and passed to ' +- '"__getitem__()" instead.\n' +- '\n' +- 'object.__setslice__(self, i, j, sequence)\n' +- '\n' +- ' Called to implement assignment to "self[i:j]". Same ' +- 'notes for *i*\n' +- ' and *j* as for "__getslice__()".\n' +- '\n' +- ' This method is deprecated. If no "__setslice__()" is ' +- 'found, or for\n' +- ' extended slicing of the form "self[i:j:k]", a slice ' +- 'object is\n' +- ' created, and passed to "__setitem__()", instead of ' +- '"__setslice__()"\n' +- ' being called.\n' +- '\n' +- 'object.__delslice__(self, i, j)\n' +- '\n' +- ' Called to implement deletion of "self[i:j]". Same notes ' +- 'for *i* and\n' +- ' *j* as for "__getslice__()". This method is deprecated. ' +- 'If no\n' +- ' "__delslice__()" is found, or for extended slicing of ' +- 'the form\n' +- ' "self[i:j:k]", a slice object is created, and passed ' +- 'to\n' +- ' "__delitem__()", instead of "__delslice__()" being ' +- 'called.\n' +- '\n' +- 'Notice that these methods are only invoked when a single ' +- 'slice with a\n' +- 'single colon is used, and the slice method is available. ' +- 'For slice\n' +- 'operations involving extended slice notation, or in ' +- 'absence of the\n' +- 'slice methods, "__getitem__()", "__setitem__()" or ' +- '"__delitem__()" is\n' +- 'called with a slice object as argument.\n' +- '\n' +- 'The following example demonstrate how to make your program ' +- 'or module\n' +- 'compatible with earlier versions of Python (assuming that ' +- 'methods\n' +- '"__getitem__()", "__setitem__()" and "__delitem__()" ' +- 'support slice\n' +- 'objects as arguments):\n' +- '\n' +- ' class MyClass:\n' +- ' ...\n' +- ' def __getitem__(self, index):\n' +- ' ...\n' +- ' def __setitem__(self, index, value):\n' +- ' ...\n' +- ' def __delitem__(self, index):\n' +- ' ...\n' +- '\n' +- ' if sys.version_info < (2, 0):\n' +- " # They won't be defined if version is at least " +- '2.0 final\n' +- '\n' +- ' def __getslice__(self, i, j):\n' +- ' return self[max(0, i):max(0, j):]\n' +- ' def __setslice__(self, i, j, seq):\n' +- ' self[max(0, i):max(0, j):] = seq\n' +- ' def __delslice__(self, i, j):\n' +- ' del self[max(0, i):max(0, j):]\n' +- ' ...\n' +- '\n' +- 'Note the calls to "max()"; these are necessary because of ' +- 'the handling\n' +- 'of negative indices before the "__*slice__()" methods are ' +- 'called.\n' +- 'When negative indexes are used, the "__*item__()" methods ' +- 'receive them\n' +- 'as provided, but the "__*slice__()" methods get a "cooked" ' +- 'form of the\n' +- 'index values. For each negative index value, the length ' +- 'of the\n' +- 'sequence is added to the index before calling the method ' +- '(which may\n' +- 'still result in a negative index); this is the customary ' +- 'handling of\n' +- 'negative indexes by the built-in sequence types, and the ' +- '"__*item__()"\n' +- 'methods are expected to do this as well. However, since ' +- 'they should\n' +- 'already be doing that, negative indexes cannot be passed ' +- 'in; they must\n' +- 'be constrained to the bounds of the sequence before being ' +- 'passed to\n' +- 'the "__*item__()" methods. Calling "max(0, i)" ' +- 'conveniently returns\n' +- 'the proper value.\n' +- '\n' +- '\n' +- 'Emulating numeric types\n' +- '=======================\n' +- '\n' +- 'The following methods can be defined to emulate numeric ' +- 'objects.\n' +- 'Methods corresponding to operations that are not supported ' +- 'by the\n' +- 'particular kind of number implemented (e.g., bitwise ' +- 'operations for\n' +- 'non-integral numbers) should be left undefined.\n' +- '\n' +- 'object.__add__(self, other)\n' +- 'object.__sub__(self, other)\n' +- 'object.__mul__(self, other)\n' +- 'object.__floordiv__(self, other)\n' +- 'object.__mod__(self, other)\n' +- 'object.__divmod__(self, other)\n' +- 'object.__pow__(self, other[, modulo])\n' +- 'object.__lshift__(self, other)\n' +- 'object.__rshift__(self, other)\n' +- 'object.__and__(self, other)\n' +- 'object.__xor__(self, other)\n' +- 'object.__or__(self, other)\n' +- '\n' +- ' These methods are called to implement the binary ' +- 'arithmetic\n' +- ' operations ("+", "-", "*", "//", "%", "divmod()", ' +- '"pow()", "**",\n' +- ' "<<", ">>", "&", "^", "|"). For instance, to evaluate ' +- 'the\n' +- ' expression "x + y", where *x* is an instance of a class ' +- 'that has an\n' +- ' "__add__()" method, "x.__add__(y)" is called. The ' +- '"__divmod__()"\n' +- ' method should be the equivalent to using ' +- '"__floordiv__()" and\n' +- ' "__mod__()"; it should not be related to ' +- '"__truediv__()" (described\n' +- ' below). Note that "__pow__()" should be defined to ' +- 'accept an\n' +- ' optional third argument if the ternary version of the ' +- 'built-in\n' +- ' "pow()" function is to be supported.\n' +- '\n' +- ' If one of those methods does not support the operation ' +- 'with the\n' +- ' supplied arguments, it should return "NotImplemented".\n' +- '\n' +- 'object.__div__(self, other)\n' +- 'object.__truediv__(self, other)\n' +- '\n' +- ' The division operator ("/") is implemented by these ' +- 'methods. The\n' +- ' "__truediv__()" method is used when ' +- '"__future__.division" is in\n' +- ' effect, otherwise "__div__()" is used. If only one of ' +- 'these two\n' +- ' methods is defined, the object will not support ' +- 'division in the\n' +- ' alternate context; "TypeError" will be raised instead.\n' +- '\n' +- 'object.__radd__(self, other)\n' +- 'object.__rsub__(self, other)\n' +- 'object.__rmul__(self, other)\n' +- 'object.__rdiv__(self, other)\n' +- 'object.__rtruediv__(self, other)\n' +- 'object.__rfloordiv__(self, other)\n' +- 'object.__rmod__(self, other)\n' +- 'object.__rdivmod__(self, other)\n' +- 'object.__rpow__(self, other)\n' +- 'object.__rlshift__(self, other)\n' +- 'object.__rrshift__(self, other)\n' +- 'object.__rand__(self, other)\n' +- 'object.__rxor__(self, other)\n' +- 'object.__ror__(self, other)\n' +- '\n' +- ' These methods are called to implement the binary ' +- 'arithmetic\n' +- ' operations ("+", "-", "*", "/", "%", "divmod()", ' +- '"pow()", "**",\n' +- ' "<<", ">>", "&", "^", "|") with reflected (swapped) ' +- 'operands.\n' +- ' These functions are only called if the left operand ' +- 'does not\n' +- ' support the corresponding operation and the operands ' +- 'are of\n' +- ' different types. [2] For instance, to evaluate the ' +- 'expression "x -\n' +- ' y", where *y* is an instance of a class that has an ' +- '"__rsub__()"\n' +- ' method, "y.__rsub__(x)" is called if "x.__sub__(y)" ' +- 'returns\n' +- ' *NotImplemented*.\n' +- '\n' +- ' Note that ternary "pow()" will not try calling ' +- '"__rpow__()" (the\n' +- ' coercion rules would become too complicated).\n' +- '\n' +- " Note: If the right operand's type is a subclass of the " +- 'left\n' +- " operand's type and that subclass provides the " +- 'reflected method\n' +- ' for the operation, this method will be called before ' +- 'the left\n' +- " operand's non-reflected method. This behavior allows " +- 'subclasses\n' +- " to override their ancestors' operations.\n" +- '\n' +- 'object.__iadd__(self, other)\n' +- 'object.__isub__(self, other)\n' +- 'object.__imul__(self, other)\n' +- 'object.__idiv__(self, other)\n' +- 'object.__itruediv__(self, other)\n' +- 'object.__ifloordiv__(self, other)\n' +- 'object.__imod__(self, other)\n' +- 'object.__ipow__(self, other[, modulo])\n' +- 'object.__ilshift__(self, other)\n' +- 'object.__irshift__(self, other)\n' +- 'object.__iand__(self, other)\n' +- 'object.__ixor__(self, other)\n' +- 'object.__ior__(self, other)\n' +- '\n' +- ' These methods are called to implement the augmented ' +- 'arithmetic\n' +- ' assignments ("+=", "-=", "*=", "/=", "//=", "%=", ' +- '"**=", "<<=",\n' +- ' ">>=", "&=", "^=", "|="). These methods should attempt ' +- 'to do the\n' +- ' operation in-place (modifying *self*) and return the ' +- 'result (which\n' +- ' could be, but does not have to be, *self*). If a ' +- 'specific method\n' +- ' is not defined, the augmented assignment falls back to ' +- 'the normal\n' +- ' methods. For instance, to execute the statement "x += ' +- 'y", where\n' +- ' *x* is an instance of a class that has an "__iadd__()" ' +- 'method,\n' +- ' "x.__iadd__(y)" is called. If *x* is an instance of a ' +- 'class that\n' +- ' does not define a "__iadd__()" method, "x.__add__(y)" ' +- 'and\n' +- ' "y.__radd__(x)" are considered, as with the evaluation ' +- 'of "x + y".\n' +- '\n' +- 'object.__neg__(self)\n' +- 'object.__pos__(self)\n' +- 'object.__abs__(self)\n' +- 'object.__invert__(self)\n' +- '\n' +- ' Called to implement the unary arithmetic operations ' +- '("-", "+",\n' +- ' "abs()" and "~").\n' +- '\n' +- 'object.__complex__(self)\n' +- 'object.__int__(self)\n' +- 'object.__long__(self)\n' +- 'object.__float__(self)\n' +- '\n' +- ' Called to implement the built-in functions "complex()", ' +- '"int()",\n' +- ' "long()", and "float()". Should return a value of the ' +- 'appropriate\n' +- ' type.\n' +- '\n' +- 'object.__oct__(self)\n' +- 'object.__hex__(self)\n' +- '\n' +- ' Called to implement the built-in functions "oct()" and ' +- '"hex()".\n' +- ' Should return a string value.\n' +- '\n' +- 'object.__index__(self)\n' +- '\n' +- ' Called to implement "operator.index()". Also called ' +- 'whenever\n' +- ' Python needs an integer object (such as in slicing). ' +- 'Must return\n' +- ' an integer (int or long).\n' +- '\n' +- ' New in version 2.5.\n' +- '\n' +- 'object.__coerce__(self, other)\n' +- '\n' +- ' Called to implement "mixed-mode" numeric arithmetic. ' +- 'Should either\n' +- ' return a 2-tuple containing *self* and *other* ' +- 'converted to a\n' +- ' common numeric type, or "None" if conversion is ' +- 'impossible. When\n' +- ' the common type would be the type of "other", it is ' +- 'sufficient to\n' +- ' return "None", since the interpreter will also ask the ' +- 'other object\n' +- ' to attempt a coercion (but sometimes, if the ' +- 'implementation of the\n' +- ' other type cannot be changed, it is useful to do the ' +- 'conversion to\n' +- ' the other type here). A return value of ' +- '"NotImplemented" is\n' +- ' equivalent to returning "None".\n' +- '\n' +- '\n' +- 'Coercion rules\n' +- '==============\n' +- '\n' +- 'This section used to document the rules for coercion. As ' +- 'the language\n' +- 'has evolved, the coercion rules have become hard to ' +- 'document\n' +- 'precisely; documenting what one version of one particular\n' +- 'implementation does is undesirable. Instead, here are ' +- 'some informal\n' +- 'guidelines regarding coercion. In Python 3, coercion will ' +- 'not be\n' +- 'supported.\n' +- '\n' +- '* If the left operand of a % operator is a string or ' +- 'Unicode object,\n' +- ' no coercion takes place and the string formatting ' +- 'operation is\n' +- ' invoked instead.\n' +- '\n' +- '* It is no longer recommended to define a coercion ' +- 'operation. Mixed-\n' +- " mode operations on types that don't define coercion pass " +- 'the\n' +- ' original arguments to the operation.\n' +- '\n' +- '* New-style classes (those derived from "object") never ' +- 'invoke the\n' +- ' "__coerce__()" method in response to a binary operator; ' +- 'the only\n' +- ' time "__coerce__()" is invoked is when the built-in ' +- 'function\n' +- ' "coerce()" is called.\n' +- '\n' +- '* For most intents and purposes, an operator that returns\n' +- ' "NotImplemented" is treated the same as one that is not ' +- 'implemented\n' +- ' at all.\n' +- '\n' +- '* Below, "__op__()" and "__rop__()" are used to signify ' +- 'the generic\n' +- ' method names corresponding to an operator; "__iop__()" ' +- 'is used for\n' +- ' the corresponding in-place operator. For example, for ' +- 'the operator\n' +- ' \'"+"\', "__add__()" and "__radd__()" are used for the ' +- 'left and right\n' +- ' variant of the binary operator, and "__iadd__()" for the ' +- 'in-place\n' +- ' variant.\n' +- '\n' +- '* For objects *x* and *y*, first "x.__op__(y)" is tried. ' +- 'If this is\n' +- ' not implemented or returns "NotImplemented", ' +- '"y.__rop__(x)" is\n' +- ' tried. If this is also not implemented or returns ' +- '"NotImplemented",\n' +- ' a "TypeError" exception is raised. But see the ' +- 'following exception:\n' +- '\n' +- '* Exception to the previous item: if the left operand is ' +- 'an instance\n' +- ' of a built-in type or a new-style class, and the right ' +- 'operand is an\n' +- ' instance of a proper subclass of that type or class and ' +- 'overrides\n' +- ' the base\'s "__rop__()" method, the right operand\'s ' +- '"__rop__()"\n' +- ' method is tried *before* the left operand\'s "__op__()" ' +- 'method.\n' +- '\n' +- ' This is done so that a subclass can completely override ' +- 'binary\n' +- ' operators. Otherwise, the left operand\'s "__op__()" ' +- 'method would\n' +- ' always accept the right operand: when an instance of a ' +- 'given class\n' +- ' is expected, an instance of a subclass of that class is ' +- 'always\n' +- ' acceptable.\n' +- '\n' +- '* When either operand type defines a coercion, this ' +- 'coercion is\n' +- ' called before that type\'s "__op__()" or "__rop__()" ' +- 'method is\n' +- ' called, but no sooner. If the coercion returns an ' +- 'object of a\n' +- ' different type for the operand whose coercion is ' +- 'invoked, part of\n' +- ' the process is redone using the new object.\n' +- '\n' +- '* When an in-place operator (like \'"+="\') is used, if ' +- 'the left\n' +- ' operand implements "__iop__()", it is invoked without ' +- 'any coercion.\n' +- ' When the operation falls back to "__op__()" and/or ' +- '"__rop__()", the\n' +- ' normal coercion rules apply.\n' +- '\n' +- '* In "x + y", if *x* is a sequence that implements ' +- 'sequence\n' +- ' concatenation, sequence concatenation is invoked.\n' +- '\n' +- '* In "x * y", if one operand is a sequence that implements ' +- 'sequence\n' +- ' repetition, and the other is an integer ("int" or ' +- '"long"), sequence\n' +- ' repetition is invoked.\n' +- '\n' +- '* Rich comparisons (implemented by methods "__eq__()" and ' +- 'so on)\n' +- ' never use coercion. Three-way comparison (implemented ' +- 'by\n' +- ' "__cmp__()") does use coercion under the same conditions ' +- 'as other\n' +- ' binary operations use it.\n' +- '\n' +- '* In the current implementation, the built-in numeric ' +- 'types "int",\n' +- ' "long", "float", and "complex" do not use coercion. All ' +- 'these types\n' +- ' implement a "__coerce__()" method, for use by the ' +- 'built-in\n' +- ' "coerce()" function.\n' +- '\n' +- ' Changed in version 2.7: The complex type no longer makes ' +- 'implicit\n' +- ' calls to the "__coerce__()" method for mixed-type binary ' +- 'arithmetic\n' +- ' operations.\n' +- '\n' +- '\n' +- 'With Statement Context Managers\n' +- '===============================\n' +- '\n' +- 'New in version 2.5.\n' +- '\n' +- 'A *context manager* is an object that defines the runtime ' +- 'context to\n' +- 'be established when executing a "with" statement. The ' +- 'context manager\n' +- 'handles the entry into, and the exit from, the desired ' +- 'runtime context\n' +- 'for the execution of the block of code. Context managers ' +- 'are normally\n' +- 'invoked using the "with" statement (described in section ' +- 'The with\n' +- 'statement), but can also be used by directly invoking ' +- 'their methods.\n' +- '\n' +- 'Typical uses of context managers include saving and ' +- 'restoring various\n' +- 'kinds of global state, locking and unlocking resources, ' +- 'closing opened\n' +- 'files, etc.\n' +- '\n' +- 'For more information on context managers, see Context ' +- 'Manager Types.\n' +- '\n' +- 'object.__enter__(self)\n' +- '\n' +- ' Enter the runtime context related to this object. The ' +- '"with"\n' +- " statement will bind this method's return value to the " +- 'target(s)\n' +- ' specified in the "as" clause of the statement, if any.\n' +- '\n' +- 'object.__exit__(self, exc_type, exc_value, traceback)\n' +- '\n' +- ' Exit the runtime context related to this object. The ' +- 'parameters\n' +- ' describe the exception that caused the context to be ' +- 'exited. If the\n' +- ' context was exited without an exception, all three ' +- 'arguments will\n' +- ' be "None".\n' +- '\n' +- ' If an exception is supplied, and the method wishes to ' +- 'suppress the\n' +- ' exception (i.e., prevent it from being propagated), it ' +- 'should\n' +- ' return a true value. Otherwise, the exception will be ' +- 'processed\n' +- ' normally upon exit from this method.\n' +- '\n' +- ' Note that "__exit__()" methods should not reraise the ' +- 'passed-in\n' +- " exception; this is the caller's responsibility.\n" +- '\n' +- 'See also: **PEP 0343** - The "with" statement\n' +- '\n' +- ' The specification, background, and examples for the ' +- 'Python "with"\n' +- ' statement.\n' +- '\n' +- '\n' +- 'Special method lookup for old-style classes\n' +- '===========================================\n' +- '\n' +- 'For old-style classes, special methods are always looked ' +- 'up in exactly\n' +- 'the same way as any other method or attribute. This is the ' +- 'case\n' +- 'regardless of whether the method is being looked up ' +- 'explicitly as in\n' +- '"x.__getitem__(i)" or implicitly as in "x[i]".\n' +- '\n' +- 'This behaviour means that special methods may exhibit ' +- 'different\n' +- 'behaviour for different instances of a single old-style ' +- 'class if the\n' +- 'appropriate special attributes are set differently:\n' +- '\n' +- ' >>> class C:\n' +- ' ... pass\n' +- ' ...\n' +- ' >>> c1 = C()\n' +- ' >>> c2 = C()\n' +- ' >>> c1.__len__ = lambda: 5\n' +- ' >>> c2.__len__ = lambda: 9\n' +- ' >>> len(c1)\n' +- ' 5\n' +- ' >>> len(c2)\n' +- ' 9\n' +- '\n' +- '\n' +- 'Special method lookup for new-style classes\n' +- '===========================================\n' +- '\n' +- 'For new-style classes, implicit invocations of special ' +- 'methods are\n' +- 'only guaranteed to work correctly if defined on an ' +- "object's type, not\n" +- "in the object's instance dictionary. That behaviour is " +- 'the reason why\n' +- 'the following code raises an exception (unlike the ' +- 'equivalent example\n' +- 'with old-style classes):\n' +- '\n' +- ' >>> class C(object):\n' +- ' ... pass\n' +- ' ...\n' +- ' >>> c = C()\n' +- ' >>> c.__len__ = lambda: 5\n' +- ' >>> len(c)\n' +- ' Traceback (most recent call last):\n' +- ' File "", line 1, in \n' +- " TypeError: object of type 'C' has no len()\n" +- '\n' +- 'The rationale behind this behaviour lies with a number of ' +- 'special\n' +- 'methods such as "__hash__()" and "__repr__()" that are ' +- 'implemented by\n' +- 'all objects, including type objects. If the implicit ' +- 'lookup of these\n' +- 'methods used the conventional lookup process, they would ' +- 'fail when\n' +- 'invoked on the type object itself:\n' +- '\n' +- ' >>> 1 .__hash__() == hash(1)\n' +- ' True\n' +- ' >>> int.__hash__() == hash(int)\n' +- ' Traceback (most recent call last):\n' +- ' File "", line 1, in \n' +- " TypeError: descriptor '__hash__' of 'int' object needs " +- 'an argument\n' +- '\n' +- 'Incorrectly attempting to invoke an unbound method of a ' +- 'class in this\n' +- "way is sometimes referred to as 'metaclass confusion', and " +- 'is avoided\n' +- 'by bypassing the instance when looking up special ' +- 'methods:\n' +- '\n' +- ' >>> type(1).__hash__(1) == hash(1)\n' +- ' True\n' +- ' >>> type(int).__hash__(int) == hash(int)\n' +- ' True\n' +- '\n' +- 'In addition to bypassing any instance attributes in the ' +- 'interest of\n' +- 'correctness, implicit special method lookup generally also ' +- 'bypasses\n' +- 'the "__getattribute__()" method even of the object\'s ' +- 'metaclass:\n' +- '\n' +- ' >>> class Meta(type):\n' +- ' ... def __getattribute__(*args):\n' +- ' ... print "Metaclass getattribute invoked"\n' +- ' ... return type.__getattribute__(*args)\n' +- ' ...\n' +- ' >>> class C(object):\n' +- ' ... __metaclass__ = Meta\n' +- ' ... def __len__(self):\n' +- ' ... return 10\n' +- ' ... def __getattribute__(*args):\n' +- ' ... print "Class getattribute invoked"\n' +- ' ... return object.__getattribute__(*args)\n' +- ' ...\n' +- ' >>> c = C()\n' +- ' >>> c.__len__() # Explicit lookup via ' +- 'instance\n' +- ' Class getattribute invoked\n' +- ' 10\n' +- ' >>> type(c).__len__(c) # Explicit lookup via ' +- 'type\n' +- ' Metaclass getattribute invoked\n' +- ' 10\n' +- ' >>> len(c) # Implicit lookup\n' +- ' 10\n' +- '\n' +- 'Bypassing the "__getattribute__()" machinery in this ' +- 'fashion provides\n' +- 'significant scope for speed optimisations within the ' +- 'interpreter, at\n' +- 'the cost of some flexibility in the handling of special ' +- 'methods (the\n' +- 'special method *must* be set on the class object itself in ' +- 'order to be\n' +- 'consistently invoked by the interpreter).\n' +- '\n' +- '-[ Footnotes ]-\n' +- '\n' +- "[1] It *is* possible in some cases to change an object's " +- 'type,\n' +- ' under certain controlled conditions. It generally ' +- "isn't a good\n" +- ' idea though, since it can lead to some very strange ' +- 'behaviour if\n' +- ' it is handled incorrectly.\n' +- '\n' +- '[2] For operands of the same type, it is assumed that if ' +- 'the non-\n' +- ' reflected method (such as "__add__()") fails the ' +- 'operation is not\n' +- ' supported, which is why the reflected method is not ' +- 'called.\n', +- 'string-methods': '\n' +- 'String Methods\n' +- '**************\n' +- '\n' +- 'Below are listed the string methods which both 8-bit ' +- 'strings and\n' +- 'Unicode objects support. Some of them are also ' +- 'available on\n' +- '"bytearray" objects.\n' +- '\n' +- "In addition, Python's strings support the sequence type " +- 'methods\n' +- 'described in the Sequence Types --- str, unicode, list, ' +- 'tuple,\n' +- 'bytearray, buffer, xrange section. To output formatted ' +- 'strings use\n' +- 'template strings or the "%" operator described in the ' +- 'String\n' +- 'Formatting Operations section. Also, see the "re" module ' +- 'for string\n' +- 'functions based on regular expressions.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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 ' +- '"UnicodeError".\n' +- ' Other possible values are "\'ignore\'", ' +- '"\'replace\'",\n' +- ' "\'xmlcharrefreplace\'", "\'backslashreplace\'" and ' +- 'any other name\n' +- ' registered via "codecs.register_error()", see section ' +- 'Codec Base\n' +- ' Classes. For a list of possible encodings, see ' +- 'section Standard\n' +- ' 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' +- '\n' +- 'str.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 suffixes\n' +- ' to look for. With optional *start*, test beginning ' +- 'at that\n' +- ' position. With optional *end*, stop comparing at ' +- 'that position.\n' +- '\n' +- ' Changed in version 2.5: Accept tuples as *suffix*.\n' +- '\n' +- 'str.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 result\n' +- ' until the current column is equal to the next tab ' +- 'position. (The\n' +- ' tab character itself is not copied.) If the ' +- 'character is a newline\n' +- ' ("\\n") or return ("\\r"), it is copied and the ' +- 'current column is\n' +- ' reset to zero. Any other character is copied ' +- 'unchanged and the\n' +- ' 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" +- '\n' +- 'str.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\n' +- ' the position of *sub*. To check if *sub* is a ' +- 'substring or not,\n' +- ' use the "in" operator:\n' +- '\n' +- " >>> 'Py' in 'Python'\n" +- ' True\n' +- '\n' +- 'str.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 String\n' +- ' Formatting Operations in new code.\n' +- '\n' +- ' New in version 2.6.\n' +- '\n' +- 'str.index(sub[, start[, end]])\n' +- '\n' +- ' Like "find()", but raise "ValueError" when the ' +- 'substring is not\n' +- ' found.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.rindex(sub[, start[, end]])\n' +- '\n' +- ' Like "rfind()" but raises "ValueError" when the ' +- 'substring *sub* is\n' +- ' not found.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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 splitting\n' +- ' from the right, "rsplit()" behaves like "split()" ' +- 'which is\n' +- ' described in detail below.\n' +- '\n' +- ' New in version 2.4.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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* argument\n' +- ' may consist of multiple characters (for example,\n' +- ' "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', ' +- '\'3\']"). Splitting an\n' +- ' 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' +- ' For example, "\' 1 2 3 \'.split()" returns ' +- '"[\'1\', \'2\', \'3\']", and\n' +- ' "\' 1 2 3 \'.split(None, 1)" returns "[\'1\', ' +- '\'2 3 \']".\n' +- '\n' +- 'str.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 "[\'ab\n' +- ' c\', \'\', \'de fg\', \'kl\']", while the same call ' +- 'with\n' +- ' "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', ' +- '\'de fg\\r\', \'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' +- '\n' +- 'str.startswith(prefix[, start[, end]])\n' +- '\n' +- ' Return "True" if string starts with the *prefix*, ' +- 'otherwise return\n' +- ' "False". *prefix* can also be a tuple of prefixes to ' +- 'look for.\n' +- ' With optional *start*, test string beginning at that ' +- 'position.\n' +- ' With optional *end*, stop comparing string at that ' +- 'position.\n' +- '\n' +- ' Changed in version 2.5: Accept tuples as *prefix*.\n' +- '\n' +- 'str.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 *chars*\n' +- ' argument defaults to removing whitespace. The *chars* ' +- 'argument is\n' +- ' not a prefix or suffix; rather, all combinations of ' +- 'its values are\n' +- ' 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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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. Note,\n' +- ' a more flexible approach is to create a custom ' +- 'character mapping\n' +- ' codec using the "codecs" module (see ' +- '"encodings.cp1251" for an\n' +- ' example).\n' +- '\n' +- 'str.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 be\n' +- ' "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' +- '\n' +- 'str.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' +- '\n' +- 'The following methods are present only on unicode ' +- 'objects:\n' +- '\n' +- 'unicode.isnumeric()\n' +- '\n' +- ' Return "True" if there are only numeric characters in ' +- 'S, "False"\n' +- ' otherwise. Numeric characters include digit ' +- 'characters, and all\n' +- ' characters that have the Unicode numeric value ' +- 'property, e.g.\n' +- ' U+2155, VULGAR FRACTION ONE FIFTH.\n' +- '\n' +- 'unicode.isdecimal()\n' +- '\n' +- ' Return "True" if there are only decimal characters in ' +- 'S, "False"\n' +- ' otherwise. Decimal characters include digit ' +- 'characters, and all\n' +- ' characters that can be used to form decimal-radix ' +- 'numbers, e.g.\n' +- ' U+0660, ARABIC-INDIC DIGIT ZERO.\n', +- 'strings': '\n' +- 'String literals\n' +- '***************\n' +- '\n' +- 'String literals are described by the following lexical ' +- 'definitions:\n' +- '\n' +- ' stringliteral ::= [stringprefix](shortstring | ' +- 'longstring)\n' +- ' stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | ' +- '"Ur" | "uR"\n' +- ' | "b" | "B" | "br" | "Br" | "bR" | "BR"\n' +- ' shortstring ::= "\'" shortstringitem* "\'" | \'"\' ' +- 'shortstringitem* \'"\'\n' +- ' longstring ::= "\'\'\'" longstringitem* "\'\'\'"\n' +- ' | \'"""\' longstringitem* \'"""\'\n' +- ' shortstringitem ::= shortstringchar | escapeseq\n' +- ' longstringitem ::= longstringchar | escapeseq\n' +- ' shortstringchar ::= \n' +- ' longstringchar ::= \n' +- ' escapeseq ::= "\\" \n' +- '\n' +- 'One syntactic restriction not indicated by these productions is ' +- 'that\n' +- 'whitespace is not allowed between the "stringprefix" and the ' +- 'rest of\n' +- 'the string literal. The source character set is defined by the\n' +- 'encoding declaration; it is ASCII if no encoding declaration is ' +- 'given\n' +- 'in the source file; see section Encoding declarations.\n' +- '\n' +- 'In plain English: String literals can be enclosed in matching ' +- 'single\n' +- 'quotes ("\'") or double quotes ("""). They can also be ' +- 'enclosed in\n' +- 'matching groups of three single or double quotes (these are ' +- 'generally\n' +- 'referred to as *triple-quoted strings*). The backslash ("\\")\n' +- 'character is used to escape characters that otherwise have a ' +- 'special\n' +- 'meaning, such as newline, backslash itself, or the quote ' +- 'character.\n' +- 'String literals may optionally be prefixed with a letter ' +- '"\'r\'" or\n' +- '"\'R\'"; such strings are called *raw strings* and use ' +- 'different rules\n' +- 'for interpreting backslash escape sequences. A prefix of ' +- '"\'u\'" or\n' +- '"\'U\'" makes the string a Unicode string. Unicode strings use ' +- 'the\n' +- 'Unicode character set as defined by the Unicode Consortium and ' +- 'ISO\n' +- '10646. Some additional escape sequences, described below, are\n' +- 'available in Unicode strings. A prefix of "\'b\'" or "\'B\'" is ' +- 'ignored in\n' +- 'Python 2; it indicates that the literal should become a bytes ' +- 'literal\n' +- 'in Python 3 (e.g. when code is automatically converted with ' +- '2to3). A\n' +- '"\'u\'" or "\'b\'" prefix may be followed by an "\'r\'" ' +- 'prefix.\n' +- '\n' +- 'In triple-quoted strings, unescaped newlines and quotes are ' +- 'allowed\n' +- '(and are retained), except that three unescaped quotes in a ' +- 'row\n' +- 'terminate the string. (A "quote" is the character used to open ' +- 'the\n' +- 'string, i.e. either "\'" or """.)\n' +- '\n' +- 'Unless an "\'r\'" or "\'R\'" prefix is present, escape ' +- 'sequences in\n' +- 'strings are interpreted according to rules similar to those ' +- 'used by\n' +- 'Standard C. The recognized escape sequences are:\n' +- '\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| Escape Sequence | Meaning | ' +- 'Notes |\n' +- '+===================+===================================+=========+\n' +- '| "\\newline" | Ignored ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\\\" | Backslash ("\\") ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\\'" | Single quote ("\'") ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\"" | Double quote (""") ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\a" | ASCII Bell (BEL) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\b" | ASCII Backspace (BS) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\f" | ASCII Formfeed (FF) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\n" | ASCII Linefeed (LF) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\N{name}" | Character named *name* in the ' +- '| |\n' +- '| | Unicode database (Unicode only) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\r" | ASCII Carriage Return (CR) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\t" | ASCII Horizontal Tab (TAB) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\uxxxx" | Character with 16-bit hex value | ' +- '(1) |\n' +- '| | *xxxx* (Unicode only) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\Uxxxxxxxx" | Character with 32-bit hex value | ' +- '(2) |\n' +- '| | *xxxxxxxx* (Unicode only) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\v" | ASCII Vertical Tab (VT) ' +- '| |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\ooo" | Character with octal value *ooo* | ' +- '(3,5) |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '| "\\xhh" | Character with hex value *hh* | ' +- '(4,5) |\n' +- '+-------------------+-----------------------------------+---------+\n' +- '\n' +- 'Notes:\n' +- '\n' +- '1. Individual code units which form parts of a surrogate pair ' +- 'can\n' +- ' be encoded using this escape sequence.\n' +- '\n' +- '2. Any Unicode character can be encoded this way, but ' +- 'characters\n' +- ' outside the Basic Multilingual Plane (BMP) will be encoded ' +- 'using a\n' +- ' surrogate pair if Python is compiled to use 16-bit code ' +- 'units (the\n' +- ' default).\n' +- '\n' +- '3. As in Standard C, up to three octal digits are accepted.\n' +- '\n' +- '4. Unlike in Standard C, exactly two hex digits are required.\n' +- '\n' +- '5. In a string literal, hexadecimal and octal escapes denote ' +- 'the\n' +- ' byte with the given value; it is not necessary that the ' +- 'byte\n' +- ' encodes a character in the source character set. In a ' +- 'Unicode\n' +- ' literal, these escapes denote a Unicode character with the ' +- 'given\n' +- ' value.\n' +- '\n' +- 'Unlike Standard C, all unrecognized escape sequences are left ' +- 'in the\n' +- 'string unchanged, i.e., *the backslash is left in the string*. ' +- '(This\n' +- 'behavior is useful when debugging: if an escape sequence is ' +- 'mistyped,\n' +- 'the resulting output is more easily recognized as broken.) It ' +- 'is also\n' +- 'important to note that the escape sequences marked as "(Unicode ' +- 'only)"\n' +- 'in the table above fall into the category of unrecognized ' +- 'escapes for\n' +- 'non-Unicode string literals.\n' +- '\n' +- 'When an "\'r\'" or "\'R\'" prefix is present, a character ' +- 'following a\n' +- 'backslash is included in the string without change, and *all\n' +- 'backslashes are left in the string*. For example, the string ' +- 'literal\n' +- '"r"\\n"" consists of two characters: a backslash and a ' +- 'lowercase "\'n\'".\n' +- 'String quotes can be escaped with a backslash, but the ' +- 'backslash\n' +- 'remains in the string; for example, "r"\\""" is a valid string ' +- 'literal\n' +- 'consisting of two characters: a backslash and a double quote; ' +- '"r"\\""\n' +- 'is not a valid string literal (even a raw string cannot end in ' +- 'an odd\n' +- 'number of backslashes). Specifically, *a raw string cannot end ' +- 'in a\n' +- 'single backslash* (since the backslash would escape the ' +- 'following\n' +- 'quote character). Note also that a single backslash followed ' +- 'by a\n' +- 'newline is interpreted as those two characters as part of the ' +- 'string,\n' +- '*not* as a line continuation.\n' +- '\n' +- 'When an "\'r\'" or "\'R\'" prefix is used in conjunction with a ' +- '"\'u\'" or\n' +- '"\'U\'" prefix, then the "\\uXXXX" and "\\UXXXXXXXX" escape ' +- 'sequences are\n' +- 'processed while *all other backslashes are left in the ' +- 'string*. For\n' +- 'example, the string literal "ur"\\u0062\\n"" consists of three ' +- 'Unicode\n' +- "characters: 'LATIN SMALL LETTER B', 'REVERSE SOLIDUS', and " +- "'LATIN\n" +- "SMALL LETTER N'. Backslashes can be escaped with a preceding\n" +- 'backslash; however, both remain in the string. As a result, ' +- '"\\uXXXX"\n' +- 'escape sequences are only recognized when there are an odd ' +- 'number of\n' +- 'backslashes.\n', +- 'subscriptions': '\n' +- 'Subscriptions\n' +- '*************\n' +- '\n' +- 'A subscription selects an item of a sequence (string, ' +- 'tuple or list)\n' +- 'or mapping (dictionary) object:\n' +- '\n' +- ' subscription ::= primary "[" expression_list "]"\n' +- '\n' +- 'The primary must evaluate to an object of a sequence or ' +- 'mapping type.\n' +- '\n' +- 'If the primary is a mapping, the expression list must ' +- 'evaluate to an\n' +- 'object whose value is one of the keys of the mapping, and ' +- 'the\n' +- 'subscription selects the value in the mapping that ' +- 'corresponds to that\n' +- 'key. (The expression list is a tuple except if it has ' +- 'exactly one\n' +- 'item.)\n' +- '\n' +- 'If the primary is a sequence, the expression (list) must ' +- 'evaluate to a\n' +- 'plain integer. If this value is negative, the length of ' +- 'the sequence\n' +- 'is added to it (so that, e.g., "x[-1]" selects the last ' +- 'item of "x".)\n' +- 'The resulting value must be a nonnegative integer less ' +- 'than the number\n' +- 'of items in the sequence, and the subscription selects ' +- 'the item whose\n' +- 'index is that value (counting from zero).\n' +- '\n' +- "A string's items are characters. A character is not a " +- 'separate data\n' +- 'type but a string of exactly one character.\n', +- 'truth': '\n' +- 'Truth Value Testing\n' +- '*******************\n' +- '\n' +- 'Any 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\n' +- 'following values are considered false:\n' +- '\n' +- '* "None"\n' +- '\n' +- '* "False"\n' +- '\n' +- '* zero of any numeric type, for example, "0", "0L", "0.0", "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 ' +- 'the\n' +- ' integer zero or "bool" value "False". [1]\n' +- '\n' +- 'All other values are considered true --- so objects of many types ' +- 'are\n' +- 'always true.\n' +- '\n' +- 'Operations and built-in functions that have a Boolean result ' +- 'always\n' +- 'return "0" or "False" for false and "1" or "True" for true, ' +- 'unless\n' +- 'otherwise stated. (Important exception: the Boolean operations ' +- '"or"\n' +- 'and "and" always return one of their operands.)\n', +- 'try': '\n' +- 'The "try" statement\n' +- '*******************\n' +- '\n' +- 'The "try" statement specifies exception handlers and/or cleanup ' +- 'code\n' +- 'for a group of statements:\n' +- '\n' +- ' try_stmt ::= try1_stmt | try2_stmt\n' +- ' try1_stmt ::= "try" ":" suite\n' +- ' ("except" [expression [("as" | ",") identifier]] ' +- '":" suite)+\n' +- ' ["else" ":" suite]\n' +- ' ["finally" ":" suite]\n' +- ' try2_stmt ::= "try" ":" suite\n' +- ' "finally" ":" suite\n' +- '\n' +- 'Changed in version 2.5: In previous versions of Python,\n' +- '"try"..."except"..."finally" did not work. "try"..."except" had to ' +- 'be\n' +- 'nested in "try"..."finally".\n' +- '\n' +- 'The "except" clause(s) specify one or more exception handlers. When ' +- 'no\n' +- 'exception occurs in the "try" clause, no exception handler is\n' +- 'executed. When an exception occurs in the "try" suite, a search for ' +- 'an\n' +- 'exception handler is started. This search inspects the except ' +- 'clauses\n' +- 'in turn until one is found that matches the exception. An ' +- 'expression-\n' +- 'less except clause, if present, must be last; it matches any\n' +- 'exception. For an except clause with an expression, that ' +- 'expression\n' +- 'is evaluated, and the clause matches the exception if the ' +- 'resulting\n' +- 'object is "compatible" with the exception. An object is ' +- 'compatible\n' +- 'with an exception if it is the class or a base class of the ' +- 'exception\n' +- 'object, or a tuple containing an item compatible with the ' +- 'exception.\n' +- '\n' +- 'If no except clause matches the exception, the search for an ' +- 'exception\n' +- 'handler continues in the surrounding code and on the invocation ' +- 'stack.\n' +- '[1]\n' +- '\n' +- 'If the evaluation of an expression in the header of an except ' +- 'clause\n' +- 'raises an exception, the original search for a handler is canceled ' +- 'and\n' +- 'a search starts for the new exception in the surrounding code and ' +- 'on\n' +- 'the call stack (it is treated as if the entire "try" statement ' +- 'raised\n' +- 'the exception).\n' +- '\n' +- 'When a matching except clause is found, the exception is assigned ' +- 'to\n' +- 'the target specified in that except clause, if present, and the ' +- 'except\n' +- "clause's suite is executed. All except clauses must have an\n" +- 'executable block. When the end of this block is reached, ' +- 'execution\n' +- 'continues normally after the entire try statement. (This means ' +- 'that\n' +- 'if two nested handlers exist for the same exception, and the ' +- 'exception\n' +- 'occurs in the try clause of the inner handler, the outer handler ' +- 'will\n' +- 'not handle the exception.)\n' +- '\n' +- "Before an except clause's suite is executed, details about the\n" +- 'exception 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\n' +- 'standard type hierarchy) identifying the point in the program ' +- 'where\n' +- 'the exception occurred. These details are also available through ' +- 'the\n' +- '"sys.exc_info()" function, which returns a tuple "(exc_type,\n' +- 'exc_value, exc_traceback)". Use of the corresponding variables is\n' +- 'deprecated in favor of this function, since their use is unsafe in ' +- 'a\n' +- 'threaded program. As of Python 1.5, the variables are restored to\n' +- 'their previous values (before the call) when returning from a ' +- 'function\n' +- 'that handled an exception.\n' +- '\n' +- 'The optional "else" clause is executed if and when control flows ' +- 'off\n' +- 'the end of the "try" clause. [2] Exceptions in the "else" clause ' +- 'are\n' +- 'not handled by the preceding "except" clauses.\n' +- '\n' +- 'If "finally" is present, it specifies a \'cleanup\' handler. The ' +- '"try"\n' +- 'clause is executed, including any "except" and "else" clauses. If ' +- 'an\n' +- 'exception occurs in any of the clauses and is not handled, the\n' +- 'exception is temporarily saved. The "finally" clause is executed. ' +- 'If\n' +- 'there is a saved exception, it is re-raised at the end of the\n' +- '"finally" clause. If the "finally" clause raises another exception ' +- 'or\n' +- 'executes a "return" or "break" statement, the saved exception is\n' +- 'discarded:\n' +- '\n' +- ' >>> def f():\n' +- ' ... try:\n' +- ' ... 1/0\n' +- ' ... finally:\n' +- ' ... return 42\n' +- ' ...\n' +- ' >>> f()\n' +- ' 42\n' +- '\n' +- 'The exception information is not available to the program during\n' +- 'execution of the "finally" clause.\n' +- '\n' +- 'When a "return", "break" or "continue" statement is executed in ' +- 'the\n' +- '"try" suite of a "try"..."finally" statement, the "finally" clause ' +- 'is\n' +- 'also executed \'on the way out.\' A "continue" statement is illegal ' +- 'in\n' +- 'the "finally" clause. (The reason is a problem with the current\n' +- 'implementation --- this restriction may be lifted in the future).\n' +- '\n' +- 'The return value of a function is determined by the last "return"\n' +- 'statement executed. Since the "finally" clause always executes, a\n' +- '"return" statement executed in the "finally" clause will always be ' +- 'the\n' +- 'last one executed:\n' +- '\n' +- ' >>> def foo():\n' +- ' ... try:\n' +- " ... return 'try'\n" +- ' ... finally:\n' +- " ... return 'finally'\n" +- ' ...\n' +- ' >>> foo()\n' +- " 'finally'\n" +- '\n' +- 'Additional information on exceptions can be found in section\n' +- 'Exceptions, and information on using the "raise" statement to ' +- 'generate\n' +- 'exceptions may be found in section The raise statement.\n', +- 'types': '\n' +- 'The standard type hierarchy\n' +- '***************************\n' +- '\n' +- 'Below is a list of the types that are built into Python. ' +- 'Extension\n' +- 'modules (written in C, Java, or other languages, depending on ' +- 'the\n' +- 'implementation) can define additional types. Future versions of\n' +- 'Python may add types to the type hierarchy (e.g., rational ' +- 'numbers,\n' +- 'efficiently stored arrays of integers, etc.).\n' +- '\n' +- 'Some of the type descriptions below contain a paragraph listing\n' +- "'special attributes.' These are attributes that provide access " +- 'to the\n' +- 'implementation and are not intended for general use. Their ' +- 'definition\n' +- 'may change in the future.\n' +- '\n' +- 'None\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". It\n' +- ' is used to signify the absence of a value in many situations, ' +- 'e.g.,\n' +- " it is returned from functions that don't explicitly return\n" +- ' anything. Its truth value is false.\n' +- '\n' +- 'NotImplemented\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' +- '\n' +- 'Ellipsis\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 "..." ' +- 'syntax\n' +- ' 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\n' +- ' only 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 ' +- 'are\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' +- '\n' +- 'Sequences\n' +- ' These represent finite ordered sets indexed by non-negative\n' +- ' numbers. The built-in function "len()" returns the number of ' +- 'items\n' +- ' of a sequence. When the length of a sequence is *n*, the index ' +- 'set\n' +- ' contains the numbers 0, 1, ..., *n*-1. Item *i* of sequence ' +- '*a* is\n' +- ' 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* ' +- 'where\n' +- ' "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *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 ' +- 'built-\n' +- ' 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 a\n' +- ' mutable sequence type.\n' +- '\n' +- 'Set 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 ' +- 'immutable\n' +- ' and *hashable*, it can be used again as an element of ' +- 'another\n' +- ' set, or as a dictionary key.\n' +- '\n' +- 'Mappings\n' +- ' These represent finite sets of objects indexed by arbitrary ' +- 'index\n' +- ' sets. The subscript notation "a[k]" selects the item indexed ' +- 'by "k"\n' +- ' from the mapping "a"; this can be used in expressions and as ' +- 'the\n' +- ' target of assignments or "del" statements. The built-in ' +- 'function\n' +- ' "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 ' +- '"1.0")\n' +- ' 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' +- '\n' +- 'Callable 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__" "func_doc" | The function\'s ' +- 'documentation | Writable |\n' +- ' | | string, or "None" if ' +- '| |\n' +- ' | | unavailable. ' +- '| |\n' +- ' ' +- '+-------------------------+---------------------------------+-------------+\n' +- ' | "__name__" "func_name" | The function\'s ' +- 'name. | Writable |\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 have ' +- '| |\n' +- ' | | a default value. ' +- '| |\n' +- ' ' +- '+-------------------------+---------------------------------+-------------+\n' +- ' | "__code__" "func_code" | The code object representing ' +- '| Writable |\n' +- ' | | 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__" "func_dict" | The namespace supporting ' +- '| Writable |\n' +- ' | | arbitrary function attributes. ' +- '| |\n' +- ' ' +- '+-------------------------+---------------------------------+-------------+\n' +- ' | "__closure__" | "None" or a tuple of cells that ' +- '| Read-only |\n' +- ' | "func_closure" | 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 ' +- '"__globals__"\n' +- ' were introduced as aliases for the corresponding "func_*"\n' +- ' 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 for\n' +- ' 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 ' +- 'the\n' +- ' 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" ' +- 'as\n' +- ' "__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 ' +- 'unbound.\n' +- ' When one is created by retrieving a user-defined function ' +- 'object\n' +- ' from a class via one of its instances, its "im_self" ' +- 'attribute\n' +- ' is the instance, and the method object is said to be bound. ' +- 'In\n' +- ' either case, the new method\'s "im_class" attribute is the ' +- 'class\n' +- ' from which the retrieval takes place, and its "im_func"\n' +- ' 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 ' +- 'restriction\n' +- ' that the first argument must be an instance of the proper ' +- 'class\n' +- ' ("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 a\n' +- ' function "f()", and "x" is an instance of "C", calling ' +- '"x.f(1)"\n' +- ' 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 ' +- '"C.f(1)"\n' +- ' is equivalent to calling "f(C,1)" where "f" is the ' +- 'underlying\n' +- ' 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 the\n' +- ' end, a "StopIteration" exception is raised and the iterator ' +- 'will\n' +- ' have reached the end of the set of values to be 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 ' +- "function's\n" +- ' name; "__self__" is set to "None" (but see the next item);\n' +- ' "__module__" is the name of the module the function was ' +- 'defined\n' +- ' 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, ' +- 'the\n' +- ' 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' +- '\n' +- 'Modules\n' +- ' Modules are imported by the "import" statement (see section ' +- 'The\n' +- ' import statement). A module object has a namespace implemented ' +- 'by a\n' +- ' 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 ' +- 'name;\n' +- ' "__doc__" is the module\'s documentation string, or "None" if\n' +- ' unavailable; "__file__" is the pathname of the file from which ' +- 'the\n' +- ' module was loaded, if it was loaded from a file. The ' +- '"__file__"\n' +- ' attribute is not present for C modules that are statically ' +- 'linked\n' +- ' into the interpreter; for extension modules loaded dynamically ' +- 'from\n' +- ' a shared library, it is the pathname of the shared library ' +- 'file.\n' +- '\n' +- 'Classes\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 ' +- 'translated\n' +- ' to "C.__dict__["x"]" (although for new-style classes in ' +- 'particular\n' +- ' there are a number of hooks which allow for other means of ' +- 'locating\n' +- ' attributes). When the attribute name is not found there, the\n' +- ' attribute search continues in the base classes. For ' +- 'old-style\n' +- ' classes, the search is depth-first, left-to-right in the order ' +- 'of\n' +- ' occurrence in the base class list. New-style classes use the ' +- 'more\n' +- ' complex C3 method resolution order which behaves correctly ' +- 'even in\n' +- " the presence of 'diamond' inheritance structures where there " +- 'are\n' +- ' multiple inheritance paths leading back to a common ancestor.\n' +- ' Additional details on the C3 MRO used by new-style classes can ' +- 'be\n' +- ' found in the documentation accompanying the 2.3 release at\n' +- ' https://www.python.org/download/releases/2.3/mro/.\n' +- '\n' +- ' When a class attribute reference (for class "C", say) would ' +- 'yield a\n' +- ' 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__" ' +- 'is\n' +- ' the module name in which the class was defined; "__dict__" is ' +- 'the\n' +- ' dictionary containing the class\'s namespace; "__bases__" is a ' +- 'tuple\n' +- ' (possibly empty or a singleton) containing the base classes, ' +- 'in the\n' +- ' order of their occurrence in the base class list; "__doc__" is ' +- 'the\n' +- " class's documentation string, or None if undefined.\n" +- '\n' +- 'Class 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 ' +- 'the\n' +- ' 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 ' +- 'instead\n' +- ' 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' +- '\n' +- 'Files\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 ' +- '(and\n' +- ' perhaps by other functions or methods provided by extension\n' +- ' modules). The objects "sys.stdin", "sys.stdout" and ' +- '"sys.stderr"\n' +- ' are initialized to file objects corresponding to the ' +- "interpreter's\n" +- ' standard input, output and error streams. See File Objects ' +- 'for\n' +- ' complete documentation of file objects.\n' +- '\n' +- 'Internal 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 ' +- 'name;\n' +- ' "co_argcount" is the number of positional arguments ' +- '(including\n' +- ' arguments with default values); "co_nlocals" is the number ' +- 'of\n' +- ' local variables used by the function (including ' +- 'arguments);\n' +- ' "co_varnames" is a tuple containing the names of the local\n' +- ' variables (starting with the argument names); "co_cellvars" ' +- 'is a\n' +- ' tuple containing the names of local variables that are\n' +- ' referenced by nested functions; "co_freevars" is a tuple\n' +- ' containing the names of free variables; "co_code" is a ' +- 'string\n' +- ' representing the sequence of bytecode instructions; ' +- '"co_consts"\n' +- ' is a tuple containing the literals used by the bytecode;\n' +- ' "co_names" is a tuple containing the names used by the ' +- 'bytecode;\n' +- ' "co_filename" is 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 a\n' +- ' number of flags for the interpreter.\n' +- '\n' +- ' The following flag bits are defined for "co_flags": bit ' +- '"0x04"\n' +- ' is set if the function uses the "*arguments" syntax to ' +- 'accept an\n' +- ' arbitrary number of positional arguments; bit "0x08" is set ' +- 'if\n' +- ' the function uses the "**keywords" syntax to accept ' +- 'arbitrary\n' +- ' keyword arguments; bit "0x20" is set if the function is a\n' +- ' generator.\n' +- '\n' +- ' Future feature declarations ("from __future__ import ' +- 'division")\n' +- ' also use bits in "co_flags" to indicate whether a code ' +- 'object\n' +- ' was compiled with a particular feature enabled: bit ' +- '"0x2000" is\n' +- ' set if the function was compiled with future division ' +- 'enabled;\n' +- ' bits "0x10" and "0x1000" were used in earlier versions of\n' +- ' 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 ' +- 'stack\n' +- ' frame (towards the caller), or "None" if this is the ' +- 'bottom\n' +- ' stack frame; "f_code" is the code object being executed in ' +- 'this\n' +- ' frame; "f_locals" is the dictionary used to look up local\n' +- ' 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" is\n' +- ' 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", and\n' +- ' also as the third item of the tuple returned by\n' +- ' "sys.exc_info()". The latter is the preferred interface, ' +- 'since\n' +- ' it works correctly when the program is using multiple ' +- 'threads.\n' +- ' When the program contains no suitable handler, the stack ' +- 'trace\n' +- ' is written (nicely formatted) to the standard error stream; ' +- 'if\n' +- ' the interpreter is interactive, it is also made available ' +- 'to the\n' +- ' user as "sys.last_traceback".\n' +- '\n' +- ' Special read-only attributes: "tb_next" is the next level ' +- 'in the\n' +- ' stack trace (towards the frame where the exception ' +- 'occurred), or\n' +- ' "None" if there is no next level; "tb_frame" points to the\n' +- ' execution frame of the current level; "tb_lineno" gives the ' +- 'line\n' +- ' number where the exception occurred; "tb_lasti" indicates ' +- 'the\n' +- ' precise instruction. The line number and last instruction ' +- 'in\n' +- ' the traceback may differ from the line number of its frame\n' +- ' object if the exception occurred in a "try" statement with ' +- 'no\n' +- ' matching except clause 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 ' +- 'the\n' +- ' built-in "slice()" function.\n' +- '\n' +- ' Special read-only attributes: "start" is the lower bound; ' +- '"stop"\n' +- ' is the upper bound; "step" is the step value; each is ' +- '"None" if\n' +- ' 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': '\n' +- 'Functions\n' +- '*********\n' +- '\n' +- 'Function objects are created by function definitions. ' +- 'The only\n' +- 'operation on a function object is to call it: ' +- '"func(argument-list)".\n' +- '\n' +- 'There are really two flavors of function objects: ' +- 'built-in functions\n' +- 'and user-defined functions. Both support the same ' +- 'operation (to call\n' +- 'the function), but the implementation is different, ' +- 'hence the\n' +- 'different object types.\n' +- '\n' +- 'See Function definitions for more information.\n', +- 'typesmapping': '\n' +- 'Mapping Types --- "dict"\n' +- '************************\n' +- '\n' +- 'A *mapping* object maps *hashable* values to arbitrary ' +- 'objects.\n' +- 'Mappings are mutable objects. There is currently only one ' +- 'standard\n' +- 'mapping type, the *dictionary*. (For other containers see ' +- 'the built\n' +- 'in "list", "set", and "tuple" classes, and the ' +- '"collections" module.)\n' +- '\n' +- "A dictionary's keys are *almost* arbitrary values. Values " +- 'that are\n' +- 'not *hashable*, that is, values containing lists, ' +- 'dictionaries or\n' +- 'other mutable types (that are compared by value rather ' +- 'than by object\n' +- 'identity) may not be used as keys. Numeric types used for ' +- 'keys obey\n' +- 'the normal rules for numeric comparison: if two numbers ' +- 'compare equal\n' +- '(such as "1" and "1.0") then they can be used ' +- 'interchangeably to index\n' +- 'the same dictionary entry. (Note however, that since ' +- 'computers store\n' +- 'floating-point numbers as approximations it is usually ' +- 'unwise to use\n' +- 'them as dictionary keys.)\n' +- '\n' +- 'Dictionaries can be created by placing a comma-separated ' +- 'list of "key:\n' +- 'value" pairs within braces, for example: "{\'jack\': 4098, ' +- "'sjoerd':\n" +- '4127}" or "{4098: \'jack\', 4127: \'sjoerd\'}", or by the ' +- '"dict"\n' +- 'constructor.\n' +- '\n' +- 'class class dict(**kwarg)\n' +- 'class class dict(mapping, **kwarg)\n' +- 'class 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 ' +- '*iterable*\n' +- ' object. Each item in the iterable must itself be an ' +- 'iterable 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' +- ' If a subclass of dict defines a method ' +- '"__missing__()" and *key*\n' +- ' is not present, the "d[key]" operation calls that ' +- 'method with\n' +- ' the key *key* as argument. The "d[key]" operation ' +- 'then returns\n' +- ' or raises whatever is returned or raised by the\n' +- ' "__missing__(key)" call. No other operations or ' +- 'methods invoke\n' +- ' "__missing__()". If "__missing__()" is not defined, ' +- '"KeyError"\n' +- ' is raised. "__missing__()" must be a method; it ' +- 'cannot be an\n' +- ' instance variable:\n' +- '\n' +- ' >>> class Counter(dict):\n' +- ' ... def __missing__(self, key):\n' +- ' ... return 0\n' +- ' >>> c = Counter()\n' +- " >>> c['red']\n" +- ' 0\n' +- " >>> c['red'] += 1\n" +- " >>> c['red']\n" +- ' 1\n' +- '\n' +- ' The example above shows part of the implementation ' +- 'of\n' +- ' "collections.Counter". A different "__missing__" ' +- 'method is used\n' +- ' by "collections.defaultdict".\n' +- '\n' +- ' New in version 2.5: Recognition of __missing__ ' +- 'methods of dict\n' +- ' subclasses.\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 not\n' +- ' 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", so\n' +- ' 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)" 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()", ' +- '"iterkeys()",\n' +- ' and "itervalues()" are called with no intervening ' +- 'modifications\n' +- ' to the dictionary, the lists will directly ' +- 'correspond. This\n' +- ' allows the creation of "(value, key)" pairs using ' +- '"zip()":\n' +- ' "pairs = zip(d.values(), d.keys())". The same ' +- 'relationship\n' +- ' holds for the "iterkeys()" and "itervalues()" ' +- 'methods: "pairs =\n' +- ' zip(d.itervalues(), d.iterkeys())" provides the same ' +- 'value for\n' +- ' "pairs". Another way to create the same list is ' +- '"pairs = [(v, k)\n' +- ' for (k, v) in 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' +- ' Dictionaries compare equal if and only if they have the ' +- 'same "(key,\n' +- ' value)" pairs.\n' +- '\n' +- '\n' +- 'Dictionary view objects\n' +- '=======================\n' +- '\n' +- 'The objects returned by "dict.viewkeys()", ' +- '"dict.viewvalues()" and\n' +- '"dict.viewitems()" are *view objects*. They provide a ' +- 'dynamic view on\n' +- "the dictionary's entries, which means that when the " +- 'dictionary\n' +- 'changes, the view reflects these changes.\n' +- '\n' +- 'Dictionary views can be iterated over to yield their ' +- 'respective data,\n' +- 'and support membership tests:\n' +- '\n' +- 'len(dictview)\n' +- '\n' +- ' Return the number of entries in the dictionary.\n' +- '\n' +- 'iter(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 using\n' +- ' "zip()": "pairs = zip(d.values(), d.keys())". Another ' +- 'way to\n' +- ' create the same list is "pairs = [(v, k) for (k, v) in ' +- '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' +- '\n' +- 'x in dictview\n' +- '\n' +- ' Return "True" if *x* is in the underlying dictionary\'s ' +- 'keys, values\n' +- ' or items (in the latter case, *x* should be a "(key, ' +- 'value)"\n' +- ' tuple).\n' +- '\n' +- 'Keys views are set-like since their entries are unique and ' +- 'hashable.\n' +- 'If all values are hashable, so that (key, value) pairs are ' +- 'unique and\n' +- 'hashable, then the items view is also set-like. (Values ' +- 'views are not\n' +- 'treated as set-like since the entries are generally not ' +- 'unique.) Then\n' +- 'these set operations are available ("other" refers either ' +- 'to another\n' +- 'view or a set):\n' +- '\n' +- 'dictview & other\n' +- '\n' +- ' Return the intersection of the dictview and the other ' +- 'object as a\n' +- ' new set.\n' +- '\n' +- 'dictview | other\n' +- '\n' +- ' Return the union of the dictview and the other object ' +- 'as a new set.\n' +- '\n' +- 'dictview - 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' +- '\n' +- 'dictview ^ 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' +- '\n' +- 'An 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': '\n' +- 'Methods\n' +- '*******\n' +- '\n' +- 'Methods are functions that are called using the attribute ' +- 'notation.\n' +- 'There are two flavors: built-in methods (such as ' +- '"append()" on lists)\n' +- 'and class instance methods. Built-in methods are ' +- 'described with the\n' +- 'types that support them.\n' +- '\n' +- 'The implementation adds two special read-only attributes ' +- 'to class\n' +- 'instance methods: "m.im_self" is the object on which the ' +- 'method\n' +- 'operates, and "m.im_func" is the function implementing the ' +- 'method.\n' +- 'Calling "m(arg-1, arg-2, ..., arg-n)" is completely ' +- 'equivalent to\n' +- 'calling "m.im_func(m.im_self, arg-1, arg-2, ..., arg-n)".\n' +- '\n' +- 'Class instance methods are either *bound* or *unbound*, ' +- 'referring to\n' +- 'whether the method was accessed through an instance or a ' +- 'class,\n' +- 'respectively. When a method is unbound, its "im_self" ' +- 'attribute will\n' +- 'be "None" and if called, an explicit "self" object must be ' +- 'passed as\n' +- 'the first argument. In this case, "self" must be an ' +- 'instance of the\n' +- "unbound method's class (or a subclass of that class), " +- 'otherwise a\n' +- '"TypeError" is raised.\n' +- '\n' +- 'Like function objects, methods objects support getting ' +- 'arbitrary\n' +- 'attributes. However, since method attributes are actually ' +- 'stored on\n' +- 'the underlying function object ("meth.im_func"), setting ' +- 'method\n' +- 'attributes on either bound or unbound methods is ' +- 'disallowed.\n' +- 'Attempting to set an attribute on a method results in an\n' +- '"AttributeError" being raised. In order to set a method ' +- 'attribute,\n' +- 'you 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" +- '\n' +- 'See The standard type hierarchy for more information.\n', +- 'typesmodules': '\n' +- 'Modules\n' +- '*******\n' +- '\n' +- 'The only special operation on a module is attribute ' +- 'access: "m.name",\n' +- 'where *m* is a module and *name* accesses a name defined ' +- "in *m*'s\n" +- 'symbol table. Module attributes can be assigned to. (Note ' +- 'that the\n' +- '"import" statement is not, strictly speaking, an operation ' +- 'on a module\n' +- 'object; "import foo" does not require a module object ' +- 'named *foo* to\n' +- 'exist, rather it requires an (external) *definition* for a ' +- 'module\n' +- 'named *foo* somewhere.)\n' +- '\n' +- 'A special attribute of every module is "__dict__". This is ' +- 'the\n' +- "dictionary containing the module's symbol table. Modifying " +- 'this\n' +- "dictionary will actually change the module's symbol table, " +- 'but direct\n' +- 'assignment to the "__dict__" attribute is not possible ' +- '(you can write\n' +- '"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", ' +- "but you can't\n" +- 'write "m.__dict__ = {}"). Modifying "__dict__" directly ' +- 'is not\n' +- 'recommended.\n' +- '\n' +- 'Modules built into the interpreter are written like this: ' +- '"". If loaded from a file, they are ' +- 'written as\n' +- '"".\n', +- 'typesseq': '\n' +- 'Sequence Types --- "str", "unicode", "list", "tuple", ' +- '"bytearray", "buffer", "xrange"\n' +- '*************************************************************************************\n' +- '\n' +- 'There are seven sequence types: strings, Unicode strings, ' +- 'lists,\n' +- 'tuples, bytearrays, buffers, and xrange objects.\n' +- '\n' +- 'For other containers see the built in "dict" and "set" ' +- 'classes, and\n' +- 'the "collections" module.\n' +- '\n' +- 'String literals are written in single or double quotes: ' +- '"\'xyzzy\'",\n' +- '""frobozz"". See String literals for more about string ' +- 'literals.\n' +- 'Unicode strings are much like strings, but are specified in ' +- 'the syntax\n' +- 'using a preceding "\'u\'" character: "u\'abc\'", "u"def"". In ' +- 'addition to\n' +- 'the functionality described here, there are also ' +- 'string-specific\n' +- 'methods described in the String Methods section. Lists are ' +- 'constructed\n' +- 'with square brackets, separating items with commas: "[a, b, ' +- 'c]".\n' +- 'Tuples are constructed by the comma operator (not within ' +- 'square\n' +- 'brackets), with or without enclosing parentheses, but an empty ' +- 'tuple\n' +- 'must have the enclosing parentheses, such as "a, b, c" or ' +- '"()". A\n' +- 'single item tuple must have a trailing comma, such as "(d,)".\n' +- '\n' +- 'Bytearray objects are created with the built-in function\n' +- '"bytearray()".\n' +- '\n' +- 'Buffer objects are not directly supported by Python syntax, ' +- 'but can be\n' +- 'created by calling the built-in function "buffer()". They ' +- "don't\n" +- 'support concatenation or repetition.\n' +- '\n' +- 'Objects of type xrange are similar to buffers in that there is ' +- 'no\n' +- 'specific syntax to create them, but they are created using ' +- 'the\n' +- '"xrange()" function. They don\'t support slicing, ' +- 'concatenation or\n' +- 'repetition, and using "in", "not in", "min()" or "max()" on ' +- 'them is\n' +- 'inefficient.\n' +- '\n' +- 'Most sequence types support the following operations. The ' +- '"in" and\n' +- '"not in" operations have the same priorities as the ' +- 'comparison\n' +- 'operations. The "+" and "*" operations have the same priority ' +- 'as the\n' +- 'corresponding numeric operations. [3] Additional methods are ' +- 'provided\n' +- 'for Mutable Sequence Types.\n' +- '\n' +- 'This table lists the sequence operations sorted in ascending ' +- 'priority.\n' +- 'In the table, *s* and *t* are sequences of the same type; *n*, ' +- '*i* and\n' +- '*j* are integers:\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" | equivalent to adding *s* to | ' +- '(2) |\n' +- '| | itself *n* times ' +- '| |\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(x)" | index of the first occurrence of ' +- '| |\n' +- '| | *x* in *s* ' +- '| |\n' +- '+--------------------+----------------------------------+------------+\n' +- '| "s.count(x)" | total number of occurrences of ' +- '| |\n' +- '| | *x* in *s* ' +- '| |\n' +- '+--------------------+----------------------------------+------------+\n' +- '\n' +- 'Sequence types also support comparisons. In particular, tuples ' +- 'and\n' +- 'lists are compared lexicographically by comparing ' +- 'corresponding\n' +- 'elements. This means that to compare equal, every element must ' +- 'compare\n' +- 'equal and the two sequences must be of the same type and have ' +- 'the same\n' +- 'length. (For full details see Comparisons in the language ' +- 'reference.)\n' +- '\n' +- 'Notes:\n' +- '\n' +- '1. 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' +- '\n' +- '2. Values of *n* less than "0" are treated as "0" (which ' +- 'yields an\n' +- ' empty sequence of the same type as *s*). Note that items ' +- 'in the\n' +- ' sequence *s* are not copied; they are referenced multiple ' +- 'times.\n' +- ' This often haunts 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 ' +- 'references\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' +- '\n' +- ' Further explanation is available in the FAQ entry How do I ' +- 'create a\n' +- ' multidimensional list?.\n' +- '\n' +- '3. If *i* or *j* is negative, the index is relative to the end ' +- 'of\n' +- ' the string: "len(s) + i" or "len(s) + j" is substituted. ' +- 'But note\n' +- ' that "-0" is still "0".\n' +- '\n' +- '4. 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 ' +- '"None",\n' +- ' use "0". If *j* is omitted or "None", use "len(s)". If ' +- '*i* is\n' +- ' greater than or equal to *j*, the slice is empty.\n' +- '\n' +- '5. 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", ' +- '"i+2*k",\n' +- ' "i+3*k" and so on, stopping when *j* is reached (but never\n' +- ' including *j*). If *i* or *j* is greater than "len(s)", ' +- 'use\n' +- ' "len(s)". If *i* or *j* are omitted or "None", they become ' +- '"end"\n' +- ' values (which end depends on the sign of *k*). Note, *k* ' +- 'cannot be\n' +- ' zero. If *k* is "None", it is treated like "1".\n' +- '\n' +- '6. **CPython implementation detail:** If *s* and *t* are both\n' +- ' strings, some Python implementations such as CPython can ' +- 'usually\n' +- ' perform an in-place optimization for assignments of the ' +- 'form "s = s\n' +- ' + t" or "s += t". When applicable, this optimization ' +- 'makes\n' +- ' quadratic run-time much less likely. This optimization is ' +- 'both\n' +- ' version and implementation dependent. For performance ' +- 'sensitive\n' +- ' code, it is 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' +- '\n' +- 'String Methods\n' +- '==============\n' +- '\n' +- 'Below are listed the string methods which both 8-bit strings ' +- 'and\n' +- 'Unicode objects support. Some of them are also available on\n' +- '"bytearray" objects.\n' +- '\n' +- "In addition, Python's strings support the sequence type " +- 'methods\n' +- 'described in the Sequence Types --- str, unicode, list, ' +- 'tuple,\n' +- 'bytearray, buffer, xrange section. To output formatted strings ' +- 'use\n' +- 'template strings or the "%" operator described in the String\n' +- 'Formatting Operations section. Also, see the "re" module for ' +- 'string\n' +- 'functions based on regular expressions.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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 ' +- '"UnicodeError".\n' +- ' Other possible values are "\'ignore\'", "\'replace\'",\n' +- ' "\'xmlcharrefreplace\'", "\'backslashreplace\'" and any ' +- 'other name\n' +- ' registered via "codecs.register_error()", see section Codec ' +- 'Base\n' +- ' Classes. For a list of possible encodings, see section ' +- 'Standard\n' +- ' 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' +- '\n' +- 'str.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 ' +- 'suffixes\n' +- ' to look for. With optional *start*, test beginning at ' +- 'that\n' +- ' position. With optional *end*, stop comparing at that ' +- 'position.\n' +- '\n' +- ' Changed in version 2.5: Accept tuples as *suffix*.\n' +- '\n' +- 'str.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 result\n' +- ' until the current column is equal to the next tab position. ' +- '(The\n' +- ' tab character itself is not copied.) If the character is a ' +- 'newline\n' +- ' ("\\n") or return ("\\r"), it is copied and the current ' +- 'column is\n' +- ' reset to zero. Any other character is copied unchanged and ' +- 'the\n' +- ' 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" +- '\n' +- 'str.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\n' +- ' the position of *sub*. To check if *sub* is a substring ' +- 'or not,\n' +- ' use the "in" operator:\n' +- '\n' +- " >>> 'Py' in 'Python'\n" +- ' True\n' +- '\n' +- 'str.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 ' +- 'String\n' +- ' Formatting Operations in new code.\n' +- '\n' +- ' New in version 2.6.\n' +- '\n' +- 'str.index(sub[, start[, end]])\n' +- '\n' +- ' Like "find()", but raise "ValueError" when the substring is ' +- 'not\n' +- ' found.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.rindex(sub[, start[, end]])\n' +- '\n' +- ' Like "rfind()" but raises "ValueError" when the substring ' +- '*sub* is\n' +- ' not found.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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 ' +- 'splitting\n' +- ' from the right, "rsplit()" behaves like "split()" which is\n' +- ' described in detail below.\n' +- '\n' +- ' New in version 2.4.\n' +- '\n' +- 'str.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' +- '\n' +- 'str.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* argument\n' +- ' may consist of multiple characters (for example,\n' +- ' "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', ' +- '\'3\']"). Splitting an\n' +- ' 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' +- ' For example, "\' 1 2 3 \'.split()" returns "[\'1\', ' +- '\'2\', \'3\']", and\n' +- ' "\' 1 2 3 \'.split(None, 1)" returns "[\'1\', \'2 3 ' +- '\']".\n' +- '\n' +- 'str.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 "[\'ab\n' +- ' c\', \'\', \'de fg\', \'kl\']", while the same call with\n' +- ' "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de ' +- 'fg\\r\', \'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' +- '\n' +- 'str.startswith(prefix[, start[, end]])\n' +- '\n' +- ' Return "True" if string starts with the *prefix*, otherwise ' +- 'return\n' +- ' "False". *prefix* can also be a tuple of prefixes to look ' +- 'for.\n' +- ' With optional *start*, test string beginning at that ' +- 'position.\n' +- ' With optional *end*, stop comparing string at that ' +- 'position.\n' +- '\n' +- ' Changed in version 2.5: Accept tuples as *prefix*.\n' +- '\n' +- 'str.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 ' +- '*chars*\n' +- ' argument defaults to removing whitespace. The *chars* ' +- 'argument is\n' +- ' not a prefix or suffix; rather, all combinations of its ' +- 'values are\n' +- ' 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' +- '\n' +- 'str.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' +- '\n' +- 'str.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' +- '\n' +- 'str.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. Note,\n' +- ' a more flexible approach is to create a custom character ' +- 'mapping\n' +- ' codec using the "codecs" module (see "encodings.cp1251" for ' +- 'an\n' +- ' example).\n' +- '\n' +- 'str.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 be\n' +- ' "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' +- '\n' +- 'str.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' +- '\n' +- 'The following methods are present only on unicode objects:\n' +- '\n' +- 'unicode.isnumeric()\n' +- '\n' +- ' Return "True" if there are only numeric characters in S, ' +- '"False"\n' +- ' otherwise. Numeric characters include digit characters, and ' +- 'all\n' +- ' characters that have the Unicode numeric value property, ' +- 'e.g.\n' +- ' U+2155, VULGAR FRACTION ONE FIFTH.\n' +- '\n' +- 'unicode.isdecimal()\n' +- '\n' +- ' Return "True" if there are only decimal characters in S, ' +- '"False"\n' +- ' otherwise. Decimal characters include digit characters, and ' +- 'all\n' +- ' characters that can be used to form decimal-radix numbers, ' +- 'e.g.\n' +- ' U+0660, ARABIC-INDIC DIGIT ZERO.\n' +- '\n' +- '\n' +- 'String Formatting Operations\n' +- '============================\n' +- '\n' +- 'String and Unicode objects have one unique built-in operation: ' +- 'the "%"\n' +- 'operator (modulo). This is also known as the string ' +- '*formatting* or\n' +- '*interpolation* operator. Given "format % values" (where ' +- '*format* is\n' +- 'a string or Unicode object), "%" conversion specifications in ' +- '*format*\n' +- 'are replaced with zero or more elements of *values*. The ' +- 'effect is\n' +- 'similar to the using "sprintf()" in the C language. If ' +- '*format* is a\n' +- 'Unicode object, or if any of the objects being converted using ' +- 'the\n' +- '"%s" conversion are Unicode objects, the result will also be a ' +- 'Unicode\n' +- 'object.\n' +- '\n' +- 'If *format* requires a single argument, *values* may be a ' +- 'single non-\n' +- 'tuple object. [5] Otherwise, *values* must be a tuple with ' +- 'exactly\n' +- 'the number of items specified by the format string, or a ' +- 'single\n' +- 'mapping object (for example, a dictionary).\n' +- '\n' +- 'A conversion specifier contains two or more characters and has ' +- 'the\n' +- 'following components, which must occur in this order:\n' +- '\n' +- '1. The "\'%\'" character, which marks the start of the ' +- 'specifier.\n' +- '\n' +- '2. Mapping key (optional), consisting of a parenthesised ' +- 'sequence\n' +- ' of characters (for example, "(somename)").\n' +- '\n' +- '3. Conversion flags (optional), which affect the result of ' +- 'some\n' +- ' conversion types.\n' +- '\n' +- '4. 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' +- '\n' +- '5. 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' +- '\n' +- '6. Length modifier (optional).\n' +- '\n' +- '7. Conversion type.\n' +- '\n' +- 'When the right argument is a dictionary (or other mapping ' +- 'type), then\n' +- 'the formats in the string *must* include a parenthesised ' +- 'mapping key\n' +- 'into that dictionary inserted immediately after the "\'%\'" ' +- 'character.\n' +- 'The mapping key selects the value to be formatted from the ' +- 'mapping.\n' +- 'For example:\n' +- '\n' +- ">>> print '%(language)s has %(number)03d quote types.' % \\\n" +- '... {"language": "Python", "number": 2}\n' +- 'Python has 002 quote types.\n' +- '\n' +- 'In this case no "*" specifiers may occur in a format (since ' +- 'they\n' +- 'require a sequential parameter list).\n' +- '\n' +- 'The 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\'" conversion |\n' +- '| | 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' +- '\n' +- 'A length modifier ("h", "l", or "L") may be present, but is ' +- 'ignored as\n' +- 'it is not necessary for Python -- so e.g. "%ld" is identical ' +- 'to "%d".\n' +- '\n' +- 'The 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' +- '\n' +- 'Notes:\n' +- '\n' +- '1. 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' +- '\n' +- '2. 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' +- '\n' +- '3. 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' +- '\n' +- '4. 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' +- '\n' +- '5. The "%r" conversion was added in Python 2.0.\n' +- '\n' +- ' The precision determines the maximal number of characters ' +- 'used.\n' +- '\n' +- '6. 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' +- '\n' +- '7. See **PEP 237**.\n' +- '\n' +- 'Since Python strings have an explicit length, "%s" conversions ' +- 'do not\n' +- 'assume that "\'\\0\'" is the end of the string.\n' +- '\n' +- 'Changed in version 2.7: "%f" conversions for numbers whose ' +- 'absolute\n' +- 'value is over 1e50 are no longer replaced by "%g" ' +- 'conversions.\n' +- '\n' +- 'Additional string operations are defined in standard modules ' +- '"string"\n' +- 'and "re".\n' +- '\n' +- '\n' +- 'XRange Type\n' +- '===========\n' +- '\n' +- 'The "xrange" type is an immutable sequence which is commonly ' +- 'used for\n' +- 'looping. The advantage of the "xrange" type is that an ' +- '"xrange"\n' +- 'object will always take the same amount of memory, no matter ' +- 'the size\n' +- 'of the range it represents. There are no consistent ' +- 'performance\n' +- 'advantages.\n' +- '\n' +- 'XRange objects have very little behavior: they only support ' +- 'indexing,\n' +- 'iteration, and the "len()" function.\n' +- '\n' +- '\n' +- 'Mutable Sequence Types\n' +- '======================\n' +- '\n' +- 'List and "bytearray" objects support additional operations ' +- 'that allow\n' +- 'in-place modification of the object. Other mutable sequence ' +- 'types\n' +- '(when added to the language) should also support these ' +- 'operations.\n' +- 'Strings and tuples are immutable sequence types: such objects ' +- 'cannot\n' +- 'be modified once created. The following operations are defined ' +- 'on\n' +- '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)] = ' +- '[x]" | (2) |\n' +- '+--------------------------------+----------------------------------+-----------------------+\n' +- '| "s.extend(x)" or "s += t" | for the most part the same ' +- 'as | (3) |\n' +- '| | "s[len(s):len(s)] = ' +- 'x" | |\n' +- '+--------------------------------+----------------------------------+-----------------------+\n' +- '| "s *= n" | updates *s* with its ' +- 'contents | (11) |\n' +- '| | repeated *n* ' +- 'times | |\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' +- '\n' +- 'Notes:\n' +- '\n' +- '1. *t* must have the same length as the slice it is ' +- 'replacing.\n' +- '\n' +- '2. The C implementation of Python has historically accepted\n' +- ' multiple parameters and implicitly joined them into a ' +- 'tuple; this\n' +- ' no longer works in Python 2.0. Use of this misfeature has ' +- 'been\n' +- ' deprecated since Python 1.4.\n' +- '\n' +- '3. *x* can be any iterable object.\n' +- '\n' +- '4. Raises "ValueError" when *x* is not found in *s*. When a\n' +- ' negative index is passed as the second or third parameter ' +- 'to the\n' +- ' "index()" method, the list length is added, as for slice ' +- 'indices.\n' +- ' If it is still negative, it is truncated to zero, as for ' +- 'slice\n' +- ' indices.\n' +- '\n' +- ' Changed in version 2.3: Previously, "index()" didn\'t have ' +- 'arguments\n' +- ' for specifying start and stop positions.\n' +- '\n' +- '5. When a negative index is passed as the first parameter to ' +- 'the\n' +- ' "insert()" method, the list length is added, as for slice ' +- 'indices.\n' +- ' If it is still negative, it is truncated to zero, as for ' +- 'slice\n' +- ' indices.\n' +- '\n' +- ' Changed in version 2.3: Previously, all negative indices ' +- 'were\n' +- ' truncated to zero.\n' +- '\n' +- '6. The "pop()" method\'s optional argument *i* defaults to ' +- '"-1", so\n' +- ' that by default the last item is removed and returned.\n' +- '\n' +- '7. 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' +- '\n' +- '8. 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 to\n' +- ' 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' +- '\n' +- '9. Starting with Python 2.3, the "sort()" method is guaranteed ' +- 'to\n' +- ' be 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' +- '\n' +- '10. **CPython implementation detail:** While a list is being\n' +- ' sorted, the effect of attempting to mutate, or even ' +- 'inspect, the\n' +- ' list is undefined. The C implementation of Python 2.3 and ' +- 'newer\n' +- ' makes the list appear empty for the duration, and raises\n' +- ' "ValueError" if it can detect that the list has been ' +- 'mutated\n' +- ' during a sort.\n' +- '\n' +- '11. The value *n* is an integer, or an object implementing\n' +- ' "__index__()". Zero and negative values of *n* clear the\n' +- ' sequence. Items in the sequence are not copied; they are\n' +- ' referenced multiple times, as explained for "s * n" under ' +- 'Sequence\n' +- ' Types --- str, unicode, list, tuple, bytearray, buffer, ' +- 'xrange.\n', +- 'typesseq-mutable': '\n' +- 'Mutable Sequence Types\n' +- '**********************\n' +- '\n' +- 'List and "bytearray" objects support additional ' +- 'operations that allow\n' +- 'in-place modification of the object. Other mutable ' +- 'sequence types\n' +- '(when added to the language) should also support these ' +- 'operations.\n' +- 'Strings and tuples are immutable sequence types: such ' +- 'objects cannot\n' +- 'be modified once created. The following operations are ' +- 'defined on\n' +- '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)] = [x]" | (2) |\n' +- '+--------------------------------+----------------------------------+-----------------------+\n' +- '| "s.extend(x)" or "s += t" | for the most part ' +- 'the same as | (3) |\n' +- '| | "s[len(s):len(s)] = ' +- 'x" | |\n' +- '+--------------------------------+----------------------------------+-----------------------+\n' +- '| "s *= n" | updates *s* with ' +- 'its contents | (11) |\n' +- '| | repeated *n* ' +- 'times | |\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' +- '\n' +- 'Notes:\n' +- '\n' +- '1. *t* must have the same length as the slice it is ' +- 'replacing.\n' +- '\n' +- '2. The C implementation of Python has historically ' +- 'accepted\n' +- ' multiple parameters and implicitly joined them into ' +- 'a tuple; this\n' +- ' no longer works in Python 2.0. Use of this ' +- 'misfeature has been\n' +- ' deprecated since Python 1.4.\n' +- '\n' +- '3. *x* can be any iterable object.\n' +- '\n' +- '4. Raises "ValueError" when *x* is not found in *s*. ' +- 'When a\n' +- ' negative index is passed as the second or third ' +- 'parameter to the\n' +- ' "index()" method, the list length is added, as for ' +- 'slice indices.\n' +- ' If it is still negative, it is truncated to zero, ' +- 'as for slice\n' +- ' indices.\n' +- '\n' +- ' Changed in version 2.3: Previously, "index()" ' +- "didn't have arguments\n" +- ' for specifying start and stop positions.\n' +- '\n' +- '5. When a negative index is passed as the first ' +- 'parameter to the\n' +- ' "insert()" method, the list length is added, as for ' +- 'slice indices.\n' +- ' If it is still negative, it is truncated to zero, ' +- 'as for slice\n' +- ' indices.\n' +- '\n' +- ' Changed in version 2.3: Previously, all negative ' +- 'indices were\n' +- ' truncated to zero.\n' +- '\n' +- '6. The "pop()" method\'s optional argument *i* ' +- 'defaults to "-1", so\n' +- ' that by default the last item is removed and ' +- 'returned.\n' +- '\n' +- '7. 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' +- '\n' +- '8. 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 to\n' +- ' 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' +- '\n' +- '9. Starting with Python 2.3, the "sort()" method is ' +- 'guaranteed to\n' +- ' be 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' +- '\n' +- '10. **CPython implementation detail:** While a list is ' +- 'being\n' +- ' sorted, the effect of attempting to mutate, or ' +- 'even inspect, the\n' +- ' list is undefined. The C implementation of Python ' +- '2.3 and newer\n' +- ' makes the list appear empty for the duration, and ' +- 'raises\n' +- ' "ValueError" if it can detect that the list has ' +- 'been mutated\n' +- ' during a sort.\n' +- '\n' +- '11. The value *n* is an integer, or an object ' +- 'implementing\n' +- ' "__index__()". Zero and negative values of *n* ' +- 'clear the\n' +- ' sequence. Items in the sequence are not copied; ' +- 'they are\n' +- ' referenced multiple times, as explained for "s * ' +- 'n" under Sequence\n' +- ' Types --- str, unicode, list, tuple, bytearray, ' +- 'buffer, xrange.\n', +- 'unary': '\n' +- 'Unary arithmetic and bitwise operations\n' +- '***************************************\n' +- '\n' +- 'All unary arithmetic and bitwise operations have the same ' +- 'priority:\n' +- '\n' +- ' u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n' +- '\n' +- 'The unary "-" (minus) operator yields the negation of its ' +- 'numeric\n' +- 'argument.\n' +- '\n' +- 'The unary "+" (plus) operator yields its numeric argument ' +- 'unchanged.\n' +- '\n' +- 'The unary "~" (invert) operator yields the bitwise inversion of ' +- 'its\n' +- 'plain or long integer argument. The bitwise inversion of "x" is\n' +- 'defined as "-(x+1)". It only applies to integral numbers.\n' +- '\n' +- 'In all three cases, if the argument does not have the proper ' +- 'type, a\n' +- '"TypeError" exception is raised.\n', +- 'while': '\n' +- 'The "while" statement\n' +- '*********************\n' +- '\n' +- 'The "while" statement is used for repeated execution as long as ' +- 'an\n' +- 'expression is true:\n' +- '\n' +- ' while_stmt ::= "while" expression ":" suite\n' +- ' ["else" ":" suite]\n' +- '\n' +- 'This repeatedly tests the expression and, if it is true, executes ' +- 'the\n' +- 'first suite; if the expression is false (which may be the first ' +- 'time\n' +- 'it is tested) the suite of the "else" clause, if present, is ' +- 'executed\n' +- 'and the loop terminates.\n' +- '\n' +- 'A "break" statement executed in the first suite terminates the ' +- 'loop\n' +- 'without executing the "else" clause\'s suite. A "continue" ' +- 'statement\n' +- 'executed in the first suite skips the rest of the suite and goes ' +- 'back\n' +- 'to testing the expression.\n', +- 'with': '\n' +- 'The "with" statement\n' +- '********************\n' +- '\n' +- 'New in version 2.5.\n' +- '\n' +- 'The "with" statement is used to wrap the execution of a block ' +- 'with\n' +- 'methods defined by a context manager (see section With Statement\n' +- 'Context Managers). This allows common ' +- '"try"..."except"..."finally"\n' +- 'usage patterns to be encapsulated for convenient reuse.\n' +- '\n' +- ' with_stmt ::= "with" with_item ("," with_item)* ":" suite\n' +- ' with_item ::= expression ["as" target]\n' +- '\n' +- 'The execution of the "with" statement with one "item" proceeds as\n' +- 'follows:\n' +- '\n' +- '1. The context expression (the expression given in the ' +- '"with_item")\n' +- ' is evaluated to obtain a context manager.\n' +- '\n' +- '2. The context manager\'s "__exit__()" is loaded for later use.\n' +- '\n' +- '3. The context manager\'s "__enter__()" method is invoked.\n' +- '\n' +- '4. 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 be\n' +- ' 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' +- '\n' +- '5. The suite is executed.\n' +- '\n' +- '6. 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, ' +- 'three\n' +- ' "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 ' +- 'reraised.\n' +- ' If the return value was true, the exception is suppressed, and\n' +- ' execution continues with the statement following the "with"\n' +- ' 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' +- '\n' +- 'With more than one item, the context managers are processed as if\n' +- 'multiple "with" statements were nested:\n' +- '\n' +- ' with A() as a, B() as b:\n' +- ' suite\n' +- '\n' +- 'is equivalent to\n' +- '\n' +- ' with A() as a:\n' +- ' with B() as b:\n' +- ' suite\n' +- '\n' +- 'Note: In Python 2.5, the "with" statement is only allowed when ' +- 'the\n' +- ' "with_statement" feature has been enabled. It is always enabled ' +- 'in\n' +- ' Python 2.6.\n' +- '\n' +- 'Changed in version 2.7: Support for multiple context expressions.\n' +- '\n' +- 'See also: **PEP 0343** - The "with" statement\n' +- '\n' +- ' The specification, background, and examples for the Python ' +- '"with"\n' +- ' statement.\n', +- 'yield': '\n' +- 'The "yield" statement\n' +- '*********************\n' +- '\n' +- ' yield_stmt ::= yield_expression\n' +- '\n' +- 'The "yield" statement is only used when defining a generator ' +- 'function,\n' +- 'and is only used in the body of the generator function. Using a\n' +- '"yield" statement in a function definition is sufficient to cause ' +- 'that\n' +- 'definition to create a generator function instead of a normal\n' +- 'function.\n' +- '\n' +- 'When a generator function is called, it returns an iterator known ' +- 'as a\n' +- 'generator iterator, or more commonly, a generator. The body of ' +- 'the\n' +- "generator function is executed by calling the generator's " +- '"next()"\n' +- 'method repeatedly until it raises an exception.\n' +- '\n' +- 'When a "yield" statement is executed, the state of the generator ' +- 'is\n' +- 'frozen and the value of "expression_list" is returned to ' +- '"next()"\'s\n' +- 'caller. By "frozen" we mean that all local state is retained,\n' +- 'including the current bindings of local variables, the ' +- 'instruction\n' +- 'pointer, and the internal evaluation stack: enough information ' +- 'is\n' +- 'saved so that the next time "next()" is invoked, the function ' +- 'can\n' +- 'proceed exactly as if the "yield" statement were just another ' +- 'external\n' +- 'call.\n' +- '\n' +- 'As of Python version 2.5, the "yield" statement is now allowed in ' +- 'the\n' +- '"try" clause of a "try" ... "finally" construct. If the ' +- 'generator is\n' +- 'not resumed before it is finalized (by reaching a zero reference ' +- 'count\n' +- "or by being garbage collected), the generator-iterator's " +- '"close()"\n' +- 'method will be called, allowing any pending "finally" clauses to\n' +- 'execute.\n' +- '\n' +- 'For full details of "yield" semantics, refer to the Yield ' +- 'expressions\n' +- 'section.\n' +- '\n' +- 'Note: In Python 2.2, the "yield" statement was only allowed when ' +- 'the\n' +- ' "generators" feature has been enabled. This "__future__" ' +- 'import\n' +- ' statement was used to enable the feature:\n' +- '\n' +- ' from __future__ import generators\n' +- '\n' +- 'See also: **PEP 0255** - Simple Generators\n' +- '\n' +- ' The proposal for adding generators and the "yield" statement ' +- 'to\n' +- ' Python.\n' +- '\n' +- ' **PEP 0342** - Coroutines via Enhanced Generators\n' +- ' The proposal that, among other generator enhancements, ' +- 'proposed\n' +- ' allowing "yield" to appear inside a "try" ... "finally" ' +- 'block.\n'} ++# Autogenerated by Sphinx on Wed Jan 6 03:48:54 2016 ++topics = {'assert': u'\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 to\n\n if __debug__:\n if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that "__debug__" and "AssertionError" refer\nto 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 (command\nline option -O). The current code generator emits no code for an\nassert statement when optimization is requested at compile time. Note\nthat it is unnecessary to include the source code for the expression\nthat failed in the error message; it will be displayed as part of the\nstack trace.\n\nAssignments to "__debug__" are illegal. The value for the built-in\nvariable is determined when the interpreter starts.\n', ++ 'assignment': u'\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\n object must be an iterable with the same number of items as there\n are targets in the target list, and the items are assigned, from\n left to 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\n square brackets: The object must be an iterable with the same number\n of 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 always\n set as an instance attribute, creating it if necessary. Thus, the\n two occurrences of "a.x" do not necessarily refer to the same\n attribute: if the RHS expression refers to a class attribute, the\n 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\n reference is evaluated. It should yield a mutable sequence object\n (such as a list). The assigned object should be a sequence object\n of the same type. Next, the lower and upper bound expressions are\n evaluated, insofar they are present; defaults are zero and the\n sequence\'s length. The bounds should evaluate to (small) integers.\n If either bound is negative, the sequence\'s length is added to it.\n The resulting bounds are clipped to lie between zero and the\n sequence\'s length, inclusive. Finally, the sequence object is asked\n to replace the slice with the items of the assigned sequence. The\n length of the slice may be different from the length of the assigned\n sequence, thus changing the length of the target sequence, if the\n object 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 the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis 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': u'\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name. See section Identifiers\nand keywords for lexical definition and section Naming and binding for\ndocumentation 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 "__spam"\noccurring in a class named "Ham" will be transformed to "_Ham__spam".\nThis transformation is independent of the syntactical context in which\nthe identifier is used. If the transformed name is extremely long\n(longer than 255 characters), implementation defined truncation may\nhappen. If the class name consists only of underscores, no\ntransformation is done.\n', ++ 'atom-literals': u"\nLiterals\n********\n\nPython supports string literals and various numeric literals:\n\n literal ::= stringliteral | integer | longinteger\n | floatnumber | imagnumber\n\nEvaluation of a literal yields an object of the given type (string,\ninteger, long integer, floating point number, complex number) with the\ngiven value. The value may be approximated in the case of floating\npoint and imaginary (complex) literals. See section Literals for\ndetails.\n\nAll literals correspond to immutable data types, and hence the\nobject's identity is less important than its value. Multiple\nevaluations of literals with the same value (either the same\noccurrence in the program text or a different occurrence) may obtain\nthe same object or a different object with the same value.\n", ++ 'attribute-access': u'\nCustomizing attribute access\n****************************\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of "x.name") for\nclass instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for "self"). "name" is the attribute name. This\n method should return the (computed) attribute value or raise an\n "AttributeError" exception.\n\n Note that if the attribute is found through the normal mechanism,\n "__getattr__()" is not called. (This is an intentional asymmetry\n between "__getattr__()" and "__setattr__()".) This is done both for\n efficiency reasons and because otherwise "__getattr__()" would have\n no way to access other attributes of the instance. Note that at\n least for instance variables, you can fake total control by not\n inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n "__getattribute__()" method below for a way to actually get total\n control in new-style classes.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If "__setattr__()" wants to assign to an instance attribute, it\n should not simply execute "self.name = value" --- this would cause\n a recursive call to itself. Instead, it should insert the value in\n the dictionary of instance attributes, e.g., "self.__dict__[name] =\n value". For new-style classes, rather than accessing the instance\n dictionary, it should call the base class method with the same\n name, for example, "object.__setattr__(self, name, value)".\n\nobject.__delattr__(self, name)\n\n Like "__setattr__()" but for attribute deletion instead of\n assignment. This should only be implemented if "del obj.name" is\n meaningful for the object.\n\n\nMore attribute access for new-style classes\n===========================================\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines "__getattr__()",\n the latter will not be called unless "__getattribute__()" either\n calls it explicitly or raises an "AttributeError". This method\n should return the (computed) attribute value or raise an\n "AttributeError" exception. In order to avoid infinite recursion in\n this method, its implementation should always call the base class\n method with the same name to access any attributes it needs, for\n example, "object.__getattribute__(self, name)".\n\n Note: This method may still be bypassed when looking up special\n methods as the result of implicit invocation via language syntax\n or built-in functions. See Special method lookup for new-style\n classes.\n\n\nImplementing Descriptors\n========================\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents). In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' "__dict__".\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or "None" when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an "AttributeError"\n exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n====================\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: "__get__()", "__set__()", and\n"__delete__()". If any of those methods are defined for an object, it\nis said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, "a.x" has a\nlookup chain starting with "a.__dict__[\'x\']", then\n"type(a).__dict__[\'x\']", and continuing through the base classes of\n"type(a)" excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass "object()" or "type()").\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe arguments are assembled depends on "a":\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: "x.__get__(a)".\n\nInstance Binding\n If binding to a new-style object instance, "a.x" is transformed\n into the call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n If binding to a new-style class, "A.x" is transformed into the\n call: "A.__dict__[\'x\'].__get__(None, A)".\n\nSuper Binding\n If "a" is an instance of "super", then the binding "super(B,\n obj).m()" searches "obj.__class__.__mro__" for the base class "A"\n immediately preceding "B" and then invokes the descriptor with the\n call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of "__get__()", "__set__()" and "__delete__()". If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary. If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor. Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method. Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary. In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe "property()" function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n=========\n\nBy default, instances of both old and new-style classes have a\ndictionary for attribute storage. This wastes space for objects\nhaving very few instance variables. The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition. The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable. Space is saved because *__dict__* is\nnot created for each instance.\n\n__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n new-style class, *__slots__* reserves space for the declared\n variables and prevents the automatic creation of *__dict__* and\n *__weakref__* for each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises "AttributeError". If\n dynamic assignment of new variables is desired, then add\n "\'__dict__\'" to the sequence of strings in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously, adding "\'__dict__\'" to the\n *__slots__* declaration would not enable the assignment of new\n attributes not specifically listed in the sequence of instance\n variable names.\n\n* Without a *__weakref__* variable for each instance, classes\n defining *__slots__* do not support weak references to its\n instances. If weak reference support is needed, then add\n "\'__weakref__\'" to the sequence of strings in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously, adding "\'__weakref__\'" to the\n *__slots__* declaration would not enable support for weak\n references.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (Implementing Descriptors) for each variable name. As a\n result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__* (which must only contain names\n of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the\n instance variable defined by the base class slot is inaccessible\n (except by retrieving its descriptor directly from the base class).\n This renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as "long", "str" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n may also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__slots__*.\n', ++ 'attribute-references': u'\nAttribute references\n********************\n\nAn attribute reference is a primary followed by a period and a name:\n\n attributeref ::= primary "." identifier\n\nThe primary must evaluate to an object of a type that supports\nattribute references, e.g., a module, list, or an instance. This\nobject is then asked to produce the attribute whose name is the\nidentifier. If this attribute is not available, the exception\n"AttributeError" is raised. Otherwise, the type and value of the\nobject produced is determined by the object. Multiple evaluations of\nthe same attribute reference may yield different objects.\n', ++ 'augassign': u'\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 the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis 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', ++ 'binary': u'\nBinary arithmetic operations\n****************************\n\nThe binary arithmetic operations have the conventional priority\nlevels. Note that some of these operations also apply to certain non-\nnumeric types. Apart from the power operator, there are only two\nlevels, one for multiplicative operators and one for additive\noperators:\n\n m_expr ::= u_expr | m_expr "*" u_expr | m_expr "//" u_expr | m_expr "/" u_expr\n | m_expr "%" u_expr\n a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n\nThe "*" (multiplication) operator yields the product of its arguments.\nThe arguments must either both be numbers, or one argument must be an\ninteger (plain or long) and the other must be a sequence. In the\nformer case, the numbers are converted to a common type and then\nmultiplied together. In the latter case, sequence repetition is\nperformed; a negative repetition factor yields an empty sequence.\n\nThe "/" (division) and "//" (floor division) operators yield the\nquotient of their arguments. The numeric arguments are first\nconverted to a common type. Plain or long integer division yields an\ninteger of the same type; the result is that of mathematical division\nwith the \'floor\' function applied to the result. Division by zero\nraises the "ZeroDivisionError" exception.\n\nThe "%" (modulo) operator yields the remainder from the division of\nthe first argument by the second. The numeric arguments are first\nconverted to a common type. A zero right argument raises the\n"ZeroDivisionError" exception. The arguments may be floating point\nnumbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals "4*0.7 +\n0.34".) The modulo operator always yields a result with the same sign\nas its second operand (or zero); the absolute value of the result is\nstrictly smaller than the absolute value of the second operand [2].\n\nThe integer division and modulo operators are connected by the\nfollowing identity: "x == (x/y)*y + (x%y)". Integer division and\nmodulo are also connected with the built-in function "divmod()":\n"divmod(x, y) == (x/y, x%y)". These identities don\'t hold for\nfloating point numbers; there similar identities hold approximately\nwhere "x/y" is replaced by "floor(x/y)" or "floor(x/y) - 1" [3].\n\nIn addition to performing the modulo operation on numbers, the "%"\noperator is also overloaded by string and unicode objects to perform\nstring formatting (also known as interpolation). The syntax for string\nformatting is described in the Python Library Reference, section\nString Formatting Operations.\n\nDeprecated since version 2.3: The floor division operator, the modulo\noperator, and the "divmod()" function are no longer defined for\ncomplex numbers. Instead, convert to a floating point number using\nthe "abs()" function if appropriate.\n\nThe "+" (addition) operator yields the sum of its arguments. The\narguments must either both be numbers or both sequences of the same\ntype. In the former case, the numbers are converted to a common type\nand then added together. In the latter case, the sequences are\nconcatenated.\n\nThe "-" (subtraction) operator yields the difference of its arguments.\nThe numeric arguments are first converted to a common type.\n', ++ 'bitwise': u'\nBinary bitwise operations\n*************************\n\nEach of the three bitwise operations has a different priority level:\n\n and_expr ::= shift_expr | and_expr "&" shift_expr\n xor_expr ::= and_expr | xor_expr "^" and_expr\n or_expr ::= xor_expr | or_expr "|" xor_expr\n\nThe "&" operator yields the bitwise AND of its arguments, which must\nbe plain or long integers. The arguments are converted to a common\ntype.\n\nThe "^" operator yields the bitwise XOR (exclusive OR) of its\narguments, which must be plain or long integers. The arguments are\nconverted to a common type.\n\nThe "|" operator yields the bitwise (inclusive) OR of its arguments,\nwhich must be plain or long integers. The arguments are converted to\na common type.\n', ++ 'bltin-code-objects': u'\nCode Objects\n************\n\nCode objects are used by the implementation to represent "pseudo-\ncompiled" executable Python code such as a function body. They differ\nfrom function objects because they don\'t contain a reference to their\nglobal execution environment. Code objects are returned by the built-\nin "compile()" function and can be extracted from function objects\nthrough their "func_code" attribute. See also the "code" module.\n\nA code object can be executed or evaluated by passing it (instead of a\nsource string) to the "exec" statement or the built-in "eval()"\nfunction.\n\nSee The standard type hierarchy for more information.\n', ++ 'bltin-ellipsis-object': u'\nThe Ellipsis Object\n*******************\n\nThis object is used by extended slice notation (see Slicings). It\nsupports no special operations. There is exactly one ellipsis object,\nnamed "Ellipsis" (a built-in name).\n\nIt is written as "Ellipsis". When in a subscript, it can also be\nwritten as "...", for example "seq[...]".\n', ++ 'bltin-file-objects': u'\nFile Objects\n************\n\nFile objects are implemented using C\'s "stdio" package and can be\ncreated with the built-in "open()" function. File objects are also\nreturned by some other built-in functions and methods, such as\n"os.popen()" and "os.fdopen()" and the "makefile()" method of socket\nobjects. Temporary files can be created using the "tempfile" module,\nand high-level file operations such as copying, moving, and deleting\nfiles and directories can be achieved with the "shutil" module.\n\nWhen a file operation fails for an I/O-related reason, the exception\n"IOError" is raised. This includes situations where the operation is\nnot defined for some reason, like "seek()" on a tty device or writing\na file opened for reading.\n\nFiles have the following methods:\n\nfile.close()\n\n Close the file. A closed file cannot be read or written any more.\n Any operation which requires that the file be open will raise a\n "ValueError" after the file has been closed. Calling "close()"\n more than once is allowed.\n\n As of Python 2.5, you can avoid having to call this method\n explicitly if you use the "with" statement. For example, the\n following code will automatically close *f* when the "with" block\n is exited:\n\n from __future__ import with_statement # This isn\'t required in Python 2.6\n\n with open("hello.txt") as f:\n for line in f:\n print line,\n\n In older versions of Python, you would have needed to do this to\n get the same effect:\n\n f = open("hello.txt")\n try:\n for line in f:\n print line,\n finally:\n f.close()\n\n Note: Not all "file-like" types in Python support use as a\n context manager for the "with" statement. If your code is\n intended to work with any file-like object, you can use the\n function "contextlib.closing()" instead of using the object\n directly.\n\nfile.flush()\n\n Flush the internal buffer, like "stdio"\'s "fflush()". This may be\n a no-op on some file-like objects.\n\n Note: "flush()" does not necessarily write the file\'s data to\n disk. Use "flush()" followed by "os.fsync()" to ensure this\n behavior.\n\nfile.fileno()\n\n Return the integer "file descriptor" that is used by the underlying\n implementation to request I/O operations from the operating system.\n This can be useful for other, lower level interfaces that use file\n descriptors, such as the "fcntl" module or "os.read()" and friends.\n\n Note: File-like objects which do not have a real file descriptor\n should *not* provide this method!\n\nfile.isatty()\n\n Return "True" if the file is connected to a tty(-like) device, else\n "False".\n\n Note: If a file-like object is not associated with a real file,\n this method should *not* be implemented.\n\nfile.next()\n\n A file object is its own iterator, for example "iter(f)" returns\n *f* (unless *f* is closed). When a file is used as an iterator,\n typically in a "for" loop (for example, "for line in f: print\n line.strip()"), the "next()" method is called repeatedly. This\n method returns the next input line, or raises "StopIteration" when\n EOF is hit when the file is open for reading (behavior is undefined\n when the file is open for writing). In order to make a "for" loop\n the most efficient way of looping over the lines of a file (a very\n common operation), the "next()" method uses a hidden read-ahead\n buffer. As a consequence of using a read-ahead buffer, combining\n "next()" with other file methods (like "readline()") does not work\n right. However, using "seek()" to reposition the file to an\n absolute position will flush the read-ahead buffer.\n\n New in version 2.3.\n\nfile.read([size])\n\n Read at most *size* bytes from the file (less if the read hits EOF\n before obtaining *size* bytes). If the *size* argument is negative\n or omitted, read all data until EOF is reached. The bytes are\n returned as a string object. An empty string is returned when EOF\n is encountered immediately. (For certain files, like ttys, it\n makes sense to continue reading after an EOF is hit.) Note that\n this method may call the underlying C function "fread()" more than\n once in an effort to acquire as close to *size* bytes as possible.\n Also note that when in non-blocking mode, less data than was\n requested may be returned, even if no *size* parameter was given.\n\n Note: This function is simply a wrapper for the underlying\n "fread()" C function, and will behave the same in corner cases,\n such as whether the EOF value is cached.\n\nfile.readline([size])\n\n Read one entire line from the file. A trailing newline character\n is kept in the string (but may be absent when a file ends with an\n incomplete line). [6] If the *size* argument is present and non-\n negative, it is a maximum byte count (including the trailing\n newline) and an incomplete line may be returned. When *size* is not\n 0, an empty string is returned *only* when EOF is encountered\n immediately.\n\n Note: Unlike "stdio"\'s "fgets()", the returned string contains\n null characters ("\'\\0\'") if they occurred in the input.\n\nfile.readlines([sizehint])\n\n Read until EOF using "readline()" and return a list containing the\n lines thus read. If the optional *sizehint* argument is present,\n instead of reading up to EOF, whole lines totalling approximately\n *sizehint* bytes (possibly after rounding up to an internal buffer\n size) are read. Objects implementing a file-like interface may\n choose to ignore *sizehint* if it cannot be implemented, or cannot\n be implemented efficiently.\n\nfile.xreadlines()\n\n This method returns the same thing as "iter(f)".\n\n New in version 2.1.\n\n Deprecated since version 2.3: Use "for line in file" instead.\n\nfile.seek(offset[, whence])\n\n Set the file\'s current position, like "stdio"\'s "fseek()". The\n *whence* argument is optional and defaults to "os.SEEK_SET" or "0"\n (absolute file positioning); other values are "os.SEEK_CUR" or "1"\n (seek relative to the current position) and "os.SEEK_END" or "2"\n (seek relative to the file\'s end). There is no return value.\n\n For example, "f.seek(2, os.SEEK_CUR)" advances the position by two\n and "f.seek(-3, os.SEEK_END)" sets the position to the third to\n last.\n\n Note that if the file is opened for appending (mode "\'a\'" or\n "\'a+\'"), any "seek()" operations will be undone at the next write.\n If the file is only opened for writing in append mode (mode "\'a\'"),\n this method is essentially a no-op, but it remains useful for files\n opened in append mode with reading enabled (mode "\'a+\'"). If the\n file is opened in text mode (without "\'b\'"), only offsets returned\n by "tell()" are legal. Use of other offsets causes undefined\n behavior.\n\n Note that not all file objects are seekable.\n\n Changed in version 2.6: Passing float values as offset has been\n deprecated.\n\nfile.tell()\n\n Return the file\'s current position, like "stdio"\'s "ftell()".\n\n Note: On Windows, "tell()" can return illegal values (after an\n "fgets()") when reading files with Unix-style line-endings. Use\n binary mode ("\'rb\'") to circumvent this problem.\n\nfile.truncate([size])\n\n Truncate the file\'s size. If the optional *size* argument is\n present, the file is truncated to (at most) that size. The size\n defaults to the current position. The current file position is not\n changed. Note that if a specified size exceeds the file\'s current\n size, the result is platform-dependent: possibilities include that\n the file may remain unchanged, increase to the specified size as if\n zero-filled, or increase to the specified size with undefined new\n content. Availability: Windows, many Unix variants.\n\nfile.write(str)\n\n Write a string to the file. There is no return value. Due to\n buffering, the string may not actually show up in the file until\n the "flush()" or "close()" method is called.\n\nfile.writelines(sequence)\n\n Write a sequence of strings to the file. The sequence can be any\n iterable object producing strings, typically a list of strings.\n There is no return value. (The name is intended to match\n "readlines()"; "writelines()" does not add line separators.)\n\nFiles support the iterator protocol. Each iteration returns the same\nresult as "readline()", and iteration ends when the "readline()"\nmethod returns an empty string.\n\nFile objects also offer a number of other interesting attributes.\nThese are not required for file-like objects, but should be\nimplemented if they make sense for the particular object.\n\nfile.closed\n\n bool indicating the current state of the file object. This is a\n read-only attribute; the "close()" method changes the value. It may\n not be available on all file-like objects.\n\nfile.encoding\n\n The encoding that this file uses. When Unicode strings are written\n to a file, they will be converted to byte strings using this\n encoding. In addition, when the file is connected to a terminal,\n the attribute gives the encoding that the terminal is likely to use\n (that information might be incorrect if the user has misconfigured\n the terminal). The attribute is read-only and may not be present\n on all file-like objects. It may also be "None", in which case the\n file uses the system default encoding for converting Unicode\n strings.\n\n New in version 2.3.\n\nfile.errors\n\n The Unicode error handler used along with the encoding.\n\n New in version 2.6.\n\nfile.mode\n\n The I/O mode for the file. If the file was created using the\n "open()" built-in function, this will be the value of the *mode*\n parameter. This is a read-only attribute and may not be present on\n all file-like objects.\n\nfile.name\n\n If the file object was created using "open()", the name of the\n file. Otherwise, some string that indicates the source of the file\n object, of the form "<...>". This is a read-only attribute and may\n not be present on all file-like objects.\n\nfile.newlines\n\n If Python was built with *universal newlines* enabled (the default)\n this read-only attribute exists, and for files opened in universal\n newline read mode it keeps track of the types of newlines\n encountered while reading the file. The values it can take are\n "\'\\r\'", "\'\\n\'", "\'\\r\\n\'", "None" (unknown, no newlines read yet) or\n a tuple containing all the newline types seen, to indicate that\n multiple newline conventions were encountered. For files not opened\n in universal newlines read mode the value of this attribute will be\n "None".\n\nfile.softspace\n\n Boolean that indicates whether a space character needs to be\n printed before another value when using the "print" statement.\n Classes that are trying to simulate a file object should also have\n a writable "softspace" attribute, which should be initialized to\n zero. This will be automatic for most classes implemented in\n Python (care may be needed for objects that override attribute\n access); types implemented in C will have to provide a writable\n "softspace" attribute.\n\n Note: This attribute is not used to control the "print"\n statement, but to allow the implementation of "print" to keep\n track of its internal state.\n', ++ 'bltin-null-object': u'\nThe Null Object\n***************\n\nThis object is returned by functions that don\'t explicitly return a\nvalue. It supports no special operations. There is exactly one null\nobject, named "None" (a built-in name).\n\nIt is written as "None".\n', ++ 'bltin-type-objects': u'\nType Objects\n************\n\nType objects represent the various object types. An object\'s type is\naccessed by the built-in function "type()". There are no special\noperations on types. The standard module "types" defines names for\nall standard built-in types.\n\nTypes are written like this: "".\n', ++ 'booleans': u'\nBoolean operations\n******************\n\n or_test ::= and_test | or_test "or" and_test\n and_test ::= not_test | and_test "and" not_test\n not_test ::= comparison | "not" not_test\n\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: "False", "None", numeric zero of all types, and empty\nstrings and containers (including strings, tuples, lists,\ndictionaries, sets and frozensets). All other values are interpreted\nas true. (See the "__nonzero__()" special method for a way to change\nthis.)\n\nThe operator "not" yields "True" if its argument is false, "False"\notherwise.\n\nThe expression "x and y" first evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\nThe expression "x or y" first evaluates *x*; if *x* is true, its value\nis returned; otherwise, *y* is evaluated and the resulting value is\nreturned.\n\n(Note that neither "and" nor "or" restrict the value and type they\nreturn to "False" and "True", but rather return the last evaluated\nargument. This is sometimes useful, e.g., if "s" is a string that\nshould be replaced by a default value if it is empty, the expression\n"s or \'foo\'" yields the desired value. Because "not" has to invent a\nvalue anyway, it does not bother to return a value of the same type as\nits argument, so e.g., "not \'foo\'" yields "False", not "\'\'".)\n', ++ 'break': u'\nThe "break" statement\n*********************\n\n break_stmt ::= "break"\n\n"break" may only occur syntactically nested in a "for" or "while"\nloop, but not nested in a function or class definition within that\nloop.\n\nIt terminates the nearest enclosing loop, skipping the optional "else"\nclause if the loop has one.\n\nIf a "for" loop is terminated by "break", the loop control target\nkeeps its current value.\n\nWhen "break" passes control out of a "try" statement with a "finally"\nclause, that "finally" clause is executed before really leaving the\nloop.\n', ++ 'callable-types': u'\nEmulating callable objects\n**************************\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, "x(arg1, arg2, ...)" is a shorthand for\n "x.__call__(arg1, arg2, ...)".\n', ++ 'calls': u'\nCalls\n*****\n\nA call calls a callable object (e.g., a *function*) with a possibly\nempty series of *arguments*:\n\n call ::= primary "(" [argument_list [","]\n | expression genexpr_for] ")"\n argument_list ::= positional_arguments ["," keyword_arguments]\n ["," "*" expression] ["," keyword_arguments]\n ["," "**" expression]\n | keyword_arguments ["," "*" expression]\n ["," "**" expression]\n | "*" expression ["," keyword_arguments] ["," "**" expression]\n | "**" expression\n positional_arguments ::= expression ("," expression)*\n keyword_arguments ::= keyword_item ("," keyword_item)*\n keyword_item ::= identifier "=" expression\n\nA trailing comma may be present after the positional and keyword\narguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and certain class instances\nthemselves are callable; extensions may define additional callable\nobject types). All argument expressions are evaluated before the call\nis attempted. Please refer to section Function definitions for the\nsyntax of formal *parameter* lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows. First, a list of unfilled slots is\ncreated for the formal parameters. If there are N positional\narguments, they are placed in the first N slots. Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on). If the slot is\nalready filled, a "TypeError" exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is "None", it fills the slot). When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition. (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.) If there are any\nunfilled slots for which no default value is specified, a "TypeError"\nexception is raised. Otherwise, the list of filled slots is used as\nthe argument list for the call.\n\n**CPython implementation detail:** An implementation may provide\nbuilt-in functions whose positional parameters do not have names, even\nif they are \'named\' for the purpose of documentation, and which\ntherefore cannot be supplied by keyword. In CPython, this is the case\nfor functions implemented in C that use "PyArg_ParseTuple()" to parse\ntheir arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a "TypeError" exception is raised, unless a formal parameter\nusing the syntax "*identifier" is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a "TypeError" exception is raised, unless a formal parameter\nusing the syntax "**identifier" is present; in this case, that formal\nparameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax "*expression" appears in the function call, "expression"\nmust evaluate to an iterable. Elements from this iterable are treated\nas if they were additional positional arguments; if there are\npositional arguments *x1*, ..., *xN*, and "expression" evaluates to a\nsequence *y1*, ..., *yM*, this is equivalent to a call with M+N\npositional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n\nA consequence of this is that although the "*expression" syntax may\nappear *after* some keyword arguments, it is processed *before* the\nkeyword arguments (and the "**expression" argument, if any -- see\nbelow). So:\n\n >>> def f(a, b):\n ... print a, b\n ...\n >>> f(b=1, *(2,))\n 2 1\n >>> f(a=1, *(2,))\n Traceback (most recent call last):\n File "", line 1, in ?\n TypeError: f() got multiple values for keyword argument \'a\'\n >>> f(1, *(2,))\n 1 2\n\nIt is unusual for both keyword arguments and the "*expression" syntax\nto be used in the same call, so in practice this confusion does not\narise.\n\nIf the syntax "**expression" appears in the function call,\n"expression" must evaluate to a mapping, the contents of which are\ntreated as additional keyword arguments. In the case of a keyword\nappearing in both "expression" and as an explicit keyword argument, a\n"TypeError" exception is raised.\n\nFormal parameters using the syntax "*identifier" or "**identifier"\ncannot be used as positional argument slots or as keyword argument\nnames. Formal parameters using the syntax "(sublist)" cannot be used\nas keyword argument names; the outermost sublist corresponds to a\nsingle unnamed argument slot, and the argument value is assigned to\nthe sublist using the usual tuple assignment rules after all other\nparameter processing is done.\n\nA call always returns some value, possibly "None", unless it raises an\nexception. How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n The code block for the function is executed, passing it the\n argument list. The first thing the code block will do is bind the\n formal parameters to the arguments; this is described in section\n Function definitions. When the code block executes a "return"\n statement, this specifies the return value of the function call.\n\na built-in function or method:\n The result is up to the interpreter; see Built-in Functions for the\n descriptions of built-in functions and methods.\n\na class object:\n A new instance of that class is returned.\n\na class instance method:\n The corresponding user-defined function is called, with an argument\n list that is one longer than the argument list of the call: the\n instance becomes the first argument.\n\na class instance:\n The class must define a "__call__()" method; the effect is then the\n same as if that method was called.\n', ++ 'class': u'\nClass definitions\n*****************\n\nA class definition defines a class object (see section The standard\ntype hierarchy):\n\n classdef ::= "class" classname [inheritance] ":" suite\n inheritance ::= "(" [expression_list] ")"\n classname ::= identifier\n\nA class definition is an executable statement. It first evaluates the\ninheritance list, if present. Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing. The class\'s suite is then executed in a new execution\nframe (see section Naming and binding), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.) When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary. The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances. To create instance\nvariables, they can be set in a method with "self.name = value". Both\nclass and instance variables are accessible through the notation\n""self.name"", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results. For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions. The evaluation rules for the decorator\nexpressions are the same as for functions. The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n there is a "finally" clause which happens to raise another\n exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n an exception or the execution of a "return", "continue", or\n "break" statement.\n\n[3] A string literal appearing as the first statement in the\n function body is transformed into the function\'s "__doc__"\n attribute and therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s "__doc__" item and\n therefore the class\'s *docstring*.\n', ++ 'comparisons': u'\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation. Also unlike C, expressions like "a < b < c" have the\ninterpretation that is conventional in mathematics:\n\n comparison ::= or_expr ( comp_operator or_expr )*\n comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="\n | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: "True" or "False".\n\nComparisons can be chained arbitrarily, e.g., "x < y <= z" is\nequivalent to "x < y and y <= z", except that "y" is evaluated only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... y\nopN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\nThe forms "<>" and "!=" are equivalent; for consistency with C, "!="\nis preferred; where "!=" is mentioned below "<>" is also accepted.\nThe "<>" spelling is considered obsolescent.\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects. The objects need not have the same type. If both are\nnumbers, they are converted to a common type. Otherwise, objects of\ndifferent types *always* compare unequal, and are ordered consistently\nbut arbitrarily. You can control comparison behavior of objects of\nnon-built-in types by defining a "__cmp__" method or rich comparison\nmethods like "__gt__", described in section Special method names.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the "in" and "not in"\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric\n equivalents (the result of the built-in function "ord()") of their\n characters. Unicode and 8-bit strings are fully interoperable in\n this behavior. [4]\n\n* Tuples and lists are compared lexicographically using comparison\n of corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, "cmp([1,2,x], [1,2,y])" returns\n the same as "cmp(x,y)". If the corresponding element does not\n exist, the shorter sequence is ordered first (for example, "[1,2] <\n [1,2,3]").\n\n* Mappings (dictionaries) compare equal if and only if their sorted\n (key, value) lists compare equal. [5] Outcomes other than equality\n are resolved consistently, but are not otherwise defined. [6]\n\n* Most other objects of built-in types compare unequal unless they\n are the same object; the choice whether one object is considered\n smaller or larger than another one is made arbitrarily but\n consistently within one execution of a program.\n\nThe operators "in" and "not in" test for collection membership. "x in\ns" evaluates to true if *x* is a member of the collection *s*, and\nfalse otherwise. "x not in s" returns the negation of "x in s". The\ncollection membership test has traditionally been bound to sequences;\nan object is a member of a collection if the collection is a sequence\nand contains an element equal to that object. However, it make sense\nfor many other object types to support membership tests without being\na sequence. In particular, dictionaries (for keys) and sets support\nmembership testing.\n\nFor the list and tuple types, "x in y" is true if and only if there\nexists an index *i* such that "x == y[i]" is true.\n\nFor the Unicode and string types, "x in y" is true if and only if *x*\nis a substring of *y*. An equivalent test is "y.find(x) != -1".\nNote, *x* and *y* need not be the same type; consequently, "u\'ab\' in\n\'abc\'" will return "True". Empty strings are always considered to be a\nsubstring of any other string, so """ in "abc"" will return "True".\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength "1".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin y" is true if and only if "y.__contains__(x)" is true.\n\nFor user-defined classes which do not define "__contains__()" but do\ndefine "__iter__()", "x in y" is true if some value "z" with "x == z"\nis produced while iterating over "y". If an exception is raised\nduring the iteration, it is as if "in" raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n"__getitem__()", "x in y" is true if and only if there is a non-\nnegative integer index *i* such that "x == y[i]", and all lower\ninteger indices do not raise "IndexError" exception. (If any other\nexception is raised, it is as if "in" raised that exception).\n\nThe operator "not in" is defined to have the inverse true value of\n"in".\n\nThe operators "is" and "is not" test for object identity: "x is y" is\ntrue if and only if *x* and *y* are the same object. "x is not y"\nyields the inverse truth value. [7]\n', ++ 'compound': u'\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way. In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe "if", "while" and "for" statements implement traditional control\nflow constructs. "try" specifies exception handlers and/or cleanup\ncode for a group of statements. Function and class definitions are\nalso syntactically compound statements.\n\nCompound statements consist of one or more \'clauses.\' A clause\nconsists of a header and a \'suite.\' The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon. A suite is a group of statements controlled by a\nclause. A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines. Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which "if" clause a following "else" clause would belong:\n\n if test1: if test2: print x\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n"print" statements are executed:\n\n if x < y < z: print x; print y; print z\n\nSummarizing:\n\n compound_stmt ::= if_stmt\n | while_stmt\n | for_stmt\n | try_stmt\n | with_stmt\n | funcdef\n | classdef\n | decorated\n suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n statement ::= stmt_list NEWLINE | compound_stmt\n stmt_list ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a "NEWLINE" possibly followed by a\n"DEDENT". Also note that optional continuation clauses always begin\nwith a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling "else"\' problem is solved in Python by\nrequiring nested "if" statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\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\n\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 executed\nand the loop terminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite. A "continue" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n\n\nThe "for" statement\n===================\n\nThe "for" statement is used to iterate over the elements of a sequence\n(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" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there was no next\nitem.\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\n loop (this can only occur for mutable sequences, i.e. lists). An\n internal counter is used to keep track of which item is used next,\n and this is incremented on each iteration. When this counter has\n reached the length of the sequence the loop terminates. This means\n that if the suite deletes the current (or a previous) item from the\n sequence, the next item will be skipped (since it gets the index of\n the 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\n\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" | ",") identifier]] ":" 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" had to be\nnested in "try"..."finally".\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started. This search inspects the except clauses\nin turn until one is found that matches the exception. An expression-\nless except clause, if present, must be last; it matches any\nexception. For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception. An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject, or a tuple containing an item compatible with the exception.\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 raised\nthe 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 are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler. The "try"\nclause is executed, including any "except" and "else" clauses. If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed. If\nthere is a saved exception, it is re-raised at the end of the\n"finally" clause. If the "finally" clause raises another exception or\nexecutes a "return" or "break" statement, the saved exception is\ndiscarded:\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 the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed. Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n >>> def foo():\n ... try:\n ... return \'try\'\n ... finally:\n ... return \'finally\'\n ...\n >>> foo()\n \'finally\'\n\nAdditional information on exceptions can be found in section\nExceptions, and information on using the "raise" statement to generate\nexceptions may be found in section The raise statement.\n\n\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 "try"..."except"..."finally"\nusage patterns to be encapsulated for 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 be\n 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, three\n "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 reraised.\n If the return value was true, the exception is suppressed, and\n execution continues with the statement following the "with"\n 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 in\n 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 "with"\n statement.\n\n\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 values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted. If a parameter has a default value, all following\nparameters must also have a default value --- this is a syntactic\nrestriction 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 Calls.\nA function call always assigns values to all parameters mentioned in\nthe parameter list, either from position arguments, from keyword\narguments, or from default values. If the form ""*identifier"" is\npresent, it is initialized to a tuple receiving any excess positional\nparameters, defaulting to the empty tuple. If the form\n""**identifier"" is present, it is initialized to a new dictionary\nreceiving any excess keyword arguments, defaulting to a new empty\ndictionary.\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\n\nClass definitions\n=================\n\nA class definition defines a class object (see section The standard\ntype hierarchy):\n\n classdef ::= "class" classname [inheritance] ":" suite\n inheritance ::= "(" [expression_list] ")"\n classname ::= identifier\n\nA class definition is an executable statement. It first evaluates the\ninheritance list, if present. Each item in the inheritance list\nshould evaluate to a class object or class type which allows\nsubclassing. The class\'s suite is then executed in a new execution\nframe (see section Naming and binding), using a newly created local\nnamespace and the original global namespace. (Usually, the suite\ncontains only function definitions.) When the class\'s suite finishes\nexecution, its execution frame is discarded but its local namespace is\nsaved. [4] A class object is then created using the inheritance list\nfor the base classes and the saved local namespace for the attribute\ndictionary. The class name is bound to this class object in the\noriginal local namespace.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass variables; they are shared by all instances. To create instance\nvariables, they can be set in a method with "self.name = value". Both\nclass and instance variables are accessible through the notation\n""self.name"", and an instance variable hides a class variable with\nthe same name when accessed in this way. Class variables can be used\nas defaults for instance variables, but using mutable values there can\nlead to unexpected results. For *new-style class*es, descriptors can\nbe used to create instance variables with different implementation\ndetails.\n\nClass definitions, like function definitions, may be wrapped by one or\nmore *decorator* expressions. The evaluation rules for the decorator\nexpressions are the same as for functions. The result must be a class\nobject, which is then bound to the class name.\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n there is a "finally" clause which happens to raise another\n exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n an exception or the execution of a "return", "continue", or\n "break" statement.\n\n[3] A string literal appearing as the first statement in the\n function body is transformed into the function\'s "__doc__"\n attribute and therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n body is transformed into the namespace\'s "__doc__" item and\n therefore the class\'s *docstring*.\n', ++ 'context-managers': u'\nWith Statement Context Managers\n*******************************\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code. Context managers are normally\ninvoked using the "with" statement (described in section The with\nstatement), but can also be used by directly invoking their methods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see Context Manager Types.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The "with"\n statement will bind this method\'s return value to the target(s)\n specified in the "as" clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be "None".\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that "__exit__()" methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python "with"\n statement.\n', ++ 'continue': u'\nThe "continue" statement\n************************\n\n continue_stmt ::= "continue"\n\n"continue" may only occur syntactically nested in a "for" or "while"\nloop, but not nested in a function or class definition or "finally"\nclause within that loop. It continues with the next cycle of the\nnearest enclosing loop.\n\nWhen "continue" passes control out of a "try" statement with a\n"finally" clause, that "finally" clause is executed before really\nstarting the next loop cycle.\n', ++ 'conversions': u'\nArithmetic conversions\n**********************\n\nWhen a description of an arithmetic operator below uses the phrase\n"the numeric arguments are converted to a common type," the arguments\nare coerced using the coercion rules listed at Coercion rules. If\nboth arguments are standard numeric types, the following coercions are\napplied:\n\n* If either argument is a complex number, the other is converted to\n complex;\n\n* otherwise, if either argument is a floating point number, the\n other is converted to floating point;\n\n* otherwise, if either argument is a long integer, the other is\n converted to long integer;\n\n* otherwise, both must be plain integers and no conversion is\n necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator). Extensions can define their own\ncoercions.\n', ++ 'customization': u'\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. "__new__()" is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of "__new__()" should be the new object instance (usually an\n instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s "__new__()" method using\n "super(currentclass, cls).__new__(cls[, ...])" with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If "__new__()" returns an instance of *cls*, then the new\n instance\'s "__init__()" method will be invoked like\n "__init__(self[, ...])", where *self* is the new instance and the\n remaining arguments are the same as were passed to "__new__()".\n\n If "__new__()" does not return an instance of *cls*, then the new\n instance\'s "__init__()" method will not be invoked.\n\n "__new__()" is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called after the instance has been created (by "__new__()"), but\n before it is returned to the caller. The arguments are those\n passed to the class constructor expression. If a base class has an\n "__init__()" method, the derived class\'s "__init__()" method, if\n any, must explicitly call it to ensure proper initialization of the\n base class part of the instance; for example:\n "BaseClass.__init__(self, [args...])".\n\n Because "__new__()" and "__init__()" work together in constructing\n objects ("__new__()" to create it, and "__init__()" to customise\n it), no non-"None" value may be returned by "__init__()"; doing so\n will cause a "TypeError" to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a "__del__()" method, the\n derived class\'s "__del__()" method, if any, must explicitly call it\n to ensure proper deletion of the base class part of the instance.\n Note that it is possible (though not recommended!) for the\n "__del__()" method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n "__del__()" methods are called for objects that still exist when\n the interpreter exits.\n\n Note: "del x" doesn\'t directly call "x.__del__()" --- the former\n decrements the reference count for "x" by one, and the latter is\n only called when "x"\'s reference count reaches zero. Some common\n situations that may prevent the reference count of an object from\n going to zero include: circular references between objects (e.g.,\n a doubly-linked list or a tree data structure with parent and\n child pointers); a reference to the object on the stack frame of\n a function that caught an exception (the traceback stored in\n "sys.exc_traceback" keeps the stack frame alive); or a reference\n to the object on the stack frame that raised an unhandled\n exception in interactive mode (the traceback stored in\n "sys.last_traceback" keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing "None" in\n "sys.exc_traceback" or "sys.last_traceback". Circular references\n which are garbage are detected when the option cycle detector is\n enabled (it\'s on by default), but can only be cleaned up if there\n are no Python-level "__del__()" methods involved. Refer to the\n documentation for the "gc" module for more information about how\n "__del__()" methods are handled by the cycle detector,\n particularly the description of the "garbage" value.\n\n Warning: Due to the precarious circumstances under which\n "__del__()" methods are invoked, exceptions that occur during\n their execution are ignored, and a warning is printed to\n "sys.stderr" instead. Also, when "__del__()" is invoked in\n response to a module being deleted (e.g., when execution of the\n program is done), other globals referenced by the "__del__()"\n method may already have been deleted or in the process of being\n torn down (e.g. the import machinery shutting down). For this\n reason, "__del__()" methods should do the absolute minimum needed\n to maintain external invariants. Starting with version 1.5,\n Python guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the "__del__()" method is called.\n\n See also the "-R" command-line option.\n\nobject.__repr__(self)\n\n Called by the "repr()" built-in function and by string conversions\n (reverse quotes) to compute the "official" string representation of\n an object. If at all possible, this should look like a valid\n Python expression that could be used to recreate an object with the\n same value (given an appropriate environment). If this is not\n possible, a string of the form "<...some useful description...>"\n should be returned. The return value must be a string object. If a\n class defines "__repr__()" but not "__str__()", then "__repr__()"\n is also used when an "informal" string representation of instances\n of that class is required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the "str()" built-in function and by the "print"\n statement to compute the "informal" string representation of an\n object. This differs from "__repr__()" in that it does not have to\n be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n New in version 2.1.\n\n These are the so-called "rich comparison" methods, and are called\n for comparison operators in preference to "__cmp__()" below. The\n correspondence between operator symbols and method names is as\n follows: "xy" call "x.__ne__(y)",\n "x>y" calls "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n A rich comparison method may return the singleton "NotImplemented"\n if it does not implement the operation for a given pair of\n arguments. By convention, "False" and "True" are returned for a\n successful comparison. However, these methods can return any value,\n so if the comparison operator is used in a Boolean context (e.g.,\n in the condition of an "if" statement), Python will call "bool()"\n on the value to determine if the result is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of "x==y" does not imply that "x!=y" is false.\n Accordingly, when defining "__eq__()", one should also define\n "__ne__()" so that the operators will behave as expected. See the\n paragraph on "__hash__()" for some important notes on creating\n *hashable* objects which support custom comparison operations and\n are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, "__lt__()" and "__gt__()" are each other\'s\n reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n and "__eq__()" and "__ne__()" are their own reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see "functools.total_ordering()".\n\nobject.__cmp__(self, other)\n\n Called by comparison operations if rich comparison (see above) is\n not defined. Should return a negative integer if "self < other",\n zero if "self == other", a positive integer if "self > other". If\n no "__cmp__()", "__eq__()" or "__ne__()" operation is defined,\n class instances are compared by object identity ("address"). See\n also the description of "__hash__()" for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys. (Note: the\n restriction that exceptions are not propagated by "__cmp__()" has\n been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n Called by built-in function "hash()" and for operations on members\n of hashed collections including "set", "frozenset", and "dict".\n "__hash__()" should return an integer. The only required property\n is that objects which compare equal have the same hash value; it is\n advised to somehow mix together (e.g. using exclusive or) the hash\n values for the components of the object that also play a part in\n comparison of objects.\n\n If a class does not define a "__cmp__()" or "__eq__()" method it\n should not define a "__hash__()" operation either; if it defines\n "__cmp__()" or "__eq__()" but not "__hash__()", its instances will\n not be usable in hashed collections. If a class defines mutable\n objects and implements a "__cmp__()" or "__eq__()" method, it\n should not implement "__hash__()", since hashable collection\n implementations require that a object\'s hash value is immutable (if\n the object\'s hash value changes, it will be in the wrong hash\n bucket).\n\n User-defined classes have "__cmp__()" and "__hash__()" methods by\n default; with them, all objects compare unequal (except with\n themselves) and "x.__hash__()" returns a result derived from\n "id(x)".\n\n Classes which inherit a "__hash__()" method from a parent class but\n change the meaning of "__cmp__()" or "__eq__()" such that the hash\n value returned is no longer appropriate (e.g. by switching to a\n value-based concept of equality instead of the default identity\n based equality) can explicitly flag themselves as being unhashable\n by setting "__hash__ = None" in the class definition. Doing so\n means that not only will instances of the class raise an\n appropriate "TypeError" when a program attempts to retrieve their\n hash value, but they will also be correctly identified as\n unhashable when checking "isinstance(obj, collections.Hashable)"\n (unlike classes which define their own "__hash__()" to explicitly\n raise "TypeError").\n\n Changed in version 2.5: "__hash__()" may now also return a long\n integer object; the 32-bit integer is then derived from the hash of\n that object.\n\n Changed in version 2.6: "__hash__" may now be set to "None" to\n explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth value testing and the built-in operation\n "bool()"; should return "False" or "True", or their integer\n equivalents "0" or "1". When this method is not defined,\n "__len__()" is called, if it is defined, and the object is\n considered true if its result is nonzero. If a class defines\n neither "__len__()" nor "__nonzero__()", all its instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called to implement "unicode()" built-in; should return a Unicode\n object. When this method is not defined, string conversion is\n attempted, and the result of string conversion is converted to\n Unicode using the system default encoding.\n', ++ 'debugger': u'\n"pdb" --- The Python Debugger\n*****************************\n\n**Source code:** Lib/pdb.py\n\n======================================================================\n\nThe module "pdb" defines an interactive source code debugger for\nPython programs. It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame. It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible --- it is actually defined as the class\n"Pdb". This is currently undocumented but easily understood by reading\nthe source. The extension interface uses the modules "bdb" and "cmd".\n\nThe debugger\'s prompt is "(Pdb)". Typical usage to run a program under\ncontrol of the debugger is:\n\n >>> import pdb\n >>> import mymodule\n >>> pdb.run(\'mymodule.test()\')\n > (0)?()\n (Pdb) continue\n > (1)?()\n (Pdb) continue\n NameError: \'spam\'\n > (1)?()\n (Pdb)\n\n"pdb.py" can also be invoked as a script to debug other scripts. For\nexample:\n\n python -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally. After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program. Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 2.4: Restarting post-mortem behavior added.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger. You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the "c" command.\n\nThe typical usage to inspect a crashed program is:\n\n >>> import pdb\n >>> import mymodule\n >>> mymodule.test()\n Traceback (most recent call last):\n File "", line 1, in ?\n File "./mymodule.py", line 4, in test\n test2()\n File "./mymodule.py", line 3, in test2\n print spam\n NameError: spam\n >>> pdb.pm()\n > ./mymodule.py(3)test2()\n -> print spam\n (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement[, globals[, locals]])\n\n Execute the *statement* (given as a string) under debugger control.\n The debugger prompt appears before any code is executed; you can\n set breakpoints and type "continue", or you can step through the\n statement using "step" or "next" (all these commands are explained\n below). The optional *globals* and *locals* arguments specify the\n environment in which the code is executed; by default the\n dictionary of the module "__main__" is used. (See the explanation\n of the "exec" statement or the "eval()" built-in function.)\n\npdb.runeval(expression[, globals[, locals]])\n\n Evaluate the *expression* (given as a string) under debugger\n control. When "runeval()" returns, it returns the value of the\n expression. Otherwise this function is similar to "run()".\n\npdb.runcall(function[, argument, ...])\n\n Call the *function* (a function or method object, not a string)\n with the given arguments. When "runcall()" returns, it returns\n whatever the function call returned. The debugger prompt appears\n as soon as the function is entered.\n\npdb.set_trace()\n\n Enter the debugger at the calling stack frame. This is useful to\n hard-code a breakpoint at a given point in a program, even if the\n code is not otherwise being debugged (e.g. when an assertion\n fails).\n\npdb.post_mortem([traceback])\n\n Enter post-mortem debugging of the given *traceback* object. If no\n *traceback* is given, it uses the one of the exception that is\n currently being handled (an exception must be being handled if the\n default is to be used).\n\npdb.pm()\n\n Enter post-mortem debugging of the traceback found in\n "sys.last_traceback".\n\nThe "run*" functions and "set_trace()" are aliases for instantiating\nthe "Pdb" class and calling the method of the same name. If you want\nto access further features, you have to do this yourself:\n\nclass pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None)\n\n "Pdb" is the debugger class.\n\n The *completekey*, *stdin* and *stdout* arguments are passed to the\n underlying "cmd.Cmd" class; see the description there.\n\n The *skip* argument, if given, must be an iterable of glob-style\n module name patterns. The debugger will not step into frames that\n originate in a module that matches one of these patterns. [1]\n\n Example call to enable tracing with *skip*:\n\n import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n New in version 2.7: The *skip* argument.\n\n run(statement[, globals[, locals]])\n runeval(expression[, globals[, locals]])\n runcall(function[, argument, ...])\n set_trace()\n\n See the documentation for the functions explained above.\n', ++ 'del': u'\nThe "del" statement\n*******************\n\n del_stmt ::= "del" target_list\n\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather than spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a "global"\nstatement in the same code block. If the name is unbound, a\n"NameError" exception will be raised.\n\nIt is illegal to delete a name from the local namespace if it occurs\nas a free variable in a nested block.\n\nDeletion of attribute references, subscriptions and slicings is passed\nto the primary object involved; deletion of a slicing is in general\nequivalent to assignment of an empty slice of the right type (but even\nthis is determined by the sliced object).\n', ++ 'dict': u'\nDictionary displays\n*******************\n\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n\n dict_display ::= "{" [key_datum_list | dict_comprehension] "}"\n key_datum_list ::= key_datum ("," key_datum)* [","]\n key_datum ::= expression ":" expression\n dict_comprehension ::= expression ":" expression comp_for\n\nA dictionary display yields a new dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is given, they are\nevaluated from left to right to define the entries of the dictionary:\neach key object is used as a key into the dictionary to store the\ncorresponding datum. This means that you can specify the same key\nmultiple times in the key/datum list, and the final dictionary\'s value\nfor that key will be the last one given.\n\nA dict comprehension, in contrast to list and set comprehensions,\nneeds two expressions separated with a colon followed by the usual\n"for" and "if" clauses. When the comprehension is run, the resulting\nkey and value elements are inserted in the new dictionary in the order\nthey are produced.\n\nRestrictions on the types of the key values are listed earlier in\nsection The standard type hierarchy. (To summarize, the key type\nshould be *hashable*, which excludes all mutable objects.) Clashes\nbetween duplicate keys are not detected; the last datum (textually\nrightmost in the display) stored for a given key value prevails.\n', ++ 'dynamic-features': u'\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 namespace\nfor the "exec". (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames. Names may be resolved in the local and global namespaces of\nthe caller. Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" functions have optional arguments to\noverride the global and local namespace. If only one namespace is\nspecified, it is used for both.\n', ++ 'else': u'\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': u'\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 is\nselected depending on the class of the instance: it must reference the\nclass of the instance or a base class thereof. The instance can be\nreceived by the handler and can carry additional information about the\nexceptional 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\n these operations is not available at the time the module is\n compiled.\n', ++ 'exec': u'\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 "return"\nand "yield" statements may not be used outside of function definitions\neven within the context of code passed to the "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 globals,\nlocals". The tuple form of "exec" provides compatibility with Python\n3, 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 "__builtin__"\nunder the key "__builtins__" (!).\n\n**Programmer\'s hints:** dynamic evaluation of expressions is supported\nby the built-in function "eval()". The built-in functions "globals()"\nand "locals()" return the current global and local dictionary,\nrespectively, which may be useful to pass around for use by "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': u'\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" statement\nis a code block. The expression read and evaluated by the built-in\nfunction "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 "with"\nstatement. The "import" statement of the form "from ... import *"\nbinds all names defined in the imported module, except those beginning\nwith an underscore. This form may only be used at the module 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 first.\nIf the name is not found there, the builtins namespace is searched.\nThe 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 global\nnamespace; this should be a dictionary or a module (in the latter case\nthe module\'s dictionary is used). By default, when in the "__main__"\nmodule, "__builtins__" is the built-in module "__builtin__" (note: no\n\'s\'); when in any other module, "__builtins__" is an alias for the\ndictionary of the "__builtin__" module itself. "__builtins__" can be\nset to a user-created dictionary to create a weak form of restricted\nexecution.\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 operation\nin the same block. If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated 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 namespace\nfor the "exec". (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames. Names may be resolved in the local and global namespaces of\nthe caller. Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" functions have optional arguments to\noverride the global and local namespace. If only one namespace is\nspecified, 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 is\nselected depending on the class of the instance: it must reference the\nclass of the instance or a base class thereof. The instance can be\nreceived by the handler and can carry additional information about the\nexceptional 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\n these operations is not available at the time the module is\n compiled.\n', ++ 'exprlists': u'\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': u'\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 "77e10".\nThe allowed range of floating point literals is implementation-\ndependent. 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': u'\nThe "for" statement\n*******************\n\nThe "for" statement is used to iterate over the elements of a sequence\n(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" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there was no next\nitem.\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\n loop (this can only occur for mutable sequences, i.e. lists). An\n internal counter is used to keep track of which item is used next,\n and this is incremented on each iteration. When this counter has\n reached the length of the sequence the loop terminates. This means\n that if the suite deletes the current (or a previous) item from the\n sequence, the next item will be skipped (since it gets the index of\n the 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': u'\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 is\npreceded by a colon "\':\'". These specify a non-default format for the\nreplacement 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 any\nnumber of index or attribute expressions. An expression of the form\n"\'.name\'" selects the named attribute using "getattr()", while an\nexpression of the form "\'[index]\'" does an index lookup using\n"__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 "__format__()"\nmethod of the value itself. However, in some cases it is desirable to\nforce a type to be formatted as a string, overriding its own\ndefinition of formatting. By converting the value to a string before\ncalling "__format__()", the normal formatting logic 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-empty\nformat 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\'", respectively.\n\nThe "\',\'" option signals the use of a comma for a thousands separator.\nFor a locale aware separator, use the "\'n\'" integer presentation type\ninstead.\n\nChanged in version 2.7: Added the "\',\'" option (see also **PEP 378**).\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 sign-\naware zero-padding for numeric types. This is equivalent to a *fill*\ncharacter 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 point\nfor a floating point value formatted with "\'g\'" or "\'G\'". For non-\nnumber types the field indicates the maximum field size - in other\nwords, how many characters will be used from the field content. The\n*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 the |\n | | current locale setting to insert the appropriate number |\n | | 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\'"\nand None). When doing so, "float()" is used to convert the integer to\na 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 "p-1" |\n | | would have exponent "exp". Then if "-4 <= exp < p", the |\n | | number is formatted with presentation type "\'f\'" and |\n | | precision "p-1-exp". Otherwise, the number is formatted |\n | | with presentation type "\'e\'" and precision "p-1". In both |\n | | cases insignificant trailing zeros are removed from the |\n | | significand, and the decimal point is also removed if |\n | | there are no remaining digits following it. Positive and |\n | | negative infinity, positive and negative zero, and nans, |\n | | are formatted as "inf", "-inf", "0", "-0" and "nan" |\n | | respectively, regardless of the precision. A precision of |\n | | "0" is treated as equivalent to a precision of "1". The |\n | | default precision is "6". |\n +-----------+------------------------------------------------------------+\n | "\'G\'" | General format. Same as "\'g\'" except switches to "\'E\'" if |\n | | the number gets too large. The representations of infinity |\n | | and NaN are uppercased, too. |\n +-----------+------------------------------------------------------------+\n | "\'n\'" | Number. This is the same as "\'g\'", except that it uses the |\n | | current locale setting to insert the appropriate number |\n | | 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 "%"-formatting,\nwith the addition of the "{}" and with ":" used instead of "%". For\nexample, "\'%03.2f\'" can be translated to "\'{: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 bases:\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': u'\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 values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted. If a parameter has a default value, all following\nparameters must also have a default value --- this is a syntactic\nrestriction 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 Calls.\nA function call always assigns values to all parameters mentioned in\nthe parameter list, either from position arguments, from keyword\narguments, or from default values. If the form ""*identifier"" is\npresent, it is initialized to a tuple receiving any excess positional\nparameters, defaulting to the empty tuple. If the form\n""**identifier"" is present, it is initialized to a new dictionary\nreceiving any excess keyword arguments, defaulting to a new empty\ndictionary.\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': u'\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 code\nblock 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. It\napplies only to code parsed at the same time as the "global"\nstatement. In particular, a "global" statement contained in an "exec"\nstatement does not affect the code block *containing* the "exec"\nstatement, and code contained in an "exec" statement is unaffected by\n"global" statements in the code containing the "exec" statement. The\nsame applies to the "eval()", "execfile()" and "compile()" functions.\n', ++ 'id-classes': u'\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 the\n last evaluation; it is stored in the "__builtin__" module. When\n not in interactive mode, "_" has no special meaning and is not\n 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 and\n elsewhere. More will likely be defined in future versions of\n Python. *Any* use of "__*__" names, in any context, that does not\n follow explicitly documented use, is subject to breakage without\n 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', ++ 'identifiers': u'\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions:\n\n identifier ::= (letter|"_") (letter | digit | "_")*\n letter ::= lowercase | uppercase\n lowercase ::= "a"..."z"\n uppercase ::= "A"..."Z"\n digit ::= "0"..."9"\n\nIdentifiers are unlimited in length. Case is significant.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers. They must\nbe spelled exactly as written here:\n\n and del from not while\n as elif global or with\n assert else if pass yield\n break except import print\n class exec in raise\n continue finally is return\n def for lambda try\n\nChanged in version 2.4: "None" became a constant and is now recognized\nby the compiler as a name for the built-in object "None". Although it\nis not a keyword, you cannot assign a different object to it.\n\nChanged in version 2.5: Using "as" and "with" as identifiers triggers\na warning. To use them as keywords, enable the "with_statement"\nfuture feature .\n\nChanged in version 2.6: "as" and "with" are full keywords.\n\n\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 the\n last evaluation; it is stored in the "__builtin__" module. When\n not in interactive mode, "_" has no special meaning and is not\n 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 and\n elsewhere. More will likely be defined in future versions of\n Python. *Any* use of "__*__" names, in any context, that does not\n follow explicitly documented use, is subject to breakage without\n 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', ++ 'if': u'\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', ++ 'imaginary': u'\nImaginary literals\n******************\n\nImaginary literals are described by the following lexical definitions:\n\n imagnumber ::= (floatnumber | intpart) ("j" | "J")\n\nAn imaginary literal yields a complex number with a real part of 0.0.\nComplex numbers are represented as a pair of floating point numbers\nand have the same restrictions on their range. To create a complex\nnumber with a nonzero real part, add a floating point number to it,\ne.g., "(3+4j)". Some examples of imaginary literals:\n\n 3.14j 10.j 10j .001j 1e100j 3.14e-10j\n', ++ 'import': u'\nThe "import" statement\n**********************\n\n import_stmt ::= "import" module ["as" name] ( "," module ["as" name] )*\n | "from" relative_module "import" identifier ["as" name]\n ( "," identifier ["as" name] )*\n | "from" relative_module "import" "(" identifier ["as" name]\n ( "," identifier ["as" name] )* [","] ")"\n | "from" module "import" "*"\n module ::= (identifier ".")* identifier\n relative_module ::= "."* module | "."+\n name ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the "import" statement occurs). The\nstatement comes in two forms differing on whether it uses the "from"\nkeyword. The first form (without "from") repeats these steps for each\nidentifier in the list. The form with "from" performs step (1) once,\nand then performs step (2) repeatedly.\n\nTo understand how step (1) occurs, one must first understand how\nPython handles hierarchical naming of modules. To help organize\nmodules and provide a hierarchy in naming, Python has a concept of\npackages. A package can contain other packages and modules while\nmodules cannot contain other modules or packages. From a file system\nperspective, packages are directories and modules are files.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n"sys.modules", the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import.\n\nIf the module is not found in the cache, then "sys.meta_path" is\nsearched (the specification for "sys.meta_path" can be found in **PEP\n302**). The object is a list of *finder* objects which are queried in\norder as to whether they know how to load the module by calling their\n"find_module()" method with the name of the module. If the module\nhappens to be contained within a package (as denoted by the existence\nof a dot in the name), then a second argument to "find_module()" is\ngiven as the value of the "__path__" attribute from the parent package\n(everything up to the last dot in the name of the module being\nimported). If a finder can find the module it returns a *loader*\n(discussed later) or returns "None".\n\nIf none of the finders on "sys.meta_path" are able to find the module\nthen some implicitly defined finders are queried. Implementations of\nPython vary in what implicit meta path finders are defined. The one\nthey all do define, though, is one that handles "sys.path_hooks",\n"sys.path_importer_cache", and "sys.path".\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to "find_module()",\n"__path__" on the parent package, is used as the source of paths. If\nthe module is not contained in a package then "sys.path" is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n"sys.path_importer_cache" caches finders for paths and is checked for\na finder. If the path does not have a finder cached then\n"sys.path_hooks" is searched by calling each object in the list with a\nsingle argument of the path, returning a finder or raises\n"ImportError". If a finder is returned then it is cached in\n"sys.path_importer_cache" and then used for that path entry. If no\nfinder can be found but the path exists then a value of "None" is\nstored in "sys.path_importer_cache" to signify that an implicit, file-\nbased finder that handles modules stored as individual files should be\nused for that path. If the path does not exist then a finder which\nalways returns "None" is placed in the cache for the path.\n\nIf no finder can find the module then "ImportError" is raised.\nOtherwise some finder returned a loader whose "load_module()" method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin "sys.modules" (a possibility if the loader is called outside of the\nimport machinery) then it is to use that module for initialization and\nnot a new module. But if the module does not exist in "sys.modules"\nthen it is to be added to that dict before initialization begins. If\nan error occurs during loading of the module and it was added to\n"sys.modules" it is to be removed from the dict. If an error occurs\nbut the module was already in "sys.modules" it is left in the dict.\n\nThe loader must set several attributes on the module. "__name__" is to\nbe set to the name of the module. "__file__" is to be the "path" to\nthe file unless the module is built-in (and thus listed in\n"sys.builtin_module_names") in which case the attribute is not set. If\nwhat is being imported is a package then "__path__" is to be set to a\nlist of paths to be searched when looking for modules and packages\ncontained within the package being imported. "__package__" is optional\nbut should be set to the name of package that contains the module or\npackage (the empty string is used for module not contained in a\npackage). "__loader__" is also optional but should be set to the\nloader object that is loading the module.\n\nIf an error occurs during loading then the loader raises "ImportError"\nif some other exception is not already being propagated. Otherwise the\nloader returns the module that was loaded and initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of "import" statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any. If the module name is followed by "as", the\nname following "as" is used as the local name for the module.\n\nThe "from" form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound. As with the first form of "import", an alternate local name\ncan be supplied by specifying ""as" localname". If a name is not\nfound, "ImportError" is raised. If the list of identifiers is\nreplaced by a star ("\'*\'"), all public names defined in the module are\nbound in the local namespace of the "import" statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named "__all__"; if defined, it must\nbe a sequence of strings which are names defined or imported by that\nmodule. The names given in "__all__" are all considered public and\nare required to exist. If "__all__" is not defined, the set of public\nnames includes all names found in the module\'s namespace which do not\nbegin with an underscore character ("\'_\'"). "__all__" should contain\nthe entire public API. It is intended to avoid accidentally exporting\nitems that are not part of the API (such as library modules which were\nimported and used within the module).\n\nThe "from" form with "*" may only occur in a module scope. If the\nwild card form of import --- "import *" --- is used in a function and\nthe function contains or is a nested block with free variables, the\ncompiler will raise a "SyntaxError".\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after "from" you\ncan specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n"from . import mod" from a module in the "pkg" package then you will\nend up importing "pkg.mod". If you execute "from ..subpkg2 import mod"\nfrom within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\nspecification for relative imports is contained within **PEP 328**.\n\n"importlib.import_module()" is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python. The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language. It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n future_statement ::= "from" "__future__" "import" feature ["as" name]\n ("," feature ["as" name])*\n | "from" "__future__" "import" "(" feature ["as" name]\n ("," feature ["as" name])* [","] ")"\n feature ::= identifier\n name ::= identifier\n\nA future statement must appear near the top of the module. The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 2.6 are "unicode_literals",\n"print_function", "absolute_import", "division", "generators",\n"nested_scopes" and "with_statement". "generators", "with_statement",\n"nested_scopes" are redundant in Python version 2.6 and above because\nthey are always enabled.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code. It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently. Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module "__future__", described later, and it will\nbe imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by an "exec" statement or calls to the built-in\nfunctions "compile()" and "execfile()" that occur in a module "M"\ncontaining a future statement will, by default, use the new syntax or\nsemantics associated with the future statement. This can, starting\nwith Python 2.2 be controlled by optional arguments to "compile()" ---\nsee the documentation of that function for details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session. If an\ninterpreter is started with the "-i" option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also:\n\n **PEP 236** - Back to the __future__\n The original proposal for the __future__ mechanism.\n', ++ 'in': u'\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation. Also unlike C, expressions like "a < b < c" have the\ninterpretation that is conventional in mathematics:\n\n comparison ::= or_expr ( comp_operator or_expr )*\n comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="\n | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: "True" or "False".\n\nComparisons can be chained arbitrarily, e.g., "x < y <= z" is\nequivalent to "x < y and y <= z", except that "y" is evaluated only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... y\nopN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\nThe forms "<>" and "!=" are equivalent; for consistency with C, "!="\nis preferred; where "!=" is mentioned below "<>" is also accepted.\nThe "<>" spelling is considered obsolescent.\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects. The objects need not have the same type. If both are\nnumbers, they are converted to a common type. Otherwise, objects of\ndifferent types *always* compare unequal, and are ordered consistently\nbut arbitrarily. You can control comparison behavior of objects of\nnon-built-in types by defining a "__cmp__" method or rich comparison\nmethods like "__gt__", described in section Special method names.\n\n(This unusual definition of comparison was used to simplify the\ndefinition of operations like sorting and the "in" and "not in"\noperators. In the future, the comparison rules for objects of\ndifferent types are likely to change.)\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* Strings are compared lexicographically using the numeric\n equivalents (the result of the built-in function "ord()") of their\n characters. Unicode and 8-bit strings are fully interoperable in\n this behavior. [4]\n\n* Tuples and lists are compared lexicographically using comparison\n of corresponding elements. This means that to compare equal, each\n element must compare equal and the two sequences must be of the same\n type and have the same length.\n\n If not equal, the sequences are ordered the same as their first\n differing elements. For example, "cmp([1,2,x], [1,2,y])" returns\n the same as "cmp(x,y)". If the corresponding element does not\n exist, the shorter sequence is ordered first (for example, "[1,2] <\n [1,2,3]").\n\n* Mappings (dictionaries) compare equal if and only if their sorted\n (key, value) lists compare equal. [5] Outcomes other than equality\n are resolved consistently, but are not otherwise defined. [6]\n\n* Most other objects of built-in types compare unequal unless they\n are the same object; the choice whether one object is considered\n smaller or larger than another one is made arbitrarily but\n consistently within one execution of a program.\n\nThe operators "in" and "not in" test for collection membership. "x in\ns" evaluates to true if *x* is a member of the collection *s*, and\nfalse otherwise. "x not in s" returns the negation of "x in s". The\ncollection membership test has traditionally been bound to sequences;\nan object is a member of a collection if the collection is a sequence\nand contains an element equal to that object. However, it make sense\nfor many other object types to support membership tests without being\na sequence. In particular, dictionaries (for keys) and sets support\nmembership testing.\n\nFor the list and tuple types, "x in y" is true if and only if there\nexists an index *i* such that "x == y[i]" is true.\n\nFor the Unicode and string types, "x in y" is true if and only if *x*\nis a substring of *y*. An equivalent test is "y.find(x) != -1".\nNote, *x* and *y* need not be the same type; consequently, "u\'ab\' in\n\'abc\'" will return "True". Empty strings are always considered to be a\nsubstring of any other string, so """ in "abc"" will return "True".\n\nChanged in version 2.3: Previously, *x* was required to be a string of\nlength "1".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin y" is true if and only if "y.__contains__(x)" is true.\n\nFor user-defined classes which do not define "__contains__()" but do\ndefine "__iter__()", "x in y" is true if some value "z" with "x == z"\nis produced while iterating over "y". If an exception is raised\nduring the iteration, it is as if "in" raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n"__getitem__()", "x in y" is true if and only if there is a non-\nnegative integer index *i* such that "x == y[i]", and all lower\ninteger indices do not raise "IndexError" exception. (If any other\nexception is raised, it is as if "in" raised that exception).\n\nThe operator "not in" is defined to have the inverse true value of\n"in".\n\nThe operators "is" and "is not" test for object identity: "x is y" is\ntrue if and only if *x* and *y* are the same object. "x is not y"\nyields the inverse truth value. [7]\n', ++ 'integers': u'\nInteger and long integer literals\n*********************************\n\nInteger and long integer literals are described by the following\nlexical definitions:\n\n longinteger ::= integer ("l" | "L")\n integer ::= decimalinteger | octinteger | hexinteger | bininteger\n decimalinteger ::= nonzerodigit digit* | "0"\n octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+\n hexinteger ::= "0" ("x" | "X") hexdigit+\n bininteger ::= "0" ("b" | "B") bindigit+\n nonzerodigit ::= "1"..."9"\n octdigit ::= "0"..."7"\n bindigit ::= "0" | "1"\n hexdigit ::= digit | "a"..."f" | "A"..."F"\n\nAlthough both lower case "\'l\'" and upper case "\'L\'" are allowed as\nsuffix for long integers, it is strongly recommended to always use\n"\'L\'", since the letter "\'l\'" looks too much like the digit "\'1\'".\n\nPlain integer literals that are above the largest representable plain\ninteger (e.g., 2147483647 when using 32-bit arithmetic) are accepted\nas if they were long integers instead. [1] There is no limit for long\ninteger literals apart from what can be stored in available memory.\n\nSome examples of plain integer literals (first row) and long integer\nliterals (second and third rows):\n\n 7 2147483647 0177\n 3L 79228162514264337593543950336L 0377L 0x100000000L\n 79228162514264337593543950336 0xdeadbeef\n', ++ 'lambda': u'\nLambdas\n*******\n\n lambda_expr ::= "lambda" [parameter_list]: expression\n old_lambda_expr ::= "lambda" [parameter_list]: old_expression\n\nLambda expressions (sometimes called lambda forms) have the same\nsyntactic position as expressions. They are a shorthand to create\nanonymous functions; the expression "lambda arguments: expression"\nyields a function object. The unnamed object behaves like a function\nobject defined with\n\n def name(arguments):\n return expression\n\nSee section Function definitions for the syntax of parameter lists.\nNote that functions created with lambda expressions cannot contain\nstatements.\n', ++ 'lists': u'\nList displays\n*************\n\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n list_display ::= "[" [expression_list | list_comprehension] "]"\n list_comprehension ::= expression list_for\n list_for ::= "for" target_list "in" old_expression_list [list_iter]\n old_expression_list ::= old_expression [("," old_expression)+ [","]]\n old_expression ::= or_test | old_lambda_expr\n list_iter ::= list_for | list_if\n list_if ::= "if" old_expression [list_iter]\n\nA list display yields a new list object. Its contents are specified\nby providing either a list of expressions or a list comprehension.\nWhen a comma-separated list of expressions is supplied, its elements\nare evaluated from left to right and placed into the list object in\nthat order. When a list comprehension is supplied, it consists of a\nsingle expression followed by at least one "for" clause and zero or\nmore "for" or "if" clauses. In this case, the elements of the new\nlist are those that would be produced by considering each of the "for"\nor "if" clauses a block, nesting from left to right, and evaluating\nthe expression to produce a list element each time the innermost block\nis reached [1].\n', ++ 'naming': u'\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" statement\nis a code block. The expression read and evaluated by the built-in\nfunction "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 "with"\nstatement. The "import" statement of the form "from ... import *"\nbinds all names defined in the imported module, except those beginning\nwith an underscore. This form may only be used at the module 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 first.\nIf the name is not found there, the builtins namespace is searched.\nThe 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 global\nnamespace; this should be a dictionary or a module (in the latter case\nthe module\'s dictionary is used). By default, when in the "__main__"\nmodule, "__builtins__" is the built-in module "__builtin__" (note: no\n\'s\'); when in any other module, "__builtins__" is an alias for the\ndictionary of the "__builtin__" module itself. "__builtins__" can be\nset to a user-created dictionary to create a weak form of restricted\nexecution.\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 operation\nin the same block. If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated 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 namespace\nfor the "exec". (In other words, "exec obj" would be illegal, but\n"exec obj in ns" would be legal.)\n\nThe "eval()", "execfile()", and "input()" functions and the "exec"\nstatement do not have access to the full environment for resolving\nnames. Names may be resolved in the local and global namespaces of\nthe caller. Free variables are not resolved in the nearest enclosing\nnamespace, but in the global namespace. [1] The "exec" statement and\nthe "eval()" and "execfile()" functions have optional arguments to\noverride the global and local namespace. If only one namespace is\nspecified, it is used for both.\n', ++ 'numbers': u'\nNumeric literals\n****************\n\nThere are four types of numeric literals: plain integers, long\nintegers, floating point numbers, and imaginary numbers. There are no\ncomplex literals (complex numbers can be formed by adding a real\nnumber and an imaginary number).\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', ++ 'numeric-types': u'\nEmulating numeric types\n***********************\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations ("+", "-", "*", "//", "%", "divmod()", "pow()", "**",\n "<<", ">>", "&", "^", "|"). For instance, to evaluate the\n expression "x + y", where *x* is an instance of a class that has an\n "__add__()" method, "x.__add__(y)" is called. The "__divmod__()"\n method should be the equivalent to using "__floordiv__()" and\n "__mod__()"; it should not be related to "__truediv__()" (described\n below). Note that "__pow__()" should be defined to accept an\n optional third argument if the ternary version of the built-in\n "pow()" function is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return "NotImplemented".\n\nobject.__div__(self, other)\nobject.__truediv__(self, other)\n\n The division operator ("/") is implemented by these methods. The\n "__truediv__()" method is used when "__future__.division" is in\n effect, otherwise "__div__()" is used. If only one of these two\n methods is defined, the object will not support division in the\n alternate context; "TypeError" will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations ("+", "-", "*", "/", "%", "divmod()", "pow()", "**",\n "<<", ">>", "&", "^", "|") with reflected (swapped) operands.\n These functions are only called if the left operand does not\n support the corresponding operation and the operands are of\n different types. [2] For instance, to evaluate the expression "x -\n y", where *y* is an instance of a class that has an "__rsub__()"\n method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n *NotImplemented*.\n\n Note that ternary "pow()" will not try calling "__rpow__()" (the\n coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left\n operand\'s type and that subclass provides the reflected method\n for the operation, this method will be called before the left\n operand\'s non-reflected method. This behavior allows subclasses\n to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n assignments ("+=", "-=", "*=", "/=", "//=", "%=", "**=", "<<=",\n ">>=", "&=", "^=", "|="). These methods should attempt to do the\n operation in-place (modifying *self*) and return the result (which\n could be, but does not have to be, *self*). If a specific method\n is not defined, the augmented assignment falls back to the normal\n methods. For instance, to execute the statement "x += y", where\n *x* is an instance of a class that has an "__iadd__()" method,\n "x.__iadd__(y)" is called. If *x* is an instance of a class that\n does not define a "__iadd__()" method, "x.__add__(y)" and\n "y.__radd__(x)" are considered, as with the evaluation of "x + y".\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations ("-", "+",\n "abs()" and "~").\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions "complex()", "int()",\n "long()", and "float()". Should return a value of the appropriate\n type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to implement the built-in functions "oct()" and "hex()".\n Should return a string value.\n\nobject.__index__(self)\n\n Called to implement "operator.index()". Also called whenever\n Python needs an integer object (such as in slicing). Must return\n an integer (int or long).\n\n New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to implement "mixed-mode" numeric arithmetic. Should either\n return a 2-tuple containing *self* and *other* converted to a\n common numeric type, or "None" if conversion is impossible. When\n the common type would be the type of "other", it is sufficient to\n return "None", since the interpreter will also ask the other object\n to attempt a coercion (but sometimes, if the implementation of the\n other type cannot be changed, it is useful to do the conversion to\n the other type here). A return value of "NotImplemented" is\n equivalent to returning "None".\n', ++ 'objects': u'\nObjects, values and types\n*************************\n\n*Objects* are Python\'s abstraction for data. All data in a Python\nprogram is represented by objects or by relations between objects. (In\na sense, and in conformance to Von Neumann\'s model of a "stored\nprogram computer," code is also represented by objects.)\n\nEvery object has an identity, a type and a value. An object\'s\n*identity* never changes once it has been created; you may think of it\nas the object\'s address in memory. The \'"is"\' operator compares the\nidentity of two objects; the "id()" function returns an integer\nrepresenting its identity (currently implemented as its address). An\nobject\'s *type* is also unchangeable. [1] An object\'s type determines\nthe operations that the object supports (e.g., "does it have a\nlength?") and also defines the possible values for objects of that\ntype. The "type()" function returns an object\'s type (which is an\nobject itself). The *value* of some objects can change. Objects\nwhose value can change are said to be *mutable*; objects whose value\nis unchangeable once they are created are called *immutable*. (The\nvalue of an immutable container object that contains a reference to a\nmutable object can change when the latter\'s value is changed; however\nthe container is still considered immutable, because the collection of\nobjects it contains cannot be changed. So, immutability is not\nstrictly the same as having an unchangeable value, it is more subtle.)\nAn object\'s mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\n\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected. An implementation is\nallowed to postpone garbage collection or omit it altogether --- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable.\n\n**CPython implementation detail:** CPython currently uses a reference-\ncounting scheme with (optional) delayed detection of cyclically linked\ngarbage, which collects most objects as soon as they become\nunreachable, but is not guaranteed to collect garbage containing\ncircular references. See the documentation of the "gc" module for\ninformation on controlling the collection of cyclic garbage. Other\nimplementations act differently and CPython may change. Do not depend\non immediate finalization of objects when they become unreachable (ex:\nalways close files).\n\nNote that the use of the implementation\'s tracing or debugging\nfacilities may keep objects alive that would normally be collectable.\nAlso note that catching an exception with a \'"try"..."except"\'\nstatement may keep objects alive.\n\nSome objects contain references to "external" resources such as open\nfiles or windows. It is understood that these resources are freed\nwhen the object is garbage-collected, but since garbage collection is\nnot guaranteed to happen, such objects also provide an explicit way to\nrelease the external resource, usually a "close()" method. Programs\nare strongly recommended to explicitly close such objects. The\n\'"try"..."finally"\' statement provides a convenient way to do this.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries. The references are part of a container\'s value. In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied. So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior. Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed. E.g., after "a = 1; b = 1",\n"a" and "b" may or may not refer to the same object with the value\none, depending on the implementation, but after "c = []; d = []", "c"\nand "d" are guaranteed to refer to two different, unique, newly\ncreated empty lists. (Note that "c = d = []" assigns the same object\nto both "c" and "d".)\n', ++ 'operator-summary': u'\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 from\nright 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...]", "{key: | Binding or tuple display, list |\n| 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"\n the control variables of each "for" it contains into the\n containing scope. However, this behavior is deprecated, and\n relying on it will not work in Python 3.\n\n[2] While "abs(x%y) < abs(y)" is true mathematically, for floats\n it 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", which\n is numerically exactly equal to "1e100". The function\n "math.fmod()" returns a result whose sign matches the sign of the\n first argument instead, and so returns "-1e-100" in this case.\n Which approach is more appropriate depends on the 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" due to\n rounding. In such cases, Python returns the latter result, in\n order to preserve that "divmod(x,y)[0] * y + x % y" be very close\n to "x".\n\n[4] While comparisons between unicode strings make sense at the\n byte level, they may be counter-intuitive to users. For example,\n the 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\n constructing lists or sorting.\n\n[6] Earlier versions of Python used lexicographic comparison of\n the 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\n dynamic nature of descriptors, you may notice seemingly unusual\n behaviour in certain uses of the "is" operator, like those\n involving comparisons between instance methods, or constants.\n Check their 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\n or bitwise unary operator on its right, that is, "2**-1" is "0.5".\n', ++ 'pass': u'\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': u'\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 2.2.\nIn Python 2.1 and before, if both arguments were of integer types and\nthe second argument was negative, an exception was raised).\n\nRaising "0.0" to a negative power results in a "ZeroDivisionError".\nRaising a negative number to a fractional power results in a\n"ValueError".\n', ++ 'print': u'\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\n built-in file objects often do not properly emulate this aspect of\n the file object\'s behavior, so it is best not to rely on this.\n\nA "\'\\n\'" character is written at the end, unless the "print" statement\nends with a comma. This is the only action if the statement contains\njust 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 ">>"\nmust evaluate to a "file-like" object, specifically an object that has\na "write()" method as described above. With this extended form, the\nsubsequent expressions are printed to this file object. If the first\nexpression evaluates to "None", then "sys.stdout" is used as the file\nfor output.\n', ++ 'raise': u'\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 is\nraised 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. The\nthree-expression form of "raise" is useful to re-raise an exception\ntransparently in an except clause, but "raise" with no expressions\nshould be preferred if the exception to be re-raised was the most\nrecently active exception in the current scope.\n\nAdditional information on exceptions can be found in section\nExceptions, and information about handling exceptions is in section\nThe try statement.\n', ++ 'return': u'\nThe "return" statement\n**********************\n\n return_stmt ::= "return" [expression_list]\n\n"return" may only occur syntactically nested in a function definition,\nnot 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 (or\n"None") as return value.\n\nWhen "return" passes control out of a "try" statement with a "finally"\nclause, that "finally" clause is executed before really leaving the\nfunction.\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" to\nbe raised.\n', ++ 'sequence-types': u'\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" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items. (For backwards compatibility, the method\n"__getslice__()" (see below) can also be defined to handle simple, but\nnot extended slices.) It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "has_key()", "get()",\n"clear()", "setdefault()", "iterkeys()", "itervalues()",\n"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving\nsimilar to those for Python\'s standard dictionary objects. The\n"UserDict" module provides a "DictMixin" class to help create those\nmethods from a base set of "__getitem__()", "__setitem__()",\n"__delitem__()", and "keys()". Mutable sequences should provide\nmethods "append()", "count()", "index()", "extend()", "insert()",\n"pop()", "remove()", "reverse()" and "sort()", like Python standard\nlist objects. Finally, sequence types should implement addition\n(meaning concatenation) and multiplication (meaning repetition) by\ndefining the methods "__add__()", "__radd__()", "__iadd__()",\n"__mul__()", "__rmul__()" and "__imul__()" described below; they\nshould not define "__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" operator;\nfor mappings, "in" should be equivalent of "has_key()"; for sequences,\nit should search through the values. It is further recommended that\nboth mappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "iterkeys()"; for sequences, it should iterate\nthrough 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 that\n doesn\'t define a "__nonzero__()" method and whose "__len__()"\n method returns zero is considered to be false in a Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of "self[key]". For sequence types,\n the accepted keys should be integers and slice objects. Note that\n the special interpretation of negative indexes (if the class wishes\n to emulate a sequence type) is up to the "__getitem__()" method. If\n *key* is of an inappropriate type, "TypeError" may be raised; if of\n a value outside the set of indexes for the sequence (after any\n special interpretation of negative values), "IndexError" should be\n raised. For mapping types, if *key* is missing (not in the\n container), "KeyError" 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.__missing__(self, key)\n\n Called by "dict"."__getitem__()" to implement "self[key]" for dict\n subclasses when key is not in the dictionary.\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__()" 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 "reversed()"\n built-in will fall back to using the sequence protocol ("__len__()"\n and "__getitem__()"). Objects that support the sequence protocol\n should only provide "__reversed__()" if they can provide an\n implementation that is more efficient than the one provided by\n "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 test\n first tries iteration via "__iter__()", then the old sequence\n iteration protocol via "__getitem__()", see this section in the\n language reference.\n', ++ 'shifting': u'\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept plain or long integers as arguments. The\narguments are converted to a common type. They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by "pow(2, n)". A\nleft shift by *n* bits is defined as multiplication with "pow(2, n)".\nNegative shift counts raise a "ValueError" exception.\n\nNote: In the current implementation, the right-hand operand is\n required to be at most "sys.maxsize". If the right-hand operand is\n larger than "sys.maxsize" an "OverflowError" exception is raised.\n', ++ 'slicings': u'\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list). Slicings may be used as expressions or as\ntargets in assignment or "del" statements. The syntax for a slicing:\n\n slicing ::= simple_slicing | extended_slicing\n simple_slicing ::= primary "[" short_slice "]"\n extended_slicing ::= primary "[" slice_list "]"\n slice_list ::= slice_item ("," slice_item)* [","]\n slice_item ::= expression | proper_slice | ellipsis\n proper_slice ::= short_slice | long_slice\n short_slice ::= [lower_bound] ":" [upper_bound]\n long_slice ::= short_slice ":" [stride]\n lower_bound ::= expression\n upper_bound ::= expression\n stride ::= expression\n ellipsis ::= "..."\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing. Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice nor ellipses). Similarly, when the slice\nlist has exactly one short slice and no trailing comma, the\ninterpretation as a simple slicing takes priority over that as an\nextended slicing.\n\nThe semantics for a simple slicing are as follows. The primary must\nevaluate to a sequence object. The lower and upper bound expressions,\nif present, must evaluate to plain integers; defaults are zero and the\n"sys.maxint", respectively. If either bound is negative, the\nsequence\'s length is added to it. The slicing now selects all items\nwith index *k* such that "i <= k < j" where *i* and *j* are the\nspecified lower and upper bounds. This may be an empty sequence. It\nis not an error if *i* or *j* lie outside the range of valid indexes\n(such items don\'t exist so they aren\'t selected).\n\nThe semantics for an extended slicing are as follows. The primary\nmust evaluate to a mapping object, and it is indexed with a key that\nis constructed from the slice list, as follows. If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key. The conversion of a slice item that is an\nexpression is that expression. The conversion of an ellipsis slice\nitem is the built-in "Ellipsis" object. The conversion of a proper\nslice is a slice object (see section The standard type hierarchy)\nwhose "start", "stop" and "step" attributes are the values of the\nexpressions given as lower bound, upper bound and stride,\nrespectively, substituting "None" for missing expressions.\n', ++ 'specialattrs': u'\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant. Some of these are not reported\nby the "dir()" built-in function.\n\nobject.__dict__\n\n A dictionary or other mapping object used to store an object\'s\n (writable) attributes.\n\nobject.__methods__\n\n Deprecated since version 2.2: Use the built-in function "dir()" to\n get a list of an object\'s attributes. This attribute is no longer\n available.\n\nobject.__members__\n\n Deprecated since version 2.2: Use the built-in function "dir()" to\n get a list of an object\'s attributes. This attribute is no longer\n available.\n\ninstance.__class__\n\n The class to which a class instance belongs.\n\nclass.__bases__\n\n The tuple of base classes of a class object.\n\nclass.__name__\n\n The name of the class or type.\n\nThe following attributes are only supported by *new-style class*es.\n\nclass.__mro__\n\n This attribute is a tuple of classes that are considered when\n looking for base classes during method resolution.\n\nclass.mro()\n\n This method can be overridden by a metaclass to customize the\n method resolution order for its instances. It is called at class\n instantiation, and its result is stored in "__mro__".\n\nclass.__subclasses__()\n\n Each new-style class keeps a list of weak references to its\n immediate subclasses. This method returns a list of all those\n references still alive. Example:\n\n >>> int.__subclasses__()\n []\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found\n in the Python Reference Manual (Basic customization).\n\n[2] As a consequence, the list "[1, 2]" is considered equal to\n "[1.0, 2.0]", and similarly for tuples.\n\n[3] They must have since the parser can\'t tell the type of the\n operands.\n\n[4] Cased characters are those with general category property\n being one of "Lu" (Letter, uppercase), "Ll" (Letter, lowercase),\n or "Lt" (Letter, titlecase).\n\n[5] To format only a tuple you should therefore provide a\n singleton tuple whose only element is the tuple to be formatted.\n\n[6] The advantage of leaving the newline on is that returning an\n empty string is then an unambiguous EOF indication. It is also\n possible (in cases where it might matter, for example, if you want\n to make an exact copy of a file while scanning its lines) to tell\n whether the last line of a file ended in a newline or not (yes\n this happens!).\n', ++ 'specialnames': u'\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators. For instance, if a class defines\na method named "__getitem__()", and "x" is an instance of this class,\nthen "x[i]" is roughly equivalent to "x.__getitem__(i)" for old-style\nclasses and "type(x).__getitem__(x, i)" for new-style classes. Except\nwhere mentioned, attempts to execute an operation raise an exception\nwhen no appropriate method is defined (typically "AttributeError" or\n"TypeError").\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled. For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense. (One example of this is the\n"NodeList" interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n Called to create a new instance of class *cls*. "__new__()" is a\n static method (special-cased so you need not declare it as such)\n that takes the class of which an instance was requested as its\n first argument. The remaining arguments are those passed to the\n object constructor expression (the call to the class). The return\n value of "__new__()" should be the new object instance (usually an\n instance of *cls*).\n\n Typical implementations create a new instance of the class by\n invoking the superclass\'s "__new__()" method using\n "super(currentclass, cls).__new__(cls[, ...])" with appropriate\n arguments and then modifying the newly-created instance as\n necessary before returning it.\n\n If "__new__()" returns an instance of *cls*, then the new\n instance\'s "__init__()" method will be invoked like\n "__init__(self[, ...])", where *self* is the new instance and the\n remaining arguments are the same as were passed to "__new__()".\n\n If "__new__()" does not return an instance of *cls*, then the new\n instance\'s "__init__()" method will not be invoked.\n\n "__new__()" is intended mainly to allow subclasses of immutable\n types (like int, str, or tuple) to customize instance creation. It\n is also commonly overridden in custom metaclasses in order to\n customize class creation.\n\nobject.__init__(self[, ...])\n\n Called after the instance has been created (by "__new__()"), but\n before it is returned to the caller. The arguments are those\n passed to the class constructor expression. If a base class has an\n "__init__()" method, the derived class\'s "__init__()" method, if\n any, must explicitly call it to ensure proper initialization of the\n base class part of the instance; for example:\n "BaseClass.__init__(self, [args...])".\n\n Because "__new__()" and "__init__()" work together in constructing\n objects ("__new__()" to create it, and "__init__()" to customise\n it), no non-"None" value may be returned by "__init__()"; doing so\n will cause a "TypeError" to be raised at runtime.\n\nobject.__del__(self)\n\n Called when the instance is about to be destroyed. This is also\n called a destructor. If a base class has a "__del__()" method, the\n derived class\'s "__del__()" method, if any, must explicitly call it\n to ensure proper deletion of the base class part of the instance.\n Note that it is possible (though not recommended!) for the\n "__del__()" method to postpone destruction of the instance by\n creating a new reference to it. It may then be called at a later\n time when this new reference is deleted. It is not guaranteed that\n "__del__()" methods are called for objects that still exist when\n the interpreter exits.\n\n Note: "del x" doesn\'t directly call "x.__del__()" --- the former\n decrements the reference count for "x" by one, and the latter is\n only called when "x"\'s reference count reaches zero. Some common\n situations that may prevent the reference count of an object from\n going to zero include: circular references between objects (e.g.,\n a doubly-linked list or a tree data structure with parent and\n child pointers); a reference to the object on the stack frame of\n a function that caught an exception (the traceback stored in\n "sys.exc_traceback" keeps the stack frame alive); or a reference\n to the object on the stack frame that raised an unhandled\n exception in interactive mode (the traceback stored in\n "sys.last_traceback" keeps the stack frame alive). The first\n situation can only be remedied by explicitly breaking the cycles;\n the latter two situations can be resolved by storing "None" in\n "sys.exc_traceback" or "sys.last_traceback". Circular references\n which are garbage are detected when the option cycle detector is\n enabled (it\'s on by default), but can only be cleaned up if there\n are no Python-level "__del__()" methods involved. Refer to the\n documentation for the "gc" module for more information about how\n "__del__()" methods are handled by the cycle detector,\n particularly the description of the "garbage" value.\n\n Warning: Due to the precarious circumstances under which\n "__del__()" methods are invoked, exceptions that occur during\n their execution are ignored, and a warning is printed to\n "sys.stderr" instead. Also, when "__del__()" is invoked in\n response to a module being deleted (e.g., when execution of the\n program is done), other globals referenced by the "__del__()"\n method may already have been deleted or in the process of being\n torn down (e.g. the import machinery shutting down). For this\n reason, "__del__()" methods should do the absolute minimum needed\n to maintain external invariants. Starting with version 1.5,\n Python guarantees that globals whose name begins with a single\n underscore are deleted from their module before other globals are\n deleted; if no other references to such globals exist, this may\n help in assuring that imported modules are still available at the\n time when the "__del__()" method is called.\n\n See also the "-R" command-line option.\n\nobject.__repr__(self)\n\n Called by the "repr()" built-in function and by string conversions\n (reverse quotes) to compute the "official" string representation of\n an object. If at all possible, this should look like a valid\n Python expression that could be used to recreate an object with the\n same value (given an appropriate environment). If this is not\n possible, a string of the form "<...some useful description...>"\n should be returned. The return value must be a string object. If a\n class defines "__repr__()" but not "__str__()", then "__repr__()"\n is also used when an "informal" string representation of instances\n of that class is required.\n\n This is typically used for debugging, so it is important that the\n representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n Called by the "str()" built-in function and by the "print"\n statement to compute the "informal" string representation of an\n object. This differs from "__repr__()" in that it does not have to\n be a valid Python expression: a more convenient or concise\n representation may be used instead. The return value must be a\n string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n New in version 2.1.\n\n These are the so-called "rich comparison" methods, and are called\n for comparison operators in preference to "__cmp__()" below. The\n correspondence between operator symbols and method names is as\n follows: "xy" call "x.__ne__(y)",\n "x>y" calls "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n A rich comparison method may return the singleton "NotImplemented"\n if it does not implement the operation for a given pair of\n arguments. By convention, "False" and "True" are returned for a\n successful comparison. However, these methods can return any value,\n so if the comparison operator is used in a Boolean context (e.g.,\n in the condition of an "if" statement), Python will call "bool()"\n on the value to determine if the result is true or false.\n\n There are no implied relationships among the comparison operators.\n The truth of "x==y" does not imply that "x!=y" is false.\n Accordingly, when defining "__eq__()", one should also define\n "__ne__()" so that the operators will behave as expected. See the\n paragraph on "__hash__()" for some important notes on creating\n *hashable* objects which support custom comparison operations and\n are usable as dictionary keys.\n\n There are no swapped-argument versions of these methods (to be used\n when the left argument does not support the operation but the right\n argument does); rather, "__lt__()" and "__gt__()" are each other\'s\n reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n and "__eq__()" and "__ne__()" are their own reflection.\n\n Arguments to rich comparison methods are never coerced.\n\n To automatically generate ordering operations from a single root\n operation, see "functools.total_ordering()".\n\nobject.__cmp__(self, other)\n\n Called by comparison operations if rich comparison (see above) is\n not defined. Should return a negative integer if "self < other",\n zero if "self == other", a positive integer if "self > other". If\n no "__cmp__()", "__eq__()" or "__ne__()" operation is defined,\n class instances are compared by object identity ("address"). See\n also the description of "__hash__()" for some important notes on\n creating *hashable* objects which support custom comparison\n operations and are usable as dictionary keys. (Note: the\n restriction that exceptions are not propagated by "__cmp__()" has\n been removed since Python 1.5.)\n\nobject.__rcmp__(self, other)\n\n Changed in version 2.1: No longer supported.\n\nobject.__hash__(self)\n\n Called by built-in function "hash()" and for operations on members\n of hashed collections including "set", "frozenset", and "dict".\n "__hash__()" should return an integer. The only required property\n is that objects which compare equal have the same hash value; it is\n advised to somehow mix together (e.g. using exclusive or) the hash\n values for the components of the object that also play a part in\n comparison of objects.\n\n If a class does not define a "__cmp__()" or "__eq__()" method it\n should not define a "__hash__()" operation either; if it defines\n "__cmp__()" or "__eq__()" but not "__hash__()", its instances will\n not be usable in hashed collections. If a class defines mutable\n objects and implements a "__cmp__()" or "__eq__()" method, it\n should not implement "__hash__()", since hashable collection\n implementations require that a object\'s hash value is immutable (if\n the object\'s hash value changes, it will be in the wrong hash\n bucket).\n\n User-defined classes have "__cmp__()" and "__hash__()" methods by\n default; with them, all objects compare unequal (except with\n themselves) and "x.__hash__()" returns a result derived from\n "id(x)".\n\n Classes which inherit a "__hash__()" method from a parent class but\n change the meaning of "__cmp__()" or "__eq__()" such that the hash\n value returned is no longer appropriate (e.g. by switching to a\n value-based concept of equality instead of the default identity\n based equality) can explicitly flag themselves as being unhashable\n by setting "__hash__ = None" in the class definition. Doing so\n means that not only will instances of the class raise an\n appropriate "TypeError" when a program attempts to retrieve their\n hash value, but they will also be correctly identified as\n unhashable when checking "isinstance(obj, collections.Hashable)"\n (unlike classes which define their own "__hash__()" to explicitly\n raise "TypeError").\n\n Changed in version 2.5: "__hash__()" may now also return a long\n integer object; the 32-bit integer is then derived from the hash of\n that object.\n\n Changed in version 2.6: "__hash__" may now be set to "None" to\n explicitly flag instances of a class as unhashable.\n\nobject.__nonzero__(self)\n\n Called to implement truth value testing and the built-in operation\n "bool()"; should return "False" or "True", or their integer\n equivalents "0" or "1". When this method is not defined,\n "__len__()" is called, if it is defined, and the object is\n considered true if its result is nonzero. If a class defines\n neither "__len__()" nor "__nonzero__()", all its instances are\n considered true.\n\nobject.__unicode__(self)\n\n Called to implement "unicode()" built-in; should return a Unicode\n object. When this method is not defined, string conversion is\n attempted, and the result of string conversion is converted to\n Unicode using the system default encoding.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of "x.name") for\nclass instances.\n\nobject.__getattr__(self, name)\n\n Called when an attribute lookup has not found the attribute in the\n usual places (i.e. it is not an instance attribute nor is it found\n in the class tree for "self"). "name" is the attribute name. This\n method should return the (computed) attribute value or raise an\n "AttributeError" exception.\n\n Note that if the attribute is found through the normal mechanism,\n "__getattr__()" is not called. (This is an intentional asymmetry\n between "__getattr__()" and "__setattr__()".) This is done both for\n efficiency reasons and because otherwise "__getattr__()" would have\n no way to access other attributes of the instance. Note that at\n least for instance variables, you can fake total control by not\n inserting any values in the instance attribute dictionary (but\n instead inserting them in another object). See the\n "__getattribute__()" method below for a way to actually get total\n control in new-style classes.\n\nobject.__setattr__(self, name, value)\n\n Called when an attribute assignment is attempted. This is called\n instead of the normal mechanism (i.e. store the value in the\n instance dictionary). *name* is the attribute name, *value* is the\n value to be assigned to it.\n\n If "__setattr__()" wants to assign to an instance attribute, it\n should not simply execute "self.name = value" --- this would cause\n a recursive call to itself. Instead, it should insert the value in\n the dictionary of instance attributes, e.g., "self.__dict__[name] =\n value". For new-style classes, rather than accessing the instance\n dictionary, it should call the base class method with the same\n name, for example, "object.__setattr__(self, name, value)".\n\nobject.__delattr__(self, name)\n\n Like "__setattr__()" but for attribute deletion instead of\n assignment. This should only be implemented if "del obj.name" is\n meaningful for the object.\n\n\nMore attribute access for new-style classes\n-------------------------------------------\n\nThe following methods only apply to new-style classes.\n\nobject.__getattribute__(self, name)\n\n Called unconditionally to implement attribute accesses for\n instances of the class. If the class also defines "__getattr__()",\n the latter will not be called unless "__getattribute__()" either\n calls it explicitly or raises an "AttributeError". This method\n should return the (computed) attribute value or raise an\n "AttributeError" exception. In order to avoid infinite recursion in\n this method, its implementation should always call the base class\n method with the same name to access any attributes it needs, for\n example, "object.__getattribute__(self, name)".\n\n Note: This method may still be bypassed when looking up special\n methods as the result of implicit invocation via language syntax\n or built-in functions. See Special method lookup for new-style\n classes.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents). In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' "__dict__".\n\nobject.__get__(self, instance, owner)\n\n Called to get the attribute of the owner class (class attribute\n access) or of an instance of that class (instance attribute\n access). *owner* is always the owner class, while *instance* is the\n instance that the attribute was accessed through, or "None" when\n the attribute is accessed through the *owner*. This method should\n return the (computed) attribute value or raise an "AttributeError"\n exception.\n\nobject.__set__(self, instance, value)\n\n Called to set the attribute on an instance *instance* of the owner\n class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n Called to delete the attribute on an instance *instance* of the\n owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol: "__get__()", "__set__()", and\n"__delete__()". If any of those methods are defined for an object, it\nis said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, "a.x" has a\nlookup chain starting with "a.__dict__[\'x\']", then\n"type(a).__dict__[\'x\']", and continuing through the base classes of\n"type(a)" excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead. Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called. Note that descriptors are only invoked for new\nstyle objects or classes (ones that subclass "object()" or "type()").\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe arguments are assembled depends on "a":\n\nDirect Call\n The simplest and least common call is when user code directly\n invokes a descriptor method: "x.__get__(a)".\n\nInstance Binding\n If binding to a new-style object instance, "a.x" is transformed\n into the call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n If binding to a new-style class, "A.x" is transformed into the\n call: "A.__dict__[\'x\'].__get__(None, A)".\n\nSuper Binding\n If "a" is an instance of "super", then the binding "super(B,\n obj).m()" searches "obj.__class__.__mro__" for the base class "A"\n immediately preceding "B" and then invokes the descriptor with the\n call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined. A descriptor can define\nany combination of "__get__()", "__set__()" and "__delete__()". If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary. If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor. Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method. Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary. In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented as non-data descriptors. Accordingly, instances can\nredefine and override methods. This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe "property()" function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of both old and new-style classes have a\ndictionary for attribute storage. This wastes space for objects\nhaving very few instance variables. The space consumption can become\nacute when creating large numbers of instances.\n\nThe default can be overridden by defining *__slots__* in a new-style\nclass definition. The *__slots__* declaration takes a sequence of\ninstance variables and reserves just enough space in each instance to\nhold a value for each variable. Space is saved because *__dict__* is\nnot created for each instance.\n\n__slots__\n\n This class variable can be assigned a string, iterable, or sequence\n of strings with variable names used by instances. If defined in a\n new-style class, *__slots__* reserves space for the declared\n variables and prevents the automatic creation of *__dict__* and\n *__weakref__* for each instance.\n\n New in version 2.2.\n\nNotes on using *__slots__*\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n attribute of that class will always be accessible, so a *__slots__*\n definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n variables not listed in the *__slots__* definition. Attempts to\n assign to an unlisted variable name raises "AttributeError". If\n dynamic assignment of new variables is desired, then add\n "\'__dict__\'" to the sequence of strings in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously, adding "\'__dict__\'" to the\n *__slots__* declaration would not enable the assignment of new\n attributes not specifically listed in the sequence of instance\n variable names.\n\n* Without a *__weakref__* variable for each instance, classes\n defining *__slots__* do not support weak references to its\n instances. If weak reference support is needed, then add\n "\'__weakref__\'" to the sequence of strings in the *__slots__*\n declaration.\n\n Changed in version 2.3: Previously, adding "\'__weakref__\'" to the\n *__slots__* declaration would not enable support for weak\n references.\n\n* *__slots__* are implemented at the class level by creating\n descriptors (Implementing Descriptors) for each variable name. As a\n result, class attributes cannot be used to set default values for\n instance variables defined by *__slots__*; otherwise, the class\n attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n where it is defined. As a result, subclasses will have a *__dict__*\n unless they also define *__slots__* (which must only contain names\n of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the\n instance variable defined by the base class slot is inaccessible\n (except by retrieving its descriptor directly from the base class).\n This renders the meaning of the program undefined. In the future, a\n check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n "variable-length" built-in types such as "long", "str" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n may also be used; however, in the future, special meaning may be\n assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n *__slots__*.\n\n Changed in version 2.6: Previously, *__class__* assignment raised an\n error if either new or old class had *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, new-style classes are constructed using "type()". A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of "type(name, bases, dict)".\n\nWhen the class definition is read, if *__metaclass__* is defined then\nthe callable assigned to it will be called instead of "type()". This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing\n the role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s "__new__()"\nmethod -- "type.__new__()" can then be called from this method to\ncreate a class with different properties. This example adds a new\nelement to the class dictionary before creating the class:\n\n class metacls(type):\n def __new__(mcs, name, bases, dict):\n dict[\'foo\'] = \'metacls was here\'\n return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom "__call__()" method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\n__metaclass__\n\n This variable can be any callable accepting arguments for "name",\n "bases", and "dict". Upon class creation, the callable is used\n instead of the built-in "type()".\n\n New in version 2.2.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If "dict[\'__metaclass__\']" exists, it is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n used (this looks for a *__class__* attribute first and if not found,\n uses its type).\n\n* Otherwise, if a global variable named __metaclass__ exists, it is\n used.\n\n* Otherwise, the old-style, classic metaclass (types.ClassType) is\n used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\n\nCustomizing instance and subclass checks\n========================================\n\nNew in version 2.6.\n\nThe following methods are used to override the default behavior of the\n"isinstance()" and "issubclass()" built-in functions.\n\nIn particular, the metaclass "abc.ABCMeta" implements these methods in\norder to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n Return true if *instance* should be considered a (direct or\n indirect) instance of *class*. If defined, called to implement\n "isinstance(instance, class)".\n\nclass.__subclasscheck__(self, subclass)\n\n Return true if *subclass* should be considered a (direct or\n indirect) subclass of *class*. If defined, called to implement\n "issubclass(subclass, class)".\n\nNote that these methods are looked up on the type (metaclass) of a\nclass. They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n **PEP 3119** - Introducing Abstract Base Classes\n Includes the specification for customizing "isinstance()" and\n "issubclass()" behavior through "__instancecheck__()" and\n "__subclasscheck__()", with motivation for this functionality in\n the context of adding Abstract Base Classes (see the "abc"\n module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n Called when the instance is "called" as a function; if this method\n is defined, "x(arg1, arg2, ...)" is a shorthand for\n "x.__call__(arg1, arg2, ...)".\n\n\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" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items. (For backwards compatibility, the method\n"__getslice__()" (see below) can also be defined to handle simple, but\nnot extended slices.) It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "has_key()", "get()",\n"clear()", "setdefault()", "iterkeys()", "itervalues()",\n"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving\nsimilar to those for Python\'s standard dictionary objects. The\n"UserDict" module provides a "DictMixin" class to help create those\nmethods from a base set of "__getitem__()", "__setitem__()",\n"__delitem__()", and "keys()". Mutable sequences should provide\nmethods "append()", "count()", "index()", "extend()", "insert()",\n"pop()", "remove()", "reverse()" and "sort()", like Python standard\nlist objects. Finally, sequence types should implement addition\n(meaning concatenation) and multiplication (meaning repetition) by\ndefining the methods "__add__()", "__radd__()", "__iadd__()",\n"__mul__()", "__rmul__()" and "__imul__()" described below; they\nshould not define "__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" operator;\nfor mappings, "in" should be equivalent of "has_key()"; for sequences,\nit should search through the values. It is further recommended that\nboth mappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "iterkeys()"; for sequences, it should iterate\nthrough 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 that\n doesn\'t define a "__nonzero__()" method and whose "__len__()"\n method returns zero is considered to be false in a Boolean context.\n\nobject.__getitem__(self, key)\n\n Called to implement evaluation of "self[key]". For sequence types,\n the accepted keys should be integers and slice objects. Note that\n the special interpretation of negative indexes (if the class wishes\n to emulate a sequence type) is up to the "__getitem__()" method. If\n *key* is of an inappropriate type, "TypeError" may be raised; if of\n a value outside the set of indexes for the sequence (after any\n special interpretation of negative values), "IndexError" should be\n raised. For mapping types, if *key* is missing (not in the\n container), "KeyError" 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.__missing__(self, key)\n\n Called by "dict"."__getitem__()" to implement "self[key]" for dict\n subclasses when key is not in the dictionary.\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__()" 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 "reversed()"\n built-in will fall back to using the sequence protocol ("__len__()"\n and "__getitem__()"). Objects that support the sequence protocol\n should only provide "__reversed__()" if they can provide an\n implementation that is more efficient than the one provided by\n "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 test\n first tries iteration via "__iter__()", then the old sequence\n iteration protocol via "__getitem__()", see this section in the\n language reference.\n\n\nAdditional methods for emulation of sequence types\n==================================================\n\nThe following optional methods can be defined to further emulate\nsequence objects. Immutable sequences methods should at most only\ndefine "__getslice__()"; mutable sequences might define all three\nmethods.\n\nobject.__getslice__(self, i, j)\n\n Deprecated since version 2.0: Support slice objects as parameters\n to the "__getitem__()" method. (However, built-in types in CPython\n currently still implement "__getslice__()". Therefore, you have to\n override it in derived classes when implementing slicing.)\n\n Called to implement evaluation of "self[i:j]". The returned object\n should be of the same type as *self*. Note that missing *i* or *j*\n in the slice expression are replaced by zero or "sys.maxsize",\n respectively. If negative indexes are used in the slice, the\n length of the sequence is added to that index. If the instance does\n not implement the "__len__()" method, an "AttributeError" is\n raised. No guarantee is made that indexes adjusted this way are not\n still negative. Indexes which are greater than the length of the\n sequence are not modified. If no "__getslice__()" is found, a slice\n object is created instead, and passed to "__getitem__()" instead.\n\nobject.__setslice__(self, i, j, sequence)\n\n Called to implement assignment to "self[i:j]". Same notes for *i*\n and *j* as for "__getslice__()".\n\n This method is deprecated. If no "__setslice__()" is found, or for\n extended slicing of the form "self[i:j:k]", a slice object is\n created, and passed to "__setitem__()", instead of "__setslice__()"\n being called.\n\nobject.__delslice__(self, i, j)\n\n Called to implement deletion of "self[i:j]". Same notes for *i* and\n *j* as for "__getslice__()". This method is deprecated. If no\n "__delslice__()" is found, or for extended slicing of the form\n "self[i:j:k]", a slice object is created, and passed to\n "__delitem__()", instead of "__delslice__()" being called.\n\nNotice that these methods are only invoked when a single slice with a\nsingle colon is used, and the slice method is available. For slice\noperations involving extended slice notation, or in absence of the\nslice methods, "__getitem__()", "__setitem__()" or "__delitem__()" is\ncalled with a slice object as argument.\n\nThe following example demonstrate how to make your program or module\ncompatible with earlier versions of Python (assuming that methods\n"__getitem__()", "__setitem__()" and "__delitem__()" support slice\nobjects as arguments):\n\n class MyClass:\n ...\n def __getitem__(self, index):\n ...\n def __setitem__(self, index, value):\n ...\n def __delitem__(self, index):\n ...\n\n if sys.version_info < (2, 0):\n # They won\'t be defined if version is at least 2.0 final\n\n def __getslice__(self, i, j):\n return self[max(0, i):max(0, j):]\n def __setslice__(self, i, j, seq):\n self[max(0, i):max(0, j):] = seq\n def __delslice__(self, i, j):\n del self[max(0, i):max(0, j):]\n ...\n\nNote the calls to "max()"; these are necessary because of the handling\nof negative indices before the "__*slice__()" methods are called.\nWhen negative indexes are used, the "__*item__()" methods receive them\nas provided, but the "__*slice__()" methods get a "cooked" form of the\nindex values. For each negative index value, the length of the\nsequence is added to the index before calling the method (which may\nstill result in a negative index); this is the customary handling of\nnegative indexes by the built-in sequence types, and the "__*item__()"\nmethods are expected to do this as well. However, since they should\nalready be doing that, negative indexes cannot be passed in; they must\nbe constrained to the bounds of the sequence before being passed to\nthe "__*item__()" methods. Calling "max(0, i)" conveniently returns\nthe proper value.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations ("+", "-", "*", "//", "%", "divmod()", "pow()", "**",\n "<<", ">>", "&", "^", "|"). For instance, to evaluate the\n expression "x + y", where *x* is an instance of a class that has an\n "__add__()" method, "x.__add__(y)" is called. The "__divmod__()"\n method should be the equivalent to using "__floordiv__()" and\n "__mod__()"; it should not be related to "__truediv__()" (described\n below). Note that "__pow__()" should be defined to accept an\n optional third argument if the ternary version of the built-in\n "pow()" function is to be supported.\n\n If one of those methods does not support the operation with the\n supplied arguments, it should return "NotImplemented".\n\nobject.__div__(self, other)\nobject.__truediv__(self, other)\n\n The division operator ("/") is implemented by these methods. The\n "__truediv__()" method is used when "__future__.division" is in\n effect, otherwise "__div__()" is used. If only one of these two\n methods is defined, the object will not support division in the\n alternate context; "TypeError" will be raised instead.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rdiv__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n These methods are called to implement the binary arithmetic\n operations ("+", "-", "*", "/", "%", "divmod()", "pow()", "**",\n "<<", ">>", "&", "^", "|") with reflected (swapped) operands.\n These functions are only called if the left operand does not\n support the corresponding operation and the operands are of\n different types. [2] For instance, to evaluate the expression "x -\n y", where *y* is an instance of a class that has an "__rsub__()"\n method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n *NotImplemented*.\n\n Note that ternary "pow()" will not try calling "__rpow__()" (the\n coercion rules would become too complicated).\n\n Note: If the right operand\'s type is a subclass of the left\n operand\'s type and that subclass provides the reflected method\n for the operation, this method will be called before the left\n operand\'s non-reflected method. This behavior allows subclasses\n to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__idiv__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n These methods are called to implement the augmented arithmetic\n assignments ("+=", "-=", "*=", "/=", "//=", "%=", "**=", "<<=",\n ">>=", "&=", "^=", "|="). These methods should attempt to do the\n operation in-place (modifying *self*) and return the result (which\n could be, but does not have to be, *self*). If a specific method\n is not defined, the augmented assignment falls back to the normal\n methods. For instance, to execute the statement "x += y", where\n *x* is an instance of a class that has an "__iadd__()" method,\n "x.__iadd__(y)" is called. If *x* is an instance of a class that\n does not define a "__iadd__()" method, "x.__add__(y)" and\n "y.__radd__(x)" are considered, as with the evaluation of "x + y".\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n Called to implement the unary arithmetic operations ("-", "+",\n "abs()" and "~").\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__long__(self)\nobject.__float__(self)\n\n Called to implement the built-in functions "complex()", "int()",\n "long()", and "float()". Should return a value of the appropriate\n type.\n\nobject.__oct__(self)\nobject.__hex__(self)\n\n Called to implement the built-in functions "oct()" and "hex()".\n Should return a string value.\n\nobject.__index__(self)\n\n Called to implement "operator.index()". Also called whenever\n Python needs an integer object (such as in slicing). Must return\n an integer (int or long).\n\n New in version 2.5.\n\nobject.__coerce__(self, other)\n\n Called to implement "mixed-mode" numeric arithmetic. Should either\n return a 2-tuple containing *self* and *other* converted to a\n common numeric type, or "None" if conversion is impossible. When\n the common type would be the type of "other", it is sufficient to\n return "None", since the interpreter will also ask the other object\n to attempt a coercion (but sometimes, if the implementation of the\n other type cannot be changed, it is useful to do the conversion to\n the other type here). A return value of "NotImplemented" is\n equivalent to returning "None".\n\n\nCoercion rules\n==============\n\nThis section used to document the rules for coercion. As the language\nhas evolved, the coercion rules have become hard to document\nprecisely; documenting what one version of one particular\nimplementation does is undesirable. Instead, here are some informal\nguidelines regarding coercion. In Python 3, coercion will not be\nsupported.\n\n* If the left operand of a % operator is a string or Unicode object,\n no coercion takes place and the string formatting operation is\n invoked instead.\n\n* It is no longer recommended to define a coercion operation. Mixed-\n mode operations on types that don\'t define coercion pass the\n original arguments to the operation.\n\n* New-style classes (those derived from "object") never invoke the\n "__coerce__()" method in response to a binary operator; the only\n time "__coerce__()" is invoked is when the built-in function\n "coerce()" is called.\n\n* For most intents and purposes, an operator that returns\n "NotImplemented" is treated the same as one that is not implemented\n at all.\n\n* Below, "__op__()" and "__rop__()" are used to signify the generic\n method names corresponding to an operator; "__iop__()" is used for\n the corresponding in-place operator. For example, for the operator\n \'"+"\', "__add__()" and "__radd__()" are used for the left and right\n variant of the binary operator, and "__iadd__()" for the in-place\n variant.\n\n* For objects *x* and *y*, first "x.__op__(y)" is tried. If this is\n not implemented or returns "NotImplemented", "y.__rop__(x)" is\n tried. If this is also not implemented or returns "NotImplemented",\n a "TypeError" exception is raised. But see the following exception:\n\n* Exception to the previous item: if the left operand is an instance\n of a built-in type or a new-style class, and the right operand is an\n instance of a proper subclass of that type or class and overrides\n the base\'s "__rop__()" method, the right operand\'s "__rop__()"\n method is tried *before* the left operand\'s "__op__()" method.\n\n This is done so that a subclass can completely override binary\n operators. Otherwise, the left operand\'s "__op__()" method would\n always accept the right operand: when an instance of a given class\n is expected, an instance of a subclass of that class is always\n acceptable.\n\n* When either operand type defines a coercion, this coercion is\n called before that type\'s "__op__()" or "__rop__()" method is\n called, but no sooner. If the coercion returns an object of a\n different type for the operand whose coercion is invoked, part of\n the process is redone using the new object.\n\n* When an in-place operator (like \'"+="\') is used, if the left\n operand implements "__iop__()", it is invoked without any coercion.\n When the operation falls back to "__op__()" and/or "__rop__()", the\n normal coercion rules apply.\n\n* In "x + y", if *x* is a sequence that implements sequence\n concatenation, sequence concatenation is invoked.\n\n* In "x * y", if one operand is a sequence that implements sequence\n repetition, and the other is an integer ("int" or "long"), sequence\n repetition is invoked.\n\n* Rich comparisons (implemented by methods "__eq__()" and so on)\n never use coercion. Three-way comparison (implemented by\n "__cmp__()") does use coercion under the same conditions as other\n binary operations use it.\n\n* In the current implementation, the built-in numeric types "int",\n "long", "float", and "complex" do not use coercion. All these types\n implement a "__coerce__()" method, for use by the built-in\n "coerce()" function.\n\n Changed in version 2.7: The complex type no longer makes implicit\n calls to the "__coerce__()" method for mixed-type binary arithmetic\n operations.\n\n\nWith Statement Context Managers\n===============================\n\nNew in version 2.5.\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code. Context managers are normally\ninvoked using the "with" statement (described in section The with\nstatement), but can also be used by directly invoking their methods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see Context Manager Types.\n\nobject.__enter__(self)\n\n Enter the runtime context related to this object. The "with"\n statement will bind this method\'s return value to the target(s)\n specified in the "as" clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n Exit the runtime context related to this object. The parameters\n describe the exception that caused the context to be exited. If the\n context was exited without an exception, all three arguments will\n be "None".\n\n If an exception is supplied, and the method wishes to suppress the\n exception (i.e., prevent it from being propagated), it should\n return a true value. Otherwise, the exception will be processed\n normally upon exit from this method.\n\n Note that "__exit__()" methods should not reraise the passed-in\n exception; this is the caller\'s responsibility.\n\nSee also:\n\n **PEP 0343** - The "with" statement\n The specification, background, and examples for the Python "with"\n statement.\n\n\nSpecial method lookup for old-style classes\n===========================================\n\nFor old-style classes, special methods are always looked up in exactly\nthe same way as any other method or attribute. This is the case\nregardless of whether the method is being looked up explicitly as in\n"x.__getitem__(i)" or implicitly as in "x[i]".\n\nThis behaviour means that special methods may exhibit different\nbehaviour for different instances of a single old-style class if the\nappropriate special attributes are set differently:\n\n >>> class C:\n ... pass\n ...\n >>> c1 = C()\n >>> c2 = C()\n >>> c1.__len__ = lambda: 5\n >>> c2.__len__ = lambda: 9\n >>> len(c1)\n 5\n >>> len(c2)\n 9\n\n\nSpecial method lookup for new-style classes\n===========================================\n\nFor new-style classes, implicit invocations of special methods are\nonly guaranteed to work correctly if defined on an object\'s type, not\nin the object\'s instance dictionary. That behaviour is the reason why\nthe following code raises an exception (unlike the equivalent example\nwith old-style classes):\n\n >>> class C(object):\n ... pass\n ...\n >>> c = C()\n >>> c.__len__ = lambda: 5\n >>> len(c)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as "__hash__()" and "__repr__()" that are implemented by\nall objects, including type objects. If the implicit lookup of these\nmethods used the conventional lookup process, they would fail when\ninvoked on the type object itself:\n\n >>> 1 .__hash__() == hash(1)\n True\n >>> int.__hash__() == hash(int)\n Traceback (most recent call last):\n File "", line 1, in \n TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n >>> type(1).__hash__(1) == hash(1)\n True\n >>> type(int).__hash__(int) == hash(int)\n True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe "__getattribute__()" method even of the object\'s metaclass:\n\n >>> class Meta(type):\n ... def __getattribute__(*args):\n ... print "Metaclass getattribute invoked"\n ... return type.__getattribute__(*args)\n ...\n >>> class C(object):\n ... __metaclass__ = Meta\n ... def __len__(self):\n ... return 10\n ... def __getattribute__(*args):\n ... print "Class getattribute invoked"\n ... return object.__getattribute__(*args)\n ...\n >>> c = C()\n >>> c.__len__() # Explicit lookup via instance\n Class getattribute invoked\n 10\n >>> type(c).__len__(c) # Explicit lookup via type\n Metaclass getattribute invoked\n 10\n >>> len(c) # Implicit lookup\n 10\n\nBypassing the "__getattribute__()" machinery in this fashion provides\nsignificant scope for speed optimisations within the interpreter, at\nthe cost of some flexibility in the handling of special methods (the\nspecial method *must* be set on the class object itself in order to be\nconsistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type,\n under certain controlled conditions. It generally isn\'t a good\n idea though, since it can lead to some very strange behaviour if\n it is handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n reflected method (such as "__add__()") fails the operation is not\n supported, which is why the reflected method is not called.\n', ++ 'string-methods': u'\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 "UnicodeError".\n Other possible values are "\'ignore\'", "\'replace\'",\n "\'xmlcharrefreplace\'", "\'backslashreplace\'" and any other name\n registered via "codecs.register_error()", see section Codec Base\n Classes. For a list of possible encodings, see section Standard\n 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 suffixes\n to look for. With optional *start*, test beginning at that\n position. With optional *end*, stop comparing at that 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 result\n until the current column is equal to the next tab position. (The\n tab character itself is not copied.) If the character is a newline\n ("\\n") or return ("\\r"), it is copied and the current column is\n reset to zero. Any other character is copied unchanged and the\n 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 within the slice "s[start:end]". Optional arguments *start*\n and *end* are interpreted as in slice notation. Return "-1" if\n *sub* is not found.\n\n Note: The "find()" method should be used only if you need to know\n the position of *sub*. To check if *sub* is a substring or not,\n use 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 String\n 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* is\n 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 splitting\n from the right, "rsplit()" behaves like "split()" which is\n 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* argument\n may consist of multiple characters (for example,\n "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n 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 For example, "\' 1 2 3 \'.split()" returns "[\'1\', \'2\', \'3\']", and\n "\' 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 "[\'ab\n c\', \'\', \'de fg\', \'kl\']", while the same call with\n "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de fg\\r\', \'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 return\n "False". *prefix* can also be a tuple of prefixes to look for.\n With optional *start*, test string beginning at that position.\n With optional *end*, stop comparing string at that 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 *chars*\n argument defaults to removing whitespace. The *chars* argument is\n not a prefix or suffix; rather, all combinations of its values are\n 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. Note,\n a more flexible approach is to create a custom character mapping\n codec using the "codecs" module (see "encodings.cp1251" for an\n 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 be\n "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, "False"\n otherwise. Numeric characters include digit characters, and all\n characters that have the Unicode numeric value property, e.g.\n U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return "True" if there are only decimal characters in S, "False"\n otherwise. Decimal characters include digit characters, and all\n characters that can be used to form decimal-radix numbers, e.g.\n U+0660, ARABIC-INDIC DIGIT ZERO.\n', ++ 'strings': u'\nString literals\n***************\n\nString literals are described by the following lexical definitions:\n\n stringliteral ::= [stringprefix](shortstring | longstring)\n stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"\n | "b" | "B" | "br" | "Br" | "bR" | "BR"\n shortstring ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n longstring ::= "\'\'\'" longstringitem* "\'\'\'"\n | \'"""\' longstringitem* \'"""\'\n shortstringitem ::= shortstringchar | escapeseq\n longstringitem ::= longstringchar | escapeseq\n shortstringchar ::= \n longstringchar ::= \n escapeseq ::= "\\" \n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the "stringprefix" and the rest of\nthe string literal. The source character set is defined by the\nencoding declaration; it is ASCII if no encoding declaration is given\nin the source file; see section Encoding declarations.\n\nIn plain English: String literals can be enclosed in matching single\nquotes ("\'") or double quotes ("""). They can also be enclosed in\nmatching groups of three single or double quotes (these are generally\nreferred to as *triple-quoted strings*). The backslash ("\\")\ncharacter is used to escape characters that otherwise have a special\nmeaning, such as newline, backslash itself, or the quote character.\nString literals may optionally be prefixed with a letter "\'r\'" or\n"\'R\'"; such strings are called *raw strings* and use different rules\nfor interpreting backslash escape sequences. A prefix of "\'u\'" or\n"\'U\'" makes the string a Unicode string. Unicode strings use the\nUnicode character set as defined by the Unicode Consortium and ISO\n10646. Some additional escape sequences, described below, are\navailable in Unicode strings. A prefix of "\'b\'" or "\'B\'" is ignored in\nPython 2; it indicates that the literal should become a bytes literal\nin Python 3 (e.g. when code is automatically converted with 2to3). A\n"\'u\'" or "\'b\'" prefix may be followed by an "\'r\'" prefix.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string. (A "quote" is the character used to open the\nstring, i.e. either "\'" or """.)\n\nUnless an "\'r\'" or "\'R\'" prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C. The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence | Meaning | Notes |\n+===================+===================================+=========+\n| "\\newline" | Ignored | |\n+-------------------+-----------------------------------+---------+\n| "\\\\" | Backslash ("\\") | |\n+-------------------+-----------------------------------+---------+\n| "\\\'" | Single quote ("\'") | |\n+-------------------+-----------------------------------+---------+\n| "\\"" | Double quote (""") | |\n+-------------------+-----------------------------------+---------+\n| "\\a" | ASCII Bell (BEL) | |\n+-------------------+-----------------------------------+---------+\n| "\\b" | ASCII Backspace (BS) | |\n+-------------------+-----------------------------------+---------+\n| "\\f" | ASCII Formfeed (FF) | |\n+-------------------+-----------------------------------+---------+\n| "\\n" | ASCII Linefeed (LF) | |\n+-------------------+-----------------------------------+---------+\n| "\\N{name}" | Character named *name* in the | |\n| | Unicode database (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| "\\r" | ASCII Carriage Return (CR) | |\n+-------------------+-----------------------------------+---------+\n| "\\t" | ASCII Horizontal Tab (TAB) | |\n+-------------------+-----------------------------------+---------+\n| "\\uxxxx" | Character with 16-bit hex value | (1) |\n| | *xxxx* (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| "\\Uxxxxxxxx" | Character with 32-bit hex value | (2) |\n| | *xxxxxxxx* (Unicode only) | |\n+-------------------+-----------------------------------+---------+\n| "\\v" | ASCII Vertical Tab (VT) | |\n+-------------------+-----------------------------------+---------+\n| "\\ooo" | Character with octal value *ooo* | (3,5) |\n+-------------------+-----------------------------------+---------+\n| "\\xhh" | Character with hex value *hh* | (4,5) |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. Individual code units which form parts of a surrogate pair can\n be encoded using this escape sequence.\n\n2. Any Unicode character can be encoded this way, but characters\n outside the Basic Multilingual Plane (BMP) will be encoded using a\n surrogate pair if Python is compiled to use 16-bit code units (the\n default).\n\n3. As in Standard C, up to three octal digits are accepted.\n\n4. Unlike in Standard C, exactly two hex digits are required.\n\n5. In a string literal, hexadecimal and octal escapes denote the\n byte with the given value; it is not necessary that the byte\n encodes a character in the source character set. In a Unicode\n literal, these escapes denote a Unicode character with the given\n value.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*. (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.) It is also\nimportant to note that the escape sequences marked as "(Unicode only)"\nin the table above fall into the category of unrecognized escapes for\nnon-Unicode string literals.\n\nWhen an "\'r\'" or "\'R\'" prefix is present, a character following a\nbackslash is included in the string without change, and *all\nbackslashes are left in the string*. For example, the string literal\n"r"\\n"" consists of two characters: a backslash and a lowercase "\'n\'".\nString quotes can be escaped with a backslash, but the backslash\nremains in the string; for example, "r"\\""" is a valid string literal\nconsisting of two characters: a backslash and a double quote; "r"\\""\nis not a valid string literal (even a raw string cannot end in an odd\nnumber of backslashes). Specifically, *a raw string cannot end in a\nsingle backslash* (since the backslash would escape the following\nquote character). Note also that a single backslash followed by a\nnewline is interpreted as those two characters as part of the string,\n*not* as a line continuation.\n\nWhen an "\'r\'" or "\'R\'" prefix is used in conjunction with a "\'u\'" or\n"\'U\'" prefix, then the "\\uXXXX" and "\\UXXXXXXXX" escape sequences are\nprocessed while *all other backslashes are left in the string*. For\nexample, the string literal "ur"\\u0062\\n"" consists of three Unicode\ncharacters: \'LATIN SMALL LETTER B\', \'REVERSE SOLIDUS\', and \'LATIN\nSMALL LETTER N\'. Backslashes can be escaped with a preceding\nbackslash; however, both remain in the string. As a result, "\\uXXXX"\nescape sequences are only recognized when there are an odd number of\nbackslashes.\n', ++ 'subscriptions': u'\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 "x".)\nThe resulting value must be a nonnegative integer less than the number\nof items in the sequence, and the subscription selects the item whose\nindex 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': u'\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", "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 the\n 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, unless\notherwise stated. (Important exception: the Boolean operations "or"\nand "and" always return one of their operands.)\n', ++ 'try': u'\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" | ",") identifier]] ":" 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" had to be\nnested in "try"..."finally".\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started. This search inspects the except clauses\nin turn until one is found that matches the exception. An expression-\nless except clause, if present, must be last; it matches any\nexception. For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception. An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject, or a tuple containing an item compatible with the exception.\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 raised\nthe 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 are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler. The "try"\nclause is executed, including any "except" and "else" clauses. If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed. If\nthere is a saved exception, it is re-raised at the end of the\n"finally" clause. If the "finally" clause raises another exception or\nexecutes a "return" or "break" statement, the saved exception is\ndiscarded:\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 the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed. Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n >>> def foo():\n ... try:\n ... return \'try\'\n ... finally:\n ... return \'finally\'\n ...\n >>> foo()\n \'finally\'\n\nAdditional information on exceptions can be found in section\nExceptions, and information on using the "raise" statement to generate\nexceptions may be found in section The raise statement.\n', ++ 'types': u'\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". It\n is used to signify the absence of a value in many situations, e.g.,\n 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 "..." syntax\n 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\n only 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 are\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 items\n of a sequence. When the length of a sequence is *n*, the index set\n contains the numbers 0, 1, ..., *n*-1. Item *i* of sequence *a* is\n 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* where\n "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *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 built-\n 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 a\n 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 immutable\n and *hashable*, it can be used again as an element of another\n 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 "k"\n from the mapping "a"; this can be used in expressions and as the\n target of assignments or "del" statements. The built-in function\n "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 "1.0")\n 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__" "func_doc" | The function\'s documentation | Writable |\n | | string, or "None" if | |\n | | unavailable. | |\n +-------------------------+---------------------------------+-------------+\n | "__name__" "func_name" | The function\'s name. | Writable |\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 have | |\n | | a default value. | |\n +-------------------------+---------------------------------+-------------+\n | "__code__" "func_code" | The code object representing | Writable |\n | | 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__" "func_dict" | The namespace supporting | Writable |\n | | arbitrary function attributes. | |\n +-------------------------+---------------------------------+-------------+\n | "__closure__" | "None" or a tuple of cells that | Read-only |\n | "func_closure" | 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 "__globals__"\n were introduced as aliases for the corresponding "func_*"\n 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 for\n 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 the\n 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" as\n "__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 unbound.\n When one is created by retrieving a user-defined function object\n from a class via one of its instances, its "im_self" attribute\n is the instance, and the method object is said to be bound. In\n either case, the new method\'s "im_class" attribute is the class\n from which the retrieval takes place, and its "im_func"\n 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 restriction\n that the first argument must be an instance of the proper class\n ("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 a\n function "f()", and "x" is an instance of "C", calling "x.f(1)"\n 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 "C.f(1)"\n is equivalent to calling "f(C,1)" where "f" is the underlying\n 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 the\n end, a "StopIteration" exception is raised and the iterator will\n have reached the end of the set of values to be 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 function\'s\n name; "__self__" is set to "None" (but see the next item);\n "__module__" is the name of the module the function was defined\n 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, the\n 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 a\n 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 name;\n "__doc__" is the module\'s documentation string, or "None" if\n unavailable; "__file__" is the pathname of the file from which the\n module was loaded, if it was loaded from a file. The "__file__"\n attribute is not present for C modules that are statically linked\n into the interpreter; for extension modules loaded dynamically from\n a shared library, it is the pathname of the 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 translated\n to "C.__dict__["x"]" (although for new-style classes in particular\n there are a number of hooks which allow for other means of locating\n attributes). When the attribute name is not found there, the\n attribute search continues in the base classes. For old-style\n classes, the search is depth-first, left-to-right in the order of\n occurrence in the base class list. New-style classes use the more\n complex C3 method resolution order which behaves correctly even in\n the presence of \'diamond\' inheritance structures where there are\n multiple inheritance paths leading back to a common ancestor.\n Additional details on the C3 MRO used by new-style classes can be\n found in the documentation accompanying the 2.3 release at\n https://www.python.org/download/releases/2.3/mro/.\n\n When a class attribute reference (for class "C", say) would yield a\n 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__" is\n the module name in which the class was defined; "__dict__" is the\n dictionary containing the class\'s namespace; "__bases__" is a tuple\n (possibly empty or a singleton) containing the base classes, in the\n order of their occurrence in the base class list; "__doc__" is the\n class\'s documentation string, or None if 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 the\n 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 instead\n 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 (and\n perhaps by other functions or methods provided by extension\n modules). The objects "sys.stdin", "sys.stdout" and "sys.stderr"\n are initialized to file objects corresponding to the interpreter\'s\n standard input, output and error streams. See File Objects for\n 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 name;\n "co_argcount" is the number of positional arguments (including\n arguments with default values); "co_nlocals" is the number of\n local variables used by the function (including arguments);\n "co_varnames" is a tuple containing the names of the local\n variables (starting with the argument names); "co_cellvars" is a\n tuple containing the names of local variables that are\n referenced by nested functions; "co_freevars" is a tuple\n containing the names of free variables; "co_code" is a string\n representing the sequence of bytecode instructions; "co_consts"\n is a tuple containing the literals used by the bytecode;\n "co_names" is a tuple containing the names used by the bytecode;\n "co_filename" is 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 a\n number of flags for the interpreter.\n\n The following flag bits are defined for "co_flags": bit "0x04"\n is set if the function uses the "*arguments" syntax to accept an\n arbitrary number of positional arguments; bit "0x08" is set if\n the function uses the "**keywords" syntax to accept arbitrary\n keyword arguments; bit "0x20" is set if the function is a\n generator.\n\n Future feature declarations ("from __future__ import division")\n also use bits in "co_flags" to indicate whether a code object\n was compiled with a particular feature enabled: bit "0x2000" is\n set if the function was compiled with future division enabled;\n bits "0x10" and "0x1000" were used in earlier versions of\n 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 stack\n frame (towards the caller), or "None" if this is the bottom\n stack frame; "f_code" is the code object being executed in this\n frame; "f_locals" is the dictionary used to look up local\n 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" is\n 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", and\n also as the third item of the tuple returned by\n "sys.exc_info()". The latter is the preferred interface, since\n it works correctly when the program is using multiple threads.\n When the program contains no suitable handler, the stack trace\n is written (nicely formatted) to the standard error stream; if\n the interpreter is interactive, it is also made available to the\n user as "sys.last_traceback".\n\n Special read-only attributes: "tb_next" is the next level in the\n stack trace (towards the frame where the exception occurred), or\n "None" if there is no next level; "tb_frame" points to the\n execution frame of the current level; "tb_lineno" gives the line\n number where the exception occurred; "tb_lasti" indicates the\n precise instruction. The line number and last instruction in\n the traceback may differ from the line number of its frame\n object if the exception occurred in a "try" statement with no\n matching except clause 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 the\n built-in "slice()" function.\n\n Special read-only attributes: "start" is the lower bound; "stop"\n is the upper bound; "step" is the step value; each is "None" if\n 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': u'\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': u'\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" module.)\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 index\nthe same dictionary entry. (Note however, that since computers store\nfloating-point numbers as approximations it is usually unwise to use\nthem as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of "key:\nvalue" pairs within braces, for example: "{\'jack\': 4098, \'sjoerd\':\n4127}" or "{4098: \'jack\', 4127: \'sjoerd\'}", or by the "dict"\nconstructor.\n\nclass dict(**kwarg)\nclass dict(mapping, **kwarg)\nclass 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 *iterable*\n object. Each item in the iterable must itself be an iterable 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 If a subclass of dict defines a method "__missing__()" and *key*\n is not present, the "d[key]" operation calls that method with\n the key *key* as argument. The "d[key]" operation then returns\n or raises whatever is returned or raised by the\n "__missing__(key)" call. No other operations or methods invoke\n "__missing__()". If "__missing__()" is not defined, "KeyError"\n is raised. "__missing__()" must be a method; it cannot be an\n instance variable:\n\n >>> class Counter(dict):\n ... def __missing__(self, key):\n ... return 0\n >>> c = Counter()\n >>> c[\'red\']\n 0\n >>> c[\'red\'] += 1\n >>> c[\'red\']\n 1\n\n The example above shows part of the implementation of\n "collections.Counter". A different "__missing__" method is used\n by "collections.defaultdict".\n\n New in version 2.5: Recognition of __missing__ methods of dict\n subclasses.\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 not\n 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", so\n 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)" 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()", "iterkeys()",\n and "itervalues()" are called with no intervening modifications\n to the dictionary, the lists will directly correspond. This\n allows the creation of "(value, key)" pairs using "zip()":\n "pairs = zip(d.values(), d.keys())". The same relationship\n holds for the "iterkeys()" and "itervalues()" methods: "pairs =\n zip(d.itervalues(), d.iterkeys())" provides the same value for\n "pairs". Another way to create the same list is "pairs = [(v, k)\n for (k, v) in 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 Dictionaries compare equal if and only if they have the same "(key,\n value)" pairs.\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 on\nthe 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 using\n "zip()": "pairs = zip(d.values(), d.keys())". Another way to\n create the same list is "pairs = [(v, k) for (k, v) in 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, values\n or items (in the latter case, *x* should be a "(key, value)"\n 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': u'\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as "append()" on lists)\nand class instance methods. Built-in methods are described with the\ntypes 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 will\nbe "None" and if called, an explicit "self" object must be passed as\nthe first argument. In this case, "self" must be an instance of the\nunbound method\'s class (or a subclass of that class), otherwise a\n"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': u'\nModules\n*******\n\nThe only special operation on a module is attribute access: "m.name",\nwhere *m* is a module and *name* accesses a name defined in *m*\'s\nsymbol table. Module attributes can be assigned to. (Note that the\n"import" statement is not, strictly speaking, an operation on a module\nobject; "import foo" does not require a module object named *foo* to\nexist, rather it requires an (external) *definition* for a module\nnamed *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 write\n"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", but you can\'t\nwrite "m.__dict__ = {}"). Modifying "__dict__" directly is not\nrecommended.\n\nModules built into the interpreter are written like this: "". If loaded from a file, they are written as\n"".\n', ++ 'typesseq': u'\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, and\nthe "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 addition to\nthe functionality described here, there are also string-specific\nmethods described in the String Methods section. Lists are constructed\nwith square brackets, separating items with commas: "[a, b, c]".\nTuples are constructed by the comma operator (not within square\nbrackets), with or without enclosing parentheses, but an empty tuple\nmust have the enclosing parentheses, such as "a, b, c" or "()". A\nsingle item tuple must have a trailing comma, such as "(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 them is\ninefficient.\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 the\ncorresponding numeric operations. [3] Additional methods are provided\nfor Mutable Sequence Types.\n\nThis table lists the sequence operations sorted in ascending priority.\nIn the table, *s* and *t* are sequences of the same type; *n*, *i* and\n*j* are integers:\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" | equivalent to adding *s* to | (2) |\n| | itself *n* times | |\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(x)" | index of the first occurrence of | |\n| | *x* in *s* | |\n+--------------------+----------------------------------+------------+\n| "s.count(x)" | total number of occurrences of | |\n| | *x* 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 reference.)\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 that items in the\n sequence *s* are not copied; they are referenced multiple times.\n This often haunts 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 references\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\n Further explanation is available in the FAQ entry How do I create a\n multidimensional list?.\n\n3. If *i* or *j* is negative, the index is relative to the end of\n the 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 "None",\n use "0". If *j* is omitted or "None", use "len(s)". If *i* is\n greater than or equal to *j*, the slice is 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", "i+2*k",\n "i+3*k" and so on, stopping when *j* is reached (but never\n including *j*). If *i* or *j* is greater than "len(s)", use\n "len(s)". If *i* or *j* are omitted or "None", they become "end"\n values (which end depends on the sign of *k*). Note, *k* cannot be\n zero. If *k* is "None", it is treated like "1".\n\n6. **CPython implementation detail:** If *s* and *t* are both\n strings, some Python implementations such as CPython can usually\n perform an in-place optimization for assignments of the form "s = s\n + t" or "s += t". When applicable, this optimization makes\n quadratic run-time much less likely. This optimization is both\n version and implementation dependent. For performance sensitive\n code, it is 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 "UnicodeError".\n Other possible values are "\'ignore\'", "\'replace\'",\n "\'xmlcharrefreplace\'", "\'backslashreplace\'" and any other name\n registered via "codecs.register_error()", see section Codec Base\n Classes. For a list of possible encodings, see section Standard\n 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 suffixes\n to look for. With optional *start*, test beginning at that\n position. With optional *end*, stop comparing at that 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 result\n until the current column is equal to the next tab position. (The\n tab character itself is not copied.) If the character is a newline\n ("\\n") or return ("\\r"), it is copied and the current column is\n reset to zero. Any other character is copied unchanged and the\n 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 within the slice "s[start:end]". Optional arguments *start*\n and *end* are interpreted as in slice notation. Return "-1" if\n *sub* is not found.\n\n Note: The "find()" method should be used only if you need to know\n the position of *sub*. To check if *sub* is a substring or not,\n use 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 String\n 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* is\n 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 splitting\n from the right, "rsplit()" behaves like "split()" which is\n 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* argument\n may consist of multiple characters (for example,\n "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n 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 For example, "\' 1 2 3 \'.split()" returns "[\'1\', \'2\', \'3\']", and\n "\' 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 "[\'ab\n c\', \'\', \'de fg\', \'kl\']", while the same call with\n "splitlines(True)" returns "[\'ab c\\n\', \'\\n\', \'de fg\\r\', \'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 return\n "False". *prefix* can also be a tuple of prefixes to look for.\n With optional *start*, test string beginning at that position.\n With optional *end*, stop comparing string at that 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 *chars*\n argument defaults to removing whitespace. The *chars* argument is\n not a prefix or suffix; rather, all combinations of its values are\n 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. Note,\n a more flexible approach is to create a custom character mapping\n codec using the "codecs" module (see "encodings.cp1251" for an\n 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 be\n "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, "False"\n otherwise. Numeric characters include digit characters, and all\n characters that have the Unicode numeric value property, e.g.\n U+2155, VULGAR FRACTION ONE FIFTH.\n\nunicode.isdecimal()\n\n Return "True" if there are only decimal characters in S, "False"\n otherwise. Decimal characters include digit characters, and all\n characters that can be used to form decimal-radix numbers, e.g.\n U+0660, ARABIC-INDIC DIGIT ZERO.\n\n\nString Formatting Operations\n============================\n\nString and Unicode objects have one unique built-in operation: the "%"\noperator (modulo). This is also known as the string *formatting* or\n*interpolation* operator. Given "format % values" (where *format* is\na string or Unicode object), "%" conversion specifications in *format*\nare replaced with zero or more elements of *values*. The effect is\nsimilar to the using "sprintf()" in the C language. If *format* is a\nUnicode object, or if any of the objects being converted using the\n"%s" conversion are Unicode objects, the result will also be a Unicode\nobject.\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\n of 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\'" conversion |\n| | 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 ignored as\nit is not necessary for Python -- so e.g. "%ld" is identical 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 not\nassume 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 "string"\nand "re".\n\n\nXRange Type\n===========\n\nThe "xrange" type is an immutable sequence which is commonly used for\nlooping. The advantage of the "xrange" type is that an "xrange"\nobject will always take the same amount of memory, no matter the size\nof the range it represents. There are no consistent performance\nadvantages.\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 allow\nin-place modification of the object. Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable 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)] = [x]" | (2) |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(x)" or "s += t" | for the most part the same as | (3) |\n| | "s[len(s):len(s)] = x" | |\n+--------------------------------+----------------------------------+-----------------------+\n| "s *= n" | updates *s* with its contents | (11) |\n| | repeated *n* times | |\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\n multiple parameters and implicitly joined them into a tuple; this\n no longer works in Python 2.0. Use of this misfeature has been\n deprecated 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\n negative index is passed as the second or third parameter to the\n "index()" method, the list length is added, as for slice indices.\n If it is still negative, it is truncated to zero, as for slice\n indices.\n\n Changed in version 2.3: Previously, "index()" didn\'t have arguments\n 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 indices.\n If it is still negative, it is truncated to zero, as for slice\n 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 to\n 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\n be 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\n sorted, the effect of attempting to mutate, or even inspect, the\n list is undefined. The C implementation of Python 2.3 and newer\n makes the list appear empty for the duration, and raises\n "ValueError" if it can detect that the list has been mutated\n during a sort.\n\n11. The value *n* is an integer, or an object implementing\n "__index__()". Zero and negative values of *n* clear the\n sequence. Items in the sequence are not copied; they are\n referenced multiple times, as explained for "s * n" under Sequence\n Types --- str, unicode, list, tuple, bytearray, buffer, xrange.\n', ++ 'typesseq-mutable': u'\nMutable Sequence Types\n**********************\n\nList and "bytearray" objects support additional operations that allow\nin-place modification of the object. Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable 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)] = [x]" | (2) |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(x)" or "s += t" | for the most part the same as | (3) |\n| | "s[len(s):len(s)] = x" | |\n+--------------------------------+----------------------------------+-----------------------+\n| "s *= n" | updates *s* with its contents | (11) |\n| | repeated *n* times | |\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\n multiple parameters and implicitly joined them into a tuple; this\n no longer works in Python 2.0. Use of this misfeature has been\n deprecated 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\n negative index is passed as the second or third parameter to the\n "index()" method, the list length is added, as for slice indices.\n If it is still negative, it is truncated to zero, as for slice\n indices.\n\n Changed in version 2.3: Previously, "index()" didn\'t have arguments\n 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 indices.\n If it is still negative, it is truncated to zero, as for slice\n 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 to\n 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\n be 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\n sorted, the effect of attempting to mutate, or even inspect, the\n list is undefined. The C implementation of Python 2.3 and newer\n makes the list appear empty for the duration, and raises\n "ValueError" if it can detect that the list has been mutated\n during a sort.\n\n11. The value *n* is an integer, or an object implementing\n "__index__()". Zero and negative values of *n* clear the\n sequence. Items in the sequence are not copied; they are\n referenced multiple times, as explained for "s * n" under Sequence\n Types --- str, unicode, list, tuple, bytearray, buffer, xrange.\n', ++ 'unary': u'\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': u'\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 executed\nand the loop terminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite. A "continue" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n', ++ 'with': u'\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 "try"..."except"..."finally"\nusage patterns to be encapsulated for 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 be\n 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, three\n "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 reraised.\n If the return value was true, the exception is suppressed, and\n execution continues with the statement following the "with"\n 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 in\n 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 "with"\n statement.\n', ++ 'yield': u'\nThe "yield" statement\n*********************\n\n yield_stmt ::= yield_expression\n\nThe "yield" statement is only used when defining a generator function,\nand is only used in the body of the generator function. Using a\n"yield" statement in a function definition is sufficient to cause that\ndefinition to create a generator function instead of a normal\nfunction.\n\nWhen a generator function is called, it returns an iterator known as a\ngenerator iterator, or more commonly, a generator. The body of the\ngenerator function is executed by calling the generator\'s "next()"\nmethod repeatedly until it raises an exception.\n\nWhen a "yield" statement is executed, the state of the generator is\nfrozen and the value of "expression_list" is returned to "next()"\'s\ncaller. By "frozen" we mean that all local state is retained,\nincluding the current bindings of local variables, the instruction\npointer, and the internal evaluation stack: enough information is\nsaved so that the next time "next()" is invoked, the function can\nproceed exactly as if the "yield" statement were just another external\ncall.\n\nAs of Python version 2.5, the "yield" statement is now allowed in the\n"try" clause of a "try" ... "finally" construct. If the generator is\nnot resumed before it is finalized (by reaching a zero reference count\nor by being garbage collected), the generator-iterator\'s "close()"\nmethod will be called, allowing any pending "finally" clauses to\nexecute.\n\nFor full details of "yield" semantics, refer to the Yield expressions\nsection.\n\nNote: In Python 2.2, the "yield" statement was only allowed when the\n "generators" feature has been enabled. This "__future__" import\n statement was used to enable the feature:\n\n from __future__ import generators\n\nSee also:\n\n **PEP 0255** - Simple Generators\n The proposal for adding generators and the "yield" statement to\n Python.\n\n **PEP 0342** - Coroutines via Enhanced Generators\n The proposal that, among other generator enhancements, proposed\n allowing "yield" to appear inside a "try" ... "finally" block.\n'} +diff -r 6d1b6a68f775 Lib/rlcompleter.py +--- a/Lib/rlcompleter.py ++++ b/Lib/rlcompleter.py +@@ -102,13 +102,16 @@ + """ + import keyword + matches = [] ++ seen = {"__builtins__"} + n = len(text) + for word in keyword.kwlist: + if word[:n] == text: ++ seen.add(word) + matches.append(word) +- for nspace in [__builtin__.__dict__, self.namespace]: ++ for nspace in [self.namespace, __builtin__.__dict__]: + for word, val in nspace.items(): +- if word[:n] == text and word != "__builtins__": ++ if word[:n] == text and word not in seen: ++ seen.add(word) + matches.append(self._callable_postfix(val, word)) + return matches + +diff -r 6d1b6a68f775 Lib/runpy.py +--- a/Lib/runpy.py ++++ b/Lib/runpy.py +@@ -97,27 +97,35 @@ + return None + + # Helper to get the loader, code and filename for a module +-def _get_module_details(mod_name): +- loader = get_loader(mod_name) +- if loader is None: +- raise ImportError("No module named %s" % mod_name) +- if loader.is_package(mod_name): ++def _get_module_details(mod_name, error=ImportError): ++ try: ++ loader = get_loader(mod_name) ++ if loader is None: ++ raise error("No module named %s" % mod_name) ++ ispkg = loader.is_package(mod_name) ++ except ImportError as e: ++ raise error(format(e)) ++ if ispkg: + if mod_name == "__main__" or mod_name.endswith(".__main__"): +- raise ImportError("Cannot use package as __main__ module") ++ raise error("Cannot use package as __main__ module") ++ __import__(mod_name) # Do not catch exceptions initializing package + try: + pkg_main_name = mod_name + ".__main__" + return _get_module_details(pkg_main_name) + except ImportError, e: +- raise ImportError(("%s; %r is a package and cannot " + ++ raise error(("%s; %r is a package and cannot " + + "be directly executed") %(e, mod_name)) +- code = loader.get_code(mod_name) ++ try: ++ code = loader.get_code(mod_name) ++ except ImportError as e: ++ raise error(format(e)) + if code is None: +- raise ImportError("No code object available for %s" % mod_name) ++ raise error("No code object available for %s" % mod_name) + filename = _get_filename(loader, mod_name) + return mod_name, loader, code, filename + + +-def _get_main_module_details(): ++def _get_main_module_details(error=ImportError): + # Helper that gives a nicer error message when attempting to + # execute a zipfile or directory by invoking __main__.py + main_name = "__main__" +@@ -125,10 +133,13 @@ + return _get_module_details(main_name) + except ImportError as exc: + if main_name in str(exc): +- raise ImportError("can't find %r module in %r" % ++ raise error("can't find %r module in %r" % + (main_name, sys.path[0])) + raise + ++class _Error(Exception): ++ """Error that _run_module_as_main() should report without a traceback""" ++ + # This function is the actual implementation of the -m switch and direct + # execution of zipfiles and directories and is deliberately kept private. + # This avoids a repeat of the situation where run_module() no longer met the +@@ -148,11 +159,12 @@ + """ + try: + if alter_argv or mod_name != "__main__": # i.e. -m switch +- mod_name, loader, code, fname = _get_module_details(mod_name) ++ mod_name, loader, code, fname = _get_module_details( ++ mod_name, _Error) + else: # i.e. directory or zipfile execution +- mod_name, loader, code, fname = _get_main_module_details() +- except ImportError as exc: +- msg = "%s: %s" % (sys.executable, str(exc)) ++ mod_name, loader, code, fname = _get_main_module_details(_Error) ++ except _Error as exc: ++ msg = "%s: %s" % (sys.executable, exc) + sys.exit(msg) + pkg_name = mod_name.rpartition('.')[0] + main_globals = sys.modules["__main__"].__dict__ +diff -r 6d1b6a68f775 Lib/sre_parse.py +--- a/Lib/sre_parse.py ++++ b/Lib/sre_parse.py +@@ -721,14 +721,14 @@ + elif tail: + raise error, "bogus characters at end of regular expression" + +- if flags & SRE_FLAG_DEBUG: +- p.dump() +- + if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE: + # the VERBOSE flag was switched on inside the pattern. to be + # on the safe side, we'll parse the whole thing again... + return parse(str, p.pattern.flags) + ++ if flags & SRE_FLAG_DEBUG: ++ p.dump() ++ + return p + + def parse_template(source, pattern): +diff -r 6d1b6a68f775 Lib/ssl.py +--- a/Lib/ssl.py ++++ b/Lib/ssl.py +@@ -380,7 +380,8 @@ + if encoding == "x509_asn": + if trust is True or purpose.oid in trust: + certs.extend(cert) +- self.load_verify_locations(cadata=certs) ++ if certs: ++ self.load_verify_locations(cadata=certs) + return certs + + def load_default_certs(self, purpose=Purpose.SERVER_AUTH): +diff -r 6d1b6a68f775 Lib/subprocess.py +--- a/Lib/subprocess.py ++++ b/Lib/subprocess.py +@@ -498,7 +498,6 @@ + 'ignore_environment': 'E', + 'verbose': 'v', + 'bytes_warning': 'b', +- 'hash_randomization': 'R', + 'py3k_warning': '3', + } + args = [] +@@ -506,6 +505,8 @@ + v = getattr(sys.flags, flag) + if v > 0: + args.append('-' + opt * v) ++ if getattr(sys.flags, 'hash_randomization') != 0: ++ args.append('-R') + for opt in sys.warnoptions: + args.append('-W' + opt) + return args +@@ -1312,8 +1313,12 @@ + os.close(errpipe_write) + + # Wait for exec to fail or succeed; possibly raising exception +- # Exception limited to 1M + data = _eintr_retry_call(os.read, errpipe_read, 1048576) ++ pickle_bits = [data] ++ while data: ++ pickle_bits.append(data) ++ data = _eintr_retry_call(os.read, errpipe_read, 1048576) ++ data = "".join(pickle_bits) + finally: + if p2cread is not None and p2cwrite is not None: + _close_in_parent(p2cread) +diff -r 6d1b6a68f775 Lib/tarfile.py +--- a/Lib/tarfile.py ++++ b/Lib/tarfile.py +@@ -1844,11 +1844,12 @@ + return [tarinfo.name for tarinfo in self.getmembers()] + + def gettarinfo(self, name=None, arcname=None, fileobj=None): +- """Create a TarInfo object for either the file `name' or the file +- object `fileobj' (using os.fstat on its file descriptor). You can +- modify some of the TarInfo's attributes before you add it using +- addfile(). If given, `arcname' specifies an alternative name for the +- file in the archive. ++ """Create a TarInfo object from the result of os.stat or equivalent ++ on an existing file. The file is either named by `name', or ++ specified as a file object `fileobj' with a file descriptor. If ++ given, `arcname' specifies an alternative name for the file in the ++ archive, otherwise, the name is taken from the 'name' attribute of ++ 'fileobj', or the 'name' argument. + """ + self._check("aw") + +@@ -1869,7 +1870,7 @@ + # Now, fill the TarInfo object with + # information specific for the file. + tarinfo = self.tarinfo() +- tarinfo.tarfile = self ++ tarinfo.tarfile = self # Not needed + + # Use os.stat or os.lstat, depending on platform + # and if symlinks shall be resolved. +@@ -2034,7 +2035,7 @@ + def addfile(self, tarinfo, fileobj=None): + """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is + given, tarinfo.size bytes are read from it and added to the archive. +- You can create TarInfo objects using gettarinfo(). ++ You can create TarInfo objects directly, or by using gettarinfo(). + On Windows platforms, `fileobj' should always be opened with mode + 'rb' to avoid irritation about the file size. + """ +diff -r 6d1b6a68f775 Lib/tempfile.py +--- a/Lib/tempfile.py ++++ b/Lib/tempfile.py +@@ -455,8 +455,8 @@ + The file is created as mkstemp() would do it. + + Returns an object with a file-like interface; the name of the file +- is accessible as file.name. The file will be automatically deleted +- when it is closed unless the 'delete' argument is set to False. ++ is accessible as its 'name' attribute. The file will be automatically ++ deleted when it is closed unless the 'delete' argument is set to False. + """ + + if dir is None: +@@ -476,7 +476,8 @@ + try: + file = _os.fdopen(fd, mode, bufsize) + return _TemporaryFileWrapper(file, name, delete) +- except: ++ except BaseException: ++ _os.unlink(name) + _os.close(fd) + raise + +diff -r 6d1b6a68f775 Lib/test/capath/0e4015b9.0 +--- /dev/null ++++ b/Lib/test/capath/0e4015b9.0 +@@ -0,0 +1,16 @@ ++-----BEGIN CERTIFICATE----- ++MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV ++BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u ++IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv ++bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG ++A1UEBhMCWFkxFzAVBgNVBAcMDkNhc3RsZSBBbnRocmF4MSMwIQYDVQQKDBpQeXRo ++b24gU29mdHdhcmUgRm91bmRhdGlvbjEjMCEGA1UEAwwac2VsZi1zaWduZWQucHl0 ++aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ ++Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm ++Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv ++EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl ++bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN ++AQEFBQADgYEAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h ++TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515 ++C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM= ++-----END CERTIFICATE----- +diff -r 6d1b6a68f775 Lib/test/capath/ce7b8643.0 +--- /dev/null ++++ b/Lib/test/capath/ce7b8643.0 +@@ -0,0 +1,16 @@ ++-----BEGIN CERTIFICATE----- ++MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV ++BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u ++IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv ++bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG ++A1UEBhMCWFkxFzAVBgNVBAcMDkNhc3RsZSBBbnRocmF4MSMwIQYDVQQKDBpQeXRo ++b24gU29mdHdhcmUgRm91bmRhdGlvbjEjMCEGA1UEAwwac2VsZi1zaWduZWQucHl0 ++aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ ++Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm ++Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv ++EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl ++bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN ++AQEFBQADgYEAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h ++TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515 ++C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM= ++-----END CERTIFICATE----- +diff -r 6d1b6a68f775 Lib/test/https_svn_python_org_root.pem +--- a/Lib/test/https_svn_python_org_root.pem ++++ /dev/null +@@ -1,41 +0,0 @@ +------BEGIN CERTIFICATE----- +-MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290 +-IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB +-IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA +-Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO +-BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi +-MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ +-ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +-CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ +-8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6 +-zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y +-fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7 +-w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc +-G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k +-epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q +-laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ +-QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU +-fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826 +-YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w +-ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY +-gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe +-MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0 +-IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy +-dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw +-czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0 +-dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl +-aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC +-AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg +-b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB +-ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc +-nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg +-18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c +-gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl +-Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY +-sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T +-SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF +-CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum +-GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk +-zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW +-omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD +------END CERTIFICATE----- +diff -r 6d1b6a68f775 Lib/test/pickletester.py +--- a/Lib/test/pickletester.py ++++ b/Lib/test/pickletester.py +@@ -6,7 +6,9 @@ + import cStringIO + import pickletools + import copy_reg ++import sys + ++from test import test_support as support + from test.test_support import TestFailed, verbose, have_unicode, TESTFN + try: + from test.test_support import _2G, _1M, precisionbigmemtest +@@ -58,6 +60,21 @@ + return inner + return decorator + ++def no_tracing(func): ++ """Decorator to temporarily turn off tracing for the duration of a test.""" ++ if not hasattr(sys, 'gettrace'): ++ return func ++ else: ++ def wrapper(*args, **kwargs): ++ original_trace = sys.gettrace() ++ try: ++ sys.settrace(None) ++ return func(*args, **kwargs) ++ finally: ++ sys.settrace(original_trace) ++ wrapper.__name__ = func.__name__ ++ return wrapper ++ + + # Return True if opcode code appears in the pickle, else False. + def opcode_in_pickle(code, pickle): +@@ -74,6 +91,16 @@ + n += 1 + return n + ++class UnseekableIO(StringIO.StringIO): ++ def peek(self, *args): ++ raise NotImplementedError ++ ++ def seek(self, *args): ++ raise NotImplementedError ++ ++ def tell(self): ++ raise NotImplementedError ++ + # We can't very well test the extension registry without putting known stuff + # in it, but we have to be careful to restore its original state. Code + # should do this: +@@ -473,6 +500,24 @@ + self.assertEqual(getattr(obj, slot, None), + getattr(objcopy, slot, None), msg=msg) + ++ def check_unpickling_error(self, errors, data): ++ try: ++ try: ++ self.loads(data) ++ except: ++ if support.verbose > 1: ++ exc_type, exc, tb = sys.exc_info() ++ print '%-32r - %s: %s' % (data, exc_type.__name__, exc) ++ raise ++ except errors: ++ pass ++ else: ++ try: ++ exc_name = errors.__name__ ++ except AttributeError: ++ exc_name = str(errors) ++ raise self.failureException('%s not raised' % exc_name) ++ + def test_load_from_canned_string(self): + expected = self._testdata + for canned in DATA0, DATA1, DATA2: +@@ -480,7 +525,7 @@ + self.assert_is_copy(expected, got) + + def test_garyp(self): +- self.assertRaises(self.error, self.loads, 'garyp') ++ self.check_unpickling_error(self.error, 'garyp') + + def test_maxint64(self): + maxint64 = (1L << 63) - 1 +@@ -490,7 +535,7 @@ + + # Try too with a bogus literal. + data = 'I' + str(maxint64) + 'JUNK\n.' +- self.assertRaises(ValueError, self.loads, data) ++ self.check_unpickling_error(ValueError, data) + + def test_insecure_strings(self): + insecure = ["abc", "2 + 2", # not quoted +@@ -511,7 +556,7 @@ + ] + for s in insecure: + buf = "S" + s + "\n." +- self.assertRaises(ValueError, self.loads, buf) ++ self.check_unpickling_error(ValueError, buf) + + def test_correctly_quoted_string(self): + goodpickles = [("S''\n.", ''), +@@ -578,11 +623,6 @@ + 'q\x00oq\x01}q\x02b.').replace('X', xname) + self.assert_is_copy(X(*args), self.loads(pickle2)) + +- def test_pop_empty_stack(self): +- # Test issue7455 +- s = '0' +- self.assertRaises((cPickle.UnpicklingError, IndexError), self.loads, s) +- + def test_load_str(self): + # From Python 2: pickle.dumps('a\x00\xa0', protocol=0) + self.assertEqual(self.loads("S'a\\x00\\xa0'\n."), 'a\x00\xa0') +@@ -607,8 +647,8 @@ + self.assertIs(self.loads('I00\n.'), False) + + def test_misc_get(self): +- self.assertRaises(self.error, self.loads, 'g0\np0\n') +- self.assertRaises(self.error, self.loads, 'h\x00q\x00') ++ self.check_unpickling_error(self.error, 'g0\np0\n') ++ self.check_unpickling_error(self.error, 'h\x00q\x00') + + def test_get(self): + pickled = '((lp100000\ng100000\nt.' +@@ -634,6 +674,148 @@ + self.assertEqual(unpickled, ([],)*2) + self.assertIs(unpickled[0], unpickled[1]) + ++ def test_bad_stack(self): ++ badpickles = [ ++ '.', # STOP ++ '0', # POP ++ '1', # POP_MARK ++ '2', # DUP ++ # '(2', # PyUnpickler doesn't raise ++ 'R', # REDUCE ++ ')R', ++ 'a', # APPEND ++ 'Na', ++ 'b', # BUILD ++ 'Nb', ++ 'd', # DICT ++ 'e', # APPENDS ++ # '(e', # PyUnpickler raises AttributeError ++ 'i__builtin__\nlist\n', # INST ++ 'l', # LIST ++ 'o', # OBJ ++ '(o', ++ 'p1\n', # PUT ++ 'q\x00', # BINPUT ++ 'r\x00\x00\x00\x00', # LONG_BINPUT ++ 's', # SETITEM ++ 'Ns', ++ 'NNs', ++ 't', # TUPLE ++ 'u', # SETITEMS ++ # '(u', # PyUnpickler doesn't raise ++ '}(Nu', ++ '\x81', # NEWOBJ ++ ')\x81', ++ '\x85', # TUPLE1 ++ '\x86', # TUPLE2 ++ 'N\x86', ++ '\x87', # TUPLE3 ++ 'N\x87', ++ 'NN\x87', ++ ] ++ for p in badpickles: ++ self.check_unpickling_error(self.bad_stack_errors, p) ++ ++ def test_bad_mark(self): ++ badpickles = [ ++ # 'N(.', # STOP ++ 'N(2', # DUP ++ 'c__builtin__\nlist\n)(R', # REDUCE ++ 'c__builtin__\nlist\n()R', ++ ']N(a', # APPEND ++ # BUILD ++ 'c__builtin__\nValueError\n)R}(b', ++ 'c__builtin__\nValueError\n)R(}b', ++ '(Nd', # DICT ++ 'N(p1\n', # PUT ++ 'N(q\x00', # BINPUT ++ 'N(r\x00\x00\x00\x00', # LONG_BINPUT ++ '}NN(s', # SETITEM ++ '}N(Ns', ++ '}(NNs', ++ '}((u', # SETITEMS ++ # NEWOBJ ++ 'c__builtin__\nlist\n)(\x81', ++ 'c__builtin__\nlist\n()\x81', ++ 'N(\x85', # TUPLE1 ++ 'NN(\x86', # TUPLE2 ++ 'N(N\x86', ++ 'NNN(\x87', # TUPLE3 ++ 'NN(N\x87', ++ 'N(NN\x87', ++ ] ++ for p in badpickles: ++ self.check_unpickling_error(self.bad_mark_errors, p) ++ ++ def test_truncated_data(self): ++ self.check_unpickling_error(EOFError, '') ++ self.check_unpickling_error(EOFError, 'N') ++ badpickles = [ ++ 'F', # FLOAT ++ 'F0.0', ++ 'F0.00', ++ 'G', # BINFLOAT ++ 'G\x00\x00\x00\x00\x00\x00\x00', ++ 'I', # INT ++ 'I0', ++ 'J', # BININT ++ 'J\x00\x00\x00', ++ 'K', # BININT1 ++ 'L', # LONG ++ 'L0', ++ 'L10', ++ 'L0L', ++ 'L10L', ++ 'M', # BININT2 ++ 'M\x00', ++ # 'P', # PERSID ++ # 'Pabc', ++ 'S', # STRING ++ "S'abc'", ++ 'T', # BINSTRING ++ 'T\x03\x00\x00', ++ 'T\x03\x00\x00\x00', ++ 'T\x03\x00\x00\x00ab', ++ 'U', # SHORT_BINSTRING ++ 'U\x03', ++ 'U\x03ab', ++ 'V', # UNICODE ++ 'Vabc', ++ 'X', # BINUNICODE ++ 'X\x03\x00\x00', ++ 'X\x03\x00\x00\x00', ++ 'X\x03\x00\x00\x00ab', ++ '(c', # GLOBAL ++ '(c__builtin__', ++ '(c__builtin__\n', ++ '(c__builtin__\nlist', ++ 'Ng', # GET ++ 'Ng0', ++ '(i', # INST ++ '(i__builtin__', ++ '(i__builtin__\n', ++ '(i__builtin__\nlist', ++ 'Nh', # BINGET ++ 'Nj', # LONG_BINGET ++ 'Nj\x00\x00\x00', ++ 'Np', # PUT ++ 'Np0', ++ 'Nq', # BINPUT ++ 'Nr', # LONG_BINPUT ++ 'Nr\x00\x00\x00', ++ '\x80', # PROTO ++ '\x82', # EXT1 ++ '\x83', # EXT2 ++ '\x84\x01', ++ '\x84', # EXT4 ++ '\x84\x01\x00\x00', ++ '\x8a', # LONG1 ++ '\x8b', # LONG4 ++ '\x8b\x00\x00\x00', ++ ] ++ for p in badpickles: ++ self.check_unpickling_error(self.truncated_errors, p) ++ + + class AbstractPickleTests(unittest.TestCase): + # Subclass must define self.dumps, self.loads. +@@ -765,6 +947,7 @@ + for proto in protocols: + s = self.dumps(i, proto) + x = self.loads(s) ++ self.assertIsInstance(x, C) + self.assertEqual(dir(x), dir(i)) + self.assertIs(x.attr, x) + +@@ -777,6 +960,7 @@ + for proto in protocols: + s = self.dumps(l, proto) + x = self.loads(s) ++ self.assertIsInstance(x, list) + self.assertEqual(len(x), 1) + self.assertEqual(dir(x[0]), dir(i)) + self.assertEqual(x[0].attr.keys(), [1]) +@@ -821,7 +1005,9 @@ + if have_unicode: + def test_unicode(self): + endcases = [u'', u'<\\u>', u'<\\\u1234>', u'<\n>', +- u'<\\>', u'<\\\U00012345>'] ++ u'<\\>', u'<\\\U00012345>', ++ # surrogates ++ u'<\udc80>'] + for proto in protocols: + for u in endcases: + p = self.dumps(u, proto) +@@ -900,6 +1086,7 @@ + s = self.dumps(a, proto) + b = self.loads(s) + self.assertEqual(a, b) ++ self.assertIs(a.__class__, b.__class__) + + def test_structseq(self): + import time +@@ -1045,6 +1232,26 @@ + self.assertEqual(B(x), B(y), detail) + self.assertEqual(x.__dict__, y.__dict__, detail) + ++ def test_newobj_proxies(self): ++ # NEWOBJ should use the __class__ rather than the raw type ++ import weakref ++ classes = myclasses[:] ++ # Cannot create weakproxies to these classes ++ for c in (MyInt, MyLong, MyStr, MyTuple): ++ classes.remove(c) ++ for proto in protocols: ++ for C in classes: ++ B = C.__base__ ++ x = C(C.sample) ++ x.foo = 42 ++ p = weakref.proxy(x) ++ s = self.dumps(p, proto) ++ y = self.loads(s) ++ self.assertEqual(type(y), type(x)) # rather than type(p) ++ detail = (proto, C, B, x, y, type(y)) ++ self.assertEqual(B(x), B(y), detail) ++ self.assertEqual(x.__dict__, y.__dict__, detail) ++ + # Register a type with copy_reg, with extension code extcode. Pickle + # an object of that type. Check that the resulting pickle uses opcode + # (EXT[124]) under proto 2, and not in proto 1. +@@ -1139,10 +1346,30 @@ + self.assertTrue(num_setitems >= 2) + + def test_simple_newobj(self): +- x = object.__new__(SimpleNewObj) # avoid __init__ ++ x = SimpleNewObj.__new__(SimpleNewObj, 0xface) # avoid __init__ + x.abc = 666 + for proto in protocols: + s = self.dumps(x, proto) ++ if proto < 1: ++ self.assertIn('\nI64206', s) # INT ++ else: ++ self.assertIn('M\xce\xfa', s) # BININT2 ++ self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2) ++ y = self.loads(s) # will raise TypeError if __init__ called ++ self.assertEqual(y.abc, 666) ++ self.assertEqual(x.__dict__, y.__dict__) ++ ++ def test_complex_newobj(self): ++ x = ComplexNewObj.__new__(ComplexNewObj, 0xface) # avoid __init__ ++ x.abc = 666 ++ for proto in protocols: ++ s = self.dumps(x, proto) ++ if proto < 1: ++ self.assertIn('\nI64206', s) # INT ++ elif proto < 2: ++ self.assertIn('M\xce\xfa', s) # BININT2 ++ else: ++ self.assertIn('U\x04FACE', s) # SHORT_BINSTRING + self.assertEqual(opcode_in_pickle(pickle.NEWOBJ, s), proto >= 2) + y = self.loads(s) # will raise TypeError if __init__ called + self.assertEqual(y.abc, 666) +@@ -1204,6 +1431,13 @@ + y = self.loads(s) + self.assertEqual(y._reduce_called, 1) + ++ @no_tracing ++ def test_bad_getattr(self): ++ # Issue #3514: crash when there is an infinite loop in __getattr__ ++ x = BadGetattr() ++ for proto in protocols: ++ self.assertRaises(RuntimeError, self.dumps, x, proto) ++ + def test_reduce_bad_iterator(self): + # Issue4176: crash when 4th and 5th items of __reduce__() + # are not iterators +@@ -1216,15 +1450,16 @@ + # 5th item is not an iterator + return dict, (), None, None, [] + +- # Protocol 0 is less strict and also accept iterables. ++ # Protocol 0 in Python implementation is less strict and also accepts ++ # iterables. + for proto in protocols: + try: + self.dumps(C(), proto) +- except (AttributeError, pickle.PickleError, cPickle.PickleError): ++ except (AttributeError, pickle.PicklingError, cPickle.PicklingError): + pass + try: + self.dumps(D(), proto) +- except (AttributeError, pickle.PickleError, cPickle.PickleError): ++ except (AttributeError, pickle.PicklingError, cPickle.PicklingError): + pass + + def test_many_puts_and_gets(self): +@@ -1255,6 +1490,39 @@ + for x_key, y_key in zip(x_keys, y_keys): + self.assertIs(x_key, y_key) + ++ def test_large_pickles(self): ++ # Test the correctness of internal buffering routines when handling ++ # large data. ++ for proto in protocols: ++ data = (1, min, 'xy' * (30 * 1024), len) ++ dumped = self.dumps(data, proto) ++ loaded = self.loads(dumped) ++ self.assertEqual(len(loaded), len(data)) ++ self.assertEqual(loaded, data) ++ ++ def _check_pickling_with_opcode(self, obj, opcode, proto): ++ pickled = self.dumps(obj, proto) ++ self.assertTrue(opcode_in_pickle(opcode, pickled)) ++ unpickled = self.loads(pickled) ++ self.assertEqual(obj, unpickled) ++ ++ def test_appends_on_non_lists(self): ++ # Issue #17720 ++ obj = REX_six([1, 2, 3]) ++ for proto in protocols: ++ if proto == 0: ++ self._check_pickling_with_opcode(obj, pickle.APPEND, proto) ++ else: ++ self._check_pickling_with_opcode(obj, pickle.APPENDS, proto) ++ ++ def test_setitems_on_non_dicts(self): ++ obj = REX_seven({1: -1, 2: -2, 3: -3}) ++ for proto in protocols: ++ if proto == 0: ++ self._check_pickling_with_opcode(obj, pickle.SETITEM, proto) ++ else: ++ self._check_pickling_with_opcode(obj, pickle.SETITEMS, proto) ++ + + # Test classes for reduce_ex + +@@ -1294,6 +1562,39 @@ + return object.__reduce__(self) + # This one used to fail with infinite recursion + ++class REX_six(object): ++ """This class is used to check the 4th argument (list iterator) of ++ the reduce protocol. ++ """ ++ def __init__(self, items=None): ++ if items is None: ++ items = [] ++ self.items = items ++ def __eq__(self, other): ++ return type(self) is type(other) and self.items == other.items ++ def append(self, item): ++ self.items.append(item) ++ def extend(self, items): ++ for item in items: ++ self.append(item) ++ def __reduce__(self): ++ return type(self), (), None, iter(self.items), None ++ ++class REX_seven(object): ++ """This class is used to check the 5th argument (dict iterator) of ++ the reduce protocol. ++ """ ++ def __init__(self, table=None): ++ if table is None: ++ table = {} ++ self.table = table ++ def __eq__(self, other): ++ return type(self) is type(other) and self.table == other.table ++ def __setitem__(self, key, value): ++ self.table[key] = value ++ def __reduce__(self): ++ return type(self), (), None, None, iter(self.table.items()) ++ + # Test classes for newobj + + class MyInt(int): +@@ -1332,10 +1633,20 @@ + class SlotList(MyList): + __slots__ = ["foo"] + +-class SimpleNewObj(object): +- def __init__(self, a, b, c): ++class SimpleNewObj(int): ++ def __init__(self, *args, **kwargs): + # raise an error, to make sure this isn't called + raise TypeError("SimpleNewObj.__init__() didn't expect to get called") ++ def __eq__(self, other): ++ return int(self) == int(other) and self.__dict__ == other.__dict__ ++ ++class ComplexNewObj(SimpleNewObj): ++ def __getnewargs__(self): ++ return ('%X' % self, 16) ++ ++class BadGetattr: ++ def __getattr__(self, key): ++ self.foo + + class AbstractPickleModuleTests(unittest.TestCase): + +@@ -1396,11 +1707,7 @@ + # Test issue4298 + s = '\x58\0\0\0\x54' + self.assertRaises(EOFError, self.module.loads, s) +- # Test issue7455 +- s = '0' +- # XXX Why doesn't pickle raise UnpicklingError? +- self.assertRaises((IndexError, cPickle.UnpicklingError), +- self.module.loads, s) ++ + + class AbstractPersistentPicklerTests(unittest.TestCase): + +@@ -1554,6 +1861,46 @@ + f.seek(0) + self.assertEqual(unpickler.load(), data2) + ++ def _check_multiple_unpicklings(self, ioclass, seekable): ++ for proto in protocols: ++ data1 = [(x, str(x)) for x in xrange(2000)] + ["abcde", len] ++ f = ioclass() ++ pickler = self.pickler_class(f, protocol=proto) ++ pickler.dump(data1) ++ pickled = f.getvalue() ++ ++ N = 5 ++ f = ioclass(pickled * N) ++ unpickler = self.unpickler_class(f) ++ for i in xrange(N): ++ if seekable: ++ pos = f.tell() ++ self.assertEqual(unpickler.load(), data1) ++ if seekable: ++ self.assertEqual(f.tell(), pos + len(pickled)) ++ self.assertRaises(EOFError, unpickler.load) ++ ++ def test_multiple_unpicklings_seekable(self): ++ self._check_multiple_unpicklings(StringIO.StringIO, True) ++ ++ def test_multiple_unpicklings_unseekable(self): ++ self._check_multiple_unpicklings(UnseekableIO, False) ++ ++ def test_unpickling_buffering_readline(self): ++ # Issue #12687: the unpickler's buffering logic could fail with ++ # text mode opcodes. ++ import io ++ data = list(xrange(10)) ++ for proto in protocols: ++ for buf_size in xrange(1, 11): ++ f = io.BufferedRandom(io.BytesIO(), buffer_size=buf_size) ++ pickler = self.pickler_class(f, protocol=proto) ++ pickler.dump(data) ++ f.seek(0) ++ unpickler = self.unpickler_class(f) ++ self.assertEqual(unpickler.load(), data) ++ ++ + class BigmemPickleTests(unittest.TestCase): + + # Memory requirements: 1 byte per character for input strings, 1 byte +diff -r 6d1b6a68f775 Lib/test/regrtest.py +--- a/Lib/test/regrtest.py ++++ b/Lib/test/regrtest.py +@@ -462,7 +462,7 @@ + + test_times = [] + test_support.use_resources = use_resources +- save_modules = sys.modules.keys() ++ save_modules = set(sys.modules) + + def accumulate_result(test, result): + ok, test_time = result +diff -r 6d1b6a68f775 Lib/test/script_helper.py +--- a/Lib/test/script_helper.py ++++ b/Lib/test/script_helper.py +@@ -134,9 +134,9 @@ + # zip_file.close() + return zip_name, os.path.join(zip_name, name_in_zip) + +-def make_pkg(pkg_dir): ++def make_pkg(pkg_dir, init_source=''): + os.mkdir(pkg_dir) +- make_script(pkg_dir, '__init__', '') ++ make_script(pkg_dir, '__init__', init_source) + + def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, + source, depth=1, compiled=False): +diff -r 6d1b6a68f775 Lib/test/selfsigned_pythontestdotnet.pem +--- a/Lib/test/selfsigned_pythontestdotnet.pem ++++ b/Lib/test/selfsigned_pythontestdotnet.pem +@@ -1,5 +1,5 @@ + -----BEGIN CERTIFICATE----- +-MIIChzCCAfCgAwIBAgIJAKGU95wKR8pSMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV ++MIIClTCCAf6gAwIBAgIJAKGU95wKR8pTMA0GCSqGSIb3DQEBBQUAMHAxCzAJBgNV + BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u + IFNvZnR3YXJlIEZvdW5kYXRpb24xIzAhBgNVBAMMGnNlbGYtc2lnbmVkLnB5dGhv + bnRlc3QubmV0MB4XDTE0MTEwMjE4MDkyOVoXDTI0MTAzMDE4MDkyOVowcDELMAkG +@@ -8,9 +8,9 @@ + aG9udGVzdC5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANDXQXW9tjyZ + Xt0Iv2tLL1+jinr4wGg36ioLDLFkMf+2Y1GL0v0BnKYG4N1OKlAU15LXGeGer8vm + Sv/yIvmdrELvhAbbo3w4a9TMYQA4XkIVLdvu3mvNOAet+8PMJxn26dbDhG809ALv +-EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjKTAnMCUGA1UdEQQeMByCGnNl +-bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MA0GCSqGSIb3DQEBBQUAA4GBAIOXmdtM +-eG9qzP9TiXW/Gc/zI4cBfdCpC+Y4gOfC9bQUC7hefix4iO3+iZjgy3X/FaRxUUoV +-HKiXcXIaWqTSUWp45cSh0MbwZXudp6JIAptzdAhvvCrPKeC9i9GvxsPD4LtDAL97 +-vSaxQBezA7hdxZd90/EeyMgVZgAnTCnvAWX9 ++EHY57lQsBS3G59RZyBPVqAqmImWNJnVzAgMBAAGjNzA1MCUGA1UdEQQeMByCGnNl ++bGYtc2lnbmVkLnB5dGhvbnRlc3QubmV0MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcN ++AQEFBQADgYEAIuzAhgMouJpNdf3URCHIineyoSt6WK/9+eyUcjlKOrDoXNZaD72h ++TXMeKYoWvJyVcSLKL8ckPtDobgP2OTt0UkyAaj0n+ZHaqq1lH2yVfGUA1ILJv515 ++C8BqbvVZuqm3i7ygmw3bqE/lYMgOrYtXXnqOrz6nvsE6Yc9V9rFflOM= + -----END CERTIFICATE----- +diff -r 6d1b6a68f775 Lib/test/test__locale.py +--- a/Lib/test/test__locale.py ++++ b/Lib/test/test__locale.py +@@ -39,7 +39,9 @@ + known_numerics = { + 'en_US': ('.', ','), + 'de_DE' : (',', '.'), +- 'fr_FR.UTF-8' : (',', ' '), ++ # The French thousands separator may be a breaking or non-breaking space ++ # depending on the platform, so do not test it ++ 'fr_FR' : (',', ''), + 'ps_AF.UTF-8' : ('\xd9\xab', '\xd9\xac'), + } + +diff -r 6d1b6a68f775 Lib/test/test_base64.py +--- a/Lib/test/test_base64.py ++++ b/Lib/test/test_base64.py +@@ -137,9 +137,30 @@ + # Non-bytes + eq(base64.urlsafe_b64decode(bytearray('01a-b_cd')), '\xd3V\xbeo\xf7\x1d') + +- def test_b64decode_error(self): ++ def test_b64decode_padding_error(self): + self.assertRaises(TypeError, base64.b64decode, 'abc') + ++ def test_b64decode_invalid_chars(self): ++ # issue 1466065: Test some invalid characters. ++ tests = ((b'%3d==', b'\xdd'), ++ (b'$3d==', b'\xdd'), ++ (b'[==', b''), ++ (b'YW]3=', b'am'), ++ (b'3{d==', b'\xdd'), ++ (b'3d}==', b'\xdd'), ++ (b'@@', b''), ++ (b'!', b''), ++ (b'YWJj\nYWI=', b'abcab')) ++ for bstr, res in tests: ++ self.assertEqual(base64.b64decode(bstr), res) ++ self.assertEqual(base64.standard_b64decode(bstr), res) ++ self.assertEqual(base64.urlsafe_b64decode(bstr), res) ++ ++ # Normal alphabet characters not discarded when alternative given ++ res = b'\xFB\xEF\xBE\xFF\xFF\xFF' ++ self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res) ++ self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res) ++ + def test_b32encode(self): + eq = self.assertEqual + eq(base64.b32encode(''), '') +@@ -206,6 +227,10 @@ + eq(base64.b16decode('0102abcdef', True), '\x01\x02\xab\xcd\xef') + # Non-bytes + eq(base64.b16decode(bytearray("0102ABCDEF")), '\x01\x02\xab\xcd\xef') ++ # Non-alphabet characters ++ self.assertRaises(TypeError, base64.b16decode, '0102AG') ++ # Incorrect "padding" ++ self.assertRaises(TypeError, base64.b16decode, '010') + + + +diff -r 6d1b6a68f775 Lib/test/test_buffer.py +--- a/Lib/test/test_buffer.py ++++ b/Lib/test/test_buffer.py +@@ -4,6 +4,8 @@ + + """ + ++import copy ++import pickle + import sys + import unittest + from test import test_support +@@ -35,6 +37,18 @@ + buf = buffer(data, sys.maxsize, sys.maxsize) + self.assertEqual(buf[:4096], "") + ++ def test_copy(self): ++ buf = buffer(b'abc') ++ with self.assertRaises(TypeError): ++ copy.copy(buf) ++ ++ # See issue #22995 ++ ## def test_pickle(self): ++ ## buf = buffer(b'abc') ++ ## for proto in range(pickle.HIGHEST_PROTOCOL + 1): ++ ## with self.assertRaises(TypeError): ++ ## pickle.dumps(buf, proto) ++ + + def test_main(): + with test_support.check_py3k_warnings(("buffer.. not supported", +diff -r 6d1b6a68f775 Lib/test/test_builtin.py +--- a/Lib/test/test_builtin.py ++++ b/Lib/test/test_builtin.py +@@ -1682,6 +1682,134 @@ + data = 'The quick Brown fox Jumped over The lazy Dog'.split() + self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) + ++ ++class TestType(unittest.TestCase): ++ def test_new_type(self): ++ A = type('A', (), {}) ++ self.assertEqual(A.__name__, 'A') ++ self.assertEqual(A.__module__, __name__) ++ self.assertEqual(A.__bases__, (object,)) ++ self.assertIs(A.__base__, object) ++ x = A() ++ self.assertIs(type(x), A) ++ self.assertIs(x.__class__, A) ++ ++ class B: ++ def ham(self): ++ return 'ham%d' % self ++ C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self}) ++ self.assertEqual(C.__name__, 'C') ++ self.assertEqual(C.__module__, __name__) ++ self.assertEqual(C.__bases__, (B, int)) ++ self.assertIs(C.__base__, int) ++ self.assertIn('spam', C.__dict__) ++ self.assertNotIn('ham', C.__dict__) ++ x = C(42) ++ self.assertEqual(x, 42) ++ self.assertIs(type(x), C) ++ self.assertIs(x.__class__, C) ++ self.assertEqual(x.ham(), 'ham42') ++ self.assertEqual(x.spam(), 'spam42') ++ self.assertEqual(x.bit_length(), 6) ++ ++ def test_type_new_keywords(self): ++ class B: ++ def ham(self): ++ return 'ham%d' % self ++ C = type.__new__(type, ++ name='C', ++ bases=(B, int), ++ dict={'spam': lambda self: 'spam%s' % self}) ++ self.assertEqual(C.__name__, 'C') ++ self.assertEqual(C.__module__, __name__) ++ self.assertEqual(C.__bases__, (B, int)) ++ self.assertIs(C.__base__, int) ++ self.assertIn('spam', C.__dict__) ++ self.assertNotIn('ham', C.__dict__) ++ ++ def test_type_name(self): ++ for name in 'A', '\xc4', 'B.A', '42', '': ++ A = type(name, (), {}) ++ self.assertEqual(A.__name__, name) ++ self.assertEqual(A.__module__, __name__) ++ with self.assertRaises(ValueError): ++ type('A\x00B', (), {}) ++ with self.assertRaises(TypeError): ++ type(u'A', (), {}) ++ ++ C = type('C', (), {}) ++ for name in 'A', '\xc4', 'B.A', '42', '': ++ C.__name__ = name ++ self.assertEqual(C.__name__, name) ++ self.assertEqual(C.__module__, __name__) ++ ++ A = type('C', (), {}) ++ with self.assertRaises(ValueError): ++ A.__name__ = 'A\x00B' ++ self.assertEqual(A.__name__, 'C') ++ with self.assertRaises(TypeError): ++ A.__name__ = u'A' ++ self.assertEqual(A.__name__, 'C') ++ ++ def test_type_doc(self): ++ tests = ('x', '\xc4', 'x\x00y', 42, None) ++ if have_unicode: ++ tests += (u'\xc4', u'x\x00y') ++ for doc in tests: ++ A = type('A', (), {'__doc__': doc}) ++ self.assertEqual(A.__doc__, doc) ++ ++ A = type('A', (), {}) ++ self.assertEqual(A.__doc__, None) ++ with self.assertRaises(AttributeError): ++ A.__doc__ = 'x' ++ ++ def test_bad_args(self): ++ with self.assertRaises(TypeError): ++ type() ++ with self.assertRaises(TypeError): ++ type('A', ()) ++ with self.assertRaises(TypeError): ++ type('A', (), {}, ()) ++ with self.assertRaises(TypeError): ++ type('A', (), dict={}) ++ with self.assertRaises(TypeError): ++ type('A', [], {}) ++ with self.assertRaises(TypeError): ++ type('A', (), UserDict.UserDict()) ++ with self.assertRaises(TypeError): ++ type('A', (None,), {}) ++ with self.assertRaises(TypeError): ++ type('A', (bool,), {}) ++ with self.assertRaises(TypeError): ++ type('A', (int, str), {}) ++ class B: ++ pass ++ with self.assertRaises(TypeError): ++ type('A', (B,), {}) ++ ++ def test_bad_slots(self): ++ with self.assertRaises(TypeError): ++ type('A', (long,), {'__slots__': 'x'}) ++ with self.assertRaises(TypeError): ++ type('A', (), {'__slots__': ''}) ++ with self.assertRaises(TypeError): ++ type('A', (), {'__slots__': '42'}) ++ with self.assertRaises(TypeError): ++ type('A', (), {'__slots__': 'x\x00y'}) ++ with self.assertRaises(TypeError): ++ type('A', (), {'__slots__': ('__dict__', '__dict__')}) ++ with self.assertRaises(TypeError): ++ type('A', (), {'__slots__': ('__weakref__', '__weakref__')}) ++ ++ class B(object): ++ pass ++ with self.assertRaises(TypeError): ++ type('A', (B,), {'__slots__': '__dict__'}) ++ with self.assertRaises(TypeError): ++ type('A', (B,), {'__slots__': '__weakref__'}) ++ ++ + def _run_unittest(*args): + with check_py3k_warnings( + (".+ not supported in 3.x", DeprecationWarning), +@@ -1696,7 +1824,7 @@ + (".+ not supported in 3.x", DeprecationWarning)): + run_unittest(TestExecFile) + numruns += 1 +- test_classes = (BuiltinTest, TestSorted) ++ test_classes = (BuiltinTest, TestSorted, TestType) + + _run_unittest(*test_classes) + +diff -r 6d1b6a68f775 Lib/test/test_cmd_line_script.py +--- a/Lib/test/test_cmd_line_script.py ++++ b/Lib/test/test_cmd_line_script.py +@@ -1,5 +1,6 @@ + # Tests command line execution of scripts + ++import contextlib + import unittest + import os + import os.path +@@ -207,18 +208,69 @@ + launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg') + self._check_import_error(launch_name, msg) + ++ @contextlib.contextmanager ++ def setup_test_pkg(self, *args): ++ with temp_dir() as script_dir, \ ++ test.test_support.change_cwd(script_dir): ++ pkg_dir = os.path.join(script_dir, 'test_pkg') ++ make_pkg(pkg_dir, *args) ++ yield pkg_dir ++ ++ def check_dash_m_failure(self, *args): ++ rc, out, err = assert_python_failure('-m', *args) ++ if verbose > 1: ++ print(out) ++ self.assertEqual(rc, 1) ++ return err ++ + def test_dash_m_error_code_is_one(self): + # If a module is invoked with the -m command line flag + # and results in an error that the return code to the + # shell is '1' +- with temp_dir() as script_dir: +- pkg_dir = os.path.join(script_dir, 'test_pkg') +- make_pkg(pkg_dir) ++ with self.setup_test_pkg() as pkg_dir: + script_name = _make_test_script(pkg_dir, 'other', "if __name__ == '__main__': raise ValueError") +- rc, out, err = assert_python_failure('-m', 'test_pkg.other', *example_args) +- if verbose > 1: +- print(out) ++ err = self.check_dash_m_failure('test_pkg.other', *example_args) ++ self.assertIn(b'ValueError', err) ++ ++ def test_dash_m_errors(self): ++ # Exercise error reporting for various invalid package executions ++ tests = ( ++ ('__builtin__', br'No code object available'), ++ ('__builtin__.x', br'No module named'), ++ ('__builtin__.x.y', br'No module named'), ++ ('os.path', br'Loader.*cannot handle'), ++ ('importlib', br'No module named.*' ++ br'is a package and cannot be directly executed'), ++ ('importlib.nonexistant', br'No module named'), ++ ) ++ for name, regex in tests: ++ rc, _, err = assert_python_failure('-m', name) + self.assertEqual(rc, 1) ++ self.assertRegexpMatches(err, regex) ++ self.assertNotIn(b'Traceback', err) ++ ++ def test_dash_m_init_traceback(self): ++ # These were wrapped in an ImportError and tracebacks were ++ # suppressed; see Issue 14285 ++ exceptions = (ImportError, AttributeError, TypeError, ValueError) ++ for exception in exceptions: ++ exception = exception.__name__ ++ init = "raise {0}('Exception in __init__.py')".format(exception) ++ with self.setup_test_pkg(init) as pkg_dir: ++ err = self.check_dash_m_failure('test_pkg') ++ self.assertIn(exception.encode('ascii'), err) ++ self.assertIn(b'Exception in __init__.py', err) ++ self.assertIn(b'Traceback', err) ++ ++ def test_dash_m_main_traceback(self): ++ # Ensure that an ImportError's traceback is reported ++ with self.setup_test_pkg() as pkg_dir: ++ main = "raise ImportError('Exception in __main__ module')" ++ _make_test_script(pkg_dir, '__main__', main) ++ err = self.check_dash_m_failure('test_pkg') ++ self.assertIn(b'ImportError', err) ++ self.assertIn(b'Exception in __main__ module', err) ++ self.assertIn(b'Traceback', err) + + + def test_main(): +diff -r 6d1b6a68f775 Lib/test/test_collections.py +--- a/Lib/test/test_collections.py ++++ b/Lib/test/test_collections.py +@@ -1,19 +1,24 @@ ++import collections ++import copy ++import doctest ++import keyword ++import operator ++import pickle ++import cPickle ++from random import choice, randrange ++import re ++import string ++import sys ++from test import test_support ++import unittest + +-import unittest, doctest, operator +-import inspect +-from test import test_support + from collections import namedtuple, Counter, OrderedDict +-from test import mapping_tests +-import pickle, cPickle, copy +-from random import randrange, shuffle +-import keyword +-import re +-import sys + from collections import Hashable, Iterable, Iterator + from collections import Sized, Container, Callable + from collections import Set, MutableSet + from collections import Mapping, MutableMapping + from collections import Sequence, MutableSequence ++ + # Silence deprecation warning + sets = test_support.import_module('sets', deprecated=True) + +@@ -178,8 +183,7 @@ + self.assertEqual(Dot(1)._fields, ('d',)) + + n = 5000 +- import string, random +- names = list(set(''.join([random.choice(string.ascii_letters) ++ names = list(set(''.join([choice(string.ascii_letters) + for j in range(10)]) for i in range(n))) + n = len(names) + Big = namedtuple('Big', names) +@@ -556,7 +560,7 @@ + + def test_issue_4920(self): + # MutableSet.pop() method did not work +- class MySet(collections.MutableSet): ++ class MySet(MutableSet): + __slots__=['__s'] + def __init__(self,items=None): + if items is None: +@@ -802,7 +806,7 @@ + self.assertTrue(issubclass(sample, Mapping)) + self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__', + '__getitem__') +- class MyMapping(collections.Mapping): ++ class MyMapping(Mapping): + def __len__(self): + return 0 + def __getitem__(self, i): +@@ -1038,290 +1042,11 @@ + self.assertRaises(TypeError, Counter().subtract, {}, {}) + self.assertRaises(TypeError, Counter.subtract) + +-class TestOrderedDict(unittest.TestCase): +- +- def test_init(self): +- with self.assertRaises(TypeError): +- OrderedDict([('a', 1), ('b', 2)], None) # too many args +- pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] +- self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input +- self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input +- self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input +- self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)], +- c=3, e=5).items()), pairs) # mixed input +- +- # make sure no positional args conflict with possible kwdargs +- self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)]) +- self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)]) +- self.assertRaises(TypeError, OrderedDict, 42) +- self.assertRaises(TypeError, OrderedDict, (), ()) +- self.assertRaises(TypeError, OrderedDict.__init__) +- +- # Make sure that direct calls to __init__ do not clear previous contents +- d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) +- d.__init__([('e', 5), ('f', 6)], g=7, d=4) +- self.assertEqual(list(d.items()), +- [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) +- +- def test_update(self): +- with self.assertRaises(TypeError): +- OrderedDict().update([('a', 1), ('b', 2)], None) # too many args +- pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] +- od = OrderedDict() +- od.update(dict(pairs)) +- self.assertEqual(sorted(od.items()), pairs) # dict input +- od = OrderedDict() +- od.update(**dict(pairs)) +- self.assertEqual(sorted(od.items()), pairs) # kwds input +- od = OrderedDict() +- od.update(pairs) +- self.assertEqual(list(od.items()), pairs) # pairs input +- od = OrderedDict() +- od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5) +- self.assertEqual(list(od.items()), pairs) # mixed input +- +- # Issue 9137: Named argument called 'other' or 'self' +- # shouldn't be treated specially. +- od = OrderedDict() +- od.update(self=23) +- self.assertEqual(list(od.items()), [('self', 23)]) +- od = OrderedDict() +- od.update(other={}) +- self.assertEqual(list(od.items()), [('other', {})]) +- od = OrderedDict() +- od.update(red=5, blue=6, other=7, self=8) +- self.assertEqual(sorted(list(od.items())), +- [('blue', 6), ('other', 7), ('red', 5), ('self', 8)]) +- +- # Make sure that direct calls to update do not clear previous contents +- # add that updates items are not moved to the end +- d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) +- d.update([('e', 5), ('f', 6)], g=7, d=4) +- self.assertEqual(list(d.items()), +- [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) +- +- self.assertRaises(TypeError, OrderedDict().update, 42) +- self.assertRaises(TypeError, OrderedDict().update, (), ()) +- self.assertRaises(TypeError, OrderedDict.update) +- +- def test_abc(self): +- self.assertIsInstance(OrderedDict(), MutableMapping) +- self.assertTrue(issubclass(OrderedDict, MutableMapping)) +- +- def test_clear(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- shuffle(pairs) +- od = OrderedDict(pairs) +- self.assertEqual(len(od), len(pairs)) +- od.clear() +- self.assertEqual(len(od), 0) +- +- def test_delitem(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- od = OrderedDict(pairs) +- del od['a'] +- self.assertNotIn('a', od) +- with self.assertRaises(KeyError): +- del od['a'] +- self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) +- +- def test_setitem(self): +- od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)]) +- od['c'] = 10 # existing element +- od['f'] = 20 # new element +- self.assertEqual(list(od.items()), +- [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)]) +- +- def test_iterators(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- shuffle(pairs) +- od = OrderedDict(pairs) +- self.assertEqual(list(od), [t[0] for t in pairs]) +- self.assertEqual(od.keys()[:], [t[0] for t in pairs]) +- self.assertEqual(od.values()[:], [t[1] for t in pairs]) +- self.assertEqual(od.items()[:], pairs) +- self.assertEqual(list(od.iterkeys()), [t[0] for t in pairs]) +- self.assertEqual(list(od.itervalues()), [t[1] for t in pairs]) +- self.assertEqual(list(od.iteritems()), pairs) +- self.assertEqual(list(reversed(od)), +- [t[0] for t in reversed(pairs)]) +- +- def test_popitem(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- shuffle(pairs) +- od = OrderedDict(pairs) +- while pairs: +- self.assertEqual(od.popitem(), pairs.pop()) +- with self.assertRaises(KeyError): +- od.popitem() +- self.assertEqual(len(od), 0) +- +- def test_pop(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- shuffle(pairs) +- od = OrderedDict(pairs) +- shuffle(pairs) +- while pairs: +- k, v = pairs.pop() +- self.assertEqual(od.pop(k), v) +- with self.assertRaises(KeyError): +- od.pop('xyz') +- self.assertEqual(len(od), 0) +- self.assertEqual(od.pop(k, 12345), 12345) +- +- # make sure pop still works when __missing__ is defined +- class Missing(OrderedDict): +- def __missing__(self, key): +- return 0 +- m = Missing(a=1) +- self.assertEqual(m.pop('b', 5), 5) +- self.assertEqual(m.pop('a', 6), 1) +- self.assertEqual(m.pop('a', 6), 6) +- with self.assertRaises(KeyError): +- m.pop('a') +- +- def test_equality(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- shuffle(pairs) +- od1 = OrderedDict(pairs) +- od2 = OrderedDict(pairs) +- self.assertEqual(od1, od2) # same order implies equality +- pairs = pairs[2:] + pairs[:2] +- od2 = OrderedDict(pairs) +- self.assertNotEqual(od1, od2) # different order implies inequality +- # comparison to regular dict is not order sensitive +- self.assertEqual(od1, dict(od2)) +- self.assertEqual(dict(od2), od1) +- # different length implied inequality +- self.assertNotEqual(od1, OrderedDict(pairs[:-1])) +- +- def test_copying(self): +- # Check that ordered dicts are copyable, deepcopyable, picklable, +- # and have a repr/eval round-trip +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- od = OrderedDict(pairs) +- update_test = OrderedDict() +- update_test.update(od) +- for i, dup in enumerate([ +- od.copy(), +- copy.copy(od), +- copy.deepcopy(od), +- pickle.loads(pickle.dumps(od, 0)), +- pickle.loads(pickle.dumps(od, 1)), +- pickle.loads(pickle.dumps(od, 2)), +- pickle.loads(pickle.dumps(od, -1)), +- eval(repr(od)), +- update_test, +- OrderedDict(od), +- ]): +- self.assertTrue(dup is not od) +- self.assertEqual(dup, od) +- self.assertEqual(list(dup.items()), list(od.items())) +- self.assertEqual(len(dup), len(od)) +- self.assertEqual(type(dup), type(od)) +- +- def test_yaml_linkage(self): +- # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. +- # In yaml, lists are native but tuples are not. +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- od = OrderedDict(pairs) +- # yaml.dump(od) --> +- # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' +- self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) +- +- def test_reduce_not_too_fat(self): +- # do not save instance dictionary if not needed +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- od = OrderedDict(pairs) +- self.assertEqual(len(od.__reduce__()), 2) +- od.x = 10 +- self.assertEqual(len(od.__reduce__()), 3) +- +- def test_repr(self): +- od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]) +- self.assertEqual(repr(od), +- "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])") +- self.assertEqual(eval(repr(od)), od) +- self.assertEqual(repr(OrderedDict()), "OrderedDict()") +- +- def test_repr_recursive(self): +- # See issue #9826 +- od = OrderedDict.fromkeys('abc') +- od['x'] = od +- self.assertEqual(repr(od), +- "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") +- +- def test_setdefault(self): +- pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] +- shuffle(pairs) +- od = OrderedDict(pairs) +- pair_order = list(od.items()) +- self.assertEqual(od.setdefault('a', 10), 3) +- # make sure order didn't change +- self.assertEqual(list(od.items()), pair_order) +- self.assertEqual(od.setdefault('x', 10), 10) +- # make sure 'x' is added to the end +- self.assertEqual(list(od.items())[-1], ('x', 10)) +- +- # make sure setdefault still works when __missing__ is defined +- class Missing(OrderedDict): +- def __missing__(self, key): +- return 0 +- self.assertEqual(Missing().setdefault(5, 9), 9) +- +- def test_reinsert(self): +- # Given insert a, insert b, delete a, re-insert a, +- # verify that a is now later than b. +- od = OrderedDict() +- od['a'] = 1 +- od['b'] = 2 +- del od['a'] +- od['a'] = 1 +- self.assertEqual(list(od.items()), [('b', 2), ('a', 1)]) +- +- def test_views(self): +- s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split() +- od = OrderedDict.fromkeys(s) +- self.assertEqual(list(od.viewkeys()), s) +- self.assertEqual(list(od.viewvalues()), [None for k in s]) +- self.assertEqual(list(od.viewitems()), [(k, None) for k in s]) +- +- # See http://bugs.python.org/issue24286 +- self.assertEqual(od.viewkeys(), dict(od).viewkeys()) +- self.assertEqual(od.viewitems(), dict(od).viewitems()) +- +- def test_override_update(self): +- # Verify that subclasses can override update() without breaking __init__() +- class MyOD(OrderedDict): +- def update(self, *args, **kwds): +- raise Exception() +- items = [('a', 1), ('c', 3), ('b', 2)] +- self.assertEqual(list(MyOD(items).items()), items) +- +-class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): +- type2test = OrderedDict +- +- def test_popitem(self): +- d = self._empty_mapping() +- self.assertRaises(KeyError, d.popitem) +- +-class MyOrderedDict(OrderedDict): +- pass +- +-class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): +- type2test = MyOrderedDict +- +- def test_popitem(self): +- d = self._empty_mapping() +- self.assertRaises(KeyError, d.popitem) +- +-import collections + + def test_main(verbose=None): + NamedTupleDocs = doctest.DocTestSuite(module=collections) + test_classes = [TestNamedTuple, NamedTupleDocs, TestOneTrickPonyABCs, +- TestCollectionABCs, TestCounter, +- TestOrderedDict, GeneralMappingTests, SubclassMappingTests] ++ TestCollectionABCs, TestCounter] + test_support.run_unittest(*test_classes) + test_support.run_doctest(collections, verbose) + +diff -r 6d1b6a68f775 Lib/test/test_compile.py +--- a/Lib/test/test_compile.py ++++ b/Lib/test/test_compile.py +@@ -576,14 +576,15 @@ + # objects are accepted, which could be not terminated. + with self.assertRaisesRegexp(TypeError, "without null bytes"): + compile(u"123\x00", "", "eval") +- with self.assertRaisesRegexp(TypeError, "without null bytes"): +- compile(buffer("123\x00"), "", "eval") +- code = compile(buffer("123\x00", 1, 2), "", "eval") +- self.assertEqual(eval(code), 23) +- code = compile(buffer("1234", 1, 2), "", "eval") +- self.assertEqual(eval(code), 23) +- code = compile(buffer("$23$", 1, 2), "", "eval") +- self.assertEqual(eval(code), 23) ++ with test_support.check_py3k_warnings(): ++ with self.assertRaisesRegexp(TypeError, "without null bytes"): ++ compile(buffer("123\x00"), "", "eval") ++ code = compile(buffer("123\x00", 1, 2), "", "eval") ++ self.assertEqual(eval(code), 23) ++ code = compile(buffer("1234", 1, 2), "", "eval") ++ self.assertEqual(eval(code), 23) ++ code = compile(buffer("$23$", 1, 2), "", "eval") ++ self.assertEqual(eval(code), 23) + + class TestStackSize(unittest.TestCase): + # These tests check that the computed stack size for a code object +@@ -622,6 +623,65 @@ + code += " x and x\n" * self.N + self.check_stack_size(code) + ++ def check_constant(self, func, expected): ++ for const in func.__code__.co_consts: ++ if repr(const) == repr(expected): ++ break ++ else: ++ self.fail("unable to find constant %r in %r" ++ % (expected, func.__code__.co_consts)) ++ ++ # Merging equal constants is not a strict requirement for the Python ++ # semantics, it's a more an implementation detail. ++ @test_support.cpython_only ++ def test_merge_constants(self): ++ # Issue #25843: compile() must merge constants which are equal ++ # and have the same type. ++ ++ def check_same_constant(const): ++ ns = {} ++ code = "f1, f2 = lambda: %r, lambda: %r" % (const, const) ++ exec(code, ns) ++ f1 = ns['f1'] ++ f2 = ns['f2'] ++ self.assertIs(f1.__code__, f2.__code__) ++ self.check_constant(f1, const) ++ self.assertEqual(repr(f1()), repr(const)) ++ ++ check_same_constant(None) ++ check_same_constant(0) ++ check_same_constant(0.0) ++ check_same_constant(b'abc') ++ check_same_constant('abc') ++ ++ def test_dont_merge_constants(self): ++ # Issue #25843: compile() must not merge constants which are equal ++ # but have a different type. ++ ++ def check_different_constants(const1, const2): ++ ns = {} ++ exec("f1, f2 = lambda: %r, lambda: %r" % (const1, const2), ns) ++ f1 = ns['f1'] ++ f2 = ns['f2'] ++ self.assertIsNot(f1.__code__, f2.__code__) ++ self.check_constant(f1, const1) ++ self.check_constant(f2, const2) ++ self.assertEqual(repr(f1()), repr(const1)) ++ self.assertEqual(repr(f2()), repr(const2)) ++ ++ check_different_constants(0, 0.0) ++ check_different_constants(+0.0, -0.0) ++ check_different_constants((0,), (0.0,)) ++ ++ # check_different_constants() cannot be used because repr(-0j) is ++ # '(-0-0j)', but when '(-0-0j)' is evaluated to 0j: we loose the sign. ++ f1, f2 = lambda: +0.0j, lambda: -0.0j ++ self.assertIsNot(f1.__code__, f2.__code__) ++ self.check_constant(f1, +0.0j) ++ self.check_constant(f2, -0.0j) ++ self.assertEqual(repr(f1()), repr(+0.0j)) ++ self.assertEqual(repr(f2()), repr(-0.0j)) ++ + + def test_main(): + test_support.run_unittest(__name__) +diff -r 6d1b6a68f775 Lib/test/test_copy.py +--- a/Lib/test/test_copy.py ++++ b/Lib/test/test_copy.py +@@ -82,7 +82,8 @@ + pass + def f(): + pass +- tests = [None, 42, 2L**100, 3.14, True, False, 1j, ++ tests = [None, Ellipsis, ++ 42, 2L**100, 3.14, True, False, 1j, + "hello", u"hello\u1234", f.func_code, + NewStyle, xrange(10), Classic, max] + for x in tests: +@@ -90,15 +91,57 @@ + + def test_copy_list(self): + x = [1, 2, 3] +- self.assertEqual(copy.copy(x), x) ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ x = [] ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) + + def test_copy_tuple(self): + x = (1, 2, 3) +- self.assertEqual(copy.copy(x), x) ++ self.assertIs(copy.copy(x), x) ++ x = () ++ self.assertIs(copy.copy(x), x) ++ x = (1, 2, 3, []) ++ self.assertIs(copy.copy(x), x) + + def test_copy_dict(self): + x = {"foo": 1, "bar": 2} +- self.assertEqual(copy.copy(x), x) ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ x = {} ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ ++ def test_copy_set(self): ++ x = {1, 2, 3} ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ x = set() ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ ++ def test_copy_frozenset(self): ++ x = frozenset({1, 2, 3}) ++ self.assertIs(copy.copy(x), x) ++ x = frozenset() ++ self.assertIs(copy.copy(x), x) ++ ++ def test_copy_bytearray(self): ++ x = bytearray(b'abc') ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ x = bytearray() ++ y = copy.copy(x) ++ self.assertEqual(y, x) ++ self.assertIsNot(y, x) + + def test_copy_inst_vanilla(self): + class C: +@@ -165,6 +208,9 @@ + return cmp(self.foo, other.foo) + x = C(42) + self.assertEqual(copy.copy(x), x) ++ # State with boolean value is false (issue #25718) ++ x = C(0.0) ++ self.assertEqual(copy.copy(x), x) + + # The deepcopy() method + +@@ -395,6 +441,12 @@ + x = C([42]) + y = copy.deepcopy(x) + self.assertEqual(y, x) ++ self.assertIsNot(y, x) ++ self.assertIsNot(y.foo, x.foo) ++ # State with boolean value is false (issue #25718) ++ x = C([]) ++ y = copy.deepcopy(x) ++ self.assertEqual(y, x) + self.assertTrue(y is not x) + self.assertTrue(y.foo is not x.foo) + +diff -r 6d1b6a68f775 Lib/test/test_cpickle.py +--- a/Lib/test/test_cpickle.py ++++ b/Lib/test/test_cpickle.py +@@ -51,6 +51,10 @@ + + error = cPickle.BadPickleGet + module = cPickle ++ bad_stack_errors = (cPickle.UnpicklingError,) ++ bad_mark_errors = (EOFError,) ++ truncated_errors = (cPickle.UnpicklingError, EOFError, ++ AttributeError, ValueError) + + class cPickleUnpicklerTests(AbstractUnpickleTests): + +@@ -63,6 +67,10 @@ + self.close(f) + + error = cPickle.BadPickleGet ++ bad_stack_errors = (cPickle.UnpicklingError,) ++ bad_mark_errors = (EOFError,) ++ truncated_errors = (cPickle.UnpicklingError, EOFError, ++ AttributeError, ValueError) + + class cStringIOCUnpicklerTests(cStringIOMixin, cPickleUnpicklerTests): + pass +diff -r 6d1b6a68f775 Lib/test/test_csv.py +--- a/Lib/test/test_csv.py ++++ b/Lib/test/test_csv.py +@@ -2,6 +2,7 @@ + # Copyright (C) 2001,2002 Python Software Foundation + # csv package unit tests + ++import copy + import sys + import os + import unittest +@@ -10,6 +11,7 @@ + import csv + import gc + import io ++import pickle + from test import test_support + + class Test_Csv(unittest.TestCase): +@@ -466,6 +468,18 @@ + self.assertRaises(TypeError, csv.reader, [], quoting = -1) + self.assertRaises(TypeError, csv.reader, [], quoting = 100) + ++ # See issue #22995 ++ ## def test_copy(self): ++ ## for name in csv.list_dialects(): ++ ## dialect = csv.get_dialect(name) ++ ## self.assertRaises(TypeError, copy.copy, dialect) ++ ++ ## def test_pickle(self): ++ ## for name in csv.list_dialects(): ++ ## dialect = csv.get_dialect(name) ++ ## for proto in range(pickle.HIGHEST_PROTOCOL + 1): ++ ## self.assertRaises(TypeError, pickle.dumps, dialect, proto) ++ + class TestCsvBase(unittest.TestCase): + def readerAssertEqual(self, input, expected_result): + fd, name = tempfile.mkstemp() +diff -r 6d1b6a68f775 Lib/test/test_descr.py +--- a/Lib/test/test_descr.py ++++ b/Lib/test/test_descr.py +@@ -4699,6 +4699,7 @@ + for o in gc.get_objects(): + self.assertIsNot(type(o), X) + ++ + class DictProxyTests(unittest.TestCase): + def setUp(self): + class C(object): +@@ -4763,6 +4764,26 @@ + type.mro(tuple) + + ++class PicklingTests(unittest.TestCase): ++ ++ def test_issue24097(self): ++ # Slot name is freed inside __getattr__ and is later used. ++ class S(str): # Not interned ++ pass ++ class A(object): ++ __slotnames__ = [S('spam')] ++ def __getattr__(self, attr): ++ if attr == 'spam': ++ A.__slotnames__[:] = [S('spam')] ++ return 42 ++ else: ++ raise AttributeError ++ ++ import copy_reg ++ expected = (copy_reg.__newobj__, (A,), ({}, {'spam': 42}), None, None) ++ self.assertEqual(A().__reduce__(2), expected) ++ ++ + def test_main(): + deprecations = [(r'complex divmod\(\), // and % are deprecated$', + DeprecationWarning)] +@@ -4774,7 +4795,8 @@ + with test_support.check_warnings(*deprecations): + # Run all local test cases, with PTypesLongInitTest first. + test_support.run_unittest(PTypesLongInitTest, OperatorsTest, +- ClassPropertiesAndMethods, DictProxyTests) ++ ClassPropertiesAndMethods, DictProxyTests, ++ PicklingTests) + + if __name__ == "__main__": + test_main() +diff -r 6d1b6a68f775 Lib/test/test_dictviews.py +--- a/Lib/test/test_dictviews.py ++++ b/Lib/test/test_dictviews.py +@@ -98,6 +98,7 @@ + self.assertEqual(d1.viewkeys() & set(d1.viewkeys()), {'a', 'b'}) + self.assertEqual(d1.viewkeys() & set(d2.viewkeys()), {'b'}) + self.assertEqual(d1.viewkeys() & set(d3.viewkeys()), set()) ++ self.assertEqual(d1.viewkeys() & tuple(d1.viewkeys()), {'a', 'b'}) + + self.assertEqual(d1.viewkeys() | d1.viewkeys(), {'a', 'b'}) + self.assertEqual(d1.viewkeys() | d2.viewkeys(), {'a', 'b', 'c'}) +@@ -106,6 +107,7 @@ + self.assertEqual(d1.viewkeys() | set(d2.viewkeys()), {'a', 'b', 'c'}) + self.assertEqual(d1.viewkeys() | set(d3.viewkeys()), + {'a', 'b', 'd', 'e'}) ++ self.assertEqual(d1.viewkeys() | (1, 2), {'a', 'b', 1, 2}) + + self.assertEqual(d1.viewkeys() ^ d1.viewkeys(), set()) + self.assertEqual(d1.viewkeys() ^ d2.viewkeys(), {'a', 'c'}) +@@ -114,6 +116,7 @@ + self.assertEqual(d1.viewkeys() ^ set(d2.viewkeys()), {'a', 'c'}) + self.assertEqual(d1.viewkeys() ^ set(d3.viewkeys()), + {'a', 'b', 'd', 'e'}) ++ self.assertEqual(d1.viewkeys() ^ tuple(d2.keys()), {'a', 'c'}) + + self.assertEqual(d1.viewkeys() - d1.viewkeys(), set()) + self.assertEqual(d1.viewkeys() - d2.viewkeys(), {'a'}) +@@ -121,6 +124,7 @@ + self.assertEqual(d1.viewkeys() - set(d1.viewkeys()), set()) + self.assertEqual(d1.viewkeys() - set(d2.viewkeys()), {'a'}) + self.assertEqual(d1.viewkeys() - set(d3.viewkeys()), {'a', 'b'}) ++ self.assertEqual(d1.viewkeys() - (0, 1), {'a', 'b'}) + + def test_items_set_operations(self): + d1 = {'a': 1, 'b': 2} +diff -r 6d1b6a68f775 Lib/test/test_doctest.py +--- a/Lib/test/test_doctest.py ++++ b/Lib/test/test_doctest.py +@@ -2582,7 +2582,7 @@ + >>> fn = tempfile.mktemp() + >>> with open(fn, 'wb') as f: + ... f.write('Test:\r\n\r\n >>> x = 1 + 1\r\n\r\nDone.\r\n') +- >>> doctest.testfile(fn, False) ++ >>> doctest.testfile(fn, module_relative=False, verbose=False) + TestResults(failed=0, attempted=1) + >>> os.remove(fn) + +@@ -2591,7 +2591,7 @@ + >>> fn = tempfile.mktemp() + >>> with open(fn, 'wb') as f: + ... f.write('Test:\n\n >>> x = 1 + 1\n\nDone.\n') +- >>> doctest.testfile(fn, False) ++ >>> doctest.testfile(fn, module_relative=False, verbose=False) + TestResults(failed=0, attempted=1) + >>> os.remove(fn) + +diff -r 6d1b6a68f775 Lib/test/test_dummy_thread.py +--- a/Lib/test/test_dummy_thread.py ++++ b/Lib/test/test_dummy_thread.py +@@ -24,14 +24,14 @@ + + def test_initlock(self): + #Make sure locks start locked +- self.assertTrue(not self.lock.locked(), ++ self.assertFalse(self.lock.locked(), + "Lock object is not initialized unlocked.") + + def test_release(self): + # Test self.lock.release() + self.lock.acquire() + self.lock.release() +- self.assertTrue(not self.lock.locked(), ++ self.assertFalse(self.lock.locked(), + "Lock object did not release properly.") + + def test_improper_release(self): +@@ -46,7 +46,7 @@ + def test_cond_acquire_fail(self): + #Test acquiring locked lock returns False + self.lock.acquire(0) +- self.assertTrue(not self.lock.acquire(0), ++ self.assertFalse(self.lock.acquire(0), + "Conditional acquiring of a locked lock incorrectly " + "succeeded.") + +@@ -58,9 +58,9 @@ + + def test_uncond_acquire_return_val(self): + #Make sure that an unconditional locking returns True. +- self.assertTrue(self.lock.acquire(1) is True, ++ self.assertIs(self.lock.acquire(1), True, + "Unconditional locking did not return True.") +- self.assertTrue(self.lock.acquire() is True) ++ self.assertIs(self.lock.acquire(), True) + + def test_uncond_acquire_blocking(self): + #Make sure that unconditional acquiring of a locked lock blocks. +@@ -80,7 +80,7 @@ + end_time = int(time.time()) + if test_support.verbose: + print "done" +- self.assertTrue((end_time - start_time) >= DELAY, ++ self.assertGreaterEqual(end_time - start_time, DELAY, + "Blocking by unconditional acquiring failed.") + + class MiscTests(unittest.TestCase): +@@ -94,7 +94,7 @@ + #Test sanity of _thread.get_ident() + self.assertIsInstance(_thread.get_ident(), int, + "_thread.get_ident() returned a non-integer") +- self.assertTrue(_thread.get_ident() != 0, ++ self.assertNotEqual(_thread.get_ident(), 0, + "_thread.get_ident() returned 0") + + def test_LockType(self): +@@ -164,7 +164,7 @@ + time.sleep(DELAY) + if test_support.verbose: + print 'done' +- self.assertTrue(testing_queue.qsize() == thread_count, ++ self.assertEqual(testing_queue.qsize(), thread_count, + "Not all %s threads executed properly after %s sec." % + (thread_count, DELAY)) + +diff -r 6d1b6a68f775 Lib/test/test_exceptions.py +--- a/Lib/test/test_exceptions.py ++++ b/Lib/test/test_exceptions.py +@@ -5,10 +5,15 @@ + import unittest + import pickle, cPickle + +-from test.test_support import (TESTFN, unlink, run_unittest, captured_output, ++from test.test_support import (TESTFN, unlink, run_unittest, captured_stderr, + check_warnings, cpython_only) + from test.test_pep352 import ignore_deprecation_warnings + ++class BrokenStrException(Exception): ++ def __str__(self): ++ raise Exception("str() is broken") ++ __repr__ = __str__ # Python 2's PyErr_WriteUnraisable() uses repr() ++ + # XXX This is not really enough, each *operation* should be tested! + + class ExceptionTests(unittest.TestCase): +@@ -375,7 +380,7 @@ + # The test prints an unraisable recursion error when + # doing "except ValueError", this is because subclass + # checking has recursion checking too. +- with captured_output("stderr"): ++ with captured_stderr(): + try: + g() + except RuntimeError: +@@ -448,7 +453,7 @@ + __metaclass__ = Meta + pass + +- with captured_output("stderr") as stderr: ++ with captured_stderr() as stderr: + try: + raise KeyError() + except MyException, e: +@@ -460,7 +465,7 @@ + else: + self.fail("Should have raised KeyError") + +- with captured_output("stderr") as stderr: ++ with captured_stderr() as stderr: + def g(): + try: + return g() +@@ -644,6 +649,62 @@ + self.assertEqual(error5.a, 1) + self.assertEqual(error5.__doc__, "") + ++ def test_unraisable(self): ++ # Issue #22836: PyErr_WriteUnraisable() should give sensible reports ++ class BrokenDel: ++ def __del__(self): ++ exc = ValueError("del is broken") ++ # In Python 3, the following line would be in the report: ++ raise exc ++ ++ class BrokenRepr(BrokenDel): ++ def __repr__(self): ++ raise AttributeError("repr() is broken") ++ ++ class BrokenExceptionDel: ++ def __del__(self): ++ exc = BrokenStrException() ++ # In Python 3, the following line would be in the report: ++ raise exc ++ ++ for test_class in (BrokenDel, BrokenRepr, BrokenExceptionDel): ++ obj = test_class() ++ with captured_stderr() as stderr: ++ del obj ++ report = stderr.getvalue() ++ self.assertRegexpMatches(report, "Exception.* ignored") ++ if test_class is BrokenRepr: ++ self.assertIn("", report) ++ else: ++ self.assertIn("__del__", report) ++ if test_class is BrokenExceptionDel: ++ self.assertIn("BrokenStrException", report) ++ self.assertIn("", report) ++ else: ++ self.assertIn("ValueError", report) ++ self.assertIn("del is broken", report) ++ self.assertTrue(report.endswith("\n")) ++ ++ def test_unhandled(self): ++ # Check for sensible reporting of unhandled exceptions ++ for exc_type in (ValueError, BrokenStrException): ++ try: ++ exc = exc_type("test message") ++ # The following line is included in the traceback report: ++ raise exc ++ except exc_type: ++ with captured_stderr() as stderr: ++ sys.__excepthook__(*sys.exc_info()) ++ report = stderr.getvalue() ++ self.assertIn("test_exceptions.py", report) ++ self.assertIn("raise exc", report) ++ self.assertIn(exc_type.__name__, report) ++ if exc_type is BrokenStrException: ++ self.assertIn("", report) ++ else: ++ self.assertIn("test message", report) ++ self.assertTrue(report.endswith("\n")) ++ + + def test_main(): + run_unittest(ExceptionTests, TestSameStrAndUnicodeMsg) +diff -r 6d1b6a68f775 Lib/test/test_fileinput.py +--- a/Lib/test/test_fileinput.py ++++ b/Lib/test/test_fileinput.py +@@ -5,7 +5,7 @@ + + import unittest + from test.test_support import verbose, TESTFN, run_unittest +-from test.test_support import unlink as safe_unlink ++from test.test_support import unlink as safe_unlink, check_warnings + import sys, re + from StringIO import StringIO + from fileinput import FileInput, hook_encoded +@@ -28,6 +28,42 @@ + for name in names: + safe_unlink(name) + ++class LineReader: ++ ++ def __init__(self): ++ self._linesread = [] ++ ++ @property ++ def linesread(self): ++ try: ++ return self._linesread[:] ++ finally: ++ self._linesread = [] ++ ++ def openhook(self, filename, mode): ++ self.it = iter(filename.splitlines(True)) ++ return self ++ ++ def readline(self, size=None): ++ line = next(self.it, '') ++ self._linesread.append(line) ++ return line ++ ++ def readlines(self, hint=-1): ++ lines = [] ++ size = 0 ++ while True: ++ line = self.readline() ++ if not line: ++ return lines ++ lines.append(line) ++ size += len(line) ++ if size >= hint: ++ return lines ++ ++ def close(self): ++ pass ++ + class BufferSizesTests(unittest.TestCase): + def test_buffer_sizes(self): + # First, run the tests with default and teeny buffer size. +@@ -228,7 +264,7 @@ + f.write('\x80') + self.addCleanup(safe_unlink, TESTFN) + +- fi = FileInput(files=TESTFN, openhook=hook_encoded('ascii'), bufsize=8) ++ fi = FileInput(files=TESTFN, openhook=hook_encoded('ascii')) + # 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') +@@ -239,6 +275,38 @@ + list(fi) + fi.close() + ++ def test_readline_buffering(self): ++ src = LineReader() ++ fi = FileInput(files=['line1\nline2', 'line3\n'], openhook=src.openhook) ++ self.assertEqual(src.linesread, []) ++ self.assertEqual(fi.readline(), 'line1\n') ++ self.assertEqual(src.linesread, ['line1\n']) ++ self.assertEqual(fi.readline(), 'line2') ++ self.assertEqual(src.linesread, ['line2']) ++ self.assertEqual(fi.readline(), 'line3\n') ++ self.assertEqual(src.linesread, ['', 'line3\n']) ++ self.assertEqual(fi.readline(), '') ++ self.assertEqual(src.linesread, ['']) ++ self.assertEqual(fi.readline(), '') ++ self.assertEqual(src.linesread, []) ++ fi.close() ++ ++ def test_iteration_buffering(self): ++ src = LineReader() ++ fi = FileInput(files=['line1\nline2', 'line3\n'], openhook=src.openhook) ++ self.assertEqual(src.linesread, []) ++ self.assertEqual(next(fi), 'line1\n') ++ self.assertEqual(src.linesread, ['line1\n']) ++ self.assertEqual(next(fi), 'line2') ++ self.assertEqual(src.linesread, ['line2']) ++ self.assertEqual(next(fi), 'line3\n') ++ self.assertEqual(src.linesread, ['', 'line3\n']) ++ self.assertRaises(StopIteration, next, fi) ++ self.assertEqual(src.linesread, ['']) ++ self.assertRaises(StopIteration, next, fi) ++ self.assertEqual(src.linesread, []) ++ fi.close() ++ + class Test_hook_encoded(unittest.TestCase): + """Unit tests for fileinput.hook_encoded()""" + +diff -r 6d1b6a68f775 Lib/test/test_float.py +--- a/Lib/test/test_float.py ++++ b/Lib/test/test_float.py +@@ -27,6 +27,12 @@ + test_dir = os.path.dirname(__file__) or os.curdir + format_testfile = os.path.join(test_dir, 'formatfloat_testcases.txt') + ++class FloatSubclass(float): ++ pass ++ ++class OtherFloatSubclass(float): ++ pass ++ + class GeneralFloatCases(unittest.TestCase): + + def test_float(self): +@@ -65,7 +71,8 @@ + factories += [unicode, CustomUnicode] + + for f in factories: +- x = f(" 3.14 ") ++ with test_support.check_py3k_warnings(quiet=True): ++ x = f(" 3.14 ") + msg = 'x has value %s and type %s' % (x, type(x).__name__) + try: + self.assertEqual(float(x), 3.14, msg=msg) +@@ -73,15 +80,17 @@ + raise AssertionError('For %s got TypeError: %s' % + (type(x).__name__, err)) + errmsg = "could not convert" +- with self.assertRaisesRegexp(ValueError, errmsg, msg=msg): ++ with self.assertRaisesRegexp(ValueError, errmsg, msg=msg), \ ++ test_support.check_py3k_warnings(quiet=True): + float(f('A' * 0x10)) + + def test_float_buffer(self): +- self.assertEqual(float(buffer('12.3', 1, 3)), 2.3) +- self.assertEqual(float(buffer('12.3\x00', 1, 3)), 2.3) +- self.assertEqual(float(buffer('12.3 ', 1, 3)), 2.3) +- self.assertEqual(float(buffer('12.3A', 1, 3)), 2.3) +- self.assertEqual(float(buffer('12.34', 1, 3)), 2.3) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(float(buffer('12.3', 1, 3)), 2.3) ++ self.assertEqual(float(buffer('12.3\x00', 1, 3)), 2.3) ++ self.assertEqual(float(buffer('12.3 ', 1, 3)), 2.3) ++ self.assertEqual(float(buffer('12.3A', 1, 3)), 2.3) ++ self.assertEqual(float(buffer('12.34', 1, 3)), 2.3) + + def check_conversion_to_int(self, x): + """Check that int(x) has the correct value and type, for a float x.""" +@@ -200,6 +209,15 @@ + return "" + self.assertRaises(TypeError, time.sleep, Foo5()) + ++ # Issue #24731 ++ class F: ++ def __float__(self): ++ return OtherFloatSubclass(42.) ++ self.assertAlmostEqual(float(F()), 42.) ++ self.assertIs(type(float(F())), OtherFloatSubclass) ++ self.assertAlmostEqual(FloatSubclass(F()), 42.) ++ self.assertIs(type(FloatSubclass(F())), FloatSubclass) ++ + def test_is_integer(self): + self.assertFalse((1.1).is_integer()) + self.assertTrue((1.).is_integer()) +diff -r 6d1b6a68f775 Lib/test/test_functools.py +--- a/Lib/test/test_functools.py ++++ b/Lib/test/test_functools.py +@@ -1,3 +1,4 @@ ++import copy + import functools + import sys + import unittest +@@ -25,6 +26,16 @@ + """ return the signature of a partial object """ + return (part.func, part.args, part.keywords, part.__dict__) + ++class MyTuple(tuple): ++ pass ++ ++class BadTuple(tuple): ++ def __add__(self, other): ++ return list(self) + list(other) ++ ++class MyDict(dict): ++ pass ++ + class TestPartial(unittest.TestCase): + + thetype = functools.partial +@@ -146,11 +157,84 @@ + self.assertEqual(join(data), '0123456789') + + def test_pickle(self): +- f = self.thetype(signature, 'asdf', bar=True) +- f.add_something_to__dict__ = True ++ f = self.thetype(signature, ['asdf'], bar=[True]) ++ f.attr = [] + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + f_copy = pickle.loads(pickle.dumps(f, proto)) +- self.assertEqual(signature(f), signature(f_copy)) ++ self.assertEqual(signature(f_copy), signature(f)) ++ ++ def test_copy(self): ++ f = self.thetype(signature, ['asdf'], bar=[True]) ++ f.attr = [] ++ f_copy = copy.copy(f) ++ self.assertEqual(signature(f_copy), signature(f)) ++ self.assertIs(f_copy.attr, f.attr) ++ self.assertIs(f_copy.args, f.args) ++ self.assertIs(f_copy.keywords, f.keywords) ++ ++ def test_deepcopy(self): ++ f = self.thetype(signature, ['asdf'], bar=[True]) ++ f.attr = [] ++ f_copy = copy.deepcopy(f) ++ self.assertEqual(signature(f_copy), signature(f)) ++ self.assertIsNot(f_copy.attr, f.attr) ++ self.assertIsNot(f_copy.args, f.args) ++ self.assertIsNot(f_copy.args[0], f.args[0]) ++ self.assertIsNot(f_copy.keywords, f.keywords) ++ self.assertIsNot(f_copy.keywords['bar'], f.keywords['bar']) ++ ++ def test_setstate(self): ++ f = self.thetype(signature) ++ f.__setstate__((capture, (1,), dict(a=10), dict(attr=[]))) ++ self.assertEqual(signature(f), ++ (capture, (1,), dict(a=10), dict(attr=[]))) ++ self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20})) ++ ++ f.__setstate__((capture, (1,), dict(a=10), None)) ++ self.assertEqual(signature(f), (capture, (1,), dict(a=10), {})) ++ self.assertEqual(f(2, b=20), ((1, 2), {'a': 10, 'b': 20})) ++ ++ f.__setstate__((capture, (1,), None, None)) ++ #self.assertEqual(signature(f), (capture, (1,), {}, {})) ++ self.assertEqual(f(2, b=20), ((1, 2), {'b': 20})) ++ self.assertEqual(f(2), ((1, 2), {})) ++ self.assertEqual(f(), ((1,), {})) ++ ++ f.__setstate__((capture, (), {}, None)) ++ self.assertEqual(signature(f), (capture, (), {}, {})) ++ self.assertEqual(f(2, b=20), ((2,), {'b': 20})) ++ self.assertEqual(f(2), ((2,), {})) ++ self.assertEqual(f(), ((), {})) ++ ++ def test_setstate_errors(self): ++ f = self.thetype(signature) ++ self.assertRaises(TypeError, f.__setstate__, (capture, (), {})) ++ self.assertRaises(TypeError, f.__setstate__, (capture, (), {}, {}, None)) ++ self.assertRaises(TypeError, f.__setstate__, [capture, (), {}, None]) ++ self.assertRaises(TypeError, f.__setstate__, (None, (), {}, None)) ++ self.assertRaises(TypeError, f.__setstate__, (capture, None, {}, None)) ++ self.assertRaises(TypeError, f.__setstate__, (capture, [], {}, None)) ++ self.assertRaises(TypeError, f.__setstate__, (capture, (), [], None)) ++ ++ def test_setstate_subclasses(self): ++ f = self.thetype(signature) ++ f.__setstate__((capture, MyTuple((1,)), MyDict(a=10), None)) ++ s = signature(f) ++ self.assertEqual(s, (capture, (1,), dict(a=10), {})) ++ self.assertIs(type(s[1]), tuple) ++ self.assertIs(type(s[2]), dict) ++ r = f() ++ self.assertEqual(r, ((1,), {'a': 10})) ++ self.assertIs(type(r[0]), tuple) ++ self.assertIs(type(r[1]), dict) ++ ++ f.__setstate__((capture, BadTuple((1,)), {}, None)) ++ s = signature(f) ++ self.assertEqual(s, (capture, (1,), {}, {})) ++ self.assertIs(type(s[1]), tuple) ++ r = f(2) ++ self.assertEqual(r, ((1, 2), {})) ++ self.assertIs(type(r[0]), tuple) + + # Issue 6083: Reference counting bug + def test_setstate_refcount(self): +@@ -167,7 +251,7 @@ + raise IndexError + + f = self.thetype(object) +- self.assertRaises(SystemError, f.__setstate__, BadSequence()) ++ self.assertRaises(TypeError, f.__setstate__, BadSequence()) + + class PartialSubclass(functools.partial): + pass +@@ -181,7 +265,14 @@ + thetype = PythonPartial + + # the python version isn't picklable +- test_pickle = test_setstate_refcount = None ++ test_pickle = None ++ test_setstate = None ++ test_setstate_errors = None ++ test_setstate_subclasses = None ++ test_setstate_refcount = None ++ ++ # the python version isn't deepcopyable ++ test_deepcopy = None + + # the python version isn't a type + test_attributes = None +diff -r 6d1b6a68f775 Lib/test/test_gdb.py +--- a/Lib/test/test_gdb.py ++++ b/Lib/test/test_gdb.py +@@ -71,6 +71,8 @@ + if (gdb_major_version, gdb_minor_version) >= (7, 4): + base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path) + out, err = subprocess.Popen(base_cmd + args, ++ # Redirect stdin to prevent GDB from messing with terminal settings ++ stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, + ).communicate() + return out, err +diff -r 6d1b6a68f775 Lib/test/test_getargs2.py +--- a/Lib/test/test_getargs2.py ++++ b/Lib/test/test_getargs2.py +@@ -331,9 +331,293 @@ + else: + self.fail('TypeError should have been raised') + ++ ++class Bytes_TestCase(unittest.TestCase): ++ def test_c(self): ++ from _testcapi import getargs_c ++ self.assertRaises(TypeError, getargs_c, 'abc') # len > 1 ++ self.assertEqual(getargs_c('a'), 97) ++ if test_support.have_unicode: ++ self.assertRaises(TypeError, getargs_c, u's') ++ self.assertRaises(TypeError, getargs_c, bytearray('a')) ++ self.assertRaises(TypeError, getargs_c, memoryview('a')) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_c, buffer('a')) ++ self.assertRaises(TypeError, getargs_c, 97) ++ self.assertRaises(TypeError, getargs_c, None) ++ ++ def test_w(self): ++ from _testcapi import getargs_w ++ self.assertRaises(TypeError, getargs_w, 'abc', 3) ++ self.assertRaises(TypeError, getargs_w, u'abc', 3) ++ self.assertRaises(TypeError, getargs_w, bytearray('bytes'), 3) ++ self.assertRaises(TypeError, getargs_w, memoryview('bytes'), 3) ++ self.assertRaises(TypeError, getargs_w, ++ memoryview(bytearray('bytes')), 3) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_w, buffer('bytes'), 3) ++ self.assertRaises(TypeError, getargs_w, ++ buffer(bytearray('bytes')), 3) ++ self.assertRaises(TypeError, getargs_w, None, 0) ++ ++ def test_w_hash(self): ++ from _testcapi import getargs_w_hash ++ self.assertRaises(TypeError, getargs_w_hash, 'abc') ++ self.assertRaises(TypeError, getargs_w_hash, u'abc') ++ self.assertRaises(TypeError, getargs_w_hash, bytearray('bytes')) ++ self.assertRaises(TypeError, getargs_w_hash, memoryview('bytes')) ++ self.assertRaises(TypeError, getargs_w_hash, ++ memoryview(bytearray('bytes'))) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_w_hash, buffer('bytes')) ++ self.assertRaises(TypeError, getargs_w_hash, ++ buffer(bytearray('bytes'))) ++ self.assertRaises(TypeError, getargs_w_hash, None) ++ ++ def test_w_star(self): ++ # getargs_w_star() modifies first and last byte ++ from _testcapi import getargs_w_star ++ self.assertRaises(TypeError, getargs_w_star, 'abc') ++ self.assertRaises(TypeError, getargs_w_star, u'abc') ++ self.assertRaises(TypeError, getargs_w_star, memoryview('bytes')) ++ buf = bytearray('bytearray') ++ self.assertEqual(getargs_w_star(buf), '[ytearra]') ++ self.assertEqual(buf, bytearray('[ytearra]')) ++ buf = bytearray(b'memoryview') ++ self.assertEqual(getargs_w_star(memoryview(buf)), '[emoryvie]') ++ self.assertEqual(buf, bytearray('[emoryvie]')) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_w_star, buffer('buffer')) ++ self.assertRaises(TypeError, getargs_w_star, ++ buffer(bytearray('buffer'))) ++ self.assertRaises(TypeError, getargs_w_star, None) ++ ++ ++class String_TestCase(unittest.TestCase): ++ def test_s(self): ++ from _testcapi import getargs_s ++ self.assertEqual(getargs_s('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_s(u'abc'), 'abc') ++ self.assertRaises(TypeError, getargs_s, 'nul:\0') ++ self.assertRaises(TypeError, getargs_s, u'nul:\0') ++ self.assertRaises(TypeError, getargs_s, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_s, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_s, buffer('buffer')) ++ self.assertRaises(TypeError, getargs_s, None) ++ ++ def test_s_star(self): ++ from _testcapi import getargs_s_star ++ self.assertEqual(getargs_s_star('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_s_star(u'abc'), 'abc') ++ self.assertEqual(getargs_s_star('nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_s_star(u'nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_s_star(bytearray('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_s_star(memoryview('abc\xe9')), 'abc\xe9') ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_s_star(buffer('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_s_star(buffer(u'abc\xe9')), ++ str(buffer(u'abc\xe9'))) ++ self.assertRaises(TypeError, getargs_s_star, None) ++ ++ def test_s_hash(self): ++ from _testcapi import getargs_s_hash ++ self.assertEqual(getargs_s_hash('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_s_hash(u'abc'), 'abc') ++ self.assertEqual(getargs_s_hash('nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_s_hash(u'nul:\0'), 'nul:\0') ++ self.assertRaises(TypeError, getargs_s_hash, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_s_hash, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_s_hash(buffer('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_s_hash(buffer(u'abc\xe9')), ++ str(buffer(u'abc\xe9'))) ++ self.assertRaises(TypeError, getargs_s_hash, None) ++ ++ def test_t_hash(self): ++ from _testcapi import getargs_t_hash ++ self.assertEqual(getargs_t_hash('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_t_hash(u'abc'), 'abc') ++ self.assertEqual(getargs_t_hash('nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_t_hash(u'nul:\0'), 'nul:\0') ++ self.assertRaises(TypeError, getargs_t_hash, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_t_hash, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_t_hash(buffer('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_t_hash(buffer(u'abc')), 'abc') ++ self.assertRaises(TypeError, getargs_t_hash, None) ++ ++ def test_z(self): ++ from _testcapi import getargs_z ++ self.assertEqual(getargs_z('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_z(u'abc'), 'abc') ++ self.assertRaises(TypeError, getargs_z, 'nul:\0') ++ self.assertRaises(TypeError, getargs_z, u'nul:\0') ++ self.assertRaises(TypeError, getargs_z, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_z, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_z, buffer('buffer')) ++ self.assertIsNone(getargs_z(None)) ++ ++ def test_z_star(self): ++ from _testcapi import getargs_z_star ++ self.assertEqual(getargs_z_star('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_z_star(u'abc'), 'abc') ++ self.assertEqual(getargs_z_star('nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_z_star(u'nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_z_star(bytearray('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_z_star(memoryview('abc\xe9')), 'abc\xe9') ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_z_star(buffer('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_z_star(buffer(u'abc\xe9')), ++ str(buffer(u'abc\xe9'))) ++ self.assertIsNone(getargs_z_star(None)) ++ ++ def test_z_hash(self): ++ from _testcapi import getargs_z_hash ++ self.assertEqual(getargs_z_hash('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_z_hash(u'abc'), 'abc') ++ self.assertEqual(getargs_z_hash('nul:\0'), 'nul:\0') ++ self.assertEqual(getargs_z_hash(u'nul:\0'), 'nul:\0') ++ self.assertRaises(TypeError, getargs_z_hash, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_z_hash, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_z_hash(buffer('abc\xe9')), 'abc\xe9') ++ self.assertEqual(getargs_z_hash(buffer(u'abc\xe9')), ++ str(buffer(u'abc\xe9'))) ++ self.assertIsNone(getargs_z_hash(None)) ++ ++ ++@test_support.requires_unicode ++class Unicode_TestCase(unittest.TestCase): ++ def test_es(self): ++ from _testcapi import getargs_es ++ self.assertEqual(getargs_es('abc'), 'abc') ++ self.assertEqual(getargs_es(u'abc'), 'abc') ++ self.assertEqual(getargs_es('abc', 'ascii'), 'abc') ++ self.assertEqual(getargs_es(u'abc\xe9', 'latin1'), 'abc\xe9') ++ self.assertRaises(UnicodeEncodeError, getargs_es, u'abc\xe9', 'ascii') ++ self.assertRaises(LookupError, getargs_es, u'abc', 'spam') ++ self.assertRaises(TypeError, getargs_es, ++ bytearray('bytearray'), 'latin1') ++ self.assertRaises(TypeError, getargs_es, ++ memoryview('memoryview'), 'latin1') ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_es(buffer('abc'), 'ascii'), 'abc') ++ self.assertEqual(getargs_es(buffer(u'abc'), 'ascii'), 'abc') ++ self.assertRaises(TypeError, getargs_es, None, 'latin1') ++ self.assertRaises(TypeError, getargs_es, 'nul:\0', 'latin1') ++ self.assertRaises(TypeError, getargs_es, u'nul:\0', 'latin1') ++ ++ def test_et(self): ++ from _testcapi import getargs_et ++ self.assertEqual(getargs_et('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_et(u'abc'), 'abc') ++ self.assertEqual(getargs_et('abc', 'ascii'), 'abc') ++ self.assertEqual(getargs_et('abc\xe9', 'ascii'), 'abc\xe9') ++ self.assertEqual(getargs_et(u'abc\xe9', 'latin1'), 'abc\xe9') ++ self.assertRaises(UnicodeEncodeError, getargs_et, u'abc\xe9', 'ascii') ++ self.assertRaises(LookupError, getargs_et, u'abc', 'spam') ++ self.assertRaises(TypeError, getargs_et, ++ bytearray('bytearray'), 'latin1') ++ self.assertRaises(TypeError, getargs_et, ++ memoryview('memoryview'), 'latin1') ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_et(buffer('abc'), 'ascii'), 'abc') ++ self.assertEqual(getargs_et(buffer(u'abc'), 'ascii'), 'abc') ++ self.assertRaises(TypeError, getargs_et, None, 'latin1') ++ self.assertRaises(TypeError, getargs_et, 'nul:\0', 'latin1') ++ self.assertRaises(TypeError, getargs_et, u'nul:\0', 'latin1') ++ ++ def test_es_hash(self): ++ from _testcapi import getargs_es_hash ++ self.assertEqual(getargs_es_hash('abc'), 'abc') ++ self.assertEqual(getargs_es_hash(u'abc'), 'abc') ++ self.assertEqual(getargs_es_hash(u'abc\xe9', 'latin1'), 'abc\xe9') ++ self.assertRaises(UnicodeEncodeError, getargs_es_hash, u'abc\xe9', 'ascii') ++ self.assertRaises(LookupError, getargs_es_hash, u'abc', 'spam') ++ self.assertRaises(TypeError, getargs_es_hash, ++ bytearray('bytearray'), 'latin1') ++ self.assertRaises(TypeError, getargs_es_hash, ++ memoryview('memoryview'), 'latin1') ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_es_hash(buffer('abc'), 'ascii'), 'abc') ++ self.assertEqual(getargs_es_hash(buffer(u'abc'), 'ascii'), 'abc') ++ self.assertRaises(TypeError, getargs_es_hash, None, 'latin1') ++ self.assertEqual(getargs_es_hash('nul:\0', 'latin1'), 'nul:\0') ++ self.assertEqual(getargs_es_hash(u'nul:\0', 'latin1'), 'nul:\0') ++ ++ buf = bytearray('x'*8) ++ self.assertEqual(getargs_es_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9') ++ self.assertEqual(buf, bytearray('abc\xe9\x00xxx')) ++ buf = bytearray('x'*5) ++ self.assertEqual(getargs_es_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9') ++ self.assertEqual(buf, bytearray('abc\xe9\x00')) ++ buf = bytearray('x'*4) ++ self.assertRaises(TypeError, getargs_es_hash, u'abc\xe9', 'latin1', buf) ++ self.assertEqual(buf, bytearray('x'*4)) ++ buf = bytearray() ++ self.assertRaises(TypeError, getargs_es_hash, u'abc\xe9', 'latin1', buf) ++ ++ def test_et_hash(self): ++ from _testcapi import getargs_et_hash ++ self.assertEqual(getargs_et_hash('abc\xe9'), 'abc\xe9') ++ self.assertEqual(getargs_et_hash(u'abc'), 'abc') ++ self.assertEqual(getargs_et_hash('abc\xe9', 'ascii'), 'abc\xe9') ++ self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1'), 'abc\xe9') ++ self.assertRaises(UnicodeEncodeError, getargs_et_hash, ++ u'abc\xe9', 'ascii') ++ self.assertRaises(LookupError, getargs_et_hash, u'abc', 'spam') ++ self.assertRaises(TypeError, getargs_et_hash, ++ bytearray('bytearray'), 'latin1') ++ self.assertRaises(TypeError, getargs_et_hash, ++ memoryview('memoryview'), 'latin1') ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(getargs_et_hash(buffer('abc'), 'ascii'), 'abc') ++ self.assertEqual(getargs_et_hash(buffer(u'abc'), 'ascii'), 'abc') ++ self.assertRaises(TypeError, getargs_et_hash, None, 'latin1') ++ self.assertEqual(getargs_et_hash('nul:\0', 'latin1'), 'nul:\0') ++ self.assertEqual(getargs_et_hash(u'nul:\0', 'latin1'), 'nul:\0') ++ ++ buf = bytearray('x'*8) ++ self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9') ++ self.assertEqual(buf, bytearray('abc\xe9\x00xxx')) ++ buf = bytearray('x'*5) ++ self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9') ++ self.assertEqual(buf, bytearray('abc\xe9\x00')) ++ buf = bytearray('x'*4) ++ self.assertRaises(TypeError, getargs_et_hash, u'abc\xe9', 'latin1', buf) ++ self.assertEqual(buf, bytearray('x'*4)) ++ buf = bytearray() ++ self.assertRaises(TypeError, getargs_et_hash, u'abc\xe9', 'latin1', buf) ++ ++ def test_u(self): ++ from _testcapi import getargs_u ++ self.assertEqual(getargs_u(u'abc\xe9'), u'abc\xe9') ++ self.assertEqual(getargs_u(u'nul:\0'), u'nul:') ++ self.assertRaises(TypeError, getargs_u, 'bytes') ++ self.assertRaises(TypeError, getargs_u, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_u, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_u, buffer('buffer')) ++ self.assertRaises(TypeError, getargs_u, None) ++ ++ def test_u_hash(self): ++ from _testcapi import getargs_u_hash ++ self.assertEqual(getargs_u_hash(u'abc\xe9'), u'abc\xe9') ++ self.assertEqual(getargs_u_hash(u'nul:\0'), u'nul:\0') ++ self.assertRaises(TypeError, getargs_u_hash, 'bytes') ++ self.assertRaises(TypeError, getargs_u_hash, bytearray('bytearray')) ++ self.assertRaises(TypeError, getargs_u_hash, memoryview('memoryview')) ++ with test_support.check_py3k_warnings(): ++ self.assertRaises(TypeError, getargs_u_hash, buffer('buffer')) ++ self.assertRaises(TypeError, getargs_u_hash, None) ++ ++ + def test_main(): + tests = [Signed_TestCase, Unsigned_TestCase, LongLong_TestCase, +- Tuple_TestCase, Keywords_TestCase] ++ Tuple_TestCase, Keywords_TestCase, ++ Bytes_TestCase, String_TestCase, Unicode_TestCase] + test_support.run_unittest(*tests) + + if __name__ == "__main__": +diff -r 6d1b6a68f775 Lib/test/test_int.py +--- a/Lib/test/test_int.py ++++ b/Lib/test/test_int.py +@@ -45,6 +45,9 @@ + (unichr(0x200), ValueError), + ] + ++class IntSubclass(int): ++ pass ++ + class IntLongCommonTests(object): + + """Mixin of test cases to share between both test_int and test_long.""" +@@ -348,7 +351,8 @@ + factories += [unicode, CustomUnicode] + + for f in factories: +- x = f('100') ++ with test_support.check_py3k_warnings(quiet=True): ++ x = f('100') + msg = 'x has value %s and type %s' % (x, type(x).__name__) + try: + self.assertEqual(int(x), 100, msg=msg) +@@ -362,15 +366,17 @@ + with self.assertRaisesRegexp(TypeError, errmsg, msg=msg): + int(x, 2) + errmsg = 'invalid literal' +- with self.assertRaisesRegexp(ValueError, errmsg, msg=msg): ++ with self.assertRaisesRegexp(ValueError, errmsg, msg=msg), \ ++ test_support.check_py3k_warnings(quiet=True): + int(f('A' * 0x10)) + + def test_int_buffer(self): +- self.assertEqual(int(buffer('123', 1, 2)), 23) +- self.assertEqual(int(buffer('123\x00', 1, 2)), 23) +- self.assertEqual(int(buffer('123 ', 1, 2)), 23) +- self.assertEqual(int(buffer('123A', 1, 2)), 23) +- self.assertEqual(int(buffer('1234', 1, 2)), 23) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(int(buffer('123', 1, 2)), 23) ++ self.assertEqual(int(buffer('123\x00', 1, 2)), 23) ++ self.assertEqual(int(buffer('123 ', 1, 2)), 23) ++ self.assertEqual(int(buffer('123A', 1, 2)), 23) ++ self.assertEqual(int(buffer('1234', 1, 2)), 23) + + def test_error_on_string_float_for_x(self): + self.assertRaises(ValueError, int, '1.2') +@@ -477,6 +483,18 @@ + self.fail("Failed to raise TypeError with %s" % + ((base, trunc_result_base),)) + ++ class TruncReturnsIntSubclass(base): ++ def __trunc__(self): ++ return True ++ good_int = TruncReturnsIntSubclass() ++ n = int(good_int) ++ self.assertEqual(n, 1) ++ self.assertIs(type(n), bool) ++ n = IntSubclass(good_int) ++ self.assertEqual(n, 1) ++ self.assertIs(type(n), IntSubclass) ++ ++ + def test_main(): + run_unittest(IntTestCases) + +diff -r 6d1b6a68f775 Lib/test/test_itertools.py +--- a/Lib/test/test_itertools.py ++++ b/Lib/test/test_itertools.py +@@ -1525,6 +1525,11 @@ + ... "Returns the nth item or a default value" + ... return next(islice(iterable, n, None), default) + ++>>> def all_equal(iterable): ++... "Returns True if all the elements are equal to each other" ++... g = groupby(iterable) ++... return next(g, True) and not next(g, False) ++ + >>> def quantify(iterable, pred=bool): + ... "Count how many times the predicate is true" + ... return sum(imap(pred, iterable)) +@@ -1623,6 +1628,9 @@ + >>> nth('abcde', 9) is None + True + ++>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')] ++[True, True, True, False, False] ++ + >>> quantify(xrange(99), lambda x: x%2==0) + 50 + +diff -r 6d1b6a68f775 Lib/test/test_locale.py +--- a/Lib/test/test_locale.py ++++ b/Lib/test/test_locale.py +@@ -493,6 +493,16 @@ + # longer accept unicode strings. + self.assertEqual(locale.normalize(u'en_US'), 'en_US.ISO8859-1') + ++ def test_setlocale_unicode(self): ++ oldlocale = locale.getlocale() ++ self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) ++ ++ user_locale = locale.setlocale(locale.LC_CTYPE, '') ++ unicode_locale = user_locale.decode('utf-8') ++ ++ user_locale2 = locale.setlocale(locale.LC_CTYPE, unicode_locale) ++ self.assertEqual(user_locale, user_locale2) ++ + + def test_main(): + tests = [ +diff -r 6d1b6a68f775 Lib/test/test_long.py +--- a/Lib/test/test_long.py ++++ b/Lib/test/test_long.py +@@ -79,6 +79,12 @@ + (unichr(0x200), ValueError), + ] + ++class LongSubclass(long): ++ pass ++ ++class OtherLongSubclass(long): ++ pass ++ + class LongTest(test_int.IntLongCommonTests, unittest.TestCase): + + ntype = long +@@ -539,6 +545,17 @@ + self.fail("Failed to raise TypeError with %s" % + ((base, trunc_result_base),)) + ++ class TruncReturnsLongSubclass(base): ++ def __long__(self): ++ return OtherLongSubclass(42L) ++ good_int = TruncReturnsLongSubclass() ++ n = long(good_int) ++ self.assertEqual(n, 42L) ++ self.assertIs(type(n), OtherLongSubclass) ++ n = LongSubclass(good_int) ++ self.assertEqual(n, 42L) ++ self.assertIs(type(n), LongSubclass) ++ + def test_misc(self): + + # check the extremes in int<->long conversion +diff -r 6d1b6a68f775 Lib/test/test_memoryview.py +--- a/Lib/test/test_memoryview.py ++++ b/Lib/test/test_memoryview.py +@@ -10,6 +10,8 @@ + import array + from test import test_support + import io ++import copy ++import pickle + + + class AbstractMemoryTests: +@@ -354,6 +356,20 @@ + #pass + + ++class OtherTest(unittest.TestCase): ++ def test_copy(self): ++ m = memoryview(b'abc') ++ with self.assertRaises(TypeError): ++ copy.copy(m) ++ ++ # See issue #22995 ++ ## def test_pickle(self): ++ ## m = memoryview(b'abc') ++ ## for proto in range(pickle.HIGHEST_PROTOCOL + 1): ++ ## with self.assertRaises(TypeError): ++ ## pickle.dumps(m, proto) ++ ++ + def test_main(): + test_support.run_unittest(__name__) + +diff -r 6d1b6a68f775 Lib/test/test_minidom.py +--- a/Lib/test/test_minidom.py ++++ b/Lib/test/test_minidom.py +@@ -1,5 +1,6 @@ + # test for xml.dom.minidom + ++import copy + import pickle + from StringIO import StringIO + from test.test_support import verbose, run_unittest, findfile +@@ -14,7 +15,13 @@ + + + tstfile = findfile("test.xml", subdir="xmltestdata") +- ++sample = ("\n" ++ "\n" ++ " \n" ++ "]> text\n" ++ " ") + + # The tests of DocumentType importing use these helpers to construct + # the documents to work with, since not all DOM builders actually +@@ -1377,52 +1384,54 @@ + self.confirm(e.isSameNode(doc.getElementById("w")) + and a2.isId) + ++ def assert_recursive_equal(self, doc, doc2): ++ stack = [(doc, doc2)] ++ while stack: ++ n1, n2 = stack.pop() ++ self.assertEqual(n1.nodeType, n2.nodeType) ++ self.assertEqual(len(n1.childNodes), len(n2.childNodes)) ++ self.assertEqual(n1.nodeName, n2.nodeName) ++ self.assertFalse(n1.isSameNode(n2)) ++ self.assertFalse(n2.isSameNode(n1)) ++ if n1.nodeType == Node.DOCUMENT_TYPE_NODE: ++ len(n1.entities) ++ len(n2.entities) ++ len(n1.notations) ++ len(n2.notations) ++ self.assertEqual(len(n1.entities), len(n2.entities)) ++ self.assertEqual(len(n1.notations), len(n2.notations)) ++ for i in range(len(n1.notations)): ++ # XXX this loop body doesn't seem to be executed? ++ no1 = n1.notations.item(i) ++ no2 = n1.notations.item(i) ++ self.assertEqual(no1.name, no2.name) ++ self.assertEqual(no1.publicId, no2.publicId) ++ self.assertEqual(no1.systemId, no2.systemId) ++ stack.append((no1, no2)) ++ for i in range(len(n1.entities)): ++ e1 = n1.entities.item(i) ++ e2 = n2.entities.item(i) ++ self.assertEqual(e1.notationName, e2.notationName) ++ self.assertEqual(e1.publicId, e2.publicId) ++ self.assertEqual(e1.systemId, e2.systemId) ++ stack.append((e1, e2)) ++ if n1.nodeType != Node.DOCUMENT_NODE: ++ self.assertTrue(n1.ownerDocument.isSameNode(doc)) ++ self.assertTrue(n2.ownerDocument.isSameNode(doc2)) ++ for i in range(len(n1.childNodes)): ++ stack.append((n1.childNodes[i], n2.childNodes[i])) ++ + def testPickledDocument(self): +- doc = parseString("\n" +- "\n" +- " \n" +- "]> text\n" +- " ") +- for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): ++ doc = parseString(sample) ++ for proto in range(pickle.HIGHEST_PROTOCOL + 1): + s = pickle.dumps(doc, proto) + doc2 = pickle.loads(s) +- stack = [(doc, doc2)] +- while stack: +- n1, n2 = stack.pop() +- self.confirm(n1.nodeType == n2.nodeType +- and len(n1.childNodes) == len(n2.childNodes) +- and n1.nodeName == n2.nodeName +- and not n1.isSameNode(n2) +- and not n2.isSameNode(n1)) +- if n1.nodeType == Node.DOCUMENT_TYPE_NODE: +- len(n1.entities) +- len(n2.entities) +- len(n1.notations) +- len(n2.notations) +- self.confirm(len(n1.entities) == len(n2.entities) +- and len(n1.notations) == len(n2.notations)) +- for i in range(len(n1.notations)): +- # XXX this loop body doesn't seem to be executed? +- no1 = n1.notations.item(i) +- no2 = n1.notations.item(i) +- self.confirm(no1.name == no2.name +- and no1.publicId == no2.publicId +- and no1.systemId == no2.systemId) +- stack.append((no1, no2)) +- for i in range(len(n1.entities)): +- e1 = n1.entities.item(i) +- e2 = n2.entities.item(i) +- self.confirm(e1.notationName == e2.notationName +- and e1.publicId == e2.publicId +- and e1.systemId == e2.systemId) +- stack.append((e1, e2)) +- if n1.nodeType != Node.DOCUMENT_NODE: +- self.confirm(n1.ownerDocument.isSameNode(doc) +- and n2.ownerDocument.isSameNode(doc2)) +- for i in range(len(n1.childNodes)): +- stack.append((n1.childNodes[i], n2.childNodes[i])) ++ self.assert_recursive_equal(doc, doc2) ++ ++ def testDeepcopiedDocument(self): ++ doc = parseString(sample) ++ doc2 = copy.deepcopy(doc) ++ self.assert_recursive_equal(doc, doc2) + + def testSerializeCommentNodeWithDoubleHyphen(self): + doc = create_doc_without_doctype() +diff -r 6d1b6a68f775 Lib/test/test_ordered_dict.py +--- /dev/null ++++ b/Lib/test/test_ordered_dict.py +@@ -0,0 +1,293 @@ ++import copy ++import pickle ++from random import shuffle ++import unittest ++from collections import OrderedDict ++from collections import MutableMapping ++from test import mapping_tests, test_support ++ ++ ++class TestOrderedDict(unittest.TestCase): ++ ++ def test_init(self): ++ with self.assertRaises(TypeError): ++ OrderedDict([('a', 1), ('b', 2)], None) # too many args ++ pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] ++ self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input ++ self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input ++ self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input ++ self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)], ++ c=3, e=5).items()), pairs) # mixed input ++ ++ # make sure no positional args conflict with possible kwdargs ++ self.assertEqual(list(OrderedDict(self=42).items()), [('self', 42)]) ++ self.assertEqual(list(OrderedDict(other=42).items()), [('other', 42)]) ++ self.assertRaises(TypeError, OrderedDict, 42) ++ self.assertRaises(TypeError, OrderedDict, (), ()) ++ self.assertRaises(TypeError, OrderedDict.__init__) ++ ++ # Make sure that direct calls to __init__ do not clear previous contents ++ d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) ++ d.__init__([('e', 5), ('f', 6)], g=7, d=4) ++ self.assertEqual(list(d.items()), ++ [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) ++ ++ def test_update(self): ++ with self.assertRaises(TypeError): ++ OrderedDict().update([('a', 1), ('b', 2)], None) # too many args ++ pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] ++ od = OrderedDict() ++ od.update(dict(pairs)) ++ self.assertEqual(sorted(od.items()), pairs) # dict input ++ od = OrderedDict() ++ od.update(**dict(pairs)) ++ self.assertEqual(sorted(od.items()), pairs) # kwds input ++ od = OrderedDict() ++ od.update(pairs) ++ self.assertEqual(list(od.items()), pairs) # pairs input ++ od = OrderedDict() ++ od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5) ++ self.assertEqual(list(od.items()), pairs) # mixed input ++ ++ # Issue 9137: Named argument called 'other' or 'self' ++ # shouldn't be treated specially. ++ od = OrderedDict() ++ od.update(self=23) ++ self.assertEqual(list(od.items()), [('self', 23)]) ++ od = OrderedDict() ++ od.update(other={}) ++ self.assertEqual(list(od.items()), [('other', {})]) ++ od = OrderedDict() ++ od.update(red=5, blue=6, other=7, self=8) ++ self.assertEqual(sorted(list(od.items())), ++ [('blue', 6), ('other', 7), ('red', 5), ('self', 8)]) ++ ++ # Make sure that direct calls to update do not clear previous contents ++ # add that updates items are not moved to the end ++ d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) ++ d.update([('e', 5), ('f', 6)], g=7, d=4) ++ self.assertEqual(list(d.items()), ++ [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) ++ ++ self.assertRaises(TypeError, OrderedDict().update, 42) ++ self.assertRaises(TypeError, OrderedDict().update, (), ()) ++ self.assertRaises(TypeError, OrderedDict.update) ++ ++ def test_abc(self): ++ self.assertIsInstance(OrderedDict(), MutableMapping) ++ self.assertTrue(issubclass(OrderedDict, MutableMapping)) ++ ++ def test_clear(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ shuffle(pairs) ++ od = OrderedDict(pairs) ++ self.assertEqual(len(od), len(pairs)) ++ od.clear() ++ self.assertEqual(len(od), 0) ++ ++ def test_delitem(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ od = OrderedDict(pairs) ++ del od['a'] ++ self.assertNotIn('a', od) ++ with self.assertRaises(KeyError): ++ del od['a'] ++ self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) ++ ++ def test_setitem(self): ++ od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)]) ++ od['c'] = 10 # existing element ++ od['f'] = 20 # new element ++ self.assertEqual(list(od.items()), ++ [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)]) ++ ++ def test_iterators(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ shuffle(pairs) ++ od = OrderedDict(pairs) ++ self.assertEqual(list(od), [t[0] for t in pairs]) ++ self.assertEqual(od.keys()[:], [t[0] for t in pairs]) ++ self.assertEqual(od.values()[:], [t[1] for t in pairs]) ++ self.assertEqual(od.items()[:], pairs) ++ self.assertEqual(list(od.iterkeys()), [t[0] for t in pairs]) ++ self.assertEqual(list(od.itervalues()), [t[1] for t in pairs]) ++ self.assertEqual(list(od.iteritems()), pairs) ++ self.assertEqual(list(reversed(od)), ++ [t[0] for t in reversed(pairs)]) ++ ++ def test_popitem(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ shuffle(pairs) ++ od = OrderedDict(pairs) ++ while pairs: ++ self.assertEqual(od.popitem(), pairs.pop()) ++ with self.assertRaises(KeyError): ++ od.popitem() ++ self.assertEqual(len(od), 0) ++ ++ def test_pop(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ shuffle(pairs) ++ od = OrderedDict(pairs) ++ shuffle(pairs) ++ while pairs: ++ k, v = pairs.pop() ++ self.assertEqual(od.pop(k), v) ++ with self.assertRaises(KeyError): ++ od.pop('xyz') ++ self.assertEqual(len(od), 0) ++ self.assertEqual(od.pop(k, 12345), 12345) ++ ++ # make sure pop still works when __missing__ is defined ++ class Missing(OrderedDict): ++ def __missing__(self, key): ++ return 0 ++ m = Missing(a=1) ++ self.assertEqual(m.pop('b', 5), 5) ++ self.assertEqual(m.pop('a', 6), 1) ++ self.assertEqual(m.pop('a', 6), 6) ++ with self.assertRaises(KeyError): ++ m.pop('a') ++ ++ def test_equality(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ shuffle(pairs) ++ od1 = OrderedDict(pairs) ++ od2 = OrderedDict(pairs) ++ self.assertEqual(od1, od2) # same order implies equality ++ pairs = pairs[2:] + pairs[:2] ++ od2 = OrderedDict(pairs) ++ self.assertNotEqual(od1, od2) # different order implies inequality ++ # comparison to regular dict is not order sensitive ++ self.assertEqual(od1, dict(od2)) ++ self.assertEqual(dict(od2), od1) ++ # different length implied inequality ++ self.assertNotEqual(od1, OrderedDict(pairs[:-1])) ++ ++ def test_copying(self): ++ # Check that ordered dicts are copyable, deepcopyable, picklable, ++ # and have a repr/eval round-trip ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ od = OrderedDict(pairs) ++ update_test = OrderedDict() ++ update_test.update(od) ++ for i, dup in enumerate([ ++ od.copy(), ++ copy.copy(od), ++ copy.deepcopy(od), ++ pickle.loads(pickle.dumps(od, 0)), ++ pickle.loads(pickle.dumps(od, 1)), ++ pickle.loads(pickle.dumps(od, 2)), ++ pickle.loads(pickle.dumps(od, -1)), ++ eval(repr(od)), ++ update_test, ++ OrderedDict(od), ++ ]): ++ self.assertTrue(dup is not od) ++ self.assertEqual(dup, od) ++ self.assertEqual(list(dup.items()), list(od.items())) ++ self.assertEqual(len(dup), len(od)) ++ self.assertEqual(type(dup), type(od)) ++ ++ def test_yaml_linkage(self): ++ # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. ++ # In yaml, lists are native but tuples are not. ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ od = OrderedDict(pairs) ++ # yaml.dump(od) --> ++ # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' ++ self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) ++ ++ def test_reduce_not_too_fat(self): ++ # do not save instance dictionary if not needed ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ od = OrderedDict(pairs) ++ self.assertEqual(len(od.__reduce__()), 2) ++ od.x = 10 ++ self.assertEqual(len(od.__reduce__()), 3) ++ ++ def test_repr(self): ++ od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]) ++ self.assertEqual(repr(od), ++ "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])") ++ self.assertEqual(eval(repr(od)), od) ++ self.assertEqual(repr(OrderedDict()), "OrderedDict()") ++ ++ def test_repr_recursive(self): ++ # See issue #9826 ++ od = OrderedDict.fromkeys('abc') ++ od['x'] = od ++ self.assertEqual(repr(od), ++ "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") ++ ++ def test_setdefault(self): ++ pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] ++ shuffle(pairs) ++ od = OrderedDict(pairs) ++ pair_order = list(od.items()) ++ self.assertEqual(od.setdefault('a', 10), 3) ++ # make sure order didn't change ++ self.assertEqual(list(od.items()), pair_order) ++ self.assertEqual(od.setdefault('x', 10), 10) ++ # make sure 'x' is added to the end ++ self.assertEqual(list(od.items())[-1], ('x', 10)) ++ ++ # make sure setdefault still works when __missing__ is defined ++ class Missing(OrderedDict): ++ def __missing__(self, key): ++ return 0 ++ self.assertEqual(Missing().setdefault(5, 9), 9) ++ ++ def test_reinsert(self): ++ # Given insert a, insert b, delete a, re-insert a, ++ # verify that a is now later than b. ++ od = OrderedDict() ++ od['a'] = 1 ++ od['b'] = 2 ++ del od['a'] ++ od['a'] = 1 ++ self.assertEqual(list(od.items()), [('b', 2), ('a', 1)]) ++ ++ def test_views(self): ++ s = 'the quick brown fox jumped over a lazy dog yesterday before dawn'.split() ++ od = OrderedDict.fromkeys(s) ++ self.assertEqual(list(od.viewkeys()), s) ++ self.assertEqual(list(od.viewvalues()), [None for k in s]) ++ self.assertEqual(list(od.viewitems()), [(k, None) for k in s]) ++ ++ # See http://bugs.python.org/issue24286 ++ self.assertEqual(od.viewkeys(), dict(od).viewkeys()) ++ self.assertEqual(od.viewitems(), dict(od).viewitems()) ++ ++ def test_override_update(self): ++ # Verify that subclasses can override update() without breaking __init__() ++ class MyOD(OrderedDict): ++ def update(self, *args, **kwds): ++ raise Exception() ++ items = [('a', 1), ('c', 3), ('b', 2)] ++ self.assertEqual(list(MyOD(items).items()), items) ++ ++class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): ++ type2test = OrderedDict ++ ++ def test_popitem(self): ++ d = self._empty_mapping() ++ self.assertRaises(KeyError, d.popitem) ++ ++class MyOrderedDict(OrderedDict): ++ pass ++ ++class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): ++ type2test = MyOrderedDict ++ ++ def test_popitem(self): ++ d = self._empty_mapping() ++ self.assertRaises(KeyError, d.popitem) ++ ++ ++def test_main(verbose=None): ++ test_classes = [TestOrderedDict, GeneralMappingTests, SubclassMappingTests] ++ test_support.run_unittest(*test_classes) ++ ++if __name__ == "__main__": ++ test_main(verbose=True) +diff -r 6d1b6a68f775 Lib/test/test_pickle.py +--- a/Lib/test/test_pickle.py ++++ b/Lib/test/test_pickle.py +@@ -1,4 +1,5 @@ + import pickle ++import struct + from cStringIO import StringIO + + from test import test_support +@@ -23,17 +24,30 @@ + + module = pickle + error = KeyError ++ bad_stack_errors = (IndexError,) ++ bad_mark_errors = (IndexError, pickle.UnpicklingError, ++ TypeError, AttributeError, EOFError) ++ truncated_errors = (pickle.UnpicklingError, EOFError, ++ AttributeError, ValueError, ++ struct.error, IndexError, ImportError, ++ TypeError, KeyError) + + class UnpicklerTests(AbstractUnpickleTests): + + error = KeyError ++ bad_stack_errors = (IndexError,) ++ bad_mark_errors = (IndexError, pickle.UnpicklingError, ++ TypeError, AttributeError, EOFError) ++ truncated_errors = (pickle.UnpicklingError, EOFError, ++ AttributeError, ValueError, ++ struct.error, IndexError, ImportError, ++ TypeError, KeyError) + + def loads(self, buf): + f = StringIO(buf) + u = pickle.Unpickler(f) + return u.load() + +- + class PicklerTests(AbstractPickleTests): + + def dumps(self, arg, proto=0, fast=0): +diff -r 6d1b6a68f775 Lib/test/test_rlcompleter.py +--- a/Lib/test/test_rlcompleter.py ++++ b/Lib/test/test_rlcompleter.py +@@ -81,6 +81,27 @@ + def test_main(): + support.run_unittest(TestRlcompleter) + ++ def test_duplicate_globals(self): ++ namespace = { ++ 'False': None, # Keyword vs builtin vs namespace ++ 'assert': None, # Keyword vs namespace ++ 'try': lambda: None, # Keyword vs callable ++ 'memoryview': None, # Callable builtin vs non-callable ++ 'Ellipsis': lambda: None, # Non-callable builtin vs callable ++ } ++ completer = rlcompleter.Completer(namespace) ++ self.assertEqual(completer.complete('False', 0), 'False') ++ self.assertIsNone(completer.complete('False', 1)) # No duplicates ++ self.assertEqual(completer.complete('assert', 0), 'assert') ++ self.assertIsNone(completer.complete('assert', 1)) ++ self.assertEqual(completer.complete('try', 0), 'try') ++ self.assertIsNone(completer.complete('try', 1)) ++ # No opening bracket "(" because we overrode the built-in class ++ self.assertEqual(completer.complete('memoryview', 0), 'memoryview') ++ self.assertIsNone(completer.complete('memoryview', 1)) ++ self.assertEqual(completer.complete('Ellipsis', 0), 'Ellipsis(') ++ self.assertIsNone(completer.complete('Ellipsis', 1)) ++ + + if __name__ == '__main__': + test_main() +diff -r 6d1b6a68f775 Lib/test/test_runpy.py +--- a/Lib/test/test_runpy.py ++++ b/Lib/test/test_runpy.py +@@ -270,6 +270,30 @@ + if verbose: print "Testing package depth:", depth + self._check_package(depth) + ++ def test_run_package_init_exceptions(self): ++ # These were previously wrapped in an ImportError; see Issue 14285 ++ exceptions = (ImportError, AttributeError, TypeError, ValueError) ++ for exception in exceptions: ++ name = exception.__name__ ++ source = "raise {0}('{0} in __init__.py.')".format(name) ++ ++ result = self._make_pkg("", 1, "__main__") ++ pkg_dir, _, mod_name = result ++ mod_name = mod_name.replace(".__main__", "") ++ try: ++ init = os.path.join(pkg_dir, "__runpy_pkg__", "__init__.py") ++ with open(init, "wt") as mod_file: ++ mod_file.write(source) ++ try: ++ run_module(mod_name) ++ except exception as err: ++ msg = "cannot be directly executed" ++ self.assertNotIn(msg, format(err)) ++ else: ++ self.fail("Nothing raised; expected {}".format(name)) ++ finally: ++ self._del_pkg(pkg_dir, 1, mod_name) ++ + def test_explicit_relative_import(self): + for depth in range(2, 5): + if verbose: print "Testing relative imports at depth:", depth +diff -r 6d1b6a68f775 Lib/test/test_site.py +--- a/Lib/test/test_site.py ++++ b/Lib/test/test_site.py +@@ -26,8 +26,13 @@ + + if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE): + # need to add user site directory for tests +- os.makedirs(site.USER_SITE) +- site.addsitedir(site.USER_SITE) ++ try: ++ os.makedirs(site.USER_SITE) ++ site.addsitedir(site.USER_SITE) ++ except OSError as exc: ++ raise unittest.SkipTest('unable to create user site directory (%r): %s' ++ % (site.USER_SITE, exc)) ++ + + class HelperFunctionsTests(unittest.TestCase): + """Tests for helper functions. +diff -r 6d1b6a68f775 Lib/test/test_socketserver.py +--- a/Lib/test/test_socketserver.py ++++ b/Lib/test/test_socketserver.py +@@ -175,6 +175,8 @@ + + def dgram_examine(self, proto, addr): + s = socket.socket(proto, socket.SOCK_DGRAM) ++ if HAVE_UNIX_SOCKETS and proto == socket.AF_UNIX: ++ s.bind(self.pickaddr(proto)) + s.sendto(TEST_STR, addr) + buf = data = receive(s, 100) + while data and '\n' not in buf: +@@ -269,27 +271,24 @@ + # Make sure select was called again: + self.assertGreater(mock_select.called, 1) + +- # Alas, on Linux (at least) recvfrom() doesn't return a meaningful +- # client address so this cannot work: ++ @requires_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) +- # +- # @requires_unix_sockets +- # def test_ThreadingUnixDatagramServer(self): +- # self.run_server(SocketServer.ThreadingUnixDatagramServer, +- # SocketServer.DatagramRequestHandler, +- # self.dgram_examine) +- # +- # @requires_unix_sockets +- # @requires_forking +- # def test_ForkingUnixDatagramServer(self): +- # self.run_server(SocketServer.ForkingUnixDatagramServer, +- # SocketServer.DatagramRequestHandler, +- # self.dgram_examine) ++ @requires_unix_sockets ++ def test_ThreadingUnixDatagramServer(self): ++ self.run_server(SocketServer.ThreadingUnixDatagramServer, ++ SocketServer.DatagramRequestHandler, ++ self.dgram_examine) ++ ++ @requires_unix_sockets ++ @requires_forking ++ def test_ForkingUnixDatagramServer(self): ++ self.run_server(ForkingUnixDatagramServer, ++ SocketServer.DatagramRequestHandler, ++ self.dgram_examine) + + @reap_threads + def test_shutdown(self): +@@ -327,6 +326,30 @@ + SocketServer.StreamRequestHandler) + + ++class MiscTestCase(unittest.TestCase): ++ ++ def test_shutdown_request_called_if_verify_request_false(self): ++ # Issue #26309: BaseServer should call shutdown_request even if ++ # verify_request is False ++ ++ class MyServer(SocketServer.TCPServer): ++ def verify_request(self, request, client_address): ++ return False ++ ++ shutdown_called = 0 ++ def shutdown_request(self, request): ++ self.shutdown_called += 1 ++ SocketServer.TCPServer.shutdown_request(self, request) ++ ++ server = MyServer((HOST, 0), SocketServer.StreamRequestHandler) ++ s = socket.socket(server.address_family, socket.SOCK_STREAM) ++ s.connect(server.server_address) ++ s.close() ++ server.handle_request() ++ self.assertEqual(server.shutdown_called, 1) ++ server.server_close() ++ ++ + def test_main(): + if imp.lock_held(): + # If the import lock is held, the threads will hang +diff -r 6d1b6a68f775 Lib/test/test_ssl.py +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -57,11 +57,12 @@ + SIGNED_CERTFILE2 = data_file("keycert4.pem") + SIGNING_CA = data_file("pycacert.pem") + +-SVN_PYTHON_ORG_ROOT_CERT = data_file("https_svn_python_org_root.pem") ++REMOTE_HOST = "self-signed.pythontest.net" ++REMOTE_ROOT_CERT = data_file("selfsigned_pythontestdotnet.pem") + + EMPTYCERT = data_file("nullcert.pem") + BADCERT = data_file("badcert.pem") +-WRONGCERT = data_file("XXXnonexisting.pem") ++NONEXISTINGCERT = data_file("XXXnonexisting.pem") + BADKEY = data_file("badkey.pem") + NOKIACERT = data_file("nokia.pem") + NULLBYTECERT = data_file("nullbytecert.pem") +@@ -244,7 +245,7 @@ + self.assertEqual(p['subjectAltName'], san) + + def test_DER_to_PEM(self): +- with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f: ++ with open(CAFILE_CACERT, 'r') as f: + pem = f.read() + d1 = ssl.PEM_cert_to_DER_cert(pem) + p2 = ssl.DER_cert_to_PEM_cert(d1) +@@ -333,17 +334,42 @@ + s.connect, (HOST, 8080)) + with self.assertRaises(IOError) as cm: + with closing(socket.socket()) as sock: +- ssl.wrap_socket(sock, certfile=WRONGCERT) ++ ssl.wrap_socket(sock, certfile=NONEXISTINGCERT) + self.assertEqual(cm.exception.errno, errno.ENOENT) + with self.assertRaises(IOError) as cm: + with closing(socket.socket()) as sock: +- ssl.wrap_socket(sock, certfile=CERTFILE, keyfile=WRONGCERT) ++ ssl.wrap_socket(sock, ++ certfile=CERTFILE, keyfile=NONEXISTINGCERT) + self.assertEqual(cm.exception.errno, errno.ENOENT) + with self.assertRaises(IOError) as cm: + with closing(socket.socket()) as sock: +- ssl.wrap_socket(sock, certfile=WRONGCERT, keyfile=WRONGCERT) ++ ssl.wrap_socket(sock, ++ certfile=NONEXISTINGCERT, keyfile=NONEXISTINGCERT) + self.assertEqual(cm.exception.errno, errno.ENOENT) + ++ def bad_cert_test(self, certfile): ++ """Check that trying to use the given client certificate fails""" ++ certfile = os.path.join(os.path.dirname(__file__) or os.curdir, ++ certfile) ++ sock = socket.socket() ++ self.addCleanup(sock.close) ++ with self.assertRaises(ssl.SSLError): ++ ssl.wrap_socket(sock, ++ certfile=certfile, ++ ssl_version=ssl.PROTOCOL_TLSv1) ++ ++ def test_empty_cert(self): ++ """Wrapping with an empty cert file""" ++ self.bad_cert_test("nullcert.pem") ++ ++ def test_malformed_cert(self): ++ """Wrapping with a badly formatted certificate (syntax error)""" ++ self.bad_cert_test("badcert.pem") ++ ++ def test_malformed_key(self): ++ """Wrapping with a badly formatted key (syntax error)""" ++ self.bad_cert_test("badkey.pem") ++ + def test_match_hostname(self): + def ok(cert, hostname): + ssl.match_hostname(cert, hostname) +@@ -772,7 +798,7 @@ + ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE) + self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE) + with self.assertRaises(IOError) as cm: +- ctx.load_cert_chain(WRONGCERT) ++ ctx.load_cert_chain(NONEXISTINGCERT) + self.assertEqual(cm.exception.errno, errno.ENOENT) + with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"): + ctx.load_cert_chain(BADCERT) +@@ -792,7 +818,7 @@ + # Mismatching key and cert + ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"): +- ctx.load_cert_chain(SVN_PYTHON_ORG_ROOT_CERT, ONLYKEY) ++ ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY) + # Password protected key and cert + ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD) + ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode()) +@@ -858,7 +884,7 @@ + self.assertRaises(TypeError, ctx.load_verify_locations) + self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None) + with self.assertRaises(IOError) as cm: +- ctx.load_verify_locations(WRONGCERT) ++ ctx.load_verify_locations(NONEXISTINGCERT) + self.assertEqual(cm.exception.errno, errno.ENOENT) + with self.assertRaises(IOError): + ctx.load_verify_locations(u'') +@@ -936,7 +962,7 @@ + self.assertRaises(TypeError, ctx.load_dh_params) + self.assertRaises(TypeError, ctx.load_dh_params, None) + with self.assertRaises(IOError) as cm: +- ctx.load_dh_params(WRONGCERT) ++ ctx.load_dh_params(NONEXISTINGCERT) + self.assertEqual(cm.exception.errno, errno.ENOENT) + with self.assertRaises(ssl.SSLError) as cm: + ctx.load_dh_params(CERTFILE) +@@ -1013,7 +1039,7 @@ + ctx.load_verify_locations(CERTFILE) + self.assertEqual(ctx.cert_store_stats(), + {'x509_ca': 0, 'crl': 0, 'x509': 1}) +- ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) ++ ctx.load_verify_locations(CAFILE_CACERT) + self.assertEqual(ctx.cert_store_stats(), + {'x509_ca': 1, 'crl': 0, 'x509': 2}) + +@@ -1023,8 +1049,8 @@ + # CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE + ctx.load_verify_locations(CERTFILE) + self.assertEqual(ctx.get_ca_certs(), []) +- # but SVN_PYTHON_ORG_ROOT_CERT is a CA cert +- ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) ++ # but CAFILE_CACERT is a CA cert ++ ctx.load_verify_locations(CAFILE_CACERT) + self.assertEqual(ctx.get_ca_certs(), + [{'issuer': ((('organizationName', 'Root CA'),), + (('organizationalUnitName', 'http://www.cacert.org'),), +@@ -1040,7 +1066,7 @@ + (('emailAddress', 'support@cacert.org'),)), + 'version': 3}]) + +- with open(SVN_PYTHON_ORG_ROOT_CERT) as f: ++ with open(CAFILE_CACERT) as f: + pem = f.read() + der = ssl.PEM_cert_to_DER_cert(pem) + self.assertEqual(ctx.get_ca_certs(True), [der]) +@@ -1215,11 +1241,11 @@ + class NetworkedTests(unittest.TestCase): + + def test_connect(self): +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE) + try: +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + self.assertEqual({}, s.getpeercert()) + finally: + s.close() +@@ -1228,27 +1254,27 @@ + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", +- s.connect, ("svn.python.org", 443)) ++ s.connect, (REMOTE_HOST, 443)) + s.close() + + # this should succeed because we specify the root cert + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT) ++ ca_certs=REMOTE_ROOT_CERT) + try: +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + self.assertTrue(s.getpeercert()) + finally: + s.close() + + def test_connect_ex(self): + # Issue #11326: check connect_ex() implementation +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT) ++ ca_certs=REMOTE_ROOT_CERT) + try: +- self.assertEqual(0, s.connect_ex(("svn.python.org", 443))) ++ self.assertEqual(0, s.connect_ex((REMOTE_HOST, 443))) + self.assertTrue(s.getpeercert()) + finally: + s.close() +@@ -1256,14 +1282,14 @@ + def test_non_blocking_connect_ex(self): + # Issue #11326: non-blocking connect_ex() should allow handshake + # to proceed after the socket gets ready. +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT, ++ ca_certs=REMOTE_ROOT_CERT, + do_handshake_on_connect=False) + try: + s.setblocking(False) +- rc = s.connect_ex(('svn.python.org', 443)) ++ rc = s.connect_ex((REMOTE_HOST, 443)) + # EWOULDBLOCK under Windows, EINPROGRESS elsewhere + self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) + # Wait for connect to finish +@@ -1285,58 +1311,62 @@ + def test_timeout_connect_ex(self): + # Issue #12065: on a timeout, connect_ex() should return the original + # errno (mimicking the behaviour of non-SSL sockets). +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT, ++ ca_certs=REMOTE_ROOT_CERT, + do_handshake_on_connect=False) + try: + s.settimeout(0.0000001) +- rc = s.connect_ex(('svn.python.org', 443)) ++ rc = s.connect_ex((REMOTE_HOST, 443)) + if rc == 0: +- self.skipTest("svn.python.org responded too quickly") ++ self.skipTest("REMOTE_HOST responded too quickly") + self.assertIn(rc, (errno.EAGAIN, errno.EWOULDBLOCK)) + finally: + s.close() + + def test_connect_ex_error(self): +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT) ++ ca_certs=REMOTE_ROOT_CERT) + try: +- rc = s.connect_ex(("svn.python.org", 444)) ++ rc = s.connect_ex((REMOTE_HOST, 444)) + # Issue #19919: Windows machines or VMs hosted on Windows + # machines sometimes return EWOULDBLOCK. +- self.assertIn(rc, (errno.ECONNREFUSED, errno.EWOULDBLOCK)) ++ errors = ( ++ errno.ECONNREFUSED, errno.EHOSTUNREACH, errno.ETIMEDOUT, ++ errno.EWOULDBLOCK, ++ ) ++ self.assertIn(rc, errors) + finally: + s.close() + + def test_connect_with_context(self): +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + # Same as test_connect, but with a separately created context + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + try: + self.assertEqual({}, s.getpeercert()) + finally: + s.close() + # Same with a server hostname + s = ctx.wrap_socket(socket.socket(socket.AF_INET), +- server_hostname="svn.python.org") +- s.connect(("svn.python.org", 443)) ++ server_hostname=REMOTE_HOST) ++ s.connect((REMOTE_HOST, 443)) + s.close() + # This should fail because we have no verification certs + ctx.verify_mode = ssl.CERT_REQUIRED + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) + self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed", +- s.connect, ("svn.python.org", 443)) ++ s.connect, (REMOTE_HOST, 443)) + s.close() + # This should succeed because we specify the root cert +- ctx.load_verify_locations(SVN_PYTHON_ORG_ROOT_CERT) ++ ctx.load_verify_locations(REMOTE_ROOT_CERT) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) +@@ -1349,12 +1379,12 @@ + # OpenSSL 0.9.8n and 1.0.0, as a result the capath directory must + # contain both versions of each certificate (same content, different + # filename) for this test to be portable across OpenSSL releases. +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) +@@ -1365,7 +1395,7 @@ + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=BYTES_CAPATH) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) +@@ -1373,15 +1403,15 @@ + s.close() + + def test_connect_cadata(self): +- with open(CAFILE_CACERT) as f: ++ with open(REMOTE_ROOT_CERT) as f: + pem = f.read().decode('ascii') + der = ssl.PEM_cert_to_DER_cert(pem) +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(cadata=pem) + with closing(ctx.wrap_socket(socket.socket(socket.AF_INET))) as s: +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + cert = s.getpeercert() + self.assertTrue(cert) + +@@ -1390,7 +1420,7 @@ + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(cadata=der) + with closing(ctx.wrap_socket(socket.socket(socket.AF_INET))) as s: +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + cert = s.getpeercert() + self.assertTrue(cert) + +@@ -1399,9 +1429,9 @@ + # Issue #5238: creating a file-like object with makefile() shouldn't + # delay closing the underlying "real socket" (here tested with its + # file descriptor, hence skipping the test under Windows). +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + ss = ssl.wrap_socket(socket.socket(socket.AF_INET)) +- ss.connect(("svn.python.org", 443)) ++ ss.connect((REMOTE_HOST, 443)) + fd = ss.fileno() + f = ss.makefile() + f.close() +@@ -1415,9 +1445,9 @@ + self.assertEqual(e.exception.errno, errno.EBADF) + + def test_non_blocking_handshake(self): +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + s = socket.socket(socket.AF_INET) +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + s.setblocking(False) + s = ssl.wrap_socket(s, + cert_reqs=ssl.CERT_NONE, +@@ -1460,12 +1490,12 @@ + if support.verbose: + sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem)) + +- _test_get_server_certificate('svn.python.org', 443, SVN_PYTHON_ORG_ROOT_CERT) ++ _test_get_server_certificate(REMOTE_HOST, 443, REMOTE_ROOT_CERT) + if support.IPV6_ENABLED: + _test_get_server_certificate('ipv6.google.com', 443) + + def test_ciphers(self): +- remote = ("svn.python.org", 443) ++ remote = (REMOTE_HOST, 443) + with support.transient_internet(remote[0]): + with closing(ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, ciphers="ALL")) as s: +@@ -1510,13 +1540,13 @@ + + def test_get_ca_certs_capath(self): + # capath certs are loaded on request +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(capath=CAPATH) + self.assertEqual(ctx.get_ca_certs(), []) + s = ctx.wrap_socket(socket.socket(socket.AF_INET)) +- s.connect(("svn.python.org", 443)) ++ s.connect((REMOTE_HOST, 443)) + try: + cert = s.getpeercert() + self.assertTrue(cert) +@@ -1527,12 +1557,12 @@ + @needs_sni + def test_context_setget(self): + # Check that the context of a connected socket can be replaced. +- with support.transient_internet("svn.python.org"): ++ with support.transient_internet(REMOTE_HOST): + ctx1 = ssl.SSLContext(ssl.PROTOCOL_TLSv1) + ctx2 = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + s = socket.socket(socket.AF_INET) + with closing(ctx1.wrap_socket(s)) as ss: +- ss.connect(("svn.python.org", 443)) ++ ss.connect((REMOTE_HOST, 443)) + self.assertIs(ss.context, ctx1) + self.assertIs(ss._sslobj.context, ctx1) + ss.context = ctx2 +@@ -1866,36 +1896,6 @@ + self.active = False + self.server.close() + +- def bad_cert_test(certfile): +- """ +- Launch a server with CERT_REQUIRED, and check that trying to +- connect to it with the given client certificate fails. +- """ +- server = ThreadedEchoServer(CERTFILE, +- certreqs=ssl.CERT_REQUIRED, +- cacerts=CERTFILE, chatty=False, +- connectionchatty=False) +- with server: +- try: +- with closing(socket.socket()) as sock: +- s = ssl.wrap_socket(sock, +- certfile=certfile, +- ssl_version=ssl.PROTOCOL_TLSv1) +- s.connect((HOST, server.port)) +- except ssl.SSLError as x: +- if support.verbose: +- sys.stdout.write("\nSSLError is %s\n" % x.args[1]) +- except OSError as x: +- if support.verbose: +- sys.stdout.write("\nOSError is %s\n" % x.args[1]) +- except OSError as x: +- if x.errno != errno.ENOENT: +- raise +- if support.verbose: +- sys.stdout.write("\OSError is %s\n" % str(x)) +- else: +- raise AssertionError("Use of invalid cert should have failed!") +- + def server_params_test(client_context, server_context, indata=b"FOO\n", + chatty=True, connectionchatty=False, sni_name=None): + """ +@@ -2134,22 +2134,38 @@ + "check_hostname requires server_hostname"): + context.wrap_socket(s) + +- def test_empty_cert(self): +- """Connecting with an empty cert file""" +- bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, +- "nullcert.pem")) +- def test_malformed_cert(self): +- """Connecting with a badly formatted certificate (syntax error)""" +- bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, +- "badcert.pem")) +- def test_nonexisting_cert(self): +- """Connecting with a non-existing cert file""" +- bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, +- "wrongcert.pem")) +- def test_malformed_key(self): +- """Connecting with a badly formatted key (syntax error)""" +- bad_cert_test(os.path.join(os.path.dirname(__file__) or os.curdir, +- "badkey.pem")) ++ def test_wrong_cert(self): ++ """Connecting when the server rejects the client's certificate ++ ++ Launch a server with CERT_REQUIRED, and check that trying to ++ connect to it with a wrong client certificate fails. ++ """ ++ certfile = os.path.join(os.path.dirname(__file__) or os.curdir, ++ "wrongcert.pem") ++ server = ThreadedEchoServer(CERTFILE, ++ certreqs=ssl.CERT_REQUIRED, ++ cacerts=CERTFILE, chatty=False, ++ connectionchatty=False) ++ with server, \ ++ closing(socket.socket()) as sock, \ ++ closing(ssl.wrap_socket(sock, ++ certfile=certfile, ++ ssl_version=ssl.PROTOCOL_TLSv1)) as s: ++ try: ++ # Expect either an SSL error about the server rejecting ++ # the connection, or a low-level connection reset (which ++ # sometimes happens on Windows) ++ s.connect((HOST, server.port)) ++ except ssl.SSLError as e: ++ if support.verbose: ++ sys.stdout.write("\nSSLError is %r\n" % e) ++ except socket.error as e: ++ if e.errno != errno.ECONNRESET: ++ raise ++ if support.verbose: ++ sys.stdout.write("\nsocket.error is %r\n" % e) ++ else: ++ self.fail("Use of invalid cert should have failed!") + + def test_rude_shutdown(self): + """A brutal shutdown of an SSL server should raise an OSError +@@ -3026,7 +3042,7 @@ + pass + + for filename in [ +- CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, BYTES_CERTFILE, ++ CERTFILE, REMOTE_ROOT_CERT, BYTES_CERTFILE, + ONLYCERT, ONLYKEY, BYTES_ONLYCERT, BYTES_ONLYKEY, + SIGNED_CERTFILE, SIGNED_CERTFILE2, SIGNING_CA, + BADCERT, BADKEY, EMPTYCERT]: +diff -r 6d1b6a68f775 Lib/test/test_str.py +--- a/Lib/test/test_str.py ++++ b/Lib/test/test_str.py +@@ -4,6 +4,9 @@ + from test import test_support, string_tests + + ++class StrSubclass(str): ++ pass ++ + class StrTest( + string_tests.CommonTest, + string_tests.MixinStrUnicodeUserStringTest, +@@ -107,6 +110,9 @@ + self.assertEqual(str(Foo6("bar")), "foos") + self.assertEqual(str(Foo7("bar")), "foos") + self.assertEqual(str(Foo8("foo")), "foofoo") ++ self.assertIs(type(str(Foo8("foo"))), Foo8) ++ self.assertEqual(StrSubclass(Foo8("foo")), "foofoo") ++ self.assertIs(type(StrSubclass(Foo8("foo"))), StrSubclass) + self.assertEqual(str(Foo9("foo")), "string") + self.assertEqual(unicode(Foo9("foo")), u"not unicode") + +diff -r 6d1b6a68f775 Lib/test/test_strptime.py +--- a/Lib/test/test_strptime.py ++++ b/Lib/test/test_strptime.py +@@ -4,8 +4,9 @@ + import time + import locale + import re ++import os + import sys +-from test import test_support ++from test import test_support as support + from datetime import date as datetime_date + + import _strptime +@@ -189,7 +190,7 @@ + + def test_whitespace_substitution(self): + # When pattern contains whitespace, make sure it is taken into account +- # so as to not allow to subpatterns to end up next to each other and ++ # so as to not allow subpatterns to end up next to each other and + # "steal" characters from each other. + pattern = self.time_re.pattern('%j %H') + self.assertFalse(re.match(pattern, "180")) +@@ -314,9 +315,10 @@ + tz_name = time.tzname[0] + if tz_name.upper() in ("UTC", "GMT"): + self.skipTest('need non-UTC/GMT timezone') +- try: +- original_tzname = time.tzname +- original_daylight = time.daylight ++ ++ with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \ ++ support.swap_attr(time, 'daylight', 1), \ ++ support.swap_attr(time, 'tzset', lambda: None): + time.tzname = (tz_name, tz_name) + time.daylight = 1 + tz_value = _strptime._strptime_time(tz_name, "%Z")[8] +@@ -324,9 +326,6 @@ + "%s lead to a timezone value of %s instead of -1 when " + "time.daylight set to %s and passing in %s" % + (time.tzname, tz_value, time.daylight, tz_name)) +- finally: +- time.tzname = original_tzname +- time.daylight = original_daylight + + def test_date_time(self): + # Test %c directive +@@ -487,14 +486,14 @@ + def test_week_0(self): + def check(value, format, *expected): + self.assertEqual(_strptime._strptime_time(value, format)[:-1], expected) +- check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, -3) ++ check('2015 0 0', '%Y %U %w', 2014, 12, 28, 0, 0, 0, 6, 362) + check('2015 0 0', '%Y %W %w', 2015, 1, 4, 0, 0, 0, 6, 4) +- check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, -2) +- check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, -2) +- check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, -1) +- check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, -1) +- check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 0) +- check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 0) ++ check('2015 0 1', '%Y %U %w', 2014, 12, 29, 0, 0, 0, 0, 363) ++ check('2015 0 1', '%Y %W %w', 2014, 12, 29, 0, 0, 0, 0, 363) ++ check('2015 0 2', '%Y %U %w', 2014, 12, 30, 0, 0, 0, 1, 364) ++ check('2015 0 2', '%Y %W %w', 2014, 12, 30, 0, 0, 0, 1, 364) ++ check('2015 0 3', '%Y %U %w', 2014, 12, 31, 0, 0, 0, 2, 365) ++ check('2015 0 3', '%Y %W %w', 2014, 12, 31, 0, 0, 0, 2, 365) + check('2015 0 4', '%Y %U %w', 2015, 1, 1, 0, 0, 0, 3, 1) + check('2015 0 4', '%Y %W %w', 2015, 1, 1, 0, 0, 0, 3, 1) + check('2015 0 5', '%Y %U %w', 2015, 1, 2, 0, 0, 0, 4, 2) +@@ -502,6 +501,20 @@ + check('2015 0 6', '%Y %U %w', 2015, 1, 3, 0, 0, 0, 5, 3) + check('2015 0 6', '%Y %W %w', 2015, 1, 3, 0, 0, 0, 5, 3) + ++ check('2009 0 0', '%Y %U %w', 2008, 12, 28, 0, 0, 0, 6, 363) ++ check('2009 0 0', '%Y %W %w', 2009, 1, 4, 0, 0, 0, 6, 4) ++ check('2009 0 1', '%Y %U %w', 2008, 12, 29, 0, 0, 0, 0, 364) ++ check('2009 0 1', '%Y %W %w', 2008, 12, 29, 0, 0, 0, 0, 364) ++ check('2009 0 2', '%Y %U %w', 2008, 12, 30, 0, 0, 0, 1, 365) ++ check('2009 0 2', '%Y %W %w', 2008, 12, 30, 0, 0, 0, 1, 365) ++ check('2009 0 3', '%Y %U %w', 2008, 12, 31, 0, 0, 0, 2, 366) ++ check('2009 0 3', '%Y %W %w', 2008, 12, 31, 0, 0, 0, 2, 366) ++ check('2009 0 4', '%Y %U %w', 2009, 1, 1, 0, 0, 0, 3, 1) ++ check('2009 0 4', '%Y %W %w', 2009, 1, 1, 0, 0, 0, 3, 1) ++ check('2009 0 5', '%Y %U %w', 2009, 1, 2, 0, 0, 0, 4, 2) ++ check('2009 0 5', '%Y %W %w', 2009, 1, 2, 0, 0, 0, 4, 2) ++ check('2009 0 6', '%Y %U %w', 2009, 1, 3, 0, 0, 0, 5, 3) ++ check('2009 0 6', '%Y %W %w', 2009, 1, 3, 0, 0, 0, 5, 3) + + class CacheTests(unittest.TestCase): + """Test that caching works properly.""" +@@ -538,7 +551,7 @@ + _strptime._strptime_time("10", "%d") + self.assertIsNot(locale_time_id, _strptime._TimeRE_cache.locale_time) + +- def test_TimeRE_recreation(self): ++ def test_TimeRE_recreation_locale(self): + # The TimeRE instance should be recreated upon changing the locale. + locale_info = locale.getlocale(locale.LC_TIME) + try: +@@ -567,9 +580,36 @@ + finally: + locale.setlocale(locale.LC_TIME, locale_info) + ++ @support.run_with_tz('STD-1DST') ++ def test_TimeRE_recreation_timezone(self): ++ # The TimeRE instance should be recreated upon changing the timezone. ++ oldtzname = time.tzname ++ tm = _strptime._strptime_time(time.tzname[0], '%Z') ++ self.assertEqual(tm.tm_isdst, 0) ++ tm = _strptime._strptime_time(time.tzname[1], '%Z') ++ self.assertEqual(tm.tm_isdst, 1) ++ # Get id of current cache object. ++ first_time_re = _strptime._TimeRE_cache ++ # Change the timezone and force a recreation of the cache. ++ os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0' ++ time.tzset() ++ tm = _strptime._strptime_time(time.tzname[0], '%Z') ++ self.assertEqual(tm.tm_isdst, 0) ++ tm = _strptime._strptime_time(time.tzname[1], '%Z') ++ self.assertEqual(tm.tm_isdst, 1) ++ # Get the new cache object's id. ++ second_time_re = _strptime._TimeRE_cache ++ # They should not be equal. ++ self.assertIsNot(first_time_re, second_time_re) ++ # Make sure old names no longer accepted. ++ with self.assertRaises(ValueError): ++ _strptime._strptime_time(oldtzname[0], '%Z') ++ with self.assertRaises(ValueError): ++ _strptime._strptime_time(oldtzname[1], '%Z') ++ + + def test_main(): +- test_support.run_unittest( ++ support.run_unittest( + getlang_Tests, + LocaleTime_Tests, + TimeRETests, +diff -r 6d1b6a68f775 Lib/test/test_support.py +--- a/Lib/test/test_support.py ++++ b/Lib/test/test_support.py +@@ -40,7 +40,7 @@ + "threading_cleanup", "reap_threads", "start_threads", "cpython_only", + "check_impl_detail", "get_attribute", "py3k_bytes", + "import_fresh_module", "threading_cleanup", "reap_children", +- "strip_python_stderr", "IPV6_ENABLED"] ++ "strip_python_stderr", "IPV6_ENABLED", "run_with_tz"] + + class Error(Exception): + """Base class for regression test exceptions.""" +@@ -1226,6 +1226,39 @@ + return decorator + + #======================================================================= ++# Decorator for running a function in a specific timezone, correctly ++# resetting it afterwards. ++ ++def run_with_tz(tz): ++ def decorator(func): ++ def inner(*args, **kwds): ++ try: ++ tzset = time.tzset ++ except AttributeError: ++ raise unittest.SkipTest("tzset required") ++ if 'TZ' in os.environ: ++ orig_tz = os.environ['TZ'] ++ else: ++ orig_tz = None ++ os.environ['TZ'] = tz ++ tzset() ++ ++ # now run the function, resetting the tz on exceptions ++ try: ++ return func(*args, **kwds) ++ finally: ++ if orig_tz is None: ++ del os.environ['TZ'] ++ else: ++ os.environ['TZ'] = orig_tz ++ time.tzset() ++ ++ inner.__name__ = func.__name__ ++ inner.__doc__ = func.__doc__ ++ return inner ++ return decorator ++ ++#======================================================================= + # Big-memory-test support. Separate from 'resources' because memory use should be configurable. + + # Some handy shorthands. Note that these are used for byte-limits as well +diff -r 6d1b6a68f775 Lib/test/test_sys.py +--- a/Lib/test/test_sys.py ++++ b/Lib/test/test_sys.py +@@ -1,9 +1,12 @@ + # -*- 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 cStringIO ++import gc ++import operator ++import os + import struct +-import operator ++import sys + + class SysModuleTest(unittest.TestCase): + +@@ -412,7 +415,10 @@ + def test_43581(self): + # Can't use sys.stdout, as this is a cStringIO object when + # the test runs under regrtest. +- self.assertTrue(sys.__stdout__.encoding == sys.__stderr__.encoding) ++ if not (os.environ.get('PYTHONIOENCODING') or ++ (sys.__stdout__.isatty() and sys.__stderr__.isatty())): ++ self.skipTest('stdout/stderr encoding is not set') ++ self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) + + def test_sys_flags(self): + self.assertTrue(sys.flags) +@@ -478,11 +484,6 @@ + self.longdigit = sys.long_info.sizeof_digit + import _testcapi + self.gc_headsize = _testcapi.SIZEOF_PYGC_HEAD +- self.file = open(test.test_support.TESTFN, 'wb') +- +- def tearDown(self): +- self.file.close() +- test.test_support.unlink(test.test_support.TESTFN) + + check_sizeof = test.test_support.check_sizeof + +@@ -526,6 +527,7 @@ + + def test_objecttypes(self): + # check all types defined in Objects/ ++ calcsize = struct.calcsize + size = test.test_support.calcobjsize + vsize = test.test_support.calcvobjsize + check = self.check_sizeof +@@ -589,9 +591,17 @@ + # method-wrapper (descriptor object) + check({}.__iter__, size('2P')) + # dict +- check({}, size('3P2P' + 8*'P2P')) ++ check({}, size('3P2P') + 8*calcsize('P2P')) + x = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} +- check(x, size('3P2P' + 8*'P2P') + 16*struct.calcsize('P2P')) ++ check(x, size('3P2P') + 8*calcsize('P2P') + 16*calcsize('P2P')) ++ # dictionary-keyview ++ check({}.viewkeys(), size('P')) ++ # dictionary-valueview ++ check({}.viewvalues(), size('P')) ++ # dictionary-itemview ++ check({}.viewitems(), size('P')) ++ # dictionary iterator ++ check(iter({}), size('P2PPP')) + # dictionary-keyiterator + check({}.iterkeys(), size('P2PPP')) + # dictionary-valueiterator +@@ -607,7 +617,12 @@ + # enumerate + check(enumerate([]), size('l3P')) + # file +- check(self.file, size('4P2i4P3i3P3i')) ++ f = file(test.test_support.TESTFN, 'wb') ++ try: ++ check(f, size('4P2i4P3i3P3i')) ++ finally: ++ f.close() ++ test.test_support.unlink(test.test_support.TESTFN) + # float + check(float(0), size('d')) + # sys.floatinfo +@@ -704,16 +719,16 @@ + check(set(sample), s) + check(frozenset(sample), s) + else: +- check(set(sample), s + newsize*struct.calcsize('lP')) +- check(frozenset(sample), s + newsize*struct.calcsize('lP')) ++ check(set(sample), s + newsize*calcsize('lP')) ++ check(frozenset(sample), s + newsize*calcsize('lP')) + # setiterator + check(iter(set()), size('P3P')) + # slice + check(slice(1), size('3P')) + # str + vh = test.test_support._vheader +- check('', struct.calcsize(vh + 'lic')) +- check('abc', struct.calcsize(vh + 'lic') + 3) ++ check('', calcsize(vh + 'lic')) ++ check('abc', calcsize(vh + 'lic') + 3) + # super + check(super(int), size('3P')) + # tuple +@@ -722,9 +737,12 @@ + # tupleiterator + check(iter(()), size('lP')) + # type +- # (PyTypeObject + PyNumberMethods + PyMappingMethods + +- # PySequenceMethods + PyBufferProcs) +- s = vsize('P2P15Pl4PP9PP11PI') + struct.calcsize('41P 10P 3P 6P') ++ s = vsize('P2P15Pl4PP9PP11PI' # PyTypeObject ++ '39P' # PyNumberMethods ++ '3P' # PyMappingMethods ++ '10P' # PySequenceMethods ++ '6P' # PyBufferProcs ++ '2P') + class newstyleclass(object): + pass + check(newstyleclass, s) +@@ -751,6 +769,32 @@ + check(xrange(1), size('3l')) + check(xrange(66000), size('3l')) + ++ def check_slots(self, obj, base, extra): ++ expected = sys.getsizeof(base) + struct.calcsize(extra) ++ if gc.is_tracked(obj) and not gc.is_tracked(base): ++ expected += self.gc_headsize ++ self.assertEqual(sys.getsizeof(obj), expected) ++ ++ def test_slots(self): ++ # check all subclassable types defined in Objects/ that allow ++ # non-empty __slots__ ++ check = self.check_slots ++ class BA(bytearray): ++ __slots__ = 'a', 'b', 'c' ++ check(BA(), bytearray(), '3P') ++ class D(dict): ++ __slots__ = 'a', 'b', 'c' ++ check(D(x=[]), {'x': []}, '3P') ++ class L(list): ++ __slots__ = 'a', 'b', 'c' ++ check(L(), [], '3P') ++ class S(set): ++ __slots__ = 'a', 'b', 'c' ++ check(S(), set(), '3P') ++ class FS(frozenset): ++ __slots__ = 'a', 'b', 'c' ++ check(FS(), frozenset(), '3P') ++ + def test_pythontypes(self): + # check all types defined in Python/ + size = test.test_support.calcobjsize +@@ -761,7 +805,12 @@ + check(_ast.AST(), size('')) + # imp.NullImporter + import imp +- check(imp.NullImporter(self.file.name), size('')) ++ f = open(test.test_support.TESTFN, 'wb') ++ try: ++ check(imp.NullImporter(f.name), size('')) ++ finally: ++ f.close() ++ test.test_support.unlink(test.test_support.TESTFN) + try: + raise TypeError + except TypeError: +diff -r 6d1b6a68f775 Lib/test/test_tarfile.py +--- a/Lib/test/test_tarfile.py ++++ b/Lib/test/test_tarfile.py +@@ -1,5 +1,3 @@ +-# -*- coding: iso-8859-15 -*- +- + import sys + import os + import shutil +@@ -62,9 +60,10 @@ + self.tar.extract("ustar/regtype", TEMPDIR) + tarinfo = self.tar.getmember("ustar/regtype") + fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") ++ with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1: ++ lines1 = fobj1.readlines() + fobj2 = self.tar.extractfile(tarinfo) + +- lines1 = fobj1.readlines() + lines2 = fobj2.readlines() + self.assertTrue(lines1 == lines2, + "fileobj.readlines() failed") +@@ -77,18 +76,17 @@ + def test_fileobj_iter(self): + self.tar.extract("ustar/regtype", TEMPDIR) + tarinfo = self.tar.getmember("ustar/regtype") +- fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") ++ with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1: ++ lines1 = fobj1.readlines() + fobj2 = self.tar.extractfile(tarinfo) +- lines1 = fobj1.readlines() + lines2 = [line for line in fobj2] + self.assertTrue(lines1 == lines2, + "fileobj.__iter__() failed") + + def test_fileobj_seek(self): + self.tar.extract("ustar/regtype", TEMPDIR) +- fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") +- data = fobj.read() +- fobj.close() ++ with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj: ++ data = fobj.read() + + tarinfo = self.tar.getmember("ustar/regtype") + fobj = self.tar.extractfile(tarinfo) +@@ -240,19 +238,24 @@ + # This test checks if tarfile.open() is able to open an empty tar + # archive successfully. Note that an empty tar archive is not the + # same as an empty file! +- tarfile.open(tmpname, self.mode.replace("r", "w")).close() ++ with tarfile.open(tmpname, self.mode.replace("r", "w")): ++ pass + try: + tar = tarfile.open(tmpname, self.mode) + tar.getnames() + except tarfile.ReadError: + self.fail("tarfile.open() failed on empty archive") +- self.assertListEqual(tar.getmembers(), []) ++ else: ++ self.assertListEqual(tar.getmembers(), []) ++ finally: ++ tar.close() + + def test_null_tarfile(self): + # Test for issue6123: Allow opening empty archives. + # This test guarantees that tarfile.open() does not treat an empty + # file as an empty tar archive. +- open(tmpname, "wb").close() ++ with open(tmpname, "wb"): ++ pass + self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode) + self.assertRaises(tarfile.ReadError, tarfile.open, tmpname) + +@@ -276,15 +279,16 @@ + for char in ('\0', 'a'): + # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a') + # are ignored correctly. +- fobj = _open(tmpname, "wb") +- fobj.write(char * 1024) +- fobj.write(tarfile.TarInfo("foo").tobuf()) +- fobj.close() ++ with _open(tmpname, "wb") as fobj: ++ fobj.write(char * 1024) ++ fobj.write(tarfile.TarInfo("foo").tobuf()) + + tar = tarfile.open(tmpname, mode="r", ignore_zeros=True) +- self.assertListEqual(tar.getnames(), ["foo"], ++ try: ++ self.assertListEqual(tar.getnames(), ["foo"], + "ignore_zeros=True should have skipped the %r-blocks" % char) +- tar.close() ++ finally: ++ tar.close() + + def test_premature_end_of_archive(self): + for size in (512, 600, 1024, 1200): +@@ -315,19 +319,21 @@ + taropen = tarfile.TarFile.taropen + + def test_no_name_argument(self): +- fobj = open(self.tarname, "rb") +- tar = tarfile.open(fileobj=fobj, mode=self.mode) +- self.assertEqual(tar.name, os.path.abspath(fobj.name)) ++ with open(self.tarname, "rb") as fobj: ++ tar = tarfile.open(fileobj=fobj, mode=self.mode) ++ self.assertEqual(tar.name, os.path.abspath(fobj.name)) + + def test_no_name_attribute(self): +- data = open(self.tarname, "rb").read() ++ with open(self.tarname, "rb") as fobj: ++ data = fobj.read() + fobj = StringIO.StringIO(data) + self.assertRaises(AttributeError, getattr, fobj, "name") + tar = tarfile.open(fileobj=fobj, mode=self.mode) + self.assertEqual(tar.name, None) + + def test_empty_name_attribute(self): +- data = open(self.tarname, "rb").read() ++ with open(self.tarname, "rb") as fobj: ++ data = fobj.read() + fobj = StringIO.StringIO(data) + fobj.name = "" + tar = tarfile.open(fileobj=fobj, mode=self.mode) +@@ -348,12 +354,14 @@ + # Skip the first member and store values from the second member + # of the testtar. + tar = tarfile.open(self.tarname, mode=self.mode) +- tar.next() +- t = tar.next() +- name = t.name +- offset = t.offset +- data = tar.extractfile(t).read() +- tar.close() ++ try: ++ tar.next() ++ t = tar.next() ++ name = t.name ++ offset = t.offset ++ data = tar.extractfile(t).read() ++ finally: ++ tar.close() + + # Open the testtar and seek to the offset of the second member. + if self.mode.endswith(":gz"): +@@ -363,26 +371,30 @@ + else: + _open = open + fobj = _open(self.tarname, "rb") +- fobj.seek(offset) ++ try: ++ fobj.seek(offset) + +- # Test if the tarfile starts with the second member. +- tar = tar.open(self.tarname, mode="r:", fileobj=fobj) +- t = tar.next() +- self.assertEqual(t.name, name) +- # Read to the end of fileobj and test if seeking back to the +- # beginning works. +- tar.getmembers() +- self.assertEqual(tar.extractfile(t).read(), data, +- "seek back did not work") +- tar.close() ++ # Test if the tarfile starts with the second member. ++ tar = tar.open(self.tarname, mode="r:", fileobj=fobj) ++ t = tar.next() ++ self.assertEqual(t.name, name) ++ # Read to the end of fileobj and test if seeking back to the ++ # beginning works. ++ tar.getmembers() ++ self.assertEqual(tar.extractfile(t).read(), data, ++ "seek back did not work") ++ tar.close() ++ finally: ++ fobj.close() + + def test_fail_comp(self): + # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file. + if self.mode == "r:": + 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) ++ with open(tarname, "rb") as fobj: ++ self.assertRaises(tarfile.ReadError, tarfile.open, ++ fileobj=fobj, mode=self.mode) + + def test_v7_dirtype(self): + # Test old style dirtype member (bug #1336623): +@@ -436,22 +448,25 @@ + # Test if extractall() correctly restores directory permissions + # and times (see issue1735). + tar = tarfile.open(tarname, encoding="iso8859-1") +- directories = [t for t in tar if t.isdir()] +- tar.extractall(TEMPDIR, directories) +- for tarinfo in directories: +- path = os.path.join(TEMPDIR, tarinfo.name) +- if sys.platform != "win32": +- # Win32 has no support for fine grained permissions. +- self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777) +- self.assertEqual(tarinfo.mtime, os.path.getmtime(path)) +- tar.close() ++ try: ++ directories = [t for t in tar if t.isdir()] ++ tar.extractall(TEMPDIR, directories) ++ for tarinfo in directories: ++ path = os.path.join(TEMPDIR, tarinfo.name) ++ if sys.platform != "win32": ++ # Win32 has no support for fine grained permissions. ++ self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777) ++ self.assertEqual(tarinfo.mtime, os.path.getmtime(path)) ++ finally: ++ tar.close() + + def test_init_close_fobj(self): + # Issue #7341: Close the internal file object in the TarFile + # constructor in case of an error. For the test we rely on + # the fact that opening an empty file raises a ReadError. + empty = os.path.join(TEMPDIR, "empty") +- open(empty, "wb").write("") ++ with open(empty, "wb") as fobj: ++ fobj.write("") + + try: + tar = object.__new__(tarfile.TarFile) +@@ -462,7 +477,7 @@ + else: + self.fail("ReadError not raised") + finally: +- os.remove(empty) ++ support.unlink(empty) + + def test_parallel_iteration(self): + # Issue #16601: Restarting iteration over tarfile continued +@@ -491,42 +506,47 @@ + + def test_compare_members(self): + tar1 = tarfile.open(tarname, encoding="iso8859-1") +- tar2 = self.tar ++ try: ++ tar2 = self.tar + +- while True: +- t1 = tar1.next() +- t2 = tar2.next() +- if t1 is None: +- break +- self.assertTrue(t2 is not None, "stream.next() failed.") ++ while True: ++ t1 = tar1.next() ++ t2 = tar2.next() ++ if t1 is None: ++ break ++ self.assertTrue(t2 is not None, "stream.next() failed.") + +- if t2.islnk() or t2.issym(): +- self.assertRaises(tarfile.StreamError, tar2.extractfile, t2) +- continue ++ if t2.islnk() or t2.issym(): ++ self.assertRaises(tarfile.StreamError, tar2.extractfile, t2) ++ continue + +- v1 = tar1.extractfile(t1) +- v2 = tar2.extractfile(t2) +- if v1 is None: +- continue +- self.assertTrue(v2 is not None, "stream.extractfile() failed") +- self.assertTrue(v1.read() == v2.read(), "stream extraction failed") +- +- tar1.close() ++ v1 = tar1.extractfile(t1) ++ v2 = tar2.extractfile(t2) ++ if v1 is None: ++ continue ++ self.assertTrue(v2 is not None, "stream.extractfile() failed") ++ self.assertTrue(v1.read() == v2.read(), "stream extraction failed") ++ finally: ++ tar1.close() + + + class DetectReadTest(unittest.TestCase): + + def _testfunc_file(self, name, mode): + try: +- tarfile.open(name, mode) ++ tar = tarfile.open(name, mode) + except tarfile.ReadError: + self.fail() ++ else: ++ tar.close() + + def _testfunc_fileobj(self, name, mode): + try: +- tarfile.open(name, mode, fileobj=open(name, "rb")) ++ tar = tarfile.open(name, mode, fileobj=open(name, "rb")) + except tarfile.ReadError: + self.fail() ++ else: ++ tar.close() + + def _test_modes(self, testfunc): + testfunc(tarname, "r") +@@ -640,7 +660,7 @@ + self._test_member(tarinfo, size=86016, chksum=md5_sparse) + + def test_find_umlauts(self): +- tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß") ++ tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf") + self._test_member(tarinfo, size=7011, chksum=md5_regtype) + + def test_find_ustar_longname(self): +@@ -653,7 +673,7 @@ + + def test_find_pax_umlauts(self): + self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1") +- tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß") ++ tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf") + self._test_member(tarinfo, size=7011, chksum=md5_regtype) + + +@@ -717,33 +737,39 @@ + + def test_pax_global_headers(self): + tar = tarfile.open(tarname, encoding="iso8859-1") ++ try: + +- tarinfo = tar.getmember("pax/regtype1") +- self.assertEqual(tarinfo.uname, "foo") +- self.assertEqual(tarinfo.gname, "bar") +- self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß") ++ tarinfo = tar.getmember("pax/regtype1") ++ self.assertEqual(tarinfo.uname, "foo") ++ self.assertEqual(tarinfo.gname, "bar") ++ self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf") + +- tarinfo = tar.getmember("pax/regtype2") +- self.assertEqual(tarinfo.uname, "") +- self.assertEqual(tarinfo.gname, "bar") +- self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß") ++ tarinfo = tar.getmember("pax/regtype2") ++ self.assertEqual(tarinfo.uname, "") ++ self.assertEqual(tarinfo.gname, "bar") ++ self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf") + +- tarinfo = tar.getmember("pax/regtype3") +- self.assertEqual(tarinfo.uname, "tarfile") +- self.assertEqual(tarinfo.gname, "tarfile") +- self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß") ++ tarinfo = tar.getmember("pax/regtype3") ++ self.assertEqual(tarinfo.uname, "tarfile") ++ self.assertEqual(tarinfo.gname, "tarfile") ++ self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf") ++ finally: ++ tar.close() + + def test_pax_number_fields(self): + # All following number fields are read from the pax header. + tar = tarfile.open(tarname, encoding="iso8859-1") +- tarinfo = tar.getmember("pax/regtype4") +- self.assertEqual(tarinfo.size, 7011) +- self.assertEqual(tarinfo.uid, 123) +- self.assertEqual(tarinfo.gid, 123) +- self.assertEqual(tarinfo.mtime, 1041808783.0) +- self.assertEqual(type(tarinfo.mtime), float) +- self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0) +- self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0) ++ try: ++ tarinfo = tar.getmember("pax/regtype4") ++ self.assertEqual(tarinfo.size, 7011) ++ self.assertEqual(tarinfo.uid, 123) ++ self.assertEqual(tarinfo.gid, 123) ++ self.assertEqual(tarinfo.mtime, 1041808783.0) ++ self.assertEqual(type(tarinfo.mtime), float) ++ self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0) ++ self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0) ++ finally: ++ tar.close() + + + class WriteTestBase(unittest.TestCase): +@@ -775,52 +801,60 @@ + # a trailing '\0'. + name = "0123456789" * 10 + tar = tarfile.open(tmpname, self.mode) +- t = tarfile.TarInfo(name) +- tar.addfile(t) +- tar.close() ++ try: ++ t = tarfile.TarInfo(name) ++ tar.addfile(t) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname) +- self.assertTrue(tar.getnames()[0] == name, +- "failed to store 100 char filename") +- tar.close() ++ try: ++ self.assertTrue(tar.getnames()[0] == name, ++ "failed to store 100 char filename") ++ finally: ++ tar.close() + + def test_tar_size(self): + # Test for bug #1013882. + tar = tarfile.open(tmpname, self.mode) +- path = os.path.join(TEMPDIR, "file") +- fobj = open(path, "wb") +- fobj.write("aaa") +- fobj.close() +- tar.add(path) +- tar.close() ++ try: ++ path = os.path.join(TEMPDIR, "file") ++ with open(path, "wb") as fobj: ++ fobj.write("aaa") ++ tar.add(path) ++ finally: ++ tar.close() + self.assertTrue(os.path.getsize(tmpname) > 0, + "tarfile is empty") + + # The test_*_size tests test for bug #1167128. + def test_file_size(self): + tar = tarfile.open(tmpname, self.mode) ++ try: + +- path = os.path.join(TEMPDIR, "file") +- fobj = open(path, "wb") +- fobj.close() +- tarinfo = tar.gettarinfo(path) +- self.assertEqual(tarinfo.size, 0) ++ path = os.path.join(TEMPDIR, "file") ++ with open(path, "wb"): ++ pass ++ tarinfo = tar.gettarinfo(path) ++ self.assertEqual(tarinfo.size, 0) + +- fobj = open(path, "wb") +- fobj.write("aaa") +- fobj.close() +- tarinfo = tar.gettarinfo(path) +- self.assertEqual(tarinfo.size, 3) +- +- tar.close() ++ with open(path, "wb") as fobj: ++ fobj.write("aaa") ++ tarinfo = tar.gettarinfo(path) ++ self.assertEqual(tarinfo.size, 3) ++ finally: ++ tar.close() + + def test_directory_size(self): + path = os.path.join(TEMPDIR, "directory") + os.mkdir(path) + try: + tar = tarfile.open(tmpname, self.mode) +- tarinfo = tar.gettarinfo(path) +- self.assertEqual(tarinfo.size, 0) ++ try: ++ tarinfo = tar.gettarinfo(path) ++ self.assertEqual(tarinfo.size, 0) ++ finally: ++ tar.close() + finally: + os.rmdir(path) + +@@ -828,16 +862,18 @@ + if hasattr(os, "link"): + link = os.path.join(TEMPDIR, "link") + target = os.path.join(TEMPDIR, "link_target") +- fobj = open(target, "wb") +- fobj.write("aaa") +- fobj.close() ++ with open(target, "wb") as fobj: ++ fobj.write("aaa") + os.link(target, link) + try: + tar = tarfile.open(tmpname, self.mode) +- # Record the link target in the inodes list. +- tar.gettarinfo(target) +- tarinfo = tar.gettarinfo(link) +- self.assertEqual(tarinfo.size, 0) ++ try: ++ # Record the link target in the inodes list. ++ tar.gettarinfo(target) ++ tarinfo = tar.gettarinfo(link) ++ self.assertEqual(tarinfo.size, 0) ++ finally: ++ tar.close() + finally: + os.remove(target) + os.remove(link) +@@ -848,26 +884,30 @@ + os.symlink("link_target", path) + try: + tar = tarfile.open(tmpname, self.mode) +- tarinfo = tar.gettarinfo(path) +- self.assertEqual(tarinfo.size, 0) ++ try: ++ tarinfo = tar.gettarinfo(path) ++ self.assertEqual(tarinfo.size, 0) ++ finally: ++ tar.close() + finally: + os.remove(path) + + def test_add_self(self): + # Test for #1257255. + dstname = os.path.abspath(tmpname) ++ tar = tarfile.open(tmpname, self.mode) ++ try: ++ self.assertTrue(tar.name == dstname, "archive name must be absolute") ++ tar.add(dstname) ++ self.assertTrue(tar.getnames() == [], "added the archive to itself") + +- tar = tarfile.open(tmpname, self.mode) +- self.assertTrue(tar.name == dstname, "archive name must be absolute") +- +- tar.add(dstname) +- self.assertTrue(tar.getnames() == [], "added the archive to itself") +- +- cwd = os.getcwd() +- os.chdir(TEMPDIR) +- tar.add(dstname) +- os.chdir(cwd) +- self.assertTrue(tar.getnames() == [], "added the archive to itself") ++ cwd = os.getcwd() ++ os.chdir(TEMPDIR) ++ tar.add(dstname) ++ os.chdir(cwd) ++ self.assertTrue(tar.getnames() == [], "added the archive to itself") ++ finally: ++ tar.close() + + def test_exclude(self): + tempdir = os.path.join(TEMPDIR, "exclude") +@@ -880,14 +920,19 @@ + exclude = os.path.isfile + + tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1") +- with test_support.check_warnings(("use the filter argument", +- DeprecationWarning)): +- tar.add(tempdir, arcname="empty_dir", exclude=exclude) +- tar.close() ++ try: ++ with test_support.check_warnings(("use the filter argument", ++ DeprecationWarning)): ++ tar.add(tempdir, arcname="empty_dir", exclude=exclude) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname, "r") +- self.assertEqual(len(tar.getmembers()), 1) +- self.assertEqual(tar.getnames()[0], "empty_dir") ++ try: ++ self.assertEqual(len(tar.getmembers()), 1) ++ self.assertEqual(tar.getnames()[0], "empty_dir") ++ finally: ++ tar.close() + finally: + shutil.rmtree(tempdir) + +@@ -907,15 +952,19 @@ + return tarinfo + + tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1") +- tar.add(tempdir, arcname="empty_dir", filter=filter) +- tar.close() ++ try: ++ tar.add(tempdir, arcname="empty_dir", filter=filter) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname, "r") +- for tarinfo in tar: +- self.assertEqual(tarinfo.uid, 123) +- self.assertEqual(tarinfo.uname, "foo") +- self.assertEqual(len(tar.getmembers()), 3) +- tar.close() ++ try: ++ for tarinfo in tar: ++ self.assertEqual(tarinfo.uid, 123) ++ self.assertEqual(tarinfo.uname, "foo") ++ self.assertEqual(len(tar.getmembers()), 3) ++ finally: ++ tar.close() + finally: + shutil.rmtree(tempdir) + +@@ -933,12 +982,16 @@ + os.mkdir(foo) + + tar = tarfile.open(tmpname, self.mode) +- tar.add(foo, arcname=path) +- tar.close() ++ try: ++ tar.add(foo, arcname=path) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname, "r") +- t = tar.next() +- tar.close() ++ try: ++ t = tar.next() ++ finally: ++ tar.close() + + if not dir: + os.remove(foo) +@@ -974,16 +1027,18 @@ + def test_cwd(self): + # Test adding the current working directory. + with support.change_cwd(TEMPDIR): +- open("foo", "w").close() +- + tar = tarfile.open(tmpname, self.mode) +- tar.add(".") +- tar.close() ++ try: ++ tar.add(".") ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname, "r") +- for t in tar: +- self.assertTrue(t.name == "." or t.name.startswith("./")) +- tar.close() ++ try: ++ for t in tar: ++ self.assertTrue(t.name == "." or t.name.startswith("./")) ++ finally: ++ tar.close() + + @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink") + def test_extractall_symlinks(self): +@@ -1100,19 +1155,18 @@ + tar.close() + + if self.mode.endswith("gz"): +- fobj = gzip.GzipFile(tmpname) +- data = fobj.read() +- fobj.close() ++ with gzip.GzipFile(tmpname) as fobj: ++ data = fobj.read() + elif self.mode.endswith("bz2"): + dec = bz2.BZ2Decompressor() +- data = open(tmpname, "rb").read() ++ with open(tmpname, "rb") as fobj: ++ data = fobj.read() + data = dec.decompress(data) + self.assertTrue(len(dec.unused_data) == 0, + "found trailing data") + else: +- fobj = open(tmpname, "rb") +- data = fobj.read() +- fobj.close() ++ with open(tmpname, "rb") as fobj: ++ data = fobj.read() + + self.assertTrue(data.count("\0") == tarfile.RECORDSIZE, + "incorrect zero padding") +@@ -1173,23 +1227,27 @@ + tarinfo.type = tarfile.LNKTYPE + + tar = tarfile.open(tmpname, "w") +- tar.format = tarfile.GNU_FORMAT +- tar.addfile(tarinfo) ++ try: ++ tar.format = tarfile.GNU_FORMAT ++ tar.addfile(tarinfo) + +- v1 = self._calc_size(name, link) +- v2 = tar.offset +- self.assertTrue(v1 == v2, "GNU longname/longlink creation failed") +- +- tar.close() ++ v1 = self._calc_size(name, link) ++ v2 = tar.offset ++ self.assertTrue(v1 == v2, "GNU longname/longlink creation failed") ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname) +- member = tar.next() +- self.assertIsNotNone(member, +- "unable to read longname member") +- self.assertEqual(tarinfo.name, member.name, +- "unable to read longname member") +- self.assertEqual(tarinfo.linkname, member.linkname, +- "unable to read longname member") ++ try: ++ member = tar.next() ++ self.assertIsNotNone(member, ++ "unable to read longname member") ++ self.assertEqual(tarinfo.name, member.name, ++ "unable to read longname member") ++ self.assertEqual(tarinfo.linkname, member.linkname, ++ "unable to read longname member") ++ finally: ++ tar.close() + + def test_longname_1023(self): + self._test(("longnam/" * 127) + "longnam") +@@ -1229,9 +1287,8 @@ + self.foo = os.path.join(TEMPDIR, "foo") + self.bar = os.path.join(TEMPDIR, "bar") + +- fobj = open(self.foo, "wb") +- fobj.write("foo") +- fobj.close() ++ with open(self.foo, "wb") as fobj: ++ fobj.write("foo") + + os.link(self.foo, self.bar) + +@@ -1240,8 +1297,8 @@ + + def tearDown(self): + self.tar.close() +- os.remove(self.foo) +- os.remove(self.bar) ++ support.unlink(self.foo) ++ support.unlink(self.bar) + + def test_add_twice(self): + # The same name will be added as a REGTYPE every +@@ -1272,44 +1329,54 @@ + tarinfo.type = tarfile.LNKTYPE + + tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT) +- tar.addfile(tarinfo) +- tar.close() ++ try: ++ tar.addfile(tarinfo) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname) +- if link: +- l = tar.getmembers()[0].linkname +- self.assertTrue(link == l, "PAX longlink creation failed") +- else: +- n = tar.getmembers()[0].name +- self.assertTrue(name == n, "PAX longname creation failed") ++ try: ++ if link: ++ l = tar.getmembers()[0].linkname ++ self.assertTrue(link == l, "PAX longlink creation failed") ++ else: ++ n = tar.getmembers()[0].name ++ self.assertTrue(name == n, "PAX longname creation failed") ++ finally: ++ tar.close() + + def test_pax_global_header(self): + pax_headers = { + u"foo": u"bar", + u"uid": u"0", + u"mtime": u"1.23", +- u"test": u"äöü", +- u"äöü": u"test"} ++ u"test": u"\xe4\xf6\xfc", ++ u"\xe4\xf6\xfc": u"test"} + + tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, + pax_headers=pax_headers) +- tar.addfile(tarfile.TarInfo("test")) +- tar.close() ++ try: ++ tar.addfile(tarfile.TarInfo("test")) ++ finally: ++ tar.close() + + # Test if the global header was written correctly. + tar = tarfile.open(tmpname, encoding="iso8859-1") +- self.assertEqual(tar.pax_headers, pax_headers) +- self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers) ++ try: ++ self.assertEqual(tar.pax_headers, pax_headers) ++ self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers) + +- # Test if all the fields are unicode. +- for key, val in tar.pax_headers.iteritems(): +- self.assertTrue(type(key) is unicode) +- self.assertTrue(type(val) is unicode) +- if key in tarfile.PAX_NUMBER_FIELDS: +- try: +- tarfile.PAX_NUMBER_FIELDS[key](val) +- except (TypeError, ValueError): +- self.fail("unable to convert pax header field") ++ # Test if all the fields are unicode. ++ for key, val in tar.pax_headers.iteritems(): ++ self.assertTrue(type(key) is unicode) ++ self.assertTrue(type(val) is unicode) ++ if key in tarfile.PAX_NUMBER_FIELDS: ++ try: ++ tarfile.PAX_NUMBER_FIELDS[key](val) ++ except (TypeError, ValueError): ++ self.fail("unable to convert pax header field") ++ finally: ++ tar.close() + + def test_pax_extended_header(self): + # The fields from the pax header have priority over the +@@ -1317,18 +1384,23 @@ + pax_headers = {u"path": u"foo", u"uid": u"123"} + + tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1") +- t = tarfile.TarInfo() +- t.name = u"äöü" # non-ASCII +- t.uid = 8**8 # too large +- t.pax_headers = pax_headers +- tar.addfile(t) +- tar.close() ++ try: ++ t = tarfile.TarInfo() ++ t.name = u"\xe4\xf6\xfc" # non-ASCII ++ t.uid = 8**8 # too large ++ t.pax_headers = pax_headers ++ tar.addfile(t) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname, encoding="iso8859-1") +- t = tar.getmembers()[0] +- self.assertEqual(t.pax_headers, pax_headers) +- self.assertEqual(t.name, "foo") +- self.assertEqual(t.uid, 123) ++ try: ++ t = tar.getmembers()[0] ++ self.assertEqual(t.pax_headers, pax_headers) ++ self.assertEqual(t.name, "foo") ++ self.assertEqual(t.uid, 123) ++ finally: ++ tar.close() + + + class UstarUnicodeTest(unittest.TestCase): +@@ -1347,57 +1419,68 @@ + + def _test_unicode_filename(self, encoding): + tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict") +- name = u"äöü" +- tar.addfile(tarfile.TarInfo(name)) +- tar.close() ++ try: ++ name = u"\xe4\xf6\xfc" ++ tar.addfile(tarfile.TarInfo(name)) ++ finally: ++ tar.close() + + tar = tarfile.open(tmpname, encoding=encoding) +- self.assertTrue(type(tar.getnames()[0]) is not unicode) +- self.assertEqual(tar.getmembers()[0].name, name.encode(encoding)) +- tar.close() ++ try: ++ self.assertTrue(type(tar.getnames()[0]) is not unicode) ++ self.assertEqual(tar.getmembers()[0].name, name.encode(encoding)) ++ finally: ++ tar.close() + + def test_unicode_filename_error(self): + tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict") +- tarinfo = tarfile.TarInfo() ++ try: ++ tarinfo = tarfile.TarInfo() + +- tarinfo.name = "äöü" +- if self.format == tarfile.PAX_FORMAT: ++ tarinfo.name = "\xe4\xf6\xfc" ++ if self.format == tarfile.PAX_FORMAT: ++ self.assertRaises(UnicodeError, tar.addfile, tarinfo) ++ else: ++ tar.addfile(tarinfo) ++ ++ tarinfo.name = u"\xe4\xf6\xfc" + self.assertRaises(UnicodeError, tar.addfile, tarinfo) +- else: +- tar.addfile(tarinfo) + +- tarinfo.name = u"äöü" +- self.assertRaises(UnicodeError, tar.addfile, tarinfo) +- +- tarinfo.name = "foo" +- tarinfo.uname = u"äöü" +- self.assertRaises(UnicodeError, tar.addfile, tarinfo) ++ tarinfo.name = "foo" ++ tarinfo.uname = u"\xe4\xf6\xfc" ++ self.assertRaises(UnicodeError, tar.addfile, tarinfo) ++ finally: ++ tar.close() + + def test_unicode_argument(self): + tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict") +- for t in tar: +- self.assertTrue(type(t.name) is str) +- self.assertTrue(type(t.linkname) is str) +- self.assertTrue(type(t.uname) is str) +- self.assertTrue(type(t.gname) is str) +- tar.close() ++ try: ++ for t in tar: ++ self.assertTrue(type(t.name) is str) ++ self.assertTrue(type(t.linkname) is str) ++ self.assertTrue(type(t.uname) is str) ++ self.assertTrue(type(t.gname) is str) ++ finally: ++ tar.close() + + def test_uname_unicode(self): +- for name in (u"äöü", "äöü"): ++ for name in (u"\xe4\xf6\xfc", "\xe4\xf6\xfc"): + t = tarfile.TarInfo("foo") + t.uname = name + t.gname = name + + fobj = StringIO.StringIO() + tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1") +- tar.addfile(t) +- tar.close() ++ try: ++ tar.addfile(t) ++ finally: ++ tar.close() + fobj.seek(0) + + tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1") + t = tar.getmember("foo") +- self.assertEqual(t.uname, "äöü") +- self.assertEqual(t.gname, "äöü") ++ self.assertEqual(t.uname, "\xe4\xf6\xfc") ++ self.assertEqual(t.gname, "\xe4\xf6\xfc") + + + class GNUUnicodeTest(UstarUnicodeTest): +@@ -1419,9 +1502,9 @@ + def test_error_handlers(self): + # Test if the unicode error handlers work correctly for characters + # that cannot be expressed in a given encoding. +- self._create_unicode_name(u"äöü") ++ self._create_unicode_name(u"\xe4\xf6\xfc") + +- for handler, name in (("utf-8", u"äöü".encode("utf8")), ++ for handler, name in (("utf-8", u"\xe4\xf6\xfc".encode("utf8")), + ("replace", "???"), ("ignore", "")): + tar = tarfile.open(tmpname, format=self.format, encoding="ascii", + errors=handler) +@@ -1433,11 +1516,11 @@ + def test_error_handler_utf8(self): + # Create a pathname that has one component representable using + # iso8859-1 and the other only in iso8859-15. +- self._create_unicode_name(u"äöü/¤") ++ self._create_unicode_name(u"\xe4\xf6\xfc/\u20ac") + + tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1", + errors="utf-8") +- self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8")) ++ self.assertEqual(tar.getnames()[0], "\xe4\xf6\xfc/" + u"\u20ac".encode("utf8")) + + + class AppendTest(unittest.TestCase): +@@ -1449,22 +1532,20 @@ + os.remove(self.tarname) + + def _add_testfile(self, fileobj=None): +- tar = tarfile.open(self.tarname, "a", fileobj=fileobj) +- tar.addfile(tarfile.TarInfo("bar")) +- tar.close() ++ with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar: ++ tar.addfile(tarfile.TarInfo("bar")) + + def _create_testtar(self, mode="w:"): +- src = tarfile.open(tarname, encoding="iso8859-1") +- t = src.getmember("ustar/regtype") +- t.name = "foo" +- f = src.extractfile(t) +- tar = tarfile.open(self.tarname, mode) +- tar.addfile(t, f) +- tar.close() ++ with tarfile.open(tarname, encoding="iso8859-1") as src: ++ t = src.getmember("ustar/regtype") ++ t.name = "foo" ++ f = src.extractfile(t) ++ with tarfile.open(self.tarname, mode) as tar: ++ tar.addfile(t, f) + + def _test(self, names=["bar"], fileobj=None): +- tar = tarfile.open(self.tarname, fileobj=fileobj) +- self.assertEqual(tar.getnames(), names) ++ with tarfile.open(self.tarname, fileobj=fileobj) as tar: ++ self.assertEqual(tar.getnames(), names) + + def test_non_existing(self): + self._add_testfile() +@@ -1483,7 +1564,8 @@ + + def test_fileobj(self): + self._create_testtar() +- data = open(self.tarname).read() ++ with open(self.tarname) as fobj: ++ data = fobj.read() + fobj = StringIO.StringIO(data) + self._add_testfile(fobj) + fobj.seek(0) +@@ -1507,7 +1589,8 @@ + # Append mode is supposed to fail if the tarfile to append to + # does not end with a zero block. + def _test_error(self, data): +- open(self.tarname, "wb").write(data) ++ with open(self.tarname, "wb") as fobj: ++ fobj.write(data) + self.assertRaises(tarfile.ReadError, self._add_testfile) + + def test_null(self): +@@ -1643,15 +1726,14 @@ + def test_fileobj(self): + # Test that __exit__() did not close the external file + # object. +- fobj = open(tmpname, "wb") +- try: +- with tarfile.open(fileobj=fobj, mode="w") as tar: +- raise Exception +- except: +- pass +- self.assertFalse(fobj.closed, "external file object was closed") +- self.assertTrue(tar.closed, "context manager failed") +- fobj.close() ++ with open(tmpname, "wb") as fobj: ++ try: ++ with tarfile.open(fileobj=fobj, mode="w") as tar: ++ raise Exception ++ except: ++ pass ++ self.assertFalse(fobj.closed, "external file object was closed") ++ self.assertTrue(tar.closed, "context manager failed") + + + class LinkEmulationTest(ReadTest): +@@ -1739,6 +1821,7 @@ + + + def test_main(): ++ support.unlink(TEMPDIR) + os.makedirs(TEMPDIR) + + tests = [ +@@ -1768,15 +1851,14 @@ + else: + tests.append(LinkEmulationTest) + +- fobj = open(tarname, "rb") +- data = fobj.read() +- fobj.close() ++ with open(tarname, "rb") as fobj: ++ data = fobj.read() + + if gzip: + # Create testtar.tar.gz and add gzip-specific tests. +- tar = gzip.open(gzipname, "wb") +- tar.write(data) +- tar.close() ++ support.unlink(gzipname) ++ with gzip.open(gzipname, "wb") as tar: ++ tar.write(data) + + tests += [ + GzipMiscReadTest, +@@ -1789,9 +1871,12 @@ + + if bz2: + # Create testtar.tar.bz2 and add bz2-specific tests. ++ support.unlink(bz2name) + tar = bz2.BZ2File(bz2name, "wb") +- tar.write(data) +- tar.close() ++ try: ++ tar.write(data) ++ finally: ++ tar.close() + + tests += [ + Bz2MiscReadTest, +diff -r 6d1b6a68f775 Lib/test/test_tempfile.py +--- a/Lib/test/test_tempfile.py ++++ b/Lib/test/test_tempfile.py +@@ -827,6 +827,13 @@ + os.close = old_close + os.fdopen = old_fdopen + ++ def test_bad_mode(self): ++ dir = tempfile.mkdtemp() ++ self.addCleanup(support.rmtree, dir) ++ with self.assertRaises(TypeError): ++ tempfile.NamedTemporaryFile(mode=(), dir=dir) ++ self.assertEqual(os.listdir(dir), []) ++ + # How to test the mode and bufsize parameters? + + test_classes.append(test_NamedTemporaryFile) +diff -r 6d1b6a68f775 Lib/test/test_thread.py +--- a/Lib/test/test_thread.py ++++ b/Lib/test/test_thread.py +@@ -233,7 +233,12 @@ + if pid == 0: # child + os.close(self.read_fd) + os.write(self.write_fd, "OK") +- sys.exit(0) ++ # Exiting the thread normally in the child process can leave ++ # any additional threads (such as the one started by ++ # importing _tkinter) still running, and this can prevent ++ # the half-zombie child process from being cleaned up. See ++ # Issue #26456. ++ os._exit(0) + else: # parent + os.close(self.write_fd) + +diff -r 6d1b6a68f775 Lib/test/test_threading.py +--- a/Lib/test/test_threading.py ++++ b/Lib/test/test_threading.py +@@ -51,7 +51,7 @@ + self.nrunning.inc() + if verbose: + print self.nrunning.get(), 'tasks are running' +- self.testcase.assertTrue(self.nrunning.get() <= 3) ++ self.testcase.assertLessEqual(self.nrunning.get(), 3) + + time.sleep(delay) + if verbose: +@@ -59,7 +59,7 @@ + + with self.mutex: + self.nrunning.dec() +- self.testcase.assertTrue(self.nrunning.get() >= 0) ++ self.testcase.assertGreaterEqual(self.nrunning.get(), 0) + if verbose: + print '%s is finished. %d tasks are running' % ( + self.name, self.nrunning.get()) +@@ -92,25 +92,25 @@ + for i in range(NUMTASKS): + t = TestThread(""%i, self, sema, mutex, numrunning) + threads.append(t) +- self.assertEqual(t.ident, None) +- self.assertTrue(re.match('', repr(t))) ++ self.assertIsNone(t.ident) ++ self.assertRegexpMatches(repr(t), r'^$') + t.start() + + if verbose: + print 'waiting for all tasks to complete' + for t in threads: + t.join(NUMTASKS) +- self.assertTrue(not t.is_alive()) ++ self.assertFalse(t.is_alive()) + self.assertNotEqual(t.ident, 0) +- self.assertFalse(t.ident is None) +- self.assertTrue(re.match('', repr(t))) ++ self.assertIsNotNone(t.ident) ++ self.assertRegexpMatches(repr(t), r'^$') + if verbose: + print 'all tasks done' + self.assertEqual(numrunning.get(), 0) + + def test_ident_of_no_threading_threads(self): + # The ident still must work for the main thread and dummy threads. +- self.assertFalse(threading.currentThread().ident is None) ++ self.assertIsNotNone(threading.currentThread().ident) + def f(): + ident.append(threading.currentThread().ident) + done.set() +@@ -118,7 +118,7 @@ + ident = [] + thread.start_new_thread(f, ()) + done.wait() +- self.assertFalse(ident[0] is None) ++ self.assertIsNotNone(ident[0]) + # Kill the "immortal" _DummyThread + del threading._active[ident[0]] + +@@ -236,7 +236,7 @@ + self.assertTrue(ret) + if verbose: + print " verifying worker hasn't exited" +- self.assertTrue(not t.finished) ++ self.assertFalse(t.finished) + if verbose: + print " attempting to raise asynch exception in worker" + result = set_async_exc(ctypes.c_long(t.id), exception) +diff -r 6d1b6a68f775 Lib/test/test_threading_local.py +--- a/Lib/test/test_threading_local.py ++++ b/Lib/test/test_threading_local.py +@@ -196,7 +196,7 @@ + wr = weakref.ref(x) + del x + gc.collect() +- self.assertIs(wr(), None) ++ self.assertIsNone(wr()) + + class PyThreadingLocalTest(unittest.TestCase, BaseLocalTest): + _local = _threading_local.local +diff -r 6d1b6a68f775 Lib/test/test_unicode.py +--- a/Lib/test/test_unicode.py ++++ b/Lib/test/test_unicode.py +@@ -33,6 +33,9 @@ + return None + codecs.register(search_function) + ++class UnicodeSubclass(unicode): ++ pass ++ + class UnicodeTest( + string_tests.CommonTest, + string_tests.MixinStrUnicodeUserStringTest, +@@ -685,9 +688,6 @@ + u'unicode remains unicode' + ) + +- class UnicodeSubclass(unicode): +- pass +- + self.assertEqual( + unicode(UnicodeSubclass('unicode subclass becomes unicode')), + u'unicode subclass becomes unicode' +@@ -1037,10 +1037,12 @@ + self.assertEqual(unicode('Andr\202 x','ascii','ignore'), u"Andr x") + self.assertEqual(unicode('Andr\202 x','ascii','replace'), u'Andr\uFFFD x') + self.assertEqual(unicode('\202 x', 'ascii', 'replace'), u'\uFFFD x') +- self.assertEqual(u'abcde'.decode('ascii', 'ignore'), +- u'abcde'.decode('ascii', errors='ignore')) +- self.assertEqual(u'abcde'.decode('ascii', 'replace'), +- u'abcde'.decode(encoding='ascii', errors='replace')) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(u'abcde'.decode('ascii', 'ignore'), ++ u'abcde'.decode('ascii', errors='ignore')) ++ with test_support.check_py3k_warnings(): ++ self.assertEqual(u'abcde'.decode('ascii', 'replace'), ++ u'abcde'.decode(encoding='ascii', errors='replace')) + + # Error handling (unknown character names) + self.assertEqual("\\N{foo}xx".decode("unicode-escape", "ignore"), u"xx") +@@ -1269,6 +1271,9 @@ + self.assertEqual(unicode(Foo6("bar")), u"foou") + self.assertEqual(unicode(Foo7("bar")), u"foou") + self.assertEqual(unicode(Foo8("foo")), u"foofoo") ++ self.assertIs(type(unicode(Foo8("foo"))), Foo8) ++ self.assertEqual(UnicodeSubclass(Foo8("foo")), u"foofoo") ++ self.assertIs(type(UnicodeSubclass(Foo8("foo"))), UnicodeSubclass) + self.assertEqual(str(Foo9("foo")), "string") + self.assertEqual(unicode(Foo9("foo")), u"not unicode") + +diff -r 6d1b6a68f775 Lib/test/test_urllib.py +--- a/Lib/test/test_urllib.py ++++ b/Lib/test/test_urllib.py +@@ -209,10 +209,26 @@ + Content-Type: text/html; charset=iso-8859-1 + """) + try: +- self.assertRaises(IOError, urllib.urlopen, "http://python.org/") ++ msg = "Redirection to url 'file:" ++ with self.assertRaisesRegexp(IOError, msg): ++ urllib.urlopen("http://python.org/") + finally: + self.unfakehttp() + ++ def test_redirect_limit_independent(self): ++ # Ticket #12923: make sure independent requests each use their ++ # own retry limit. ++ for i in range(urllib.FancyURLopener().maxtries): ++ self.fakehttp(b'''HTTP/1.1 302 Found ++Location: file://guidocomputer.athome.com:/python/license ++Connection: close ++''') ++ try: ++ self.assertRaises(IOError, urllib.urlopen, ++ "http://something") ++ finally: ++ self.unfakehttp() ++ + def test_empty_socket(self): + # urlopen() raises IOError if the underlying socket does not send any + # data. (#1680230) +diff -r 6d1b6a68f775 Lib/test/test_urllib2.py +--- a/Lib/test/test_urllib2.py ++++ b/Lib/test/test_urllib2.py +@@ -6,7 +6,7 @@ + import StringIO + + import urllib2 +-from urllib2 import Request, OpenerDirector ++from urllib2 import Request, OpenerDirector, AbstractDigestAuthHandler + + try: + import ssl +@@ -1290,6 +1290,16 @@ + else: + self.assertTrue(False) + ++ def test_unsupported_algorithm(self): ++ handler = AbstractDigestAuthHandler() ++ with self.assertRaises(ValueError) as exc: ++ handler.get_algorithm_impls('invalid') ++ self.assertEqual( ++ str(exc.exception), ++ "Unsupported digest authentication algorithm 'invalid'" ++ ) ++ ++ + class RequestTests(unittest.TestCase): + + def setUp(self): +@@ -1350,6 +1360,11 @@ + req = Request(url) + self.assertEqual(req.get_full_url(), url) + ++ def test_private_attributes(self): ++ self.assertFalse(hasattr(self.get, '_Request__r_xxx')) ++ # Issue #6500: infinite recursion ++ self.assertFalse(hasattr(self.get, '_Request__r_method')) ++ + def test_HTTPError_interface(self): + """ + Issue 13211 reveals that HTTPError didn't implement the URLError +diff -r 6d1b6a68f775 Lib/test/test_xml_etree_c.py +--- a/Lib/test/test_xml_etree_c.py ++++ b/Lib/test/test_xml_etree_c.py +@@ -30,6 +30,38 @@ + finally: + data = None + ++ def test_del_attribute(self): ++ element = cET.Element('tag') ++ ++ element.tag = 'TAG' ++ with self.assertRaises(AttributeError): ++ del element.tag ++ self.assertEqual(element.tag, 'TAG') ++ ++ with self.assertRaises(AttributeError): ++ del element.text ++ self.assertIsNone(element.text) ++ element.text = 'TEXT' ++ with self.assertRaises(AttributeError): ++ del element.text ++ self.assertEqual(element.text, 'TEXT') ++ ++ with self.assertRaises(AttributeError): ++ del element.tail ++ self.assertIsNone(element.tail) ++ element.tail = 'TAIL' ++ with self.assertRaises(AttributeError): ++ del element.tail ++ self.assertEqual(element.tail, 'TAIL') ++ ++ with self.assertRaises(AttributeError): ++ del element.attrib ++ self.assertEqual(element.attrib, {}) ++ element.attrib = {'A': 'B', 'C': 'D'} ++ with self.assertRaises(AttributeError): ++ del element.attrib ++ self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'}) ++ + + def test_main(): + from test import test_xml_etree, test_xml_etree_c +diff -r 6d1b6a68f775 Lib/test/test_xmlrpc.py +--- a/Lib/test/test_xmlrpc.py ++++ b/Lib/test/test_xmlrpc.py +@@ -23,13 +23,6 @@ + except ImportError: + gzip = None + +-try: +- unicode +-except NameError: +- have_unicode = False +-else: +- have_unicode = True +- + alist = [{'astring': 'foo@bar.baz.spam', + 'afloat': 7283.43, + 'anint': 2**20, +@@ -37,8 +30,6 @@ + 'anotherlist': ['.zyx.41'], + 'abase64': xmlrpclib.Binary("my dog has fleas"), + 'boolean': xmlrpclib.False, +- 'unicode': u'\u4000\u6000\u8000', +- u'ukey\u4000': 'regular value', + 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'), + 'datetime2': xmlrpclib.DateTime( + (2005, 02, 10, 11, 41, 23, 0, 1, -1)), +@@ -46,6 +37,12 @@ + datetime.datetime(2005, 02, 10, 11, 41, 23)), + }] + ++if test_support.have_unicode: ++ alist[0].update({ ++ 'unicode': test_support.u(r'\u4000\u6000\u8000'), ++ test_support.u(r'ukey\u4000'): 'regular value', ++ }) ++ + class XMLRPCTestCase(unittest.TestCase): + + def test_dump_load(self): +@@ -150,6 +147,25 @@ + xmlrpclib.loads(strg)[0][0]) + self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,)) + ++ @test_support.requires_unicode ++ def test_dump_encoding(self): ++ value = {test_support.u(r'key\u20ac\xa4'): ++ test_support.u(r'value\u20ac\xa4')} ++ strg = xmlrpclib.dumps((value,), encoding='iso-8859-15') ++ strg = "" + strg ++ self.assertEqual(xmlrpclib.loads(strg)[0][0], value) ++ ++ strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', ++ methodresponse=True) ++ self.assertEqual(xmlrpclib.loads(strg)[0][0], value) ++ ++ methodname = test_support.u(r'method\u20ac\xa4') ++ strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', ++ methodname=methodname) ++ self.assertEqual(xmlrpclib.loads(strg)[0][0], value) ++ self.assertEqual(xmlrpclib.loads(strg)[1], methodname) ++ ++ @test_support.requires_unicode + def test_default_encoding_issues(self): + # SF bug #1115989: wrong decoding in '_stringify' + utf8 = """ +@@ -182,7 +198,7 @@ + temp_sys.setdefaultencoding(old_encoding) + + items = d.items() +- if have_unicode: ++ if test_support.have_unicode: + self.assertEqual(s, u"abc \x95") + self.assertIsInstance(s, unicode) + self.assertEqual(items, [(u"def \x96", u"ghi \x97")]) +@@ -282,7 +298,7 @@ + # The evt is set twice. First when the server is ready to serve. + # Second when the server has been shutdown. The user must clear + # the event after it has been set the first time to catch the second set. +-def http_server(evt, numrequests, requestHandler=None): ++def http_server(evt, numrequests, requestHandler=None, encoding=None): + class TestInstanceClass: + def div(self, x, y): + return x // y +@@ -306,6 +322,7 @@ + if not requestHandler: + requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler + serv = MyXMLRPCServer(("localhost", 0), requestHandler, ++ encoding=encoding, + logRequests=False, bind_and_activate=False) + try: + serv.socket.settimeout(3) +@@ -322,6 +339,7 @@ + serv.register_multicall_functions() + serv.register_function(pow) + serv.register_function(lambda x,y: x+y, 'add') ++ serv.register_function(lambda x: x, test_support.u(r't\xea\u0161t')) + serv.register_function(my_function) + serv.register_instance(TestInstanceClass()) + evt.set() +@@ -463,9 +481,10 @@ + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) + ++ @test_support.requires_unicode + def test_nonascii(self): +- start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t' +- end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n' ++ start_string = test_support.u(r'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t') ++ end_string = test_support.u(r'h\N{LATIN SMALL LETTER O WITH HORN}n') + + try: + p = xmlrpclib.ServerProxy(URL) +@@ -477,10 +496,38 @@ + # protocol error; provide additional information in test output + self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) + ++ @test_support.requires_unicode + def test_unicode_host(self): + server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT)) + self.assertEqual(server.add("a", u"\xe9"), u"a\xe9") + ++ @test_support.requires_unicode ++ def test_client_encoding(self): ++ start_string = unichr(0x20ac) ++ end_string = unichr(0xa4) ++ ++ try: ++ p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15') ++ self.assertEqual(p.add(start_string, end_string), ++ start_string + end_string) ++ except (xmlrpclib.ProtocolError, socket.error) as e: ++ # ignore failures due to non-blocking socket unavailable errors. ++ if not is_unavailable_exception(e): ++ # protocol error; provide additional information in test output ++ self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) ++ ++ @test_support.requires_unicode ++ def test_nonascii_methodname(self): ++ try: ++ p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15') ++ m = getattr(p, 't\xea\xa8t') ++ self.assertEqual(m(42), 42) ++ except (xmlrpclib.ProtocolError, socket.error) as e: ++ # ignore failures due to non-blocking socket unavailable errors. ++ if not is_unavailable_exception(e): ++ # protocol error; provide additional information in test output ++ self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) ++ + # [ch] The test 404 is causing lots of false alarms. + def XXXtest_404(self): + # send POST with httplib, it should return 404 header and +@@ -498,6 +545,7 @@ + p = xmlrpclib.ServerProxy(URL) + meth = p.system.listMethods() + expected_methods = set(['pow', 'div', 'my_function', 'add', ++ test_support.u(r't\xea\u0161t'), + 'system.listMethods', 'system.methodHelp', + 'system.methodSignature', 'system.multicall']) + self.assertEqual(set(meth), expected_methods) +@@ -600,6 +648,27 @@ + conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye') + conn.close() + ++class SimpleServerEncodingTestCase(BaseServerTestCase): ++ @staticmethod ++ def threadFunc(evt, numrequests, requestHandler=None, encoding=None): ++ http_server(evt, numrequests, requestHandler, 'iso-8859-15') ++ ++ @test_support.requires_unicode ++ def test_server_encoding(self): ++ start_string = unichr(0x20ac) ++ end_string = unichr(0xa4) ++ ++ try: ++ p = xmlrpclib.ServerProxy(URL) ++ self.assertEqual(p.add(start_string, end_string), ++ start_string + end_string) ++ except (xmlrpclib.ProtocolError, socket.error) as e: ++ # ignore failures due to non-blocking socket unavailable errors. ++ if not is_unavailable_exception(e): ++ # protocol error; provide additional information in test output ++ self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) ++ ++ + class MultiPathServerTestCase(BaseServerTestCase): + threadFunc = staticmethod(http_multi_server) + request_count = 2 +@@ -1032,6 +1101,7 @@ + xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase, + BinaryTestCase, FaultTestCase, TransportSubclassTestCase] + xmlrpc_tests.append(SimpleServerTestCase) ++ xmlrpc_tests.append(SimpleServerEncodingTestCase) + xmlrpc_tests.append(KeepaliveServerTestCase1) + xmlrpc_tests.append(KeepaliveServerTestCase2) + xmlrpc_tests.append(GzipServerTestCase) +diff -r 6d1b6a68f775 Lib/test/test_zipfile64.py +--- a/Lib/test/test_zipfile64.py ++++ b/Lib/test/test_zipfile64.py +@@ -79,15 +79,19 @@ + def testStored(self): + # Try the temp file first. If we do TESTFN2 first, then it hogs + # gigabytes of disk space for the duration of the test. +- for f in TemporaryFile(), TESTFN2: ++ with TemporaryFile() as f: + self.zipTest(f, zipfile.ZIP_STORED) ++ self.assertFalse(f.closed) ++ self.zipTest(TESTFN2, zipfile.ZIP_STORED) + +- if zlib: +- def testDeflated(self): +- # Try the temp file first. If we do TESTFN2 first, then it hogs +- # gigabytes of disk space for the duration of the test. +- for f in TemporaryFile(), TESTFN2: +- self.zipTest(f, zipfile.ZIP_DEFLATED) ++ @unittest.skipUnless(zlib, "requires zlib") ++ def testDeflated(self): ++ # Try the temp file first. If we do TESTFN2 first, then it hogs ++ # gigabytes of disk space for the duration of the test. ++ with TemporaryFile() as f: ++ self.zipTest(f, zipfile.ZIP_DEFLATED) ++ self.assertFalse(f.closed) ++ self.zipTest(TESTFN2, zipfile.ZIP_DEFLATED) + + def tearDown(self): + for fname in TESTFN, TESTFN2: +diff -r 6d1b6a68f775 Lib/urllib.py +--- a/Lib/urllib.py ++++ b/Lib/urllib.py +@@ -629,18 +629,20 @@ + def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): + """Error 302 -- relocated (temporarily).""" + self.tries += 1 +- if self.maxtries and self.tries >= self.maxtries: +- if hasattr(self, "http_error_500"): +- meth = self.http_error_500 +- else: +- meth = self.http_error_default ++ try: ++ if self.maxtries and self.tries >= self.maxtries: ++ if hasattr(self, "http_error_500"): ++ meth = self.http_error_500 ++ else: ++ meth = self.http_error_default ++ return meth(url, fp, 500, ++ "Internal Server Error: Redirect Recursion", ++ headers) ++ result = self.redirect_internal(url, fp, errcode, errmsg, ++ headers, data) ++ return result ++ finally: + self.tries = 0 +- return meth(url, fp, 500, +- "Internal Server Error: Redirect Recursion", headers) +- result = self.redirect_internal(url, fp, errcode, errmsg, headers, +- data) +- self.tries = 0 +- return result + + def redirect_internal(self, url, fp, errcode, errmsg, headers, data): + if 'location' in headers: +diff -r 6d1b6a68f775 Lib/urllib2.py +--- a/Lib/urllib2.py ++++ b/Lib/urllib2.py +@@ -248,11 +248,9 @@ + # methods getting called in a non-standard order. this may be + # too complicated and/or unnecessary. + # XXX should the __r_XXX attributes be public? +- if attr[:12] == '_Request__r_': +- name = attr[12:] +- if hasattr(Request, 'get_' + name): +- getattr(self, 'get_' + name)() +- return getattr(self, attr) ++ if attr in ('_Request__r_type', '_Request__r_host'): ++ getattr(self, 'get_' + attr[12:])() ++ return self.__dict__[attr] + raise AttributeError, attr + + def get_method(self): +@@ -1073,6 +1071,9 @@ + elif algorithm == 'SHA': + H = lambda x: hashlib.sha1(x).hexdigest() + # XXX MD5-sess ++ else: ++ raise ValueError("Unsupported digest authentication " ++ "algorithm %r" % algorithm.lower()) + KD = lambda s, d: H("%s:%s" % (s, d)) + return H, KD + +diff -r 6d1b6a68f775 Lib/xml/dom/minicompat.py +--- a/Lib/xml/dom/minicompat.py ++++ b/Lib/xml/dom/minicompat.py +@@ -65,10 +65,10 @@ + length = property(_get_length, _set_length, + doc="The number of nodes in the NodeList.") + +- def __getstate__(self): +- return list(self) +- ++ # For backward compatibility + def __setstate__(self, state): ++ if state is None: ++ state = [] + self[:] = state + + +diff -r 6d1b6a68f775 Lib/xml/etree/ElementTree.py +--- a/Lib/xml/etree/ElementTree.py ++++ b/Lib/xml/etree/ElementTree.py +@@ -1198,9 +1198,14 @@ + if not hasattr(source, "read"): + source = open(source, "rb") + close_source = True +- if not parser: +- parser = XMLParser(target=TreeBuilder()) +- return _IterParseIterator(source, events, parser, close_source) ++ try: ++ if not parser: ++ parser = XMLParser(target=TreeBuilder()) ++ return _IterParseIterator(source, events, parser, close_source) ++ except: ++ if close_source: ++ source.close() ++ raise + + class _IterParseIterator(object): + +@@ -1252,34 +1257,40 @@ + raise ValueError("unknown event %r" % event) + + def next(self): +- while 1: +- try: +- item = self._events[self._index] +- self._index += 1 +- return item +- except IndexError: +- pass +- if self._error: +- e = self._error +- self._error = None +- raise e +- if self._parser is None: +- self.root = self._root +- if self._close_file: +- self._file.close() +- raise StopIteration +- # load event buffer +- del self._events[:] +- self._index = 0 +- data = self._file.read(16384) +- if data: ++ try: ++ while 1: + try: +- self._parser.feed(data) +- except SyntaxError as exc: +- self._error = exc +- else: +- self._root = self._parser.close() +- self._parser = None ++ item = self._events[self._index] ++ self._index += 1 ++ return item ++ except IndexError: ++ pass ++ if self._error: ++ e = self._error ++ self._error = None ++ raise e ++ if self._parser is None: ++ self.root = self._root ++ break ++ # load event buffer ++ del self._events[:] ++ self._index = 0 ++ data = self._file.read(16384) ++ if data: ++ try: ++ self._parser.feed(data) ++ except SyntaxError as exc: ++ self._error = exc ++ else: ++ self._root = self._parser.close() ++ self._parser = None ++ except: ++ if self._close_file: ++ self._file.close() ++ raise ++ if self._close_file: ++ self._file.close() ++ raise StopIteration + + def __iter__(self): + return self +diff -r 6d1b6a68f775 Lib/xmlrpclib.py +--- a/Lib/xmlrpclib.py ++++ b/Lib/xmlrpclib.py +@@ -393,7 +393,7 @@ + elif datetime and isinstance(other, datetime.datetime): + s = self.value + o = other.strftime("%Y%m%dT%H:%M:%S") +- elif isinstance(other, (str, unicode)): ++ elif isinstance(other, basestring): + s = self.value + o = other + elif hasattr(other, "timetuple"): +@@ -703,9 +703,8 @@ + + if unicode: + def dump_unicode(self, value, write, escape=escape): +- value = value.encode(self.encoding) + write("") +- write(escape(value)) ++ write(escape(value).encode(self.encoding, 'xmlcharrefreplace')) + write("\n") + dispatch[UnicodeType] = dump_unicode + +@@ -732,12 +731,13 @@ + write("\n") + for k, v in value.items(): + write("\n") +- if type(k) is not StringType: +- if unicode and type(k) is UnicodeType: +- k = k.encode(self.encoding) +- else: +- raise TypeError, "dictionary key must be string" +- write("%s\n" % escape(k)) ++ if type(k) is StringType: ++ k = escape(k) ++ elif unicode and type(k) is UnicodeType: ++ k = escape(k).encode(self.encoding, 'xmlcharrefreplace') ++ else: ++ raise TypeError, "dictionary key must be string" ++ write("%s\n" % k) + dump(v, write) + write("\n") + write("\n") +@@ -1099,7 +1099,7 @@ + if methodname: + # a method call + if not isinstance(methodname, StringType): +- methodname = methodname.encode(encoding) ++ methodname = methodname.encode(encoding, 'xmlcharrefreplace') + data = ( + xmlheader, + "\n" +@@ -1560,7 +1560,7 @@ + allow_none=0, use_datetime=0, context=None): + # establish a "logical" server connection + +- if isinstance(uri, unicode): ++ if unicode and isinstance(uri, unicode): + uri = uri.encode('ISO-8859-1') + + # get the url +diff -r 6d1b6a68f775 Mac/BuildScript/build-installer.py +--- a/Mac/BuildScript/build-installer.py ++++ b/Mac/BuildScript/build-installer.py +@@ -206,7 +206,7 @@ + + LT_10_5 = bool(getDeptargetTuple() < (10, 5)) + +- if getDeptargetTuple() < (10, 6): ++ if not (10, 5) < getDeptargetTuple() < (10, 10): + # The OpenSSL libs shipped with OS X 10.5 and earlier are + # hopelessly out-of-date and do not include Apple's tie-in to + # the root certificates in the user and system keychains via TEA +@@ -226,7 +226,8 @@ + # now more obvious with cert checking enabled by default in the + # standard library. + # +- # For builds with 10.6+ SDKs, continue to use the deprecated but ++ # For builds with 10.6 through 10.9 SDKs, ++ # continue to use the deprecated but + # less out-of-date Apple 0.9.8 libs for now. While they are less + # secure than using an up-to-date 1.0.1 version, doing so + # avoids the big problems of forcing users to have to manage +@@ -234,12 +235,16 @@ + # APIs for cert validation from keychains if validation using the + # standard OpenSSL locations (/System/Library/OpenSSL, normally empty) + # fails. ++ # ++ # Since Apple removed the header files for the deprecated system ++ # OpenSSL as of the Xcode 7 release (for OS X 10.10+), we do not ++ # have much choice but to build our own copy here, too. + + result.extend([ + dict( +- name="OpenSSL 1.0.2d", +- url="https://www.openssl.org/source/openssl-1.0.2d.tar.gz", +- checksum='38dd619b2e77cbac69b99f52a053d25a', ++ name="OpenSSL 1.0.2g", ++ url="https://www.openssl.org/source/openssl-1.0.2g.tar.gz", ++ checksum='f3c710c045cdee5fd114feb69feba7aa', + patches=[ + "openssl_sdk_makedepend.patch", + ], +diff -r 6d1b6a68f775 Mac/BuildScript/openssl_sdk_makedepend.patch +--- a/Mac/BuildScript/openssl_sdk_makedepend.patch ++++ b/Mac/BuildScript/openssl_sdk_makedepend.patch +@@ -1,18 +1,17 @@ + # HG changeset patch +-# Parent 25a9af415e8c3faf591c360d5f0e361d049b2b43 ++# Parent d377390f787c0739a3e89f669def72d7167e5108 + # openssl_sdk_makedepend.patch + # +-# using openssl 1.0.2d ++# using openssl 1.0.2f + # + # - support building with an OS X SDK +-# - allow "make depend" to use compilers with names other than "gcc" + + diff Configure + + diff --git a/Configure b/Configure + --- a/Configure + +++ b/Configure +-@@ -617,12 +617,12 @@ ++@@ -638,12 +638,12 @@ + + ##### MacOS X (a.k.a. Rhapsody or Darwin) setup + "rhapsody-ppc-cc","cc:-O3 -DB_ENDIAN::(unknown):MACOSX_RHAPSODY::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}::", +@@ -31,24 +30,13 @@ + "debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", + # iPhoneOS/iOS + "iphoneos-cross","llvm-gcc:-O3 -isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fomit-frame-pointer -fno-common::-D_REENTRANT:iOS:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib", +-@@ -1685,7 +1685,7 @@ ++@@ -1717,8 +1717,7 @@ + s/^CC=.*$/CC= $cc/; + s/^AR=\s*ar/AR= $ar/; + s/^RANLIB=.*/RANLIB= $ranlib/; + - s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $cc eq "gcc"; +-+ s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/; ++- s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $ecc eq "gcc" || $ecc eq "clang"; +++ s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ + } + s/^CFLAG=.*$/CFLAG= $cflags/; + s/^DEPFLAG=.*$/DEPFLAG=$depflags/; +-diff --git a/util/domd b/util/domd +---- a/util/domd +-+++ b/util/domd +-@@ -14,7 +14,7 @@ +- cp Makefile Makefile.save +- # fake the presence of Kerberos +- touch $TOP/krb5.h +--if expr "$MAKEDEPEND" : '.*gcc$' > /dev/null; then +-+if true ; then # was: if expr "$MAKEDEPEND" : '.*gcc$' > /dev/null; then +- args="" +- while [ $# -gt 0 ]; do +- if [ "$1" != "--" ]; then args="$args $1"; fi +diff -r 6d1b6a68f775 Mac/BuildScript/resources/License.rtf +--- a/Mac/BuildScript/resources/License.rtf ++++ b/Mac/BuildScript/resources/License.rtf +@@ -54,7 +54,7 @@ + \b0 \ + 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, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee.\ ++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, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 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.\ + \ +diff -r 6d1b6a68f775 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-2015 Python Software Foundation ++ %VERSION%, © 2001-2016 Python Software Foundation + CFBundleIconFile + IDLE.icns + CFBundleIdentifier +diff -r 6d1b6a68f775 Mac/IDLE/Makefile.in +--- a/Mac/IDLE/Makefile.in ++++ b/Mac/IDLE/Makefile.in +@@ -7,6 +7,7 @@ + LDFLAGS=@LDFLAGS@ + srcdir= @srcdir@ + VERSION= @VERSION@ ++LIBDEST=$(prefix)/lib/python$(VERSION) + UNIVERSALSDK=@UNIVERSALSDK@ + builddir= ../.. + PYTHONFRAMEWORK=@PYTHONFRAMEWORK@ +@@ -28,13 +29,28 @@ + + all: IDLE.app + +-install: IDLE.app $(srcdir)/config-main.def $(srcdir)/config-extensions.def ++install: IDLE.app + test -d "$(DESTDIR)$(PYTHONAPPSDIR)" || mkdir -p "$(DESTDIR)$(PYTHONAPPSDIR)" + -test -d "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" && rm -r "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" + /bin/cp -PR IDLE.app "$(DESTDIR)$(PYTHONAPPSDIR)" + touch "$(DESTDIR)$(PYTHONAPPSDIR)/IDLE.app" +- /bin/cp $(srcdir)/config-main.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-main.def" +- /bin/cp $(srcdir)/config-extensions.def "$(DESTDIR)$(prefix)/lib/python$(VERSION)/idlelib/config-extensions.def" ++ if [ -f "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def" ]; then \ ++ /bin/cp -p "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def" \ ++ "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def~" ; \ ++ sed -e 's!name= IDLE Classic Windows!name= IDLE Classic OSX!g' \ ++ < "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def~" \ ++ > "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def" ; \ ++ rm "$(DESTDIR)$(LIBDEST)/idlelib/config-main.def~" ; \ ++ fi ++ if [ -f "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def" ]; then \ ++ /bin/cp -p "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def" \ ++ "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def~" ; \ ++ sed -e 's!zoom-height=!zoom-height=!g' \ ++ -e 's! "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def" ; \ ++ rm "$(DESTDIR)$(LIBDEST)/idlelib/config-extensions.def~" ; \ ++ fi + + clean: + rm -rf IDLE.app +diff -r 6d1b6a68f775 Mac/IDLE/config-extensions.def +--- a/Mac/IDLE/config-extensions.def ++++ /dev/null +@@ -1,93 +0,0 @@ +-# config-extensions.def +-# +-# IDLE reads several config files to determine user preferences. This +-# file is the default configuration file for IDLE extensions settings. +-# +-# Each extension must have at least one section, named after the extension +-# module. This section must contain an 'enable' item (=1 to enable the +-# extension, =0 to disable it), it may contain 'enable_editor' or 'enable_shell' +-# items, to apply it only to editor/shell windows, and may also contain any +-# other general configuration items for the extension. +-# +-# Each extension must define at least one section named ExtensionName_bindings +-# or ExtensionName_cfgBindings. If present, ExtensionName_bindings defines +-# virtual event bindings for the extension that are not user re-configurable. +-# If present, ExtensionName_cfgBindings defines virtual event bindings for the +-# extension that may be sensibly re-configured. +-# +-# If there are no keybindings for a menus' virtual events, include lines like +-# <>= (See [CodeContext], below.) +-# +-# Currently it is necessary to manually modify this file to change extension +-# key bindings and default values. To customize, create +-# ~/.idlerc/config-extensions.cfg and append the appropriate customized +-# section(s). Those sections will override the defaults in this file. +-# +-# Note: If a keybinding is already in use when the extension is +-# loaded, the extension's virtual event's keybinding will be set to ''. +-# +-# See config-keys.def for notes on specifying keys and extend.txt for +-# information on creating IDLE extensions. +- +-[FormatParagraph] +-enable=1 +-[FormatParagraph_cfgBindings] +-format-paragraph= +- +-[AutoExpand] +-enable=1 +-[AutoExpand_cfgBindings] +-expand-word= +- +-[ZoomHeight] +-enable=1 +-[ZoomHeight_cfgBindings] +-zoom-height= +- +-[ScriptBinding] +-enable=1 +-[ScriptBinding_cfgBindings] +-run-module= +-check-module= +- +-[CallTips] +-enable=1 +-[CallTips_cfgBindings] +-force-open-calltip= +-[CallTips_bindings] +-try-open-calltip= +-refresh-calltip= +- +-[ParenMatch] +-enable=1 +-style= expression +-flash-delay= 500 +-bell= 1 +-[ParenMatch_cfgBindings] +-flash-paren= +-[ParenMatch_bindings] +-paren-closed= +- +-[AutoComplete] +-enable=1 +-popupwait=2000 +-[AutoComplete_cfgBindings] +-force-open-completions= +-[AutoComplete_bindings] +-autocomplete= +-try-open-completions= +- +-[CodeContext] +-enable=1 +-enable_shell=0 +-numlines=3 +-visible=0 +-bgcolor=LightGray +-fgcolor=Black +-[CodeContext_bindings] +-toggle-code-context= +- +-[RstripExtension] +-enable=1 +-enable_shell=0 +-enable_editor=1 +diff -r 6d1b6a68f775 Mac/IDLE/config-main.def +--- a/Mac/IDLE/config-main.def ++++ /dev/null +@@ -1,79 +0,0 @@ +-# IDLE reads several config files to determine user preferences. This +-# file is the default config file for general idle settings. +-# +-# When IDLE starts, it will look in +-# the following two sets of files, in order: +-# +-# default configuration +-# --------------------- +-# config-main.def the default general config file +-# config-extensions.def the default extension config file +-# config-highlight.def the default highlighting config file +-# config-keys.def the default keybinding config file +-# +-# user configuration +-# ------------------- +-# ~/.idlerc/config-main.cfg the user general config file +-# ~/.idlerc/config-extensions.cfg the user extension config file +-# ~/.idlerc/config-highlight.cfg the user highlighting config file +-# ~/.idlerc/config-keys.cfg the user keybinding config file +-# +-# On Windows2000 and Windows XP the .idlerc directory is at +-# Documents and Settings\\.idlerc +-# +-# On Windows98 it is at c:\.idlerc +-# +-# Any options the user saves through the config dialog will be saved to +-# the relevant user config file. Reverting any general setting to the +-# default causes that entry to be wiped from the user file and re-read +-# from the default file. User highlighting themes or keybinding sets are +-# retained unless specifically deleted within the config dialog. Choosing +-# one of the default themes or keysets just applies the relevant settings +-# from the default file. +-# +-# Additional help sources are listed in the [HelpFiles] section and must be +-# viewable by a web browser (or the Windows Help viewer in the case of .chm +-# files). These sources will be listed on the Help menu. The pattern is +-# +-# You can't use a semi-colon in a menu item or path. The path will be platform +-# specific because of path separators, drive specs etc. +-# +-# It is best to use the Configuration GUI to set up additional help sources! +-# Example: +-#1 = My Extra Help Source;/usr/share/doc/foo/index.html +-#2 = Another Help Source;/path/to/another.pdf +- +-[General] +-editor-on-startup= 0 +-autosave= 0 +-print-command-posix=lpr %s +-print-command-win=start /min notepad /p %s +-delete-exitfunc= 1 +- +-[EditorWindow] +-width= 80 +-height= 40 +-font= courier +-font-size= 10 +-font-bold= 0 +-encoding= none +- +-[FormatParagraph] +-paragraph=70 +- +-[Indent] +-use-spaces= 1 +-num-spaces= 4 +- +-[Theme] +-default= 1 +-name= IDLE Classic +- +-[Keys] +-default= 1 +-name= IDLE Classic OSX +- +-[History] +-cyclic=1 +- +-[HelpFiles] +diff -r 6d1b6a68f775 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-2015 Python Software Foundation ++ %VERSION%, © 2001-2016 Python Software Foundation + CFBundleIconFile + PythonLauncher.icns + CFBundleIdentifier +diff -r 6d1b6a68f775 Mac/README +--- a/Mac/README ++++ b/Mac/README +@@ -46,7 +46,10 @@ + The optional argument specifies which OS X SDK should be used to perform the + build. This defaults to ``/Developer/SDKs/MacOSX.10.4u.sdk``. When building + on OS X 10.5 or later, you can specify ``/`` to use the installed system +- headers rather than an SDK. ++ headers rather than an SDK. As of OS X 10.9, you should install the optional ++ system headers from the Command Line Tools component using ``xcode-select``:: ++ ++ $ sudo xcode-select --install + + See the section _`Building and using a universal binary of Python on Mac OS X` + for more information. +diff -r 6d1b6a68f775 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) 2001-2015 Python Software Foundation. ++ %version%, (c) 2001-2016 Python Software Foundation. + CFBundleHelpBookFolder + + Documentation +@@ -37,7 +37,7 @@ + CFBundleInfoDictionaryVersion + 6.0 + CFBundleLongVersionString +- %version%, (c) 2001-2015 Python Software Foundation. ++ %version%, (c) 2001-2016 Python Software Foundation. + CFBundleName + Python + CFBundlePackageType +@@ -55,7 +55,7 @@ + NSAppleScriptEnabled + + NSHumanReadableCopyright +- (c) 2001-2015 Python Software Foundation. ++ (c) 2001-2016 Python Software Foundation. + NSHighResolutionCapable + + +diff -r 6d1b6a68f775 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) 2001-2015 Python Software Foundation. ++ %VERSION%, (c) 2001-2016 Python Software Foundation. + CFBundleLongVersionString +- %VERSION%, (c) 2001-2015 Python Software Foundation. ++ %VERSION%, (c) 2001-2016 Python Software Foundation. + CFBundleSignature + ???? + CFBundleVersion +diff -r 6d1b6a68f775 Makefile.pre.in +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -211,6 +211,11 @@ + # The task to run while instrument when building the profile-opt target + PROFILE_TASK=-m test.regrtest --pgo + ++# report files for gcov / lcov coverage report ++COVERAGE_INFO= $(abs_builddir)/coverage.info ++COVERAGE_REPORT=$(abs_builddir)/lcov-report ++COVERAGE_REPORT_OPTIONS=--no-branch-coverage --title "CPython lcov report" ++ + # === Definitions added by makesetup === + + +@@ -457,11 +462,46 @@ + build_all_use_profile: + $(MAKE) all CFLAGS="$(CFLAGS) $(PGO_PROF_USE_FLAG)" + ++# Compile and run with gcov ++.PHONY=coverage coverage-lcov coverage-report + coverage: + @echo "Building with support for coverage checking:" +- $(MAKE) clean ++ $(MAKE) clean profile-removal + $(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov" + ++coverage-lcov: ++ @echo "Creating Coverage HTML report with LCOV:" ++ @rm -f $(COVERAGE_INFO) ++ @rm -rf $(COVERAGE_REPORT) ++ @lcov --capture --directory $(abs_builddir) \ ++ --base-directory $(realpath $(abs_builddir)) \ ++ --path $(realpath $(abs_srcdir)) \ ++ --output-file $(COVERAGE_INFO) ++ : # remove 3rd party modules and system headers ++ @lcov --remove $(COVERAGE_INFO) \ ++ '*/Modules/_ctypes/libffi*/*' \ ++ '*/Modules/expat/*' \ ++ '*/Modules/zlib/*' \ ++ '*/Include/*' \ ++ '/usr/include/*' \ ++ '/usr/local/include/*' \ ++ --output-file $(COVERAGE_INFO) ++ @genhtml $(COVERAGE_INFO) --output-directory $(COVERAGE_REPORT) \ ++ $(COVERAGE_REPORT_OPTIONS) ++ @echo ++ @echo "lcov report at $(COVERAGE_REPORT)/index.html" ++ @echo ++ ++coverage-report: ++ : # force rebuilding of parser ++ @touch $(GRAMMAR_INPUT) ++ : # build with coverage info ++ $(MAKE) coverage ++ : # run tests, ignore failures ++ $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) || true ++ : # build lcov report ++ $(MAKE) coverage-lcov ++ + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +@@ -488,11 +528,15 @@ + exit 1 ; \ + fi + ++# This is shared by the math and cmath modules ++Modules/_math.o: Modules/_math.c Modules/_math.h ++ $(CC) -c $(CCSHARED) $(PY_CFLAGS) -o $@ $< ++ + # Build the shared modules + # Under GNU make, MAKEFLAGS are sorted and normalized; the 's' for + # -s, --silent or --quiet is always the first char. + # Under BSD make, MAKEFLAGS might be " -s -v x=y". +-sharedmods: $(BUILDPYTHON) pybuilddir.txt ++sharedmods: $(BUILDPYTHON) pybuilddir.txt Modules/_math.o + @case "$$MAKEFLAGS" in \ + *\ -s*|s*) quiet="-q";; \ + *) quiet="";; \ +@@ -914,6 +958,10 @@ + # $(PYTHON) -> python2 -> python$(VERSION)) + # Also create equivalent chains for other installed files + bininstall: altbininstall ++ if test ! -d $(DESTDIR)$(LIBPC); then \ ++ echo "Creating directory $(LIBPC)"; \ ++ $(INSTALL) -d -m $(DIRMODE) $(DESTDIR)$(LIBPC); \ ++ fi + -if test -f $(DESTDIR)$(BINDIR)/$(PYTHON) -o -h $(DESTDIR)$(BINDIR)/$(PYTHON); \ + then rm -f $(DESTDIR)$(BINDIR)/$(PYTHON); \ + else true; \ +@@ -1350,6 +1398,7 @@ + profile-removal: + find . -name '*.gc??' -exec rm -f {} ';' + find . -name '*.profclang?' -exec rm -f {} ';' ++ find . -name '*.dyn' -exec rm -f {} ';' + + clobber: clean profile-removal + -rm -f $(BUILDPYTHON) $(PGEN) $(LIBRARY) $(LDLIBRARY) $(DLLLIBRARY) \ +diff -r 6d1b6a68f775 Misc/ACKS +--- a/Misc/ACKS ++++ b/Misc/ACKS +@@ -45,8 +45,8 @@ + Juancarlo Añez + Chris Angelico + Jérémy Anger ++Jon Anglin + Ankur Ankan +-Jon Anglin + Heidi Annexstad + Ramchandra Apte + Éric Araujo +@@ -163,8 +163,8 @@ + Georg Brandl + Christopher Brannon + Terrence Brannon ++Sven Brauch + Germán M. Bravo +-Sven Brauch + Erik Bray + Brian Brazil + Demian Brecht +@@ -336,6 +336,7 @@ + Yves Dionne + Daniel Dittmar + Josip Djolonga ++Walter Dörwald + Jaromir Dolecek + Ismail Donmez + Robert Donohue +@@ -362,7 +363,6 @@ + Eugene Dvurechenski + Josip Dzolonga + Maxim Dzumanenko +-Walter Dörwald + Hans Eckardt + Rodolpho Eckhardt + Ulrich Eckhardt +@@ -466,6 +466,7 @@ + Stephen M. Gava + Xavier de Gaye + Harry Henry Gebel ++Tamás Bence Gedai + Marius Gedminas + Thomas Gellekum + Gabriel Genellina +@@ -727,15 +728,17 @@ + Jeff Knupp + Kubilay Kocak + Greg Kochanski ++Manvisha Kodali + Damon Kohler + Marko Kohtala + Vajrasky Kok + Guido Kollerie + Jacek Konieczny +-Марк Коренберг + Arkady Koplyarov + Peter A. Koren ++Марк Коренберг + Vlad Korolev ++Anna Koroliuk + Joseph Koshy + Daniel Kozan + Jerzy Kozera +@@ -826,7 +829,9 @@ + Mirko Liss + Nick Lockwood + Stephanie Lockwood ++Martin von Löwis + Hugo Lopes Tavares ++Guillermo López-Anglada + Anne Lord + Tom Loredo + Justin Love +@@ -843,8 +848,6 @@ + Taras Lyapun + Jim Lynch + Mikael Lyngvig +-Martin von Löwis +-Guillermo López-Anglada + Jeff MacDonald + John Machin + Andrew I MacIntyre +@@ -869,9 +872,9 @@ + Alex Martelli + Anthony Martin + Owen Martin ++Sidney San Martín + Westley Martínez + Sébastien Martini +-Sidney San Martín + Roger Masse + Nick Mathewson + Simon Mathieu +@@ -906,15 +909,15 @@ + Ezio Melotti + Doug Mennella + Brian Merrell ++Alexis Métaireau + Luke Mewburn + Carl Meyer + Mike Meyer + Piotr Meyer +-Alexis Métaireau + Steven Miale +-Trent Mick + Jason Michalski + Franck Michea ++Trent Mick + Tom Middleton + Thomas Miedema + Stan Mihai +@@ -1013,11 +1016,13 @@ + Denis S. Otkidach + Peter Otten + Michael Otteneder +-R. M. Oudkerk ++Richard Oudkerk + Russel Owen + Joonas Paalasmaa + Martin Packman + Shriphani Palakodety ++Julien Palard ++Aviv Palivoda + Ondrej Palkovsky + Mike Pall + Todd R. Palmer +@@ -1030,6 +1035,7 @@ + Peter Parente + Alexandre Parenteau + Dan Parisien ++HyeSoo Park + William Park + Heikki Partanen + Harri Pasanen +@@ -1071,8 +1077,8 @@ + François Pinard + Tom Pinckney + Zach Pincus ++Michael Piotrowski + Zero Piraeus +-Michael Piotrowski + Antoine Pitrou + Jean-François Piéronne + Oleg Plakhotnyuk +@@ -1100,15 +1106,16 @@ + Steve Purcell + Eduardo Pérez + Fernando Pérez ++Kevin Jing Qiu + Pierre Quentel + Brian Quinlan +-Kevin Jing Qiu + Anders Qvist + Thomas Rachel + Ram Rachum + Jérôme Radix + Burton Radons + Jeff Ramnani ++Varpu Rantala + Brodie Rao + Senko Rasic + Antti Rasinen +@@ -1152,6 +1159,7 @@ + Mark Roberts + Andy Robinson + Jim Robinson ++Daniel Rocco + Mark Roddy + Kevin Rodgers + Sean Rodman +@@ -1209,7 +1217,6 @@ + Hugh Sasse + Bob Savage + Ben Sayer +-sbt + Luca Sbardella + Marco Scataglini + Andrew Schaaf +@@ -1248,8 +1255,8 @@ + Denis Severson + Ian Seyer + Daniel Shahaf ++Mark Shannon + Ha Shao +-Mark Shannon + Richard Shapiro + Varun Sharma + Vlad Shcherbina +@@ -1418,6 +1425,7 @@ + Sebastian Ortiz Vasquez + Alexandre Vassalotti + Nadeem Vawda ++Sye van der Veen + Frank Vercruesse + Mike Verdone + Jaap Vermeulen +@@ -1436,6 +1444,7 @@ + Guido Vranken + Martijn Vries + Sjoerd de Vries ++Jonas Wagner + Niki W. Waibel + Wojtek Walczak + Charles Waldman +@@ -1445,10 +1454,10 @@ + Rodrigo Steinmuller Wanderley + Dingyuan Wang + Ke Wang ++Liang-Bo Wang + Greg Ward + Tom Wardill + Zachary Ware +-Jonas Wagner + Barry Warsaw + Steve Waterbury + Bob Watson +@@ -1483,6 +1492,7 @@ + Carol Willing + Steven Willis + Frank Willison ++Alex Willmer + Geoff Wilson + Greg V. Wilson + J Derek Wilson +diff -r 6d1b6a68f775 Misc/HISTORY +--- a/Misc/HISTORY ++++ b/Misc/HISTORY +@@ -1845,7 +1845,7 @@ + + - Patch #1110248: SYNC_FLUSH the zlib buffer for GZipFile.flush. + +-- Patch #1107973: Allow to iterate over the lines of a tarfile.ExFileObject. ++- Patch #1107973: Allow iterating over the lines of a tarfile.ExFileObject. + + - Patch #1104111: Alter setup.py --help and --help-commands. + +@@ -2822,7 +2822,7 @@ + same as when the argument is omitted). + [SF bug 658254, patch 663482] + +-- nntplib does now allow to ignore a .netrc file. ++- nntplib does now allow ignoring a .netrc file. + + - urllib2 now recognizes Basic authentication even if other authentication + schemes are offered. +@@ -3240,7 +3240,7 @@ + + - fcntl.ioctl now warns if the mutate flag is not specified. + +-- nt now properly allows to refer to UNC roots, e.g. in nt.stat(). ++- nt now properly allows referring to UNC roots, e.g. in nt.stat(). + + - the weakref module now supports additional objects: array.array, + sre.pattern_objects, file objects, and sockets. +@@ -5798,7 +5798,7 @@ + - New functions PyErr_SetExcFromWindowsErr() and + PyErr_SetExcFromWindowsErrWithFilename(). Similar to + PyErr_SetFromWindowsErrWithFilename() and +- PyErr_SetFromWindowsErr(), but they allow to specify ++ PyErr_SetFromWindowsErr(), but they allow specifying + the exception type to raise. Available on Windows. + + - Py_FatalError() is now declared as taking a const char* argument. It +@@ -6678,8 +6678,8 @@ + - property() now takes 4 keyword arguments: fget, fset, fdel and doc. + These map to read-only attributes 'fget', 'fset', 'fdel', and '__doc__' + in the constructed property object. fget, fset and fdel weren't +- discoverable from Python in 2.2a3. __doc__ is new, and allows to +- associate a docstring with a property. ++ discoverable from Python in 2.2a3. __doc__ is new, and allows ++ associating a docstring with a property. + + - Comparison overloading is now more completely implemented. For + example, a str subclass instance can properly be compared to a str +@@ -7094,7 +7094,7 @@ + ----- + + - regrtest.py now knows which tests are expected to be skipped on some +- platforms, allowing to give clearer test result output. regrtest ++ platforms, allowing clearer test result output to be given. regrtest + also has optional --use/-u switch to run normally disabled tests + which require network access or consume significant disk resources. + +diff -r 6d1b6a68f775 Misc/NEWS +--- a/Misc/NEWS ++++ b/Misc/NEWS +@@ -2,6 +2,214 @@ + Python News + +++++++++++ + ++What's New in Python 2.7.12? ++============================ ++ ++*Release date: XXXX-XX-XX* ++ ++Core and Builtins ++----------------- ++ ++- Issue #22836: Ensure exception reports from PyErr_Display() and ++ PyErr_WriteUnraisable() are sensible even when formatting them produces ++ secondary errors. This affects the reports produced by ++ sys.__excepthook__() and when __del__() raises an exception. ++ ++- Issue #22847: Improve method cache efficiency. ++ ++- Issue #25843: When compiling code, don't merge constants if they are equal ++ but have a different types. For example, ``f1, f2 = lambda: 1, lambda: 1.0`` ++ is now correctly compiled to two different functions: ``f1()`` returns ``1`` ++ (``int``) and ``f2()`` returns ``1.0`` (``int``), even if ``1`` and ``1.0`` ++ are equal. ++ ++- Issue #22995: [UPDATE] Remove the one of the pickleability tests in ++ _PyObject_GetState() due to regressions observed in Cython-based projects. ++ ++- Issue #25961: Disallowed null characters in the type name. ++ ++- Issue #22995: Instances of extension types with a state that aren't ++ subclasses of list or dict and haven't implemented any pickle-related ++ methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, ++ or __getstate__), can no longer be pickled. Including memoryview. ++ ++- Issue #20440: Massive replacing unsafe attribute setting code with special ++ macro Py_SETREF. ++ ++- Issue #25421: __sizeof__ methods of builtin types now use dynamic basic size. ++ This allows sys.getsize() to work correctly with their subclasses with ++ __slots__ defined. ++ ++- Issue #19543: Added Py3k warning for decoding unicode. ++ ++- Issue #24097: Fixed crash in object.__reduce__() if slot name is freed inside ++ __getattr__. ++ ++- Issue #24731: Fixed crash on converting objects with special methods ++ __str__, __trunc__, and __float__ returning instances of subclasses of ++ str, long, and float to subclasses of str, long, and float correspondingly. ++ ++- Issue #26478: Fix semantic bugs when using binary operators with dictionary ++ views and tuples. ++ ++- Issue #26171: Fix possible integer overflow and heap corruption in ++ zipimporter.get_data(). ++ ++Library ++------- ++ ++- Issue #26313: ssl.py _load_windows_store_certs fails if windows cert store ++ is empty. Patch by Baji. ++ ++- Issue #26513: Fixes platform module detection of Windows Server ++ ++- Issue #23718: Fixed parsing time in week 0 before Jan 1. Original patch by ++ Tamás Bence Gedai. ++ ++- Issue #26177: Fixed the keys() method for Canvas and Scrollbar widgets. ++ ++- Issue #15068: Got rid of excessive buffering in the fileinput module. ++ The bufsize parameter is no longer used. ++ ++- Issue #2202: Fix UnboundLocalError in ++ AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu Dupuy. ++ ++- Issue #26475: Fixed debugging output for regular expressions with the (?x) ++ flag. ++ ++- Issue #26385: Remove the file if the internal fdopen() call in ++ NamedTemporaryFile() fails. Based on patch by Silent Ghost. ++ ++- Issue #26309: In the "socketserver" module, shut down the request (closing ++ the connected socket) when verify_request() returns false. Based on patch ++ by Aviv Palivoda. ++ ++- Issue #25939: On Windows open the cert store readonly in ssl.enum_certificates. ++ ++- Issue #24303: Fix random EEXIST upon multiprocessing semaphores creation with ++ Linux PID namespaces enabled. ++ ++- Issue #25698: Importing module if the stack is too deep no longer replaces ++ imported module with the empty one. ++ ++- Issue #12923: Reset FancyURLopener's redirect counter even if there is an ++ exception. Based on patches by Brian Brazil and Daniel Rocco. ++ ++- Issue #25945: Fixed a crash when unpickle the functools.partial object with ++ wrong state. Fixed a leak in failed functools.partial constructor. ++ "args" and "keywords" attributes of functools.partial have now always types ++ tuple and dict correspondingly. ++ ++- Issue #19883: Fixed possible integer overflows in zipimport. ++ ++- Issue #26147: xmlrpclib now works with unicode not encodable with used ++ non-UTF-8 encoding. ++ ++- Issue #16620: Fixed AttributeError in msilib.Directory.glob(). ++ ++- Issue #21847: Fixed xmlrpclib on Unicode-disabled builds. ++ ++- Issue #6500: Fixed infinite recursion in urllib2.Request.__getattr__(). ++ ++- Issue #26083: Workaround a subprocess bug that raises an incorrect ++ "ValueError: insecure string pickle" exception instead of the actual ++ exception on some platforms such as Mac OS X when an exception raised ++ in the forked child process prior to the exec() was large enough that ++ it overflowed the internal errpipe_read pipe buffer. ++ ++- Issue #24103: Fixed possible use after free in ElementTree.iterparse(). ++ ++- Issue #20954: _args_from_interpreter_flags used by multiprocessing and some ++ tests no longer behaves incorrectly in the presence of the PYTHONHASHSEED ++ environment variable. ++ ++- Issue #14285: When executing a package with the "python -m package" option, ++ and package initialization raises ImportError, a proper traceback is now ++ reported. ++ ++- Issue #6478: _strptime's regexp cache now is reset after changing timezone ++ with time.tzset(). ++ ++- Issue #25718: Fixed copying object with state with boolean value is false. ++ ++- Issue #25742: :func:`locale.setlocale` now accepts a Unicode string for ++ its second parameter. ++ ++- Issue #10131: Fixed deep copying of minidom documents. Based on patch ++ by Marian Ganisin. ++ ++- Issue #25725: Fixed a reference leak in cPickle.loads() when unpickling ++ invalid data including tuple instructions. ++ ++- Issue #25663: In the Readline completer, avoid listing duplicate global ++ names, and search the global namespace before searching builtins. ++ ++- Issue #25688: Fixed file leak in ElementTree.iterparse() raising an error. ++ ++- Issue #23914: Fixed SystemError raised by CPickle unpickler on broken data. ++ ++- Issue #25924: Avoid unnecessary serialization of getaddrinfo(3) calls on ++ OS X versions 10.5 or higher. Original patch by A. Jesse Jiryu Davis. ++ ++- Issue #26406: Avoid unnecessary serialization of getaddrinfo(3) calls on ++ current versions of OpenBSD and NetBSD. Patch by A. Jesse Jiryu Davis. ++ ++IDLE ++---- ++ ++- Issue #26417: Prevent spurious errors and incorrect defaults when ++ installing IDLE 2.7 on OS X: default configuration settings are ++ no longer installed from OS X specific copies. ++ ++Tests ++----- ++ ++- Issue #25940: Changed test_ssl to use self-signed.pythontest.net. This ++ avoids relying on svn.python.org, which recently changed root certificate. ++ ++- Issue #25616: Tests for OrderedDict are extracted from test_collections ++ into separate file test_ordered_dict. ++ ++Build ++----- ++ ++- Issue #19450: Update Windows builds to use SQLite 3.8.11.0. ++ ++- Issue #17603: Avoid error about nonexistant fileblocks.o file by using a ++ lower-level check for st_blocks in struct stat. ++ ++- Issue #26465: Update Windows builds to use OpenSSL 1.0.2g. ++ ++- Issue #24421: Compile Modules/_math.c once, before building extensions. ++ Previously it could fail to compile properly if the math and cmath builds ++ were concurrent. ++ ++- Issue #25824: Fixes sys.winver to not include any architecture suffix. ++ ++- Issue #25348: Added ``--pgo`` and ``--pgo-job`` arguments to ++ ``PCbuild\build.bat`` for building with Profile-Guided Optimization. The ++ old ``PCbuild\build_pgo.bat`` script is now deprecated, and simply calls ++ ``PCbuild\build.bat --pgo %*``. ++ ++- Issue #25827: Add support for building with ICC to ``configure``, including ++ a new ``--with-icc`` flag. ++ ++- Issue #25696: Fix installation of Python on UNIX with make -j9. ++ ++- Issue #26465: Update OS X 10.5+ 32-bit-only installer to build ++ and link with OpenSSL 1.0.2g. ++ ++- Issue #26268: Update Windows builds to use OpenSSL 1.0.2f. ++ ++- Issue #25136: Support Apple Xcode 7's new textual SDK stub libraries. ++ ++C API ++----- ++ ++- Issue #26476: Fixed compilation error when use PyErr_BadInternalCall() in C++. ++ Patch by Jeroen Demeyer. ++ ++ + What's New in Python 2.7.11? + ============================ + +@@ -491,8 +699,8 @@ + - Issue #21802: The reader in BufferedRWPair now is closed even when closing + writer failed in BufferedRWPair.close(). + +-- Issue #23671: string.Template now allows to specify the "self" parameter as +- keyword argument. string.Formatter now allows to specify the "self" and ++- Issue #23671: string.Template now allows specifying the "self" parameter as ++ a keyword argument. string.Formatter now allows specifying the "self" and + the "format_string" parameters as keyword arguments. + + - Issue #21560: An attempt to write a data of wrong type no longer cause +@@ -1027,7 +1235,7 @@ + move version to end. + + - Issue #14105: Idle debugger breakpoints no longer disappear +- when inseting or deleting lines. ++ when inserting or deleting lines. + + Extension Modules + ----------------- +diff -r 6d1b6a68f775 Modules/_bsddb.c +--- a/Modules/_bsddb.c ++++ b/Modules/_bsddb.c +@@ -1607,9 +1607,8 @@ + } + + /* Save a reference to the callback in the secondary DB. */ +- Py_XDECREF(secondaryDB->associateCallback); + Py_XINCREF(callback); +- secondaryDB->associateCallback = callback; ++ Py_SETREF(secondaryDB->associateCallback, callback); + secondaryDB->primaryDBType = _DB_get_type(self); + + /* PyEval_InitThreads is called here due to a quirk in python 1.5 +@@ -2498,9 +2497,8 @@ + DB_set_private(DBObject* self, PyObject* private_obj) + { + /* We can set the private field even if db is closed */ +- Py_DECREF(self->private_obj); + Py_INCREF(private_obj); +- self->private_obj = private_obj; ++ Py_SETREF(self->private_obj, private_obj); + RETURN_NONE(); + } + +@@ -6998,9 +6996,8 @@ + DBEnv_set_private(DBEnvObject* self, PyObject* private_obj) + { + /* We can set the private field even if dbenv is closed */ +- Py_DECREF(self->private_obj); + Py_INCREF(private_obj); +- self->private_obj = private_obj; ++ Py_SETREF(self->private_obj, private_obj); + RETURN_NONE(); + } + +@@ -7253,9 +7250,8 @@ + return NULL; + } + +- Py_XDECREF(self->event_notifyCallback); + Py_INCREF(notifyFunc); +- self->event_notifyCallback = notifyFunc; ++ Py_SETREF(self->event_notifyCallback, notifyFunc); + + /* This is to workaround a problem with un-initialized threads (see + comment in DB_associate) */ +@@ -7413,9 +7409,8 @@ + MYDB_END_ALLOW_THREADS; + RETURN_IF_ERR(); + +- Py_DECREF(self->rep_transport); + Py_INCREF(rep_transport); +- self->rep_transport = rep_transport; ++ Py_SETREF(self->rep_transport, rep_transport); + RETURN_NONE(); + } + +diff -r 6d1b6a68f775 Modules/_collectionsmodule.c +--- a/Modules/_collectionsmodule.c ++++ b/Modules/_collectionsmodule.c +@@ -3,8 +3,6 @@ + + /* collections module implementation of a deque() datatype + Written and maintained by Raymond D. Hettinger +- Copyright (c) 2004 Python Software Foundation. +- All rights reserved. + */ + + /* The block length may be set to any number over 1. Larger numbers +@@ -1103,7 +1101,7 @@ + Py_ssize_t res; + Py_ssize_t blocks; + +- res = sizeof(dequeobject); ++ res = _PyObject_SIZE(Py_TYPE(deque)); + blocks = (deque->leftindex + deque->len + BLOCKLEN - 1) / BLOCKLEN; + assert(deque->leftindex + deque->len - 1 == + (blocks - 1) * BLOCKLEN + deque->rightindex); +diff -r 6d1b6a68f775 Modules/_csv.c +--- a/Modules/_csv.c ++++ b/Modules/_csv.c +@@ -276,9 +276,8 @@ + return -1; + } + else { +- Py_XDECREF(*target); + Py_INCREF(src); +- *target = src; ++ Py_SETREF(*target, src); + } + } + return 0; +@@ -770,8 +769,7 @@ + static int + parse_reset(ReaderObj *self) + { +- Py_XDECREF(self->fields); +- self->fields = PyList_New(0); ++ Py_SETREF(self->fields, PyList_New(0)); + if (self->fields == NULL) + return -1; + self->field_len = 0; +diff -r 6d1b6a68f775 Modules/_ctypes/_ctypes.c +--- a/Modules/_ctypes/_ctypes.c ++++ b/Modules/_ctypes/_ctypes.c +@@ -424,8 +424,7 @@ + Py_DECREF((PyObject *)dict); + return NULL; + } +- Py_DECREF(result->tp_dict); +- result->tp_dict = (PyObject *)dict; ++ Py_SETREF(result->tp_dict, (PyObject *)dict); + dict->format = _ctypes_alloc_format_string(NULL, "B"); + if (dict->format == NULL) { + Py_DECREF(result); +@@ -903,8 +902,7 @@ + return -1; + } + Py_INCREF(proto); +- Py_XDECREF(stgdict->proto); +- stgdict->proto = proto; ++ Py_SETREF(stgdict->proto, proto); + return 0; + } + +@@ -994,8 +992,7 @@ + Py_DECREF((PyObject *)stgdict); + return NULL; + } +- Py_DECREF(result->tp_dict); +- result->tp_dict = (PyObject *)stgdict; ++ Py_SETREF(result->tp_dict, (PyObject *)stgdict); + + return (PyObject *)result; + } +@@ -1460,8 +1457,7 @@ + Py_DECREF((PyObject *)stgdict); + return NULL; + } +- Py_DECREF(result->tp_dict); +- result->tp_dict = (PyObject *)stgdict; ++ Py_SETREF(result->tp_dict, (PyObject *)stgdict); + + /* Special case for character arrays. + A permanent annoyance: char arrays are also strings! +@@ -1884,8 +1880,7 @@ + Py_DECREF((PyObject *)stgdict); + return NULL; + } +- Py_DECREF(result->tp_dict); +- result->tp_dict = (PyObject *)stgdict; ++ Py_SETREF(result->tp_dict, (PyObject *)stgdict); + + return (PyObject *)result; + } +@@ -2393,8 +2388,7 @@ + Py_DECREF((PyObject *)stgdict); + return NULL; + } +- Py_DECREF(result->tp_dict); +- result->tp_dict = (PyObject *)stgdict; ++ Py_SETREF(result->tp_dict, (PyObject *)stgdict); + + if (-1 == make_funcptrtype_dict(stgdict)) { + Py_DECREF(result); +@@ -2536,8 +2530,7 @@ + } + ob = PyCData_GetContainer(target); + if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) { +- Py_XDECREF(ob->b_objects); +- ob->b_objects = keep; /* refcount consumed */ ++ Py_SETREF(ob->b_objects, keep); /* refcount consumed */ + return 0; + } + key = unique_key(target, index); +@@ -3059,9 +3052,8 @@ + "the errcheck attribute must be callable"); + return -1; + } +- Py_XDECREF(self->errcheck); + Py_XINCREF(ob); +- self->errcheck = ob; ++ Py_SETREF(self->errcheck, ob); + return 0; + } + +@@ -3089,11 +3081,9 @@ + "restype must be a type, a callable, or None"); + return -1; + } +- Py_XDECREF(self->checker); +- Py_XDECREF(self->restype); + Py_INCREF(ob); +- self->restype = ob; +- self->checker = PyObject_GetAttrString(ob, "_check_retval_"); ++ Py_SETREF(self->restype, ob); ++ Py_SETREF(self->checker, PyObject_GetAttrString(ob, "_check_retval_")); + if (self->checker == NULL) + PyErr_Clear(); + return 0; +@@ -3130,11 +3120,9 @@ + converters = converters_from_argtypes(ob); + if (!converters) + return -1; +- Py_XDECREF(self->converters); +- self->converters = converters; +- Py_XDECREF(self->argtypes); ++ Py_SETREF(self->converters, converters); + Py_INCREF(ob); +- self->argtypes = ob; ++ Py_SETREF(self->argtypes, ob); + } + return 0; + } +@@ -3509,7 +3497,7 @@ + return NULL; + } + +- /* XXX XXX This would allow to pass additional options. For COM ++ /* XXX XXX This would allow passing additional options. For COM + method *implementations*, we would probably want different + behaviour than in 'normal' callback functions: return a HRESULT if + an exception occurs in the callback, and print the traceback not +diff -r 6d1b6a68f775 Modules/_ctypes/libffi/m4/libtool.m4 +--- a/Modules/_ctypes/libffi/m4/libtool.m4 ++++ b/Modules/_ctypes/libffi/m4/libtool.m4 +@@ -1121,7 +1121,7 @@ + # If we don't find anything, use the default library path according + # to the aix ld manual. + # Store the results from the different compilers for each TAGNAME. +-# Allow to override them for all tags through lt_cv_aix_libpath. ++# Allow overriding them for all tags through lt_cv_aix_libpath. + m4_defun([_LT_SYS_MODULE_PATH_AIX], + [m4_require([_LT_DECL_SED])dnl + if test set = "${lt_cv_aix_libpath+set}"; then +diff -r 6d1b6a68f775 Modules/_curses_panel.c +--- a/Modules/_curses_panel.c ++++ b/Modules/_curses_panel.c +@@ -283,9 +283,8 @@ + PyErr_SetString(PyCursesError, "replace_panel() returned ERR"); + return NULL; + } +- Py_DECREF(po->wo); +- po->wo = temp; +- Py_INCREF(po->wo); ++ Py_INCREF(temp); ++ Py_SETREF(po->wo, temp); + Py_INCREF(Py_None); + return Py_None; + } +diff -r 6d1b6a68f775 Modules/_elementtree.c +--- a/Modules/_elementtree.c ++++ b/Modules/_elementtree.c +@@ -337,9 +337,9 @@ + } + + LOCAL(int) +-element_resize(ElementObject* self, int extra) ++element_resize(ElementObject* self, Py_ssize_t extra) + { +- int size; ++ Py_ssize_t size; + PyObject* *children; + + /* make sure self->children can hold the given number of extra +@@ -359,6 +359,13 @@ + * be safe. + */ + size = size ? size : 1; ++ if ((size_t)size > PY_SSIZE_T_MAX/sizeof(PyObject*)) ++ goto nomemory; ++ if (size > INT_MAX) { ++ PyErr_SetString(PyExc_OverflowError, ++ "too many children"); ++ return -1; ++ } + if (self->extra->children != self->extra->_children) { + /* Coverity CID #182 size_error: Allocating 1 bytes to pointer + * "children", which needs at least 4 bytes. Although it's a +@@ -1253,18 +1260,19 @@ + } + + static int +-element_setitem(PyObject* self_, Py_ssize_t index, PyObject* item) ++element_setitem(PyObject* self_, Py_ssize_t index_, PyObject* item) + { + ElementObject* self = (ElementObject*) self_; +- int i; ++ int i, index; + PyObject* old; + +- if (!self->extra || index < 0 || index >= self->extra->length) { ++ if (!self->extra || index_ < 0 || index_ >= self->extra->length) { + PyErr_SetString( + PyExc_IndexError, + "child assignment index out of range"); + return -1; + } ++ index = (int)index_; + + old = self->extra->children[index]; + +@@ -1373,6 +1381,7 @@ + &start, &stop, &step, &slicelen) < 0) { + return -1; + } ++ assert(slicelen <= self->extra->length); + + if (value == NULL) + newlen = 0; +@@ -1390,15 +1399,17 @@ + + if (step != 1 && newlen != slicelen) + { ++ Py_XDECREF(seq); + PyErr_Format(PyExc_ValueError, + #if (PY_VERSION_HEX < 0x02050000) + "attempt to assign sequence of size %d " + "to extended slice of size %d", ++ (int)newlen, (int)slicelen + #else + "attempt to assign sequence of size %zd " + "to extended slice of size %zd", ++ newlen, slicelen + #endif +- newlen, slicelen + ); + return -1; + } +@@ -1407,12 +1418,12 @@ + /* Resize before creating the recycle bin, to prevent refleaks. */ + if (newlen > slicelen) { + if (element_resize(self, newlen - slicelen) < 0) { +- if (seq) { +- Py_DECREF(seq); +- } ++ Py_XDECREF(seq); + return -1; + } + } ++ assert(newlen - slicelen <= INT_MAX - self->extra->length); ++ assert(newlen - slicelen >= -self->extra->length); + + if (slicelen > 0) { + /* to avoid recursive calls to this method (via decref), move +@@ -1420,9 +1431,7 @@ + we're done modifying the element */ + recycle = PyList_New(slicelen); + if (!recycle) { +- if (seq) { +- Py_DECREF(seq); +- } ++ Py_XDECREF(seq); + return -1; + } + for (cur = start, i = 0; i < slicelen; +@@ -1448,11 +1457,9 @@ + self->extra->children[cur] = element; + } + +- self->extra->length += newlen - slicelen; +- +- if (seq) { +- Py_DECREF(seq); +- } ++ self->extra->length += (int)(newlen - slicelen); ++ ++ Py_XDECREF(seq); + + /* discard the recycle bin, and everything in it */ + Py_XDECREF(recycle); +@@ -1566,9 +1573,8 @@ + } + + if (strcmp(name, "tag") == 0) { +- Py_DECREF(self->tag); +- self->tag = value; +- Py_INCREF(self->tag); ++ Py_INCREF(value); ++ Py_SETREF(self->tag, value); + } else if (strcmp(name, "text") == 0) { + Py_DECREF(JOIN_OBJ(self->text)); + self->text = value; +@@ -1580,9 +1586,8 @@ + } else if (strcmp(name, "attrib") == 0) { + if (!self->extra) + element_new_extra(self, NULL); +- Py_DECREF(self->extra->attrib); +- self->extra->attrib = value; +- Py_INCREF(self->extra->attrib); ++ Py_INCREF(value); ++ Py_SETREF(self->extra->attrib, value); + } else { + PyErr_SetString(PyExc_AttributeError, name); + return -1; +@@ -1713,6 +1718,23 @@ + PyObject_Del(self); + } + ++LOCAL(int) ++treebuilder_append_event(TreeBuilderObject *self, PyObject *action, ++ PyObject *node) ++{ ++ if (action != NULL) { ++ PyObject *res = PyTuple_Pack(2, action, node); ++ if (res == NULL) ++ return -1; ++ if (PyList_Append(self->events, res) < 0) { ++ Py_DECREF(res); ++ return -1; ++ } ++ Py_DECREF(res); ++ } ++ return 0; ++} ++ + /* -------------------------------------------------------------------- */ + /* handlers */ + +@@ -1776,26 +1798,14 @@ + } + self->index++; + +- Py_DECREF(this); + Py_INCREF(node); +- self->this = (ElementObject*) node; +- +- Py_DECREF(self->last); ++ Py_SETREF(self->this, (ElementObject*) node); ++ + Py_INCREF(node); +- self->last = (ElementObject*) node; +- +- if (self->start_event_obj) { +- PyObject* res; +- PyObject* action = self->start_event_obj; +- res = PyTuple_New(2); +- if (res) { +- Py_INCREF(action); PyTuple_SET_ITEM(res, 0, (PyObject*) action); +- Py_INCREF(node); PyTuple_SET_ITEM(res, 1, (PyObject*) node); +- PyList_Append(self->events, res); +- Py_DECREF(res); +- } else +- PyErr_Clear(); /* FIXME: propagate error */ +- } ++ Py_SETREF(self->last, (ElementObject*) node); ++ ++ if (treebuilder_append_event(self, self->start_event_obj, node) < 0) ++ goto error; + + return node; + +@@ -1843,7 +1853,7 @@ + LOCAL(PyObject*) + treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag) + { +- PyObject* item; ++ ElementObject *item; + + if (self->data) { + if (self->this == self->last) { +@@ -1868,73 +1878,20 @@ + return NULL; + } + ++ item = self->last; ++ self->last = self->this; + self->index--; +- +- item = PyList_GET_ITEM(self->stack, self->index); +- Py_INCREF(item); +- +- Py_DECREF(self->last); +- +- self->last = (ElementObject*) self->this; +- self->this = (ElementObject*) item; +- +- if (self->end_event_obj) { +- PyObject* res; +- PyObject* action = self->end_event_obj; +- PyObject* node = (PyObject*) self->last; +- res = PyTuple_New(2); +- if (res) { +- Py_INCREF(action); PyTuple_SET_ITEM(res, 0, (PyObject*) action); +- Py_INCREF(node); PyTuple_SET_ITEM(res, 1, (PyObject*) node); +- PyList_Append(self->events, res); +- Py_DECREF(res); +- } else +- PyErr_Clear(); /* FIXME: propagate error */ +- } ++ self->this = (ElementObject *) PyList_GET_ITEM(self->stack, self->index); ++ Py_INCREF(self->this); ++ Py_DECREF(item); ++ ++ if (treebuilder_append_event(self, self->end_event_obj, (PyObject*)self->last) < 0) ++ return NULL; + + Py_INCREF(self->last); + return (PyObject*) self->last; + } + +-LOCAL(void) +-treebuilder_handle_namespace(TreeBuilderObject* self, int start, +- PyObject *prefix, PyObject *uri) +-{ +- PyObject* res; +- PyObject* action; +- PyObject* parcel; +- +- if (!self->events) +- return; +- +- if (start) { +- if (!self->start_ns_event_obj) +- return; +- action = self->start_ns_event_obj; +- parcel = Py_BuildValue("OO", prefix, uri); +- if (!parcel) +- return; +- Py_INCREF(action); +- } else { +- if (!self->end_ns_event_obj) +- return; +- action = self->end_ns_event_obj; +- Py_INCREF(action); +- parcel = Py_None; +- Py_INCREF(parcel); +- } +- +- res = PyTuple_New(2); +- +- if (res) { +- PyTuple_SET_ITEM(res, 0, action); +- PyTuple_SET_ITEM(res, 1, parcel); +- PyList_Append(self->events, res); +- Py_DECREF(res); +- } else +- PyErr_Clear(); /* FIXME: propagate error */ +-} +- + /* -------------------------------------------------------------------- */ + /* methods (in alphabetical order) */ + +@@ -2263,8 +2220,10 @@ + /* attributes */ + if (attrib_in[0]) { + attrib = PyDict_New(); +- if (!attrib) ++ if (!attrib) { ++ Py_DECREF(tag); + return; ++ } + while (attrib_in[0] && attrib_in[1]) { + PyObject* key = makeuniversal(self, attrib_in[0]); + PyObject* value = makestring(attrib_in[1], strlen(attrib_in[1])); +@@ -2272,6 +2231,7 @@ + Py_XDECREF(value); + Py_XDECREF(key); + Py_DECREF(attrib); ++ Py_DECREF(tag); + return; + } + ok = PyDict_SetItem(attrib, key, value); +@@ -2279,6 +2239,7 @@ + Py_DECREF(key); + if (ok < 0) { + Py_DECREF(attrib); ++ Py_DECREF(tag); + return; + } + attrib_in += 2; +@@ -2296,8 +2257,10 @@ + if (attrib == Py_None) { + Py_DECREF(attrib); + attrib = PyDict_New(); +- if (!attrib) ++ if (!attrib) { ++ Py_DECREF(tag); + return; ++ } + } + res = PyObject_CallFunction(self->handle_start, "OO", tag, attrib); + } else +@@ -2360,8 +2323,16 @@ + expat_start_ns_handler(XMLParserObject* self, const XML_Char* prefix, + const XML_Char *uri) + { +- PyObject* sprefix = NULL; +- PyObject* suri = NULL; ++ TreeBuilderObject *target = (TreeBuilderObject*) self->target; ++ PyObject *parcel; ++ PyObject *sprefix = NULL; ++ PyObject *suri = NULL; ++ ++ if (PyErr_Occurred()) ++ return; ++ ++ if (!target->events || !target->start_ns_event_obj) ++ return; + + if (uri) + suri = makestring(uri, strlen(uri)); +@@ -2379,20 +2350,27 @@ + return; + } + +- treebuilder_handle_namespace( +- (TreeBuilderObject*) self->target, 1, sprefix, suri +- ); +- ++ parcel = PyTuple_Pack(2, sprefix, suri); + Py_DECREF(sprefix); + Py_DECREF(suri); ++ if (!parcel) ++ return; ++ treebuilder_append_event(target, target->start_ns_event_obj, parcel); ++ Py_DECREF(parcel); + } + + static void + expat_end_ns_handler(XMLParserObject* self, const XML_Char* prefix_in) + { +- treebuilder_handle_namespace( +- (TreeBuilderObject*) self->target, 0, NULL, NULL +- ); ++ TreeBuilderObject *target = (TreeBuilderObject*) self->target; ++ ++ if (PyErr_Occurred()) ++ return; ++ ++ if (!target->events) ++ return; ++ ++ treebuilder_append_event(target, target->end_ns_event_obj, Py_None); + } + + static void +@@ -2708,8 +2686,14 @@ + break; + } + ++ if (PyString_GET_SIZE(buffer) > INT_MAX) { ++ Py_DECREF(buffer); ++ Py_DECREF(reader); ++ PyErr_SetString(PyExc_OverflowError, "size does not fit in an int"); ++ return NULL; ++ } + res = expat_parse( +- self, PyString_AS_STRING(buffer), PyString_GET_SIZE(buffer), 0 ++ self, PyString_AS_STRING(buffer), (int)PyString_GET_SIZE(buffer), 0 + ); + + Py_DECREF(buffer); +@@ -2760,8 +2744,7 @@ + target = (TreeBuilderObject*) self->target; + + Py_INCREF(events); +- Py_XDECREF(target->events); +- target->events = events; ++ Py_SETREF(target->events, events); + + /* clear out existing events */ + Py_CLEAR(target->start_event_obj); +@@ -2783,33 +2766,28 @@ + char* event; + if (!PyString_Check(item)) + goto error; ++ Py_INCREF(item); + event = PyString_AS_STRING(item); + if (strcmp(event, "start") == 0) { +- Py_INCREF(item); +- target->start_event_obj = item; ++ Py_SETREF(target->start_event_obj, item); + } else if (strcmp(event, "end") == 0) { +- Py_INCREF(item); +- Py_XDECREF(target->end_event_obj); +- target->end_event_obj = item; ++ Py_SETREF(target->end_event_obj, item); + } else if (strcmp(event, "start-ns") == 0) { +- Py_INCREF(item); +- Py_XDECREF(target->start_ns_event_obj); +- target->start_ns_event_obj = item; ++ Py_SETREF(target->start_ns_event_obj, item); + EXPAT(SetNamespaceDeclHandler)( + self->parser, + (XML_StartNamespaceDeclHandler) expat_start_ns_handler, + (XML_EndNamespaceDeclHandler) expat_end_ns_handler + ); + } else if (strcmp(event, "end-ns") == 0) { +- Py_INCREF(item); +- Py_XDECREF(target->end_ns_event_obj); +- target->end_ns_event_obj = item; ++ Py_SETREF(target->end_ns_event_obj, item); + EXPAT(SetNamespaceDeclHandler)( + self->parser, + (XML_StartNamespaceDeclHandler) expat_start_ns_handler, + (XML_EndNamespaceDeclHandler) expat_end_ns_handler + ); + } else { ++ Py_DECREF(item); + PyErr_Format( + PyExc_ValueError, + "unknown event '%s'", event +diff -r 6d1b6a68f775 Modules/_functoolsmodule.c +--- a/Modules/_functoolsmodule.c ++++ b/Modules/_functoolsmodule.c +@@ -128,7 +128,6 @@ + Py_INCREF(func); + pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX); + if (pto->args == NULL) { +- pto->kw = NULL; + Py_DECREF(pto); + return NULL; + } +@@ -138,10 +137,6 @@ + return NULL; + } + +- +- pto->weakreflist = NULL; +- pto->dict = NULL; +- + return (PyObject *)pto; + } + +@@ -162,11 +157,11 @@ + partial_call(partialobject *pto, PyObject *args, PyObject *kw) + { + PyObject *ret; +- PyObject *argappl = NULL, *kwappl = NULL; ++ PyObject *argappl, *kwappl; + + assert (PyCallable_Check(pto->fn)); + assert (PyTuple_Check(pto->args)); +- assert (pto->kw == Py_None || PyDict_Check(pto->kw)); ++ assert (PyDict_Check(pto->kw)); + + if (PyTuple_GET_SIZE(pto->args) == 0) { + argappl = args; +@@ -178,11 +173,12 @@ + argappl = PySequence_Concat(pto->args, args); + if (argappl == NULL) + return NULL; ++ assert(PyTuple_Check(argappl)); + } + +- if (pto->kw == Py_None) { ++ if (PyDict_Size(pto->kw) == 0) { + kwappl = kw; +- Py_XINCREF(kw); ++ Py_XINCREF(kwappl); + } else { + kwappl = PyDict_Copy(pto->kw); + if (kwappl == NULL) { +@@ -289,25 +285,45 @@ + partial_setstate(partialobject *pto, PyObject *state) + { + PyObject *fn, *fnargs, *kw, *dict; +- if (!PyArg_ParseTuple(state, "OOOO", +- &fn, &fnargs, &kw, &dict)) ++ ++ if (!PyTuple_Check(state) || ++ !PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) || ++ !PyCallable_Check(fn) || ++ !PyTuple_Check(fnargs) || ++ (kw != Py_None && !PyDict_Check(kw))) ++ { ++ PyErr_SetString(PyExc_TypeError, "invalid partial state"); + return NULL; +- Py_XDECREF(pto->fn); +- Py_XDECREF(pto->args); +- Py_XDECREF(pto->kw); +- Py_XDECREF(pto->dict); +- pto->fn = fn; +- pto->args = fnargs; +- pto->kw = kw; +- if (dict != Py_None) { +- pto->dict = dict; +- Py_INCREF(dict); +- } else { +- pto->dict = NULL; + } ++ ++ if(!PyTuple_CheckExact(fnargs)) ++ fnargs = PySequence_Tuple(fnargs); ++ else ++ Py_INCREF(fnargs); ++ if (fnargs == NULL) ++ return NULL; ++ ++ if (kw == Py_None) ++ kw = PyDict_New(); ++ else if(!PyDict_CheckExact(kw)) ++ kw = PyDict_Copy(kw); ++ else ++ Py_INCREF(kw); ++ if (kw == NULL) { ++ Py_DECREF(fnargs); ++ return NULL; ++ } ++ + Py_INCREF(fn); +- Py_INCREF(fnargs); +- Py_INCREF(kw); ++ if (dict == Py_None) ++ dict = NULL; ++ else ++ Py_INCREF(dict); ++ ++ Py_SETREF(pto->fn, fn); ++ Py_SETREF(pto->args, fnargs); ++ Py_SETREF(pto->kw, kw); ++ Py_SETREF(pto->dict, dict); + Py_RETURN_NONE; + } + +diff -r 6d1b6a68f775 Modules/_io/bufferedio.c +--- a/Modules/_io/bufferedio.c ++++ b/Modules/_io/bufferedio.c +@@ -391,7 +391,7 @@ + { + Py_ssize_t res; + +- res = sizeof(buffered); ++ res = _PyObject_SIZE(Py_TYPE(self)); + if (self->buffer) + res += self->buffer_size; + return PyLong_FromSsize_t(res); +@@ -1028,8 +1028,7 @@ + Py_CLEAR(res); + goto end; + } +- Py_CLEAR(res); +- res = _PyBytes_Join(_PyIO_empty_bytes, chunks); ++ Py_SETREF(res, _PyBytes_Join(_PyIO_empty_bytes, chunks)); + + end: + LEAVE_BUFFERED(self) +@@ -1264,9 +1263,8 @@ + if (_PyIOBase_check_readable(raw, Py_True) == NULL) + return -1; + +- Py_CLEAR(self->raw); + Py_INCREF(raw); +- self->raw = raw; ++ Py_SETREF(self->raw, raw); + self->buffer_size = buffer_size; + self->readable = 1; + self->writable = 0; +@@ -1687,9 +1685,8 @@ + if (_PyIOBase_check_writable(raw, Py_True) == NULL) + return -1; + +- Py_CLEAR(self->raw); + Py_INCREF(raw); +- self->raw = raw; ++ Py_SETREF(self->raw, raw); + self->readable = 0; + self->writable = 1; + +@@ -2344,9 +2341,8 @@ + if (_PyIOBase_check_writable(raw, Py_True) == NULL) + return -1; + +- Py_CLEAR(self->raw); + Py_INCREF(raw); +- self->raw = raw; ++ Py_SETREF(self->raw, raw); + self->buffer_size = buffer_size; + self->readable = 1; + self->writable = 1; +diff -r 6d1b6a68f775 Modules/_io/bytesio.c +--- a/Modules/_io/bytesio.c ++++ b/Modules/_io/bytesio.c +@@ -809,7 +809,7 @@ + { + Py_ssize_t res; + +- res = sizeof(bytesio); ++ res = _PyObject_SIZE(Py_TYPE(self)); + if (self->buf) + res += self->buf_size; + return PyLong_FromSsize_t(res); +diff -r 6d1b6a68f775 Modules/_io/textio.c +--- a/Modules/_io/textio.c ++++ b/Modules/_io/textio.c +@@ -966,8 +966,7 @@ + "Oi", self->decoder, (int)self->readtranslate); + if (incrementalDecoder == NULL) + goto error; +- Py_CLEAR(self->decoder); +- self->decoder = incrementalDecoder; ++ Py_SETREF(self->decoder, incrementalDecoder); + } + } + +@@ -1347,8 +1346,7 @@ + static void + textiowrapper_set_decoded_chars(textio *self, PyObject *chars) + { +- Py_CLEAR(self->decoded_chars); +- self->decoded_chars = chars; ++ Py_SETREF(self->decoded_chars, chars); + self->decoded_chars_used = 0; + } + +@@ -1477,8 +1475,7 @@ + goto fail; + } + Py_DECREF(dec_buffer); +- Py_CLEAR(self->snapshot); +- self->snapshot = Py_BuildValue("NN", dec_flags, next_input); ++ Py_SETREF(self->snapshot, Py_BuildValue("NN", dec_flags, next_input)); + } + Py_DECREF(input_chunk); + +@@ -1578,8 +1575,7 @@ + if (chunks != NULL) { + if (result != NULL && PyList_Append(chunks, result) < 0) + goto fail; +- Py_CLEAR(result); +- result = PyUnicode_Join(_PyIO_empty_str, chunks); ++ Py_SETREF(result, PyUnicode_Join(_PyIO_empty_str, chunks)); + if (result == NULL) + goto fail; + Py_CLEAR(chunks); +@@ -1836,8 +1832,7 @@ + if (chunks != NULL) { + if (line != NULL && PyList_Append(chunks, line) < 0) + goto error; +- Py_CLEAR(line); +- line = PyUnicode_Join(_PyIO_empty_str, chunks); ++ Py_SETREF(line, PyUnicode_Join(_PyIO_empty_str, chunks)); + if (line == NULL) + goto error; + Py_DECREF(chunks); +diff -r 6d1b6a68f775 Modules/_json.c +--- a/Modules/_json.c ++++ b/Modules/_json.c +@@ -1717,8 +1717,7 @@ + } + else if (PyUnicode_Check(s->encoding)) { + PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL); +- Py_DECREF(s->encoding); +- s->encoding = tmp; ++ Py_SETREF(s->encoding, tmp); + } + if (s->encoding == NULL) + goto bail; +diff -r 6d1b6a68f775 Modules/_multiprocessing/semaphore.c +--- a/Modules/_multiprocessing/semaphore.c ++++ b/Modules/_multiprocessing/semaphore.c +@@ -429,7 +429,7 @@ + int kind, maxvalue, value; + PyObject *result; + static char *kwlist[] = {"kind", "value", "maxvalue", NULL}; +- static int counter = 0; ++ int try = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist, + &kind, &value, &maxvalue)) +@@ -440,10 +440,18 @@ + return NULL; + } + +- PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%d", (long)getpid(), counter++); ++ /* Create a semaphore with a unique name. The bytes returned by ++ * _PyOS_URandom() are treated as unsigned long to ensure that the filename ++ * is valid (no special characters). */ ++ do { ++ unsigned long suffix; ++ _PyOS_URandom((char *)&suffix, sizeof(suffix)); ++ PyOS_snprintf(buffer, sizeof(buffer), "/mp%ld-%lu", (long)getpid(), ++ suffix); ++ SEM_CLEAR_ERROR(); ++ handle = SEM_CREATE(buffer, value, maxvalue); ++ } while ((handle == SEM_FAILED) && (errno == EEXIST) && (++try < 100)); + +- SEM_CLEAR_ERROR(); +- handle = SEM_CREATE(buffer, value, maxvalue); + /* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */ + if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0) + goto failure; +diff -r 6d1b6a68f775 Modules/_sqlite/connection.c +--- a/Modules/_sqlite/connection.c ++++ b/Modules/_sqlite/connection.c +@@ -228,8 +228,8 @@ + node = node->next; + } + +- Py_DECREF(self->statement_cache); +- self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self); ++ Py_SETREF(self->statement_cache, ++ (pysqlite_Cache *)PyObject_CallFunction((PyObject *)&pysqlite_CacheType, "O", self)); + Py_DECREF(self); + self->statement_cache->decref_factory = 0; + } +@@ -346,9 +346,8 @@ + _pysqlite_drop_unused_cursor_references(self); + + if (cursor && self->row_factory != Py_None) { +- Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory); + Py_INCREF(self->row_factory); +- ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory; ++ Py_SETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory); + } + + return cursor; +@@ -816,8 +815,7 @@ + } + } + +- Py_DECREF(self->statements); +- self->statements = new_list; ++ Py_SETREF(self->statements, new_list); + } + + static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self) +@@ -848,8 +846,7 @@ + } + } + +- Py_DECREF(self->cursors); +- self->cursors = new_list; ++ Py_SETREF(self->cursors, new_list); + } + + PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) +diff -r 6d1b6a68f775 Modules/_sqlite/cursor.c +--- a/Modules/_sqlite/cursor.c ++++ b/Modules/_sqlite/cursor.c +@@ -172,8 +172,7 @@ + return 0; + } + +- Py_XDECREF(self->row_cast_map); +- self->row_cast_map = PyList_New(0); ++ Py_SETREF(self->row_cast_map, PyList_New(0)); + + for (i = 0; i < sqlite3_column_count(self->statement->st); i++) { + converter = NULL; +@@ -544,9 +543,8 @@ + } + + /* reset description and rowcount */ +- Py_DECREF(self->description); + Py_INCREF(Py_None); +- self->description = Py_None; ++ Py_SETREF(self->description, Py_None); + self->rowcount = -1L; + + func_args = PyTuple_New(1); +@@ -560,10 +558,10 @@ + + if (self->statement) { + (void)pysqlite_statement_reset(self->statement); +- Py_DECREF(self->statement); + } + +- self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args); ++ Py_SETREF(self->statement, ++ (pysqlite_Statement *)pysqlite_cache_get(self->connection->statement_cache, func_args)); + Py_DECREF(func_args); + + if (!self->statement) { +@@ -571,8 +569,8 @@ + } + + if (self->statement->in_use) { +- Py_DECREF(self->statement); +- self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType); ++ Py_SETREF(self->statement, ++ PyObject_New(pysqlite_Statement, &pysqlite_StatementType)); + if (!self->statement) { + goto error; + } +@@ -683,8 +681,7 @@ + numcols = sqlite3_column_count(self->statement->st); + Py_END_ALLOW_THREADS + +- Py_DECREF(self->description); +- self->description = PyTuple_New(numcols); ++ Py_SETREF(self->description, PyTuple_New(numcols)); + if (!self->description) { + goto error; + } +diff -r 6d1b6a68f775 Modules/_sre.c +--- a/Modules/_sre.c ++++ b/Modules/_sre.c +@@ -2054,8 +2054,7 @@ + if (!copy) + return 0; + +- Py_DECREF(*object); +- *object = copy; ++ Py_SETREF(*object, copy); + + return 1; /* success */ + } +diff -r 6d1b6a68f775 Modules/_ssl.c +--- a/Modules/_ssl.c ++++ b/Modules/_ssl.c +@@ -1467,8 +1467,7 @@ + return -1; + #else + Py_INCREF(value); +- Py_DECREF(self->ctx); +- self->ctx = (PySSLContext *) value; ++ Py_SETREF(self->ctx, (PySSLContext *)value); + SSL_set_SSL_CTX(self->ssl, self->ctx->ctx); + #endif + } else { +@@ -3654,7 +3653,9 @@ + if (result == NULL) { + return NULL; + } +- hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name); ++ hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL, ++ CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE, ++ store_name); + if (hStore == NULL) { + Py_DECREF(result); + return PyErr_SetFromWindowsErr(GetLastError()); +@@ -3742,7 +3743,9 @@ + if (result == NULL) { + return NULL; + } +- hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name); ++ hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL, ++ CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE, ++ store_name); + if (hStore == NULL) { + Py_DECREF(result); + return PyErr_SetFromWindowsErr(GetLastError()); +diff -r 6d1b6a68f775 Modules/_struct.c +--- a/Modules/_struct.c ++++ b/Modules/_struct.c +@@ -1377,15 +1377,13 @@ + + if (PyString_Check(o_format)) { + Py_INCREF(o_format); +- Py_CLEAR(soself->s_format); +- soself->s_format = o_format; ++ Py_SETREF(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; ++ Py_SETREF(soself->s_format, str); + } + else { + PyErr_Format(PyExc_TypeError, +@@ -1737,7 +1735,7 @@ + { + Py_ssize_t size; + +- size = sizeof(PyStructObject) + sizeof(formatcode) * (self->s_len + 1); ++ size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode) * (self->s_len + 1); + return PyLong_FromSsize_t(size); + } + +diff -r 6d1b6a68f775 Modules/_testcapimodule.c +--- a/Modules/_testcapimodule.c ++++ b/Modules/_testcapimodule.c +@@ -1115,6 +1115,267 @@ + return Py_None; + } + ++static PyObject * ++getargs_c(PyObject *self, PyObject *args) ++{ ++ char c; ++ if (!PyArg_ParseTuple(args, "c", &c)) ++ return NULL; ++ return PyInt_FromLong((unsigned char)c); ++} ++ ++static PyObject * ++getargs_s(PyObject *self, PyObject *args) ++{ ++ const char *str; ++ if (!PyArg_ParseTuple(args, "s", &str)) ++ return NULL; ++ return PyBytes_FromString(str); ++} ++ ++static PyObject * ++getargs_s_star(PyObject *self, PyObject *args) ++{ ++ Py_buffer buffer; ++ PyObject *bytes; ++ if (!PyArg_ParseTuple(args, "s*", &buffer)) ++ return NULL; ++ bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len); ++ PyBuffer_Release(&buffer); ++ return bytes; ++} ++ ++static PyObject * ++getargs_s_hash(PyObject *self, PyObject *args) ++{ ++ const char *str; ++ int size; ++ if (!PyArg_ParseTuple(args, "s#", &str, &size)) ++ return NULL; ++ return PyBytes_FromStringAndSize(str, size); ++} ++ ++static PyObject * ++getargs_t_hash(PyObject *self, PyObject *args) ++{ ++ const char *str; ++ int size; ++ if (!PyArg_ParseTuple(args, "t#", &str, &size)) ++ return NULL; ++ return PyBytes_FromStringAndSize(str, size); ++} ++ ++static PyObject * ++getargs_z(PyObject *self, PyObject *args) ++{ ++ const char *str; ++ if (!PyArg_ParseTuple(args, "z", &str)) ++ return NULL; ++ if (str != NULL) ++ return PyBytes_FromString(str); ++ else ++ Py_RETURN_NONE; ++} ++ ++static PyObject * ++getargs_z_star(PyObject *self, PyObject *args) ++{ ++ Py_buffer buffer; ++ PyObject *bytes; ++ if (!PyArg_ParseTuple(args, "z*", &buffer)) ++ return NULL; ++ if (buffer.buf != NULL) ++ bytes = PyBytes_FromStringAndSize(buffer.buf, buffer.len); ++ else { ++ Py_INCREF(Py_None); ++ bytes = Py_None; ++ } ++ PyBuffer_Release(&buffer); ++ return bytes; ++} ++ ++static PyObject * ++getargs_z_hash(PyObject *self, PyObject *args) ++{ ++ const char *str; ++ int size; ++ if (!PyArg_ParseTuple(args, "z#", &str, &size)) ++ return NULL; ++ if (str != NULL) ++ return PyBytes_FromStringAndSize(str, size); ++ else ++ Py_RETURN_NONE; ++} ++ ++static PyObject * ++getargs_w(PyObject *self, PyObject *args) ++{ ++ char *str; ++ Py_ssize_t size; ++ ++ if (!PyArg_ParseTuple(args, "wn", &str, &size)) ++ return NULL; ++ ++ if (2 <= size) { ++ str[0] = '['; ++ str[size-1] = ']'; ++ } ++ ++ return PyBytes_FromStringAndSize(str, size); ++} ++ ++static PyObject * ++getargs_w_hash(PyObject *self, PyObject *args) ++{ ++ char *str; ++ int size; ++ ++ if (!PyArg_ParseTuple(args, "w#", &str, &size)) ++ return NULL; ++ ++ if (2 <= size) { ++ str[0] = '['; ++ str[size-1] = ']'; ++ } ++ ++ return PyBytes_FromStringAndSize(str, size); ++} ++ ++static PyObject * ++getargs_w_star(PyObject *self, PyObject *args) ++{ ++ Py_buffer buffer; ++ PyObject *result; ++ char *str; ++ ++ if (!PyArg_ParseTuple(args, "w*", &buffer)) ++ return NULL; ++ ++ if (2 <= buffer.len) { ++ str = buffer.buf; ++ str[0] = '['; ++ str[buffer.len-1] = ']'; ++ } ++ ++ result = PyBytes_FromStringAndSize(buffer.buf, buffer.len); ++ PyBuffer_Release(&buffer); ++ return result; ++} ++ ++#ifdef Py_USING_UNICODE ++ ++static int ++_ustrlen(const Py_UNICODE *u) ++{ ++ int i = 0; ++ const Py_UNICODE *v = u; ++ while (*v != 0) { i++; v++; } ++ return i; ++} ++ ++static PyObject * ++getargs_u(PyObject *self, PyObject *args) ++{ ++ const Py_UNICODE *str; ++ int size; ++ if (!PyArg_ParseTuple(args, "u", &str)) ++ return NULL; ++ size = _ustrlen(str); ++ return PyUnicode_FromUnicode(str, size); ++} ++ ++static PyObject * ++getargs_u_hash(PyObject *self, PyObject *args) ++{ ++ const Py_UNICODE *str; ++ int size; ++ if (!PyArg_ParseTuple(args, "u#", &str, &size)) ++ return NULL; ++ return PyUnicode_FromUnicode(str, size); ++} ++ ++#endif ++ ++static PyObject * ++getargs_es(PyObject *self, PyObject *args) ++{ ++ PyObject *arg, *result; ++ const char *encoding = NULL; ++ char *str; ++ ++ if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding)) ++ return NULL; ++ if (!PyArg_Parse(arg, "es", encoding, &str)) ++ return NULL; ++ result = PyBytes_FromString(str); ++ PyMem_Free(str); ++ return result; ++} ++ ++static PyObject * ++getargs_et(PyObject *self, PyObject *args) ++{ ++ PyObject *arg, *result; ++ const char *encoding = NULL; ++ char *str; ++ ++ if (!PyArg_ParseTuple(args, "O|s", &arg, &encoding)) ++ return NULL; ++ if (!PyArg_Parse(arg, "et", encoding, &str)) ++ return NULL; ++ result = PyBytes_FromString(str); ++ PyMem_Free(str); ++ return result; ++} ++ ++static PyObject * ++getargs_es_hash(PyObject *self, PyObject *args) ++{ ++ PyObject *arg, *result; ++ const char *encoding = NULL; ++ PyByteArrayObject *buffer = NULL; ++ char *str = NULL; ++ int size; ++ ++ if (!PyArg_ParseTuple(args, "O|sO!", ++ &arg, &encoding, &PyByteArray_Type, &buffer)) ++ return NULL; ++ if (buffer != NULL) { ++ str = PyByteArray_AS_STRING(buffer); ++ size = PyByteArray_GET_SIZE(buffer); ++ } ++ if (!PyArg_Parse(arg, "es#", encoding, &str, &size)) ++ return NULL; ++ result = PyBytes_FromStringAndSize(str, size); ++ if (buffer == NULL) ++ PyMem_Free(str); ++ return result; ++} ++ ++static PyObject * ++getargs_et_hash(PyObject *self, PyObject *args) ++{ ++ PyObject *arg, *result; ++ const char *encoding = NULL; ++ PyByteArrayObject *buffer = NULL; ++ char *str = NULL; ++ int size; ++ ++ if (!PyArg_ParseTuple(args, "O|sO!", ++ &arg, &encoding, &PyByteArray_Type, &buffer)) ++ return NULL; ++ if (buffer != NULL) { ++ str = PyByteArray_AS_STRING(buffer); ++ size = PyByteArray_GET_SIZE(buffer); ++ } ++ if (!PyArg_Parse(arg, "et#", encoding, &str, &size)) ++ return NULL; ++ result = PyBytes_FromStringAndSize(str, size); ++ if (buffer == NULL) ++ PyMem_Free(str); ++ return result; ++} ++ + #ifdef Py_USING_UNICODE + + static volatile int x; +@@ -1335,7 +1596,12 @@ + static PyObject * + test_null_strings(PyObject *self) + { +- PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Unicode(NULL); ++ PyObject *o1 = PyObject_Str(NULL); ++#ifdef Py_USING_UNICODE ++ PyObject *o2 = PyObject_Unicode(NULL); ++#else ++ PyObject *o2 = PyObject_Str(NULL); ++#endif + PyObject *tuple = PyTuple_Pack(2, o1, o2); + Py_XDECREF(o1); + Py_XDECREF(o2); +@@ -1385,6 +1651,7 @@ + Py_RETURN_NONE; + } + ++#ifdef Py_USING_UNICODE + static int test_run_counter = 0; + + static PyObject * +@@ -1407,6 +1674,7 @@ + else + return NULL; + } ++#endif + + + #ifdef WITH_THREAD +@@ -2045,7 +2313,9 @@ + {"raise_exception", raise_exception, METH_VARARGS}, + {"set_errno", set_errno, METH_VARARGS}, + {"test_config", (PyCFunction)test_config, METH_NOARGS}, ++#ifdef Py_USING_UNICODE + {"test_datetime_capi", test_datetime_capi, METH_NOARGS}, ++#endif + {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS}, + {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS}, + {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS}, +@@ -2057,7 +2327,9 @@ + METH_NOARGS}, + {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS}, + {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS}, ++#ifdef Py_USING_UNICODE + {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS}, ++#endif + {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS}, + {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS}, + {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS, +@@ -2082,12 +2354,31 @@ + {"test_long_long_and_overflow", + (PyCFunction)test_long_long_and_overflow, METH_NOARGS}, + {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS}, ++#endif ++ {"getargs_c", getargs_c, METH_VARARGS}, ++ {"getargs_s", getargs_s, METH_VARARGS}, ++ {"getargs_s_star", getargs_s_star, METH_VARARGS}, ++ {"getargs_s_hash", getargs_s_hash, METH_VARARGS}, ++ {"getargs_t_hash", getargs_t_hash, METH_VARARGS}, ++ {"getargs_z", getargs_z, METH_VARARGS}, ++ {"getargs_z_star", getargs_z_star, METH_VARARGS}, ++ {"getargs_z_hash", getargs_z_hash, METH_VARARGS}, ++ {"getargs_w", getargs_w, METH_VARARGS}, ++ {"getargs_w_star", getargs_w_star, METH_VARARGS}, ++ {"getargs_w_hash", getargs_w_hash, METH_VARARGS}, ++#ifdef Py_USING_UNICODE ++ {"getargs_u", getargs_u, METH_VARARGS}, ++ {"getargs_u_hash", getargs_u_hash, METH_VARARGS}, ++#endif ++ {"getargs_es", getargs_es, METH_VARARGS}, ++ {"getargs_et", getargs_et, METH_VARARGS}, ++ {"getargs_es_hash", getargs_es_hash, METH_VARARGS}, ++ {"getargs_et_hash", getargs_et_hash, METH_VARARGS}, ++#ifdef Py_USING_UNICODE + {"codec_incrementalencoder", + (PyCFunction)codec_incrementalencoder, METH_VARARGS}, + {"codec_incrementaldecoder", + (PyCFunction)codec_incrementaldecoder, METH_VARARGS}, +-#endif +-#ifdef Py_USING_UNICODE + {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, + {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, + {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS}, +diff -r 6d1b6a68f775 Modules/arraymodule.c +--- a/Modules/arraymodule.c ++++ b/Modules/arraymodule.c +@@ -1541,7 +1541,7 @@ + array_sizeof(arrayobject *self, PyObject *unused) + { + Py_ssize_t res; +- res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize; ++ res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize; + return PyLong_FromSsize_t(res); + } + +diff -r 6d1b6a68f775 Modules/bz2module.c +--- a/Modules/bz2module.c ++++ b/Modules/bz2module.c +@@ -1953,9 +1953,8 @@ + self->running = 0; + input_left += bzs->avail_in; + if (input_left != 0) { +- Py_DECREF(self->unused_data); +- self->unused_data = +- PyString_FromStringAndSize(bzs->next_in, input_left); ++ Py_SETREF(self->unused_data, ++ PyString_FromStringAndSize(bzs->next_in, input_left)); + if (self->unused_data == NULL) + goto error; + } +diff -r 6d1b6a68f775 Modules/cPickle.c +--- a/Modules/cPickle.c ++++ b/Modules/cPickle.c +@@ -689,8 +689,7 @@ + } + if (! str) return -1; + +- Py_XDECREF(self->last_string); +- self->last_string = str; ++ Py_SETREF(self->last_string, str); + + if (! (*s = PyString_AsString(str))) return -1; + +@@ -716,8 +715,7 @@ + if ((str_size = PyString_Size(str)) < 0) + return -1; + +- Py_XDECREF(self->last_string); +- self->last_string = str; ++ Py_SETREF(self->last_string, str); + + if (! (*s = PyString_AsString(str))) + return -1; +@@ -3228,9 +3226,8 @@ + "attribute deletion is not supported"); + return -1; + } +- Py_XDECREF(p->pers_func); + Py_INCREF(v); +- p->pers_func = v; ++ Py_SETREF(p->pers_func, v); + return 0; + } + +@@ -3242,9 +3239,8 @@ + "attribute deletion is not supported"); + return -1; + } +- Py_XDECREF(p->inst_pers_func); + Py_INCREF(v); +- p->inst_pers_func = v; ++ Py_SETREF(p->inst_pers_func, v); + return 0; + } + +@@ -3270,9 +3266,8 @@ + PyErr_SetString(PyExc_TypeError, "memo must be a dictionary"); + return -1; + } +- Py_XDECREF(p->memo); + Py_INCREF(v); +- p->memo = v; ++ Py_SETREF(p->memo, v); + return 0; + } + +@@ -3798,35 +3793,26 @@ + + + static int +-load_tuple(Unpicklerobject *self) ++load_counted_tuple(Unpicklerobject *self, int len) + { + PyObject *tup; +- Py_ssize_t i; +- +- if ((i = marker(self)) < 0) return -1; +- if (!( tup=Pdata_popTuple(self->stack, i))) return -1; ++ ++ if (self->stack->length < len) ++ return stackUnderflow(); ++ ++ if (!(tup = Pdata_popTuple(self->stack, self->stack->length - len))) ++ return -1; + PDATA_PUSH(self->stack, tup, -1); + return 0; + } + + static int +-load_counted_tuple(Unpicklerobject *self, int len) ++load_tuple(Unpicklerobject *self) + { +- PyObject *tup = PyTuple_New(len); +- +- if (tup == NULL) +- return -1; +- +- while (--len >= 0) { +- PyObject *element; +- +- PDATA_POP(self->stack, element); +- if (element == NULL) +- return -1; +- PyTuple_SET_ITEM(tup, len, element); +- } +- PDATA_PUSH(self->stack, tup, -1); +- return 0; ++ Py_ssize_t i; ++ ++ if ((i = marker(self)) < 0) return -1; ++ return load_counted_tuple(self, self->stack->length - i); + } + + static int +@@ -3945,6 +3931,10 @@ + Py_ssize_t i; + + if ((i = marker(self)) < 0) return -1; ++ ++ if (self->stack->length - i < 1) ++ return stackUnderflow(); ++ + if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1; + PDATA_POP(self->stack, class); + if (class) { +@@ -3974,7 +3964,10 @@ + if (!module_name) return -1; + + if ((len = self->readline_func(self, &s)) >= 0) { +- if (len < 2) return bad_readline(); ++ if (len < 2) { ++ Py_DECREF(module_name); ++ return bad_readline(); ++ } + if ((class_name = PyString_FromStringAndSize(s, len - 1))) { + class = find_class(module_name, class_name, + self->find_class); +@@ -4496,6 +4489,8 @@ + static int + load_append(Unpicklerobject *self) + { ++ if (self->stack->length - 1 <= 0) ++ return stackUnderflow(); + return do_append(self, self->stack->length - 1); + } + +@@ -4503,7 +4498,10 @@ + static int + load_appends(Unpicklerobject *self) + { +- return do_append(self, marker(self)); ++ Py_ssize_t i = marker(self); ++ if (i < 0) ++ return -1; ++ return do_append(self, i); + } + + +@@ -4515,6 +4513,14 @@ + + if (!( (len=self->stack->length) >= x + && x > 0 )) return stackUnderflow(); ++ if (len == x) /* nothing to do */ ++ return 0; ++ if ((len - x) % 2 != 0) { ++ /* Currupt or hostile pickle -- we never write one like this. */ ++ PyErr_SetString(UnpicklingError, ++ "odd number of items for SETITEMS"); ++ return -1; ++ } + + dict=self->stack->data[x-1]; + +@@ -4542,7 +4548,10 @@ + static int + load_setitems(Unpicklerobject *self) + { +- return do_setitems(self, marker(self)); ++ Py_ssize_t i = marker(self); ++ if (i < 0) ++ return -1; ++ return do_setitems(self, i); + } + + +@@ -5653,16 +5662,14 @@ + { + + if (!strcmp(name, "persistent_load")) { +- Py_XDECREF(self->pers_func); +- self->pers_func = value; + Py_XINCREF(value); ++ Py_SETREF(self->pers_func, value); + return 0; + } + + if (!strcmp(name, "find_global")) { +- Py_XDECREF(self->find_class); +- self->find_class = value; + Py_XINCREF(value); ++ Py_SETREF(self->find_class, value); + return 0; + } + +@@ -5678,9 +5685,8 @@ + "memo must be a dictionary"); + return -1; + } +- Py_XDECREF(self->memo); +- self->memo = value; + Py_INCREF(value); ++ Py_SETREF(self->memo, value); + return 0; + } + +diff -r 6d1b6a68f775 Modules/cdmodule.c +--- a/Modules/cdmodule.c ++++ b/Modules/cdmodule.c +@@ -628,12 +628,10 @@ + CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback, + (void *) self); + #endif +- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback); + Py_INCREF(func); +- self->ob_cdcallbacks[type].ob_cdcallback = func; +- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); ++ Py_SETREF(self->ob_cdcallbacks[type].ob_cdcallback, func); + Py_INCREF(funcarg); +- self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg; ++ Py_SETREF(self->ob_cdcallbacks[type].ob_cdcallbackarg, funcarg); + + /* + if (type == cd_audio) { +diff -r 6d1b6a68f775 Modules/getaddrinfo.c +--- a/Modules/getaddrinfo.c ++++ b/Modules/getaddrinfo.c +@@ -15,14 +15,14 @@ + * 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 ++ * 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 ++ * 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 GAI_ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN GAI_ANY WAY ++ * 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. + */ +diff -r 6d1b6a68f775 Modules/itertoolsmodule.c +--- a/Modules/itertoolsmodule.c ++++ b/Modules/itertoolsmodule.c +@@ -4,8 +4,6 @@ + + /* Itertools module written and maintained + by Raymond D. Hettinger +- Copyright (c) 2003 Python Software Foundation. +- All rights reserved. + */ + + +@@ -494,8 +492,7 @@ + link = teedataobject_jumplink(to->dataobj); + if (link == NULL) + return NULL; +- Py_DECREF(to->dataobj); +- to->dataobj = (teedataobject *)link; ++ Py_SETREF(to->dataobj, (teedataobject *)link); + to->index = 0; + } + value = teedataobject_getitem(to->dataobj, to->index); +diff -r 6d1b6a68f775 Modules/mathmodule.c +--- a/Modules/mathmodule.c ++++ b/Modules/mathmodule.c +@@ -379,9 +379,8 @@ + Implementations of the error function erf(x) and the complementary error + function erfc(x). + +- Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed., +- Cambridge University Press), we use a series approximation for erf for +- small x, and a continued fraction approximation for erfc(x) for larger x; ++ Method: we use a series approximation for erf for small x, and a continued ++ fraction approximation for erfc(x) for larger x; + combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x), + this gives us erf(x) and erfc(x) for all x. + +diff -r 6d1b6a68f775 Modules/mmapmodule.c +--- a/Modules/mmapmodule.c ++++ b/Modules/mmapmodule.c +@@ -655,7 +655,7 @@ + { + Py_ssize_t res; + +- res = sizeof(mmap_object); ++ res = _PyObject_SIZE(Py_TYPE(self)); + if (self->tagname) + res += strlen(self->tagname) + 1; + return PyLong_FromSsize_t(res); +diff -r 6d1b6a68f775 Modules/parsermodule.c +--- a/Modules/parsermodule.c ++++ b/Modules/parsermodule.c +@@ -720,7 +720,7 @@ + { + Py_ssize_t res; + +- res = sizeof(PyST_Object) + _PyNode_SizeOf(st->st_node); ++ res = _PyObject_SIZE(Py_TYPE(st)) + _PyNode_SizeOf(st->st_node); + return PyLong_FromSsize_t(res); + } + +diff -r 6d1b6a68f775 Modules/python.c +--- a/Modules/python.c ++++ b/Modules/python.c +@@ -3,7 +3,7 @@ + #include "Python.h" + + #ifdef __FreeBSD__ +-#include ++#include + #endif + + int +@@ -15,10 +15,7 @@ + * exceptions by default. Here we disable them. + */ + #ifdef __FreeBSD__ +- fp_except_t m; +- +- m = fpgetmask(); +- fpsetmask(m & ~FP_X_OFL); ++ fedisableexcept(FE_OVERFLOW); + #endif + return Py_Main(argc, argv); + } +diff -r 6d1b6a68f775 Modules/signalmodule.c +--- a/Modules/signalmodule.c ++++ b/Modules/signalmodule.c +@@ -621,8 +621,7 @@ + if (Handlers[SIGINT].func == DefaultHandler) { + /* Install default int handler */ + Py_INCREF(IntHandler); +- Py_DECREF(Handlers[SIGINT].func); +- Handlers[SIGINT].func = IntHandler; ++ Py_SETREF(Handlers[SIGINT].func, IntHandler); + old_siginthandler = PyOS_setsig(SIGINT, signal_handler); + } + +diff -r 6d1b6a68f775 Modules/socketmodule.c +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -82,6 +82,11 @@ + */ + + #ifdef __APPLE__ ++#include ++/* for getaddrinfo thread safety test on old versions of OS X */ ++#ifndef MAC_OS_X_VERSION_10_5 ++#define MAC_OS_X_VERSION_10_5 1050 ++#endif + /* + * inet_aton is not available on OSX 10.3, yet we want to use a binary + * that was build on 10.4 or later to work on that release, weak linking +@@ -178,15 +183,32 @@ + # define USE_GETHOSTBYNAME_LOCK + #endif + +-/* To use __FreeBSD_version */ ++/* To use __FreeBSD_version, __OpenBSD__, and __NetBSD_Version__ */ + #ifdef HAVE_SYS_PARAM_H + #include + #endif + /* On systems on which getaddrinfo() is believed to not be thread-safe, +- (this includes the getaddrinfo emulation) protect access with a lock. */ +-#if defined(WITH_THREAD) && (defined(__APPLE__) || \ ++ (this includes the getaddrinfo emulation) protect access with a lock. ++ ++ getaddrinfo is thread-safe on Mac OS X 10.5 and later. Originally it was ++ a mix of code including an unsafe implementation from an old BSD's ++ libresolv. In 10.5 Apple reimplemented it as a safe IPC call to the ++ mDNSResponder process. 10.5 is the first be UNIX '03 certified, which ++ includes the requirement that getaddrinfo be thread-safe. See issue #25924. ++ ++ It's thread-safe in OpenBSD starting with 5.4, released Nov 2013: ++ http://www.openbsd.org/plus54.html ++ ++ It's thread-safe in NetBSD starting with 4.0, released Dec 2007: ++ ++http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/net/getaddrinfo.c.diff?r1=1.82&r2=1.83 ++*/ ++#if defined(WITH_THREAD) && ( \ ++ (defined(__APPLE__) && \ ++ MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) || \ + (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \ +- defined(__OpenBSD__) || defined(__NetBSD__) || \ ++ (defined(__OpenBSD__) && OpenBSD+0 < 201311) || \ ++ (defined(__NetBSD__) && __NetBSD_Version__+0 < 400000000) || \ + defined(__VMS) || !defined(HAVE_GETADDRINFO)) + #define USE_GETADDRINFO_LOCK + #endif +diff -r 6d1b6a68f775 Modules/zipimport.c +--- a/Modules/zipimport.c ++++ b/Modules/zipimport.c +@@ -44,8 +44,8 @@ + static PyObject *zip_directory_cache = NULL; + + /* forward decls */ +-static PyObject *read_directory(char *archive); +-static PyObject *get_data(char *archive, PyObject *toc_entry); ++static PyObject *read_directory(const char *archive); ++static PyObject *get_data(const char *archive, PyObject *toc_entry); + static PyObject *get_module_code(ZipImporter *self, char *fullname, + int *p_ispackage, char **p_modpath); + +@@ -644,23 +644,43 @@ + + /* implementation */ + +-/* Given a buffer, return the long that is represented by the first ++/* Given a buffer, return the unsigned int that is represented by the first + 4 bytes, encoded as little endian. This partially reimplements + marshal.c:r_long() */ +-static long +-get_long(unsigned char *buf) { +- long x; ++static unsigned int ++get_uint32(const unsigned char *buf) ++{ ++ unsigned int x; + x = buf[0]; +- x |= (long)buf[1] << 8; +- x |= (long)buf[2] << 16; +- x |= (long)buf[3] << 24; +-#if SIZEOF_LONG > 4 +- /* Sign extension for 64-bit machines */ +- x |= -(x & 0x80000000L); +-#endif ++ x |= (unsigned int)buf[1] << 8; ++ x |= (unsigned int)buf[2] << 16; ++ x |= (unsigned int)buf[3] << 24; + return x; + } + ++/* Given a buffer, return the unsigned int that is represented by the first ++ 2 bytes, encoded as little endian. This partially reimplements ++ marshal.c:r_short() */ ++static unsigned short ++get_uint16(const unsigned char *buf) ++{ ++ unsigned short x; ++ x = buf[0]; ++ x |= (unsigned short)buf[1] << 8; ++ return x; ++} ++ ++static void ++set_file_error(const char *archive, int eof) ++{ ++ if (eof) { ++ PyErr_SetString(PyExc_EOFError, "EOF read where not expected"); ++ } ++ else { ++ PyErr_SetFromErrnoWithFilename(PyExc_IOError, archive); ++ } ++} ++ + /* + read_directory(archive) -> files dict (new reference) + +@@ -683,18 +703,20 @@ + data_size and file_offset are 0. + */ + static PyObject * +-read_directory(char *archive) ++read_directory(const char *archive) + { + PyObject *files = NULL; + FILE *fp; +- long compress, crc, data_size, file_size, file_offset, date, time; +- long header_offset, name_size, header_size, header_position; +- long i, l, count; ++ unsigned short compress, time, date, name_size; ++ unsigned int crc, data_size, file_size, header_size, header_offset; ++ unsigned long file_offset, header_position; ++ unsigned long arc_offset; /* Absolute offset to start of the zip-archive. */ ++ unsigned int count, i; ++ unsigned char buffer[46]; + size_t length; + char path[MAXPATHLEN + 5]; + char name[MAXPATHLEN + 5]; +- char *p, endof_central_dir[22]; +- long arc_offset; /* offset from beginning of file to start of zip-archive */ ++ const char *errmsg = NULL; + + if (strlen(archive) > MAXPATHLEN) { + PyErr_SetString(PyExc_OverflowError, +@@ -711,98 +733,145 @@ + } + + if (fseek(fp, -22, SEEK_END) == -1) { +- fclose(fp); +- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive); +- return NULL; ++ goto file_error; + } +- header_position = ftell(fp); +- if (fread(endof_central_dir, 1, 22, fp) != 22) { +- fclose(fp); +- PyErr_Format(ZipImportError, "can't read Zip file: " +- "'%.200s'", archive); +- return NULL; ++ header_position = (unsigned long)ftell(fp); ++ if (header_position == (unsigned long)-1) { ++ goto file_error; + } +- if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) { ++ assert(header_position <= (unsigned long)LONG_MAX); ++ if (fread(buffer, 1, 22, fp) != 22) { ++ goto file_error; ++ } ++ if (get_uint32(buffer) != 0x06054B50u) { + /* Bad: End of Central Dir signature */ +- fclose(fp); +- PyErr_Format(ZipImportError, "not a Zip file: " +- "'%.200s'", archive); +- return NULL; ++ errmsg = "not a Zip file"; ++ goto invalid_header; + } + +- header_size = get_long((unsigned char *)endof_central_dir + 12); +- header_offset = get_long((unsigned char *)endof_central_dir + 16); +- arc_offset = header_position - header_offset - header_size; +- header_offset += arc_offset; ++ header_size = get_uint32(buffer + 12); ++ header_offset = get_uint32(buffer + 16); ++ if (header_position < header_size) { ++ errmsg = "bad central directory size"; ++ goto invalid_header; ++ } ++ if (header_position < header_offset) { ++ errmsg = "bad central directory offset"; ++ goto invalid_header; ++ } ++ if (header_position - header_size < header_offset) { ++ errmsg = "bad central directory size or offset"; ++ goto invalid_header; ++ } ++ header_position -= header_size; ++ arc_offset = header_position - header_offset; + + files = PyDict_New(); +- if (files == NULL) ++ if (files == NULL) { + goto error; ++ } + + length = (long)strlen(path); + path[length] = SEP; + + /* Start of Central Directory */ + count = 0; ++ if (fseek(fp, (long)header_position, 0) == -1) { ++ goto file_error; ++ } + for (;;) { + PyObject *t; ++ size_t n; + int err; + +- if (fseek(fp, header_offset, 0) == -1) /* Start of file header */ +- goto fseek_error; +- l = PyMarshal_ReadLongFromFile(fp); +- if (l != 0x02014B50) ++ n = fread(buffer, 1, 46, fp); ++ if (n < 4) { ++ goto eof_error; ++ } ++ /* Start of file header */ ++ if (get_uint32(buffer) != 0x02014B50u) { + break; /* Bad: Central Dir File Header */ +- if (fseek(fp, header_offset + 10, 0) == -1) +- goto fseek_error; +- compress = PyMarshal_ReadShortFromFile(fp); +- time = PyMarshal_ReadShortFromFile(fp); +- date = PyMarshal_ReadShortFromFile(fp); +- crc = PyMarshal_ReadLongFromFile(fp); +- data_size = PyMarshal_ReadLongFromFile(fp); +- file_size = PyMarshal_ReadLongFromFile(fp); +- name_size = PyMarshal_ReadShortFromFile(fp); +- header_size = 46 + name_size + +- PyMarshal_ReadShortFromFile(fp) + +- PyMarshal_ReadShortFromFile(fp); +- if (fseek(fp, header_offset + 42, 0) == -1) +- goto fseek_error; +- file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset; +- if (name_size > MAXPATHLEN) ++ } ++ if (n != 46) { ++ goto eof_error; ++ } ++ compress = get_uint16(buffer + 10); ++ time = get_uint16(buffer + 12); ++ date = get_uint16(buffer + 14); ++ crc = get_uint32(buffer + 16); ++ data_size = get_uint32(buffer + 20); ++ file_size = get_uint32(buffer + 24); ++ name_size = get_uint16(buffer + 28); ++ header_size = (unsigned int)name_size + ++ get_uint16(buffer + 30) /* extra field */ + ++ get_uint16(buffer + 32) /* comment */; ++ ++ file_offset = get_uint32(buffer + 42); ++ if (file_offset > header_offset) { ++ errmsg = "bad local header offset"; ++ goto invalid_header; ++ } ++ file_offset += arc_offset; ++ ++ if (name_size > MAXPATHLEN) { + name_size = MAXPATHLEN; +- +- p = name; +- for (i = 0; i < name_size; i++) { +- *p = (char)getc(fp); +- if (*p == '/') +- *p = SEP; +- p++; + } +- *p = 0; /* Add terminating null byte */ +- header_offset += header_size; ++ if (fread(name, 1, name_size, fp) != name_size) { ++ goto file_error; ++ } ++ name[name_size] = '\0'; /* Add terminating null byte */ ++ if (SEP != '/') { ++ for (i = 0; i < name_size; i++) { ++ if (name[i] == '/') { ++ name[i] = SEP; ++ } ++ } ++ } ++ /* Skip the rest of the header. ++ * On Windows, calling fseek to skip over the fields we don't use is ++ * slower than reading the data because fseek flushes stdio's ++ * internal buffers. See issue #8745. */ ++ assert(header_size <= 3*0xFFFFu); ++ for (i = name_size; i < header_size; i++) { ++ if (getc(fp) == EOF) { ++ goto file_error; ++ } ++ } + + strncpy(path + length + 1, name, MAXPATHLEN - length - 1); + +- t = Py_BuildValue("siiiiiii", path, compress, data_size, ++ t = Py_BuildValue("sHIIkHHI", path, compress, data_size, + file_size, file_offset, time, date, crc); +- if (t == NULL) ++ if (t == NULL) { + goto error; ++ } + err = PyDict_SetItemString(files, name, t); + Py_DECREF(t); +- if (err != 0) ++ if (err != 0) { + goto error; ++ } + count++; + } + fclose(fp); +- if (Py_VerboseFlag) +- PySys_WriteStderr("# zipimport: found %ld names in %s\n", +- count, archive); ++ if (Py_VerboseFlag) { ++ PySys_WriteStderr("# zipimport: found %u names in %.200s\n", ++ count, archive); ++ } + return files; +-fseek_error: +- fclose(fp); +- Py_XDECREF(files); +- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive); +- return NULL; ++ ++eof_error: ++ set_file_error(archive, !ferror(fp)); ++ goto error; ++ ++file_error: ++ PyErr_Format(ZipImportError, "can't read Zip file: %.200s", archive); ++ goto error; ++ ++invalid_header: ++ assert(errmsg != NULL); ++ PyErr_Format(ZipImportError, "%s: %.200s", errmsg, archive); ++ goto error; ++ + error: + fclose(fp); + Py_XDECREF(files); +@@ -844,23 +913,28 @@ + /* Given a path to a Zip file and a toc_entry, return the (uncompressed) + data as a new reference. */ + static PyObject * +-get_data(char *archive, PyObject *toc_entry) ++get_data(const char *archive, PyObject *toc_entry) + { +- PyObject *raw_data, *data = NULL, *decompress; ++ PyObject *raw_data = NULL, *data, *decompress; + char *buf; + FILE *fp; +- int err; +- Py_ssize_t bytes_read = 0; +- long l; +- char *datapath; +- long compress, data_size, file_size, file_offset; +- long time, date, crc; ++ const char *datapath; ++ unsigned short compress, time, date; ++ unsigned int crc; ++ Py_ssize_t data_size, file_size; ++ long file_offset, header_size; ++ unsigned char buffer[30]; ++ const char *errmsg = NULL; + +- if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress, ++ if (!PyArg_ParseTuple(toc_entry, "sHnnlHHI", &datapath, &compress, + &data_size, &file_size, &file_offset, &time, + &date, &crc)) { + return NULL; + } ++ if (data_size < 0) { ++ PyErr_Format(ZipImportError, "negative data size"); ++ return NULL; ++ } + + fp = fopen(archive, "rb"); + if (!fp) { +@@ -871,54 +945,51 @@ + + /* Check to make sure the local file header is correct */ + if (fseek(fp, file_offset, 0) == -1) { ++ goto file_error; ++ } ++ if (fread(buffer, 1, 30, fp) != 30) { ++ goto eof_error; ++ } ++ if (get_uint32(buffer) != 0x04034B50u) { ++ /* Bad: Local File Header */ ++ errmsg = "bad local file header"; ++ goto invalid_header; ++ } ++ ++ header_size = (unsigned int)30 + ++ get_uint16(buffer + 26) /* file name */ + ++ get_uint16(buffer + 28) /* extra field */; ++ if (file_offset > LONG_MAX - header_size) { ++ errmsg = "bad local file header size"; ++ goto invalid_header; ++ } ++ file_offset += header_size; /* Start of file data */ ++ ++ if (data_size > LONG_MAX - 1) { + fclose(fp); +- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive); ++ PyErr_NoMemory(); + return NULL; + } +- +- l = PyMarshal_ReadLongFromFile(fp); +- if (l != 0x04034B50) { +- /* Bad: Local File Header */ +- PyErr_Format(ZipImportError, +- "bad local file header in %s", +- archive); +- fclose(fp); +- return NULL; +- } +- if (fseek(fp, file_offset + 26, 0) == -1) { +- fclose(fp); +- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive); +- return NULL; +- } +- +- l = 30 + PyMarshal_ReadShortFromFile(fp) + +- PyMarshal_ReadShortFromFile(fp); /* local header size */ +- file_offset += l; /* Start of file data */ +- + raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ? + data_size : data_size + 1); ++ + if (raw_data == NULL) { +- fclose(fp); +- return NULL; ++ goto error; + } + buf = PyString_AsString(raw_data); + +- err = fseek(fp, file_offset, 0); +- if (err == 0) { +- bytes_read = fread(buf, 1, data_size, fp); +- } else { +- fclose(fp); +- PyErr_Format(ZipImportError, "can't read Zip file: %s", archive); +- return NULL; ++ if (fseek(fp, file_offset, 0) == -1) { ++ goto file_error; + } +- fclose(fp); +- if (err || bytes_read != data_size) { ++ if (fread(buf, 1, data_size, fp) != (size_t)data_size) { + PyErr_SetString(PyExc_IOError, + "zipimport: can't read data"); +- Py_DECREF(raw_data); +- return NULL; ++ goto error; + } + ++ fclose(fp); ++ fp = NULL; ++ + if (compress != 0) { + buf[data_size] = 'Z'; /* saw this in zipfile.py */ + data_size++; +@@ -938,9 +1009,28 @@ + } + data = PyObject_CallFunction(decompress, "Oi", raw_data, -15); + Py_DECREF(decompress); +-error: + Py_DECREF(raw_data); + return data; ++ ++eof_error: ++ set_file_error(archive, !ferror(fp)); ++ goto error; ++ ++file_error: ++ PyErr_Format(ZipImportError, "can't read Zip file: %.200s", archive); ++ goto error; ++ ++invalid_header: ++ assert(errmsg != NULL); ++ PyErr_Format(ZipImportError, "%s: %.200s", errmsg, archive); ++ goto error; ++ ++error: ++ if (fp != NULL) { ++ fclose(fp); ++ } ++ Py_XDECREF(raw_data); ++ return NULL; + } + + /* Lenient date/time comparison function. The precision of the mtime +@@ -962,38 +1052,40 @@ + to .py if available and we don't want to mask other errors). + Returns a new reference. */ + static PyObject * +-unmarshal_code(char *pathname, PyObject *data, time_t mtime) ++unmarshal_code(const char *pathname, PyObject *data, time_t mtime) + { + PyObject *code; +- char *buf = PyString_AsString(data); ++ unsigned char *buf = (unsigned char *)PyString_AsString(data); + Py_ssize_t size = PyString_Size(data); + +- if (size <= 9) { ++ if (size < 8) { + PyErr_SetString(ZipImportError, + "bad pyc data"); + return NULL; + } + +- if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) { +- if (Py_VerboseFlag) ++ if (get_uint32(buf) != (unsigned int)PyImport_GetMagicNumber()) { ++ if (Py_VerboseFlag) { + PySys_WriteStderr("# %s has bad magic\n", + pathname); ++ } + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + +- if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4), +- mtime)) { +- if (Py_VerboseFlag) ++ if (mtime != 0 && !eq_mtime(get_uint32(buf + 4), mtime)) { ++ if (Py_VerboseFlag) { + PySys_WriteStderr("# %s has bad mtime\n", + pathname); ++ } + Py_INCREF(Py_None); + return Py_None; /* signal caller to try alternative */ + } + +- code = PyMarshal_ReadObjectFromString(buf + 8, size - 8); +- if (code == NULL) ++ code = PyMarshal_ReadObjectFromString((char *)buf + 8, size - 8); ++ if (code == NULL) { + return NULL; ++ } + if (!PyCode_Check(code)) { + Py_DECREF(code); + PyErr_Format(PyExc_TypeError, +diff -r 6d1b6a68f775 Modules/zlibmodule.c +--- a/Modules/zlibmodule.c ++++ b/Modules/zlibmodule.c +@@ -101,7 +101,7 @@ + PyDoc_STRVAR(compressobj__doc__, + "compressobj([level]) -- Return a compressor object.\n" + "\n" +-"Optional arg level is the compression level, in 0-9."); ++"Optional arg level is the compression level, in 0-9 or -1."); + + PyDoc_STRVAR(decompressobj__doc__, + "decompressobj([wbits]) -- Return a decompressor object.\n" +@@ -491,8 +491,7 @@ + PyString_AS_STRING(self->unused_data), old_size); + Py_MEMCPY(PyString_AS_STRING(new_data) + old_size, + self->zst.next_in, self->zst.avail_in); +- Py_DECREF(self->unused_data); +- self->unused_data = new_data; ++ Py_SETREF(self->unused_data, new_data); + self->zst.avail_in = 0; + } + } +@@ -504,8 +503,7 @@ + (char *)self->zst.next_in, self->zst.avail_in); + if (new_data == NULL) + return -1; +- Py_DECREF(self->unconsumed_tail); +- self->unconsumed_tail = new_data; ++ Py_SETREF(self->unconsumed_tail, new_data); + } + return 0; + } +@@ -733,11 +731,9 @@ + } + + Py_INCREF(self->unused_data); ++ Py_SETREF(retval->unused_data, self->unused_data); + Py_INCREF(self->unconsumed_tail); +- Py_XDECREF(retval->unused_data); +- Py_XDECREF(retval->unconsumed_tail); +- retval->unused_data = self->unused_data; +- retval->unconsumed_tail = self->unconsumed_tail; ++ Py_SETREF(retval->unconsumed_tail, self->unconsumed_tail); + + /* Mark it as being initialized */ + retval->is_initialised = 1; +@@ -784,11 +780,9 @@ + } + + Py_INCREF(self->unused_data); ++ Py_SETREF(retval->unused_data, self->unused_data); + Py_INCREF(self->unconsumed_tail); +- Py_XDECREF(retval->unused_data); +- Py_XDECREF(retval->unconsumed_tail); +- retval->unused_data = self->unused_data; +- retval->unconsumed_tail = self->unconsumed_tail; ++ Py_SETREF(retval->unconsumed_tail, self->unconsumed_tail); + + /* Mark it as being initialized */ + retval->is_initialised = 1; +diff -r 6d1b6a68f775 Objects/bytearrayobject.c +--- a/Objects/bytearrayobject.c ++++ b/Objects/bytearrayobject.c +@@ -2780,7 +2780,7 @@ + { + Py_ssize_t res; + +- res = sizeof(PyByteArrayObject) + self->ob_alloc * sizeof(char); ++ res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char); + return PyInt_FromSsize_t(res); + } + +diff -r 6d1b6a68f775 Objects/codeobject.c +--- a/Objects/codeobject.c ++++ b/Objects/codeobject.c +@@ -376,11 +376,140 @@ + return 0; + } + ++PyObject* ++_PyCode_ConstantKey(PyObject *op) ++{ ++ PyObject *key; ++ ++ /* Py_None is a singleton */ ++ if (op == Py_None ++ || PyInt_CheckExact(op) ++ || PyLong_CheckExact(op) ++ || PyBool_Check(op) ++ || PyBytes_CheckExact(op) ++#ifdef Py_USING_UNICODE ++ || PyUnicode_CheckExact(op) ++#endif ++ /* code_richcompare() uses _PyCode_ConstantKey() internally */ ++ || PyCode_Check(op)) { ++ key = PyTuple_Pack(2, Py_TYPE(op), op); ++ } ++ else if (PyFloat_CheckExact(op)) { ++ double d = PyFloat_AS_DOUBLE(op); ++ /* all we need is to make the tuple different in either the 0.0 ++ * or -0.0 case from all others, just to avoid the "coercion". ++ */ ++ if (d == 0.0 && copysign(1.0, d) < 0.0) ++ key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None); ++ else ++ key = PyTuple_Pack(2, Py_TYPE(op), op); ++ } ++#ifndef WITHOUT_COMPLEX ++ else if (PyComplex_CheckExact(op)) { ++ Py_complex z; ++ int real_negzero, imag_negzero; ++ /* For the complex case we must make complex(x, 0.) ++ different from complex(x, -0.) and complex(0., y) ++ different from complex(-0., y), for any x and y. ++ All four complex zeros must be distinguished.*/ ++ z = PyComplex_AsCComplex(op); ++ real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; ++ imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; ++ /* use True, False and None singleton as tags for the real and imag ++ * sign, to make tuples different */ ++ if (real_negzero && imag_negzero) { ++ key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True); ++ } ++ else if (imag_negzero) { ++ key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False); ++ } ++ else if (real_negzero) { ++ key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None); ++ } ++ else { ++ key = PyTuple_Pack(2, Py_TYPE(op), op); ++ } ++ } ++#endif ++ else if (PyTuple_CheckExact(op)) { ++ Py_ssize_t i, len; ++ PyObject *tuple; ++ ++ len = PyTuple_GET_SIZE(op); ++ tuple = PyTuple_New(len); ++ if (tuple == NULL) ++ return NULL; ++ ++ for (i=0; i < len; i++) { ++ PyObject *item, *item_key; ++ ++ item = PyTuple_GET_ITEM(op, i); ++ item_key = _PyCode_ConstantKey(item); ++ if (item_key == NULL) { ++ Py_DECREF(tuple); ++ return NULL; ++ } ++ ++ PyTuple_SET_ITEM(tuple, i, item_key); ++ } ++ ++ key = PyTuple_Pack(3, Py_TYPE(op), op, tuple); ++ Py_DECREF(tuple); ++ } ++ else if (PyFrozenSet_CheckExact(op)) { ++ Py_ssize_t pos = 0; ++ PyObject *item; ++ long hash; ++ Py_ssize_t i, len; ++ PyObject *tuple, *set; ++ ++ len = PySet_GET_SIZE(op); ++ tuple = PyTuple_New(len); ++ if (tuple == NULL) ++ return NULL; ++ ++ i = 0; ++ while (_PySet_NextEntry(op, &pos, &item, &hash)) { ++ PyObject *item_key; ++ ++ item_key = _PyCode_ConstantKey(item); ++ if (item_key == NULL) { ++ Py_DECREF(tuple); ++ return NULL; ++ } ++ ++ assert(i < len); ++ PyTuple_SET_ITEM(tuple, i, item_key); ++ i++; ++ } ++ set = PyFrozenSet_New(tuple); ++ Py_DECREF(tuple); ++ if (set == NULL) ++ return NULL; ++ ++ key = PyTuple_Pack(3, Py_TYPE(op), op, set); ++ Py_DECREF(set); ++ return key; ++ } ++ else { ++ /* for other types, use the object identifier as an unique identifier ++ * to ensure that they are seen as unequal. */ ++ PyObject *obj_id = PyLong_FromVoidPtr(op); ++ if (obj_id == NULL) ++ return NULL; ++ ++ key = PyTuple_Pack(3, Py_TYPE(op), op, obj_id); ++ Py_DECREF(obj_id); ++ } ++ return key; ++} ++ + static PyObject * + code_richcompare(PyObject *self, PyObject *other, int op) + { + PyCodeObject *co, *cp; + int eq; ++ PyObject *consts1, *consts2; + PyObject *res; + + if ((op != Py_EQ && op != Py_NE) || +@@ -413,8 +542,21 @@ + if (!eq) goto unequal; + eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); + if (eq <= 0) goto unequal; +- eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); ++ ++ /* compare constants */ ++ consts1 = _PyCode_ConstantKey(co->co_consts); ++ if (!consts1) ++ return NULL; ++ consts2 = _PyCode_ConstantKey(cp->co_consts); ++ if (!consts2) { ++ Py_DECREF(consts1); ++ return NULL; ++ } ++ eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ); ++ Py_DECREF(consts1); ++ Py_DECREF(consts2); + if (eq <= 0) goto unequal; ++ + eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); +diff -r 6d1b6a68f775 Objects/descrobject.c +--- a/Objects/descrobject.c ++++ b/Objects/descrobject.c +@@ -1332,8 +1332,7 @@ + PyObject *get_doc = PyObject_GetAttrString(get, "__doc__"); + if (get_doc) { + if (Py_TYPE(self) == &PyProperty_Type) { +- Py_XDECREF(prop->prop_doc); +- prop->prop_doc = get_doc; ++ Py_SETREF(prop->prop_doc, get_doc); + } + else { + /* If this is a property subclass, put __doc__ +diff -r 6d1b6a68f775 Objects/dictobject.c +--- a/Objects/dictobject.c ++++ b/Objects/dictobject.c +@@ -749,6 +749,36 @@ + return ep->me_value; + } + ++/* Variant of PyDict_GetItem() that doesn't suppress exceptions. ++ This returns NULL *with* an exception set if an exception occurred. ++ It returns NULL *without* an exception set if the key wasn't present. ++*/ ++PyObject * ++_PyDict_GetItemWithError(PyObject *op, PyObject *key) ++{ ++ long hash; ++ PyDictObject *mp = (PyDictObject *)op; ++ PyDictEntry *ep; ++ if (!PyDict_Check(op)) { ++ PyErr_BadInternalCall(); ++ return NULL; ++ } ++ if (!PyString_CheckExact(key) || ++ (hash = ((PyStringObject *) key)->ob_shash) == -1) ++ { ++ hash = PyObject_Hash(key); ++ if (hash == -1) { ++ return NULL; ++ } ++ } ++ ++ ep = (mp->ma_lookup)(mp, key, hash); ++ if (ep == NULL) { ++ return NULL; ++ } ++ return ep->me_value; ++} ++ + static int + dict_set_item_by_hash_or_entry(register PyObject *op, PyObject *key, + long hash, PyDictEntry *ep, PyObject *value) +@@ -2152,7 +2182,7 @@ + { + Py_ssize_t res; + +- res = sizeof(PyDictObject); ++ res = _PyObject_SIZE(Py_TYPE(mp)); + if (mp->ma_table != mp->ma_smalltable) + res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry); + return PyInt_FromSsize_t(res); +@@ -2968,7 +2998,8 @@ + if (result == NULL) + return NULL; + +- tmp = PyObject_CallMethod(result, "difference_update", "O", other); ++ ++ tmp = PyObject_CallMethod(result, "difference_update", "(O)", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; +@@ -2986,7 +3017,7 @@ + if (result == NULL) + return NULL; + +- tmp = PyObject_CallMethod(result, "intersection_update", "O", other); ++ tmp = PyObject_CallMethod(result, "intersection_update", "(O)", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; +@@ -3004,7 +3035,7 @@ + if (result == NULL) + return NULL; + +- tmp = PyObject_CallMethod(result, "update", "O", other); ++ tmp = PyObject_CallMethod(result, "update", "(O)", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; +@@ -3022,8 +3053,7 @@ + if (result == NULL) + return NULL; + +- tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O", +- other); ++ tmp = PyObject_CallMethod(result, "symmetric_difference_update", "(O)", other); + if (tmp == NULL) { + Py_DECREF(result); + return NULL; +diff -r 6d1b6a68f775 Objects/exceptions.c +--- a/Objects/exceptions.c ++++ b/Objects/exceptions.c +@@ -58,14 +58,12 @@ + if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) + return -1; + +- Py_DECREF(self->args); +- self->args = args; +- Py_INCREF(self->args); ++ Py_INCREF(args); ++ Py_SETREF(self->args, args); + + if (PyTuple_GET_SIZE(self->args) == 1) { +- Py_CLEAR(self->message); +- self->message = PyTuple_GET_ITEM(self->args, 0); +- Py_INCREF(self->message); ++ Py_INCREF(PyTuple_GET_ITEM(self->args, 0)); ++ Py_SETREF(self->message, PyTuple_GET_ITEM(self->args, 0)); + } + return 0; + } +@@ -280,9 +278,8 @@ + PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary"); + return -1; + } +- Py_CLEAR(self->dict); + Py_INCREF(val); +- self->dict = val; ++ Py_SETREF(self->dict, val); + return 0; + } + +@@ -308,8 +305,7 @@ + seq = PySequence_Tuple(val); + if (!seq) + return -1; +- Py_CLEAR(self->args); +- self->args = seq; ++ Py_SETREF(self->args, seq); + return 0; + } + +@@ -521,12 +517,14 @@ + + if (size == 0) + return 0; +- Py_CLEAR(self->code); +- if (size == 1) +- self->code = PyTuple_GET_ITEM(args, 0); +- else if (size > 1) +- self->code = args; +- Py_INCREF(self->code); ++ if (size == 1) { ++ Py_INCREF(PyTuple_GET_ITEM(args, 0)); ++ Py_SETREF(self->code, PyTuple_GET_ITEM(args, 0)); ++ } ++ else { /* size > 1 */ ++ Py_INCREF(args); ++ Py_SETREF(self->code, args); ++ } + return 0; + } + +@@ -609,26 +607,22 @@ + &myerrno, &strerror, &filename)) { + return -1; + } +- Py_CLEAR(self->myerrno); /* replacing */ +- self->myerrno = myerrno; +- Py_INCREF(self->myerrno); ++ Py_INCREF(myerrno); ++ Py_SETREF(self->myerrno, myerrno); + +- Py_CLEAR(self->strerror); /* replacing */ +- self->strerror = strerror; +- Py_INCREF(self->strerror); ++ Py_INCREF(strerror); ++ Py_SETREF(self->strerror, strerror); + + /* self->filename will remain Py_None otherwise */ + if (filename != NULL) { +- Py_CLEAR(self->filename); /* replacing */ +- self->filename = filename; +- Py_INCREF(self->filename); ++ Py_INCREF(filename); ++ Py_SETREF(self->filename, filename); + + subslice = PyTuple_GetSlice(args, 0, 2); + if (!subslice) + return -1; + +- Py_DECREF(self->args); /* replacing args */ +- self->args = subslice; ++ Py_SETREF(self->args, subslice); + } + return 0; + } +@@ -879,8 +873,7 @@ + return -1; + posix_errno = winerror_to_errno(errcode); + +- Py_CLEAR(self->winerror); +- self->winerror = self->myerrno; ++ Py_SETREF(self->winerror, self->myerrno); + + o_errcode = PyInt_FromLong(posix_errno); + if (!o_errcode) +@@ -1065,9 +1058,8 @@ + return -1; + + if (lenargs >= 1) { +- Py_CLEAR(self->msg); +- self->msg = PyTuple_GET_ITEM(args, 0); +- Py_INCREF(self->msg); ++ Py_INCREF(PyTuple_GET_ITEM(args, 0)); ++ Py_SETREF(self->msg, PyTuple_GET_ITEM(args, 0)); + } + if (lenargs == 2) { + info = PyTuple_GET_ITEM(args, 1); +@@ -1082,21 +1074,17 @@ + return -1; + } + +- Py_CLEAR(self->filename); +- self->filename = PyTuple_GET_ITEM(info, 0); +- Py_INCREF(self->filename); ++ Py_INCREF(PyTuple_GET_ITEM(info, 0)); ++ Py_SETREF(self->filename, PyTuple_GET_ITEM(info, 0)); + +- Py_CLEAR(self->lineno); +- self->lineno = PyTuple_GET_ITEM(info, 1); +- Py_INCREF(self->lineno); ++ Py_INCREF(PyTuple_GET_ITEM(info, 1)); ++ Py_SETREF(self->lineno, PyTuple_GET_ITEM(info, 1)); + +- Py_CLEAR(self->offset); +- self->offset = PyTuple_GET_ITEM(info, 2); +- Py_INCREF(self->offset); ++ Py_INCREF(PyTuple_GET_ITEM(info, 2)); ++ Py_SETREF(self->offset, PyTuple_GET_ITEM(info, 2)); + +- Py_CLEAR(self->text); +- self->text = PyTuple_GET_ITEM(info, 3); +- Py_INCREF(self->text); ++ Py_INCREF(PyTuple_GET_ITEM(info, 3)); ++ Py_SETREF(self->text, PyTuple_GET_ITEM(info, 3)); + + Py_DECREF(info); + } +@@ -1329,8 +1317,7 @@ + PyObject *obj = PyString_FromString(value); + if (!obj) + return -1; +- Py_CLEAR(*attr); +- *attr = obj; ++ Py_SETREF(*attr, obj); + return 0; + } + +diff -r 6d1b6a68f775 Objects/fileobject.c +--- a/Objects/fileobject.c ++++ b/Objects/fileobject.c +@@ -574,10 +574,8 @@ + oerrors = Py_None; + Py_INCREF(Py_None); + } +- Py_DECREF(file->f_encoding); +- file->f_encoding = str; +- Py_DECREF(file->f_errors); +- file->f_errors = oerrors; ++ Py_SETREF(file->f_encoding, str); ++ Py_SETREF(file->f_errors, oerrors); + return 1; + } + +diff -r 6d1b6a68f775 Objects/floatobject.c +--- a/Objects/floatobject.c ++++ b/Objects/floatobject.c +@@ -1839,7 +1839,7 @@ + tmp = float_new(&PyFloat_Type, args, kwds); + if (tmp == NULL) + return NULL; +- assert(PyFloat_CheckExact(tmp)); ++ assert(PyFloat_Check(tmp)); + newobj = type->tp_alloc(type, 0); + if (newobj == NULL) { + Py_DECREF(tmp); +diff -r 6d1b6a68f775 Objects/frameobject.c +--- a/Objects/frameobject.c ++++ b/Objects/frameobject.c +@@ -859,8 +859,7 @@ + } + } else if (values[j] != value) { + Py_XINCREF(value); +- Py_XDECREF(values[j]); +- values[j] = value; ++ Py_SETREF(values[j], value); + } + Py_XDECREF(value); + } +diff -r 6d1b6a68f775 Objects/funcobject.c +--- a/Objects/funcobject.c ++++ b/Objects/funcobject.c +@@ -116,8 +116,7 @@ + PyErr_SetString(PyExc_SystemError, "non-tuple default args"); + return -1; + } +- Py_XDECREF(((PyFunctionObject *) op) -> func_defaults); +- ((PyFunctionObject *) op) -> func_defaults = defaults; ++ Py_SETREF(((PyFunctionObject *)op)->func_defaults, defaults); + return 0; + } + +@@ -149,8 +148,7 @@ + closure->ob_type->tp_name); + return -1; + } +- Py_XDECREF(((PyFunctionObject *) op) -> func_closure); +- ((PyFunctionObject *) op) -> func_closure = closure; ++ Py_SETREF(((PyFunctionObject *)op)->func_closure, closure); + return 0; + } + +@@ -430,8 +428,7 @@ + + if (name != Py_None) { + Py_INCREF(name); +- Py_DECREF(newfunc->func_name); +- newfunc->func_name = name; ++ Py_SETREF(newfunc->func_name, name); + } + if (defaults != Py_None) { + Py_INCREF(defaults); +diff -r 6d1b6a68f775 Objects/listobject.c +--- a/Objects/listobject.c ++++ b/Objects/listobject.c +@@ -2469,7 +2469,7 @@ + { + Py_ssize_t res; + +- res = sizeof(PyListObject) + self->allocated * sizeof(void*); ++ res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*); + return PyInt_FromSsize_t(res); + } + +diff -r 6d1b6a68f775 Objects/longobject.c +--- a/Objects/longobject.c ++++ b/Objects/longobject.c +@@ -4068,7 +4068,7 @@ + tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); + if (tmp == NULL) + return NULL; +- assert(PyLong_CheckExact(tmp)); ++ assert(PyLong_Check(tmp)); + n = Py_SIZE(tmp); + if (n < 0) + n = -n; +diff -r 6d1b6a68f775 Objects/setobject.c +--- a/Objects/setobject.c ++++ b/Objects/setobject.c +@@ -2,9 +2,6 @@ + /* set object implementation + Written and maintained by Raymond D. Hettinger + Derived from Lib/sets.py and Objects/dictobject.c. +- +- Copyright (c) 2003-2007 Python Software Foundation. +- All rights reserved. + */ + + #include "Python.h" +@@ -1985,7 +1982,7 @@ + { + Py_ssize_t res; + +- res = sizeof(PySetObject); ++ res = _PyObject_SIZE(Py_TYPE(so)); + if (so->table != so->smalltable) + res = res + (so->mask + 1) * sizeof(setentry); + return PyInt_FromSsize_t(res); +diff -r 6d1b6a68f775 Objects/stringobject.c +--- a/Objects/stringobject.c ++++ b/Objects/stringobject.c +@@ -3719,7 +3719,7 @@ + tmp = string_new(&PyString_Type, args, kwds); + if (tmp == NULL) + return NULL; +- assert(PyString_CheckExact(tmp)); ++ assert(PyString_Check(tmp)); + n = PyString_GET_SIZE(tmp); + pnew = type->tp_alloc(type, n); + if (pnew != NULL) { +@@ -3865,8 +3865,7 @@ + return; + } + v = string_concat((PyStringObject *) *pv, w); +- Py_DECREF(*pv); +- *pv = v; ++ Py_SETREF(*pv, v); + } + + void +@@ -4751,8 +4750,7 @@ + t = PyDict_GetItem(interned, (PyObject *)s); + if (t) { + Py_INCREF(t); +- Py_DECREF(*p); +- *p = t; ++ Py_SETREF(*p, t); + return; + } + +diff -r 6d1b6a68f775 Objects/typeobject.c +--- a/Objects/typeobject.c ++++ b/Objects/typeobject.c +@@ -13,10 +13,11 @@ + MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large + strings are used as attribute names. */ + #define MCACHE_MAX_ATTR_SIZE 100 +-#define MCACHE_SIZE_EXP 10 ++#define MCACHE_SIZE_EXP 12 + #define MCACHE_HASH(version, name_hash) \ +- (((unsigned int)(version) * (unsigned int)(name_hash)) \ +- >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP)) ++ (((unsigned int)(version) ^ (unsigned int)(name_hash)) \ ++ & ((1 << MCACHE_SIZE_EXP) - 1)) ++ + #define MCACHE_HASH_METHOD(type, name) \ + MCACHE_HASH((type)->tp_version_tag, \ + ((PyStringObject *)(name))->ob_shash) +@@ -33,12 +34,32 @@ + static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP]; + static unsigned int next_version_tag = 0; + ++#define MCACHE_STATS 0 ++ ++#if MCACHE_STATS ++static size_t method_cache_hits = 0; ++static size_t method_cache_misses = 0; ++static size_t method_cache_collisions = 0; ++#endif ++ + unsigned int + PyType_ClearCache(void) + { + Py_ssize_t i; + unsigned int cur_version_tag = next_version_tag - 1; + ++#if MCACHE_STATS ++ size_t total = method_cache_hits + method_cache_collisions + method_cache_misses; ++ fprintf(stderr, "-- Method cache hits = %zd (%d%%)\n", ++ method_cache_hits, (int) (100.0 * method_cache_hits / total)); ++ fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n", ++ method_cache_misses, (int) (100.0 * method_cache_misses / total)); ++ fprintf(stderr, "-- Method cache collisions = %zd (%d%%)\n", ++ method_cache_collisions, (int) (100.0 * method_cache_collisions / total)); ++ fprintf(stderr, "-- Method cache size = %zd KB\n", ++ sizeof(method_cache) / 1024); ++#endif ++ + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].version = 0; + Py_CLEAR(method_cache[i].name); +@@ -166,9 +187,8 @@ + are borrowed reference */ + for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { + method_cache[i].value = NULL; +- Py_XDECREF(method_cache[i].name); +- method_cache[i].name = Py_None; + Py_INCREF(Py_None); ++ Py_SETREF(method_cache[i].name, Py_None); + } + /* mark all version tags as invalid */ + PyType_Modified(&PyBaseObject_Type); +@@ -245,8 +265,8 @@ + } + if (strlen(PyString_AS_STRING(value)) + != (size_t)PyString_GET_SIZE(value)) { +- PyErr_Format(PyExc_ValueError, +- "__name__ must not contain null bytes"); ++ PyErr_SetString(PyExc_ValueError, ++ "type name must not contain null characters"); + return -1; + } + +@@ -2072,8 +2092,8 @@ + PyTypeObject *type, *base, *tmptype, *winner; + PyHeapTypeObject *et; + PyMemberDef *mp; +- Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak; +- int j, may_add_dict, may_add_weak; ++ Py_ssize_t i, nbases, nslots, slotoffset; ++ int j, may_add_dict, may_add_weak, add_dict, add_weak; + + assert(args != NULL && PyTuple_Check(args)); + assert(kwds == NULL || PyDict_Check(kwds)); +@@ -2343,6 +2363,18 @@ + type->tp_as_mapping = &et->as_mapping; + type->tp_as_buffer = &et->as_buffer; + type->tp_name = PyString_AS_STRING(name); ++ if (!type->tp_name) { ++ Py_DECREF(bases); ++ Py_DECREF(type); ++ return NULL; ++ } ++ if (strlen(type->tp_name) != (size_t)PyString_GET_SIZE(name)) { ++ PyErr_SetString(PyExc_ValueError, ++ "type name must not contain null characters"); ++ Py_DECREF(bases); ++ Py_DECREF(type); ++ return NULL; ++ } + + /* Set tp_base and tp_bases */ + type->tp_bases = bases; +@@ -2363,8 +2395,10 @@ + tmp = PyDict_GetItemString(tmp, "__name__"); + if (tmp != NULL) { + if (PyDict_SetItemString(dict, "__module__", +- tmp) < 0) ++ tmp) < 0) { ++ Py_DECREF(type); + return NULL; ++ } + } + } + } +@@ -2492,8 +2526,12 @@ + /* fast path */ + h = MCACHE_HASH_METHOD(type, name); + if (method_cache[h].version == type->tp_version_tag && +- method_cache[h].name == name) ++ method_cache[h].name == name) { ++#if MCACHE_STATS ++ method_cache_hits++; ++#endif + return method_cache[h].value; ++ } + } + + /* Look in tp_dict of types in MRO */ +@@ -2527,6 +2565,13 @@ + method_cache[h].version = type->tp_version_tag; + method_cache[h].value = res; /* borrowed */ + Py_INCREF(name); ++ assert(((PyStringObject *)(name))->ob_shash != -1); ++#if MCACHE_STATS ++ if (method_cache[h].name != Py_None && method_cache[h].name != name) ++ method_cache_collisions++; ++ else ++ method_cache_misses++; ++#endif + Py_DECREF(method_cache[h].name); + method_cache[h].name = name; + } +@@ -3209,6 +3254,7 @@ + PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL; + PyObject *copyreg = NULL, *newobj = NULL, *res = NULL; + Py_ssize_t i, n; ++ int required_state = 0; + + cls = PyObject_GetAttrString(obj, "__class__"); + if (cls == NULL) +@@ -3216,7 +3262,7 @@ + + if (PyType_Check(cls) && ((PyTypeObject *)cls)->tp_new == NULL) { + PyErr_Format(PyExc_TypeError, +- "can't pickle %s objects", ++ "can't pickle %.200s objects", + ((PyTypeObject *)cls)->tp_name); + return NULL; + } +@@ -3225,7 +3271,9 @@ + if (getnewargs != NULL) { + args = PyObject_CallObject(getnewargs, NULL); + Py_DECREF(getnewargs); +- if (args != NULL && !PyTuple_Check(args)) { ++ if (args == NULL) ++ goto end; ++ if (!PyTuple_Check(args)) { + PyErr_Format(PyExc_TypeError, + "__getnewargs__ should return a tuple, " + "not '%.200s'", Py_TYPE(args)->tp_name); +@@ -3234,10 +3282,8 @@ + } + else { + PyErr_Clear(); +- args = PyTuple_New(0); +- } +- if (args == NULL) +- goto end; ++ required_state = !PyList_Check(obj) && !PyDict_Check(obj); ++ } + + getstate = PyObject_GetAttrString(obj, "__getstate__"); + if (getstate != NULL) { +@@ -3248,6 +3294,14 @@ + } + else { + PyErr_Clear(); ++ ++ if (required_state && obj->ob_type->tp_itemsize) { ++ PyErr_Format(PyExc_TypeError, ++ "can't pickle %.200s objects", ++ Py_TYPE(obj)->tp_name); ++ goto end; ++ } ++ + state = PyObject_GetAttrString(obj, "__dict__"); + if (state == NULL) { + PyErr_Clear(); +@@ -3257,8 +3311,9 @@ + names = slotnames(cls); + if (names == NULL) + goto end; ++ assert(names == Py_None || PyList_Check(names)); ++ + if (names != Py_None) { +- assert(PyList_Check(names)); + slots = PyDict_New(); + if (slots == NULL) + goto end; +@@ -3269,12 +3324,16 @@ + for (i = 0; i < PyList_GET_SIZE(names); i++) { + PyObject *name, *value; + name = PyList_GET_ITEM(names, i); ++ Py_INCREF(name); + value = PyObject_GetAttr(obj, name); +- if (value == NULL) ++ if (value == NULL) { ++ Py_DECREF(name); + PyErr_Clear(); ++ } + else { + int err = PyDict_SetItem(slots, name, + value); ++ Py_DECREF(name); + Py_DECREF(value); + if (err) + goto end; +@@ -3316,7 +3375,7 @@ + if (newobj == NULL) + goto end; + +- n = PyTuple_GET_SIZE(args); ++ n = args ? PyTuple_GET_SIZE(args) : 0; + args2 = PyTuple_New(n+1); + if (args2 == NULL) + goto end; +@@ -6213,7 +6272,7 @@ + sanity checks and constructing a new argument + list. Cut all that nonsense short -- this speeds + up instance creation tremendously. */ +- specific = (void *)type->tp_new; ++ specific = (void *)((PyTypeObject *)PyCFunction_GET_SELF(descr))->tp_new; + /* XXX I'm not 100% sure that there isn't a hole + in this reasoning that requires additional + sanity checks. I'll buy the first person to +diff -r 6d1b6a68f775 Objects/unicodeobject.c +--- a/Objects/unicodeobject.c ++++ b/Objects/unicodeobject.c +@@ -436,8 +436,7 @@ + return -1; + Py_UNICODE_COPY(w->str, v->str, + length < v->length ? length : v->length); +- Py_DECREF(*unicode); +- *unicode = w; ++ Py_SETREF(*unicode, w); + return 0; + } + +@@ -1288,6 +1287,9 @@ + goto onError; + } + ++ if (PyErr_WarnPy3k("decoding Unicode is not supported in 3.x", 1) < 0) ++ goto onError; ++ + if (encoding == NULL) + encoding = PyUnicode_GetDefaultEncoding(); + +diff -r 6d1b6a68f775 PC/VS9.0/pyproject.vsprops +--- a/PC/VS9.0/pyproject.vsprops ++++ b/PC/VS9.0/pyproject.vsprops +@@ -82,7 +82,7 @@ + /> + + + + +- $(opensslDir)include;%(AdditionalIncludeDirectories) ++ $(opensslIncludeDir);%(AdditionalIncludeDirectories) + + + ws2_32.lib;$(OutDir)libeay$(PyDebugExt).lib;$(OutDir)ssleay$(PyDebugExt).lib;%(AdditionalDependencies) +diff -r 6d1b6a68f775 PCbuild/_ssl.vcxproj +--- a/PCbuild/_ssl.vcxproj ++++ b/PCbuild/_ssl.vcxproj +@@ -61,7 +61,7 @@ + + + +- $(opensslDir)include;%(AdditionalIncludeDirectories) ++ $(opensslIncludeDir);%(AdditionalIncludeDirectories) + + + ws2_32.lib;crypt32.lib;$(OutDir)libeay$(PyDebugExt).lib;$(OutDir)ssleay$(PyDebugExt).lib;%(AdditionalDependencies) +diff -r 6d1b6a68f775 PCbuild/build.bat +--- a/PCbuild/build.bat ++++ b/PCbuild/build.bat +@@ -24,6 +24,8 @@ + echo. -v Increased output messages + echo. -k Attempt to kill any running Pythons before building (usually done + echo. automatically by the pythoncore project) ++echo. --pgo Build with Profile-Guided Optimization. This flag ++echo. overrides -c and -d + echo. + echo.Available flags to avoid building certain modules. + echo.These flags have no effect if '-e' is not given: +@@ -38,6 +40,8 @@ + echo. Set the platform (default: Win32) + echo. -t Build ^| Rebuild ^| Clean ^| CleanAll + echo. Set the target manually ++echo. --pgo-job The job to use for PGO training; implies --pgo ++echo. (default: "-m test.regrtest --pgo") + exit /b 127 + + :Run +@@ -50,6 +54,12 @@ + set parallel= + set verbose=/nologo /v:m + set kill= ++set do_pgo= ++set pgo_job=-m test.regrtest --pgo ++set on_64_bit=true ++ ++rem This may not be 100% accurate, but close enough. ++if "%ProgramFiles(x86)%"=="" (set on_64_bit=false) + + :CheckOpts + if "%~1"=="-h" goto Usage +@@ -62,6 +72,8 @@ + if "%~1"=="-M" (set parallel=) & shift & goto CheckOpts + if "%~1"=="-v" (set verbose=/v:n) & shift & goto CheckOpts + if "%~1"=="-k" (set kill=true) & shift & goto CheckOpts ++if "%~1"=="--pgo" (set do_pgo=true) & shift & goto CheckOpts ++if "%~1"=="--pgo-job" (set do_pgo=true) & (set pgo_job=%~2) & shift & shift & goto CheckOpts + rem These use the actual property names used by MSBuild. We could just let + rem them in through the environment, but we specify them on the command line + rem anyway for visibility so set defaults after this +@@ -77,15 +89,49 @@ + + if "%IncludeExternals%"=="true" call "%dir%get_externals.bat" + +-if "%platf%"=="x64" (set vs_platf=x86_amd64) ++if "%platf%"=="x64" ( ++ if "%on_64_bit%"=="true" ( ++ rem This ought to always be correct these days... ++ set vs_platf=amd64 ++ ) else ( ++ if "%do_pgo%"=="true" ( ++ echo.ERROR: Cannot cross-compile with PGO ++ echo. 32bit operating system detected, if this is incorrect, ++ echo. make sure the ProgramFiles(x86^) environment variable is set ++ exit /b 1 ++ ) ++ set vs_platf=x86_amd64 ++ ) ++) + + rem Setup the environment + call "%dir%env.bat" %vs_platf% >nul + +-if "%kill%"=="true" ( +- msbuild /v:m /nologo /target:KillPython "%dir%\pythoncore.vcxproj" /p:Configuration=%conf% /p:Platform=%platf% /p:KillPython=true ++if "%kill%"=="true" call :Kill ++ ++if "%do_pgo%"=="true" ( ++ set conf=PGInstrument ++ call :Build ++ del /s "%dir%\*.pgc" ++ del /s "%dir%\..\Lib\*.pyc" ++ echo on ++ call "%dir%\..\python.bat" %pgo_job% ++ @echo off ++ call :Kill ++ set conf=PGUpdate + ) ++goto Build + ++:Kill ++echo on ++msbuild "%dir%\pythoncore.vcxproj" /t:KillPython %verbose%^ ++ /p:Configuration=%conf% /p:Platform=%platf%^ ++ /p:KillPython=true ++ ++@echo off ++goto :eof ++ ++:Build + rem Call on MSBuild to do the work, echo the command. + rem Passing %1-9 is not the preferred option, but argument parsing in + rem batch is, shall we say, "lackluster" +@@ -96,3 +142,6 @@ + /p:IncludeSSL=%IncludeSSL% /p:IncludeTkinter=%IncludeTkinter%^ + /p:IncludeBsddb=%IncludeBsddb%^ + %1 %2 %3 %4 %5 %6 %7 %8 %9 ++ ++@echo off ++goto :eof +diff -r 6d1b6a68f775 PCbuild/build_pgo.bat +--- a/PCbuild/build_pgo.bat ++++ b/PCbuild/build_pgo.bat +@@ -1,48 +1,6 @@ + @echo off +-rem A batch program to build PGO (Profile guided optimization) by first +-rem building instrumented binaries, then running the testsuite, and +-rem finally building the optimized code. +-rem Note, after the first instrumented run, one can just keep on +-rem building the PGUpdate configuration while developing. ++echo.DeprecationWarning: ++echo. This script is deprecated, use `build.bat --pgo` instead. ++echo. + +-setlocal +-set platf=Win32 +-set parallel=/m +-set dir=%~dp0 +- +-rem use the performance testsuite. This is quick and simple +-set job1="%dir%..\tools\pybench\pybench.py" -n 1 -C 1 --with-gc +-set path1="%dir%..\tools\pybench" +- +-rem or the whole testsuite for more thorough testing +-set job2="%dir%..\lib\test\regrtest.py" +-set path2="%dir%..\lib" +- +-set job=%job1% +-set clrpath=%path1% +- +-:CheckOpts +-if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts +-if "%1"=="-2" (set job=%job2%) & (set clrpath=%path2%) & shift & goto CheckOpts +-if "%1"=="-M" (set parallel=) & shift & goto CheckOpts +- +- +-rem We cannot cross compile PGO builds, as the optimization needs to be run natively +-set vs_platf=x86 +-set PGO=%dir%win32-pgo +- +-if "%platf%"=="x64" (set vs_platf=amd64) & (set PGO=%dir%amd64-pgo) +-rem Setup the environment +-call "%dir%env.bat" %vs_platf% +- +- +-rem build the instrumented version +-msbuild "%dir%pcbuild.proj" %parallel% /t:Build /p:Configuration=PGInstrument /p:Platform=%platf% %1 %2 %3 %4 %5 %6 %7 %8 %9 +- +-rem remove .pyc files, .pgc files and execute the job +-"%PGO%\python.exe" "%dir%rmpyc.py" %clrpath% +-del "%PGO%\*.pgc" +-"%PGO%\python.exe" %job% +- +-rem build optimized version +-msbuild "%dir%pcbuild.proj" %parallel% /t:Build /p:Configuration=PGUpdate /p:Platform=%platf% %1 %2 %3 %4 %5 %6 %7 %8 %9 ++call "%~dp0build.bat" --pgo %* +diff -r 6d1b6a68f775 PCbuild/env.bat +--- a/PCbuild/env.bat ++++ b/PCbuild/env.bat +@@ -10,6 +10,12 @@ + + echo Build environments: x86, amd64, x86_amd64 + echo. ++ ++rem Set up the v90 tools first. This is mostly needed to allow PGInstrument ++rem builds to find the PGO DLL. Do it first so the newer MSBuild is found ++rem before the one from v90 (vcvarsall.bat prepends to PATH). ++call "%VS90COMNTOOLS%..\..\VC\vcvarsall.bat" %* ++ + set VSTOOLS=%VS140COMNTOOLS% + if "%VSTOOLS%"=="" set VSTOOLS=%VS120COMNTOOLS% + if "%VSTOOLS%"=="" set VSTOOLS=%VS110COMNTOOLS% +diff -r 6d1b6a68f775 PCbuild/get_externals.bat +--- a/PCbuild/get_externals.bat ++++ b/PCbuild/get_externals.bat +@@ -58,8 +58,8 @@ + set libraries=%libraries% bzip2-1.0.6 + if NOT "%IncludeBsddb%"=="false" set libraries=%libraries% db-4.7.25.0 + if NOT "%IncludeSSL%"=="false" set libraries=%libraries% nasm-2.11.06 +-if NOT "%IncludeSSL%"=="false" set libraries=%libraries% openssl-1.0.2d +-set libraries=%libraries% sqlite-3.6.21 ++if NOT "%IncludeSSL%"=="false" set libraries=%libraries% openssl-1.0.2g ++set libraries=%libraries% sqlite-3.8.11.0 + if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tcl-8.5.15.0 + if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tk-8.5.15.0 + if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tix-8.4.3.5 +diff -r 6d1b6a68f775 PCbuild/openssl.props +--- a/PCbuild/openssl.props ++++ b/PCbuild/openssl.props +@@ -15,9 +15,8 @@ + + + +- ++ + +- + + + +@@ -51,7 +50,7 @@ + + + 4244;4267 +- $(opensslDir);$(opensslDir)include;$(opensslDir)crypto;$(opensslDir)crypto\asn1;$(opensslDir)crypto\evp;$(opensslDir)crypto\modes ++ $(opensslDir);$(opensslIncludeDir);$(opensslDir)crypto;$(opensslDir)crypto\asn1;$(opensslDir)crypto\evp;$(opensslDir)crypto\modes + $(_PreprocessorDefinitionList);%(PreprocessorDefinitions) + + +diff -r 6d1b6a68f775 PCbuild/pyproject.props +--- a/PCbuild/pyproject.props ++++ b/PCbuild/pyproject.props +@@ -49,6 +49,9 @@ + false + MultiThreadedDebugDLL + ++ ++ Strict ++ + + $(OutDir);%(AdditionalLibraryDirectories) + true +diff -r 6d1b6a68f775 PCbuild/python.props +--- a/PCbuild/python.props ++++ b/PCbuild/python.props +@@ -11,6 +11,8 @@ + Give a default for BasePlatformToolset as well, it's used by ICC and ignored otherwise + --> + v90 ++ false ++ true + + $([System.IO.Path]::GetFullPath(`$(PySourcePath)externals\`)) +- $(ExternalsDir)sqlite-3.6.21\ ++ $(ExternalsDir)sqlite-3.8.11.0\ + $(ExternalsDir)bzip2-1.0.6\ + $(ExternalsDir)db-4.7.25.0 +- $(ExternalsDir)openssl-1.0.2d\ ++ $(ExternalsDir)openssl-1.0.2g\ ++ $(opensslDir)include32 ++ $(opensslDir)include64 + $(ExternalsDir)\nasm-2.11.06\ + + +@@ -102,7 +106,6 @@ + + + $(MajorVersionNumber).$(MinorVersionNumber) +- $(SysWinVer)-32 + + + +diff -r 6d1b6a68f775 PCbuild/readme.txt +--- a/PCbuild/readme.txt ++++ b/PCbuild/readme.txt +@@ -183,7 +183,7 @@ + Homepage: + http://www.bzip.org/ + _ssl +- Python wrapper for version 1.0.2d of the OpenSSL secure sockets ++ Python wrapper for version 1.0.2g of the OpenSSL secure sockets + library, which is built by ssl.vcxproj + Homepage: + http://www.openssl.org/ +@@ -218,7 +218,7 @@ + functionality to _ssl or _hashlib. They will not clean up their output + with the normal Clean target; CleanAll should be used instead. + _sqlite3 +- Wraps SQLite 3.6.21, which is itself built by sqlite3.vcxproj ++ Wraps SQLite 3.8.11.0, which is itself built by sqlite3.vcxproj + Homepage: + http://www.sqlite.org/ + _tkinter +diff -r 6d1b6a68f775 Python/_warnings.c +--- a/Python/_warnings.c ++++ b/Python/_warnings.c +@@ -528,8 +528,7 @@ + goto handle_error; + } + else if (!is_true) { +- Py_DECREF(*filename); +- *filename = PyString_FromString("__main__"); ++ Py_SETREF(*filename, PyString_FromString("__main__")); + if (*filename == NULL) + goto handle_error; + } +diff -r 6d1b6a68f775 Python/ceval.c +--- a/Python/ceval.c ++++ b/Python/ceval.c +@@ -4360,8 +4360,7 @@ + Py_INCREF(self); + func = PyMethod_GET_FUNCTION(func); + Py_INCREF(func); +- Py_DECREF(*pfunc); +- *pfunc = self; ++ Py_SETREF(*pfunc, self); + na++; + n++; + } else +diff -r 6d1b6a68f775 Python/compile.c +--- a/Python/compile.c ++++ b/Python/compile.c +@@ -338,7 +338,7 @@ + return NULL; + } + k = PyList_GET_ITEM(list, i); +- k = PyTuple_Pack(2, k, k->ob_type); ++ k = _PyCode_ConstantKey(k); + if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { + Py_XDECREF(k); + Py_DECREF(v); +@@ -399,7 +399,7 @@ + return NULL; + } + i++; +- tuple = PyTuple_Pack(2, k, k->ob_type); ++ tuple = _PyCode_ConstantKey(k); + if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { + Py_DECREF(sorted_keys); + Py_DECREF(item); +@@ -944,49 +944,8 @@ + { + PyObject *t, *v; + Py_ssize_t arg; +- double d; +- +- /* necessary to make sure types aren't coerced (e.g., int and long) */ +- /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ +- if (PyFloat_Check(o)) { +- d = PyFloat_AS_DOUBLE(o); +- /* all we need is to make the tuple different in either the 0.0 +- * or -0.0 case from all others, just to avoid the "coercion". +- */ +- if (d == 0.0 && copysign(1.0, d) < 0.0) +- t = PyTuple_Pack(3, o, o->ob_type, Py_None); +- else +- t = PyTuple_Pack(2, o, o->ob_type); +- } +-#ifndef WITHOUT_COMPLEX +- else if (PyComplex_Check(o)) { +- Py_complex z; +- int real_negzero, imag_negzero; +- /* For the complex case we must make complex(x, 0.) +- different from complex(x, -0.) and complex(0., y) +- different from complex(-0., y), for any x and y. +- All four complex zeros must be distinguished.*/ +- z = PyComplex_AsCComplex(o); +- real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; +- imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; +- if (real_negzero && imag_negzero) { +- t = PyTuple_Pack(5, o, o->ob_type, +- Py_None, Py_None, Py_None); +- } +- else if (imag_negzero) { +- t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); +- } +- else if (real_negzero) { +- t = PyTuple_Pack(3, o, o->ob_type, Py_None); +- } +- else { +- t = PyTuple_Pack(2, o, o->ob_type); +- } +- } +-#endif /* WITHOUT_COMPLEX */ +- else { +- t = PyTuple_Pack(2, o, o->ob_type); +- } ++ ++ t = _PyCode_ConstantKey(o); + if (t == NULL) + return -1; + +@@ -1287,7 +1246,7 @@ + compiler_lookup_arg(PyObject *dict, PyObject *name) + { + PyObject *k, *v; +- k = PyTuple_Pack(2, name, name->ob_type); ++ k = _PyCode_ConstantKey(name); + if (k == NULL) + return -1; + v = PyDict_GetItem(dict, k); +@@ -1455,9 +1414,8 @@ + if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s, + s->lineno)) + return 0; +- Py_XDECREF(c->u->u_private); +- c->u->u_private = s->v.ClassDef.name; +- Py_INCREF(c->u->u_private); ++ Py_INCREF(s->v.ClassDef.name); ++ Py_SETREF(c->u->u_private, s->v.ClassDef.name); + str = PyString_InternFromString("__name__"); + if (!str || !compiler_nameop(c, str, Load)) { + Py_XDECREF(str); +@@ -3795,7 +3753,7 @@ + i = PyInt_AS_LONG(v); + /* The keys of the dictionary are tuples. (see compiler_add_o) + The object we want is always first, though. */ +- k = PyTuple_GET_ITEM(k, 0); ++ k = PyTuple_GET_ITEM(k, 1); + Py_INCREF(k); + assert((i - offset) < size); + assert((i - offset) >= 0); +diff -r 6d1b6a68f775 Python/errors.c +--- a/Python/errors.c ++++ b/Python/errors.c +@@ -227,14 +227,11 @@ + tstate = PyThreadState_GET(); + if (++tstate->recursion_depth > Py_GetRecursionLimit()) { + --tstate->recursion_depth; +- /* throw away the old exception... */ +- Py_DECREF(*exc); +- Py_DECREF(*val); +- /* ... and use the recursion error instead */ +- *exc = PyExc_RuntimeError; +- *val = PyExc_RecursionErrorInst; +- Py_INCREF(*exc); +- Py_INCREF(*val); ++ /* throw away the old exception and use the recursion error instead */ ++ Py_INCREF(PyExc_RuntimeError); ++ Py_SETREF(*exc, PyExc_RuntimeError); ++ Py_INCREF(PyExc_RecursionErrorInst); ++ Py_SETREF(*val, PyExc_RecursionErrorInst); + /* just keeping the old traceback */ + return; + } +@@ -535,7 +532,7 @@ + #endif /* MS_WINDOWS */ + + void +-_PyErr_BadInternalCall(char *filename, int lineno) ++_PyErr_BadInternalCall(const char *filename, int lineno) + { + PyErr_Format(PyExc_SystemError, + "%s:%d: bad argument to internal function", +@@ -699,12 +696,18 @@ + PyFile_WriteString(className, f); + if (v && v != Py_None) { + PyFile_WriteString(": ", f); +- PyFile_WriteObject(v, f, 0); ++ if (PyFile_WriteObject(v, f, 0) < 0) { ++ PyErr_Clear(); ++ PyFile_WriteString("", f); ++ } + } + Py_XDECREF(moduleName); + } + PyFile_WriteString(" in ", f); +- PyFile_WriteObject(obj, f, 0); ++ if (PyFile_WriteObject(obj, f, 0) < 0) { ++ PyErr_Clear(); ++ PyFile_WriteString("", f); ++ } + PyFile_WriteString(" ignored\n", f); + PyErr_Clear(); /* Just in case */ + } +diff -r 6d1b6a68f775 Python/getargs.c +--- a/Python/getargs.c ++++ b/Python/getargs.c +@@ -346,7 +346,7 @@ + flags, levels, msgbuf, + sizeof(msgbuf), &freelist); + if (msg) { +- seterror(i+1, msg, levels, fname, msg); ++ seterror(i+1, msg, levels, fname, message); + return cleanreturn(0, freelist); + } + } +@@ -533,9 +533,17 @@ + { + assert(expected != NULL); + assert(arg != NULL); +- PyOS_snprintf(msgbuf, bufsize, +- "must be %.50s, not %.50s", expected, +- arg == Py_None ? "None" : arg->ob_type->tp_name); ++ if (expected[0] == '(') { ++ PyOS_snprintf(msgbuf, bufsize, ++ "%.100s", expected); ++ strncpy(msgbuf, expected, bufsize); ++ msgbuf[bufsize-1] = '\0'; ++ } ++ else { ++ PyOS_snprintf(msgbuf, bufsize, ++ "must be %.50s, not %.50s", expected, ++ arg == Py_None ? "None" : arg->ob_type->tp_name); ++ } + return msgbuf; + } + +@@ -753,7 +761,7 @@ + else if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongMask(arg); + else +- return converterr("integer", arg, msgbuf, bufsize); ++ return converterr("an integer", arg, msgbuf, bufsize); + *p = ival; + break; + } +@@ -781,7 +789,7 @@ + else if (PyLong_Check(arg)) + ival = PyLong_AsUnsignedLongLongMask(arg); + else +- return converterr("integer", arg, msgbuf, bufsize); ++ return converterr("an integer", arg, msgbuf, bufsize); + *p = ival; + break; + } +@@ -1127,9 +1135,11 @@ + } else { + if (size + 1 > BUFFER_LEN) { + Py_DECREF(s); +- return converterr( +- "(buffer overflow)", +- arg, msgbuf, bufsize); ++ PyErr_Format(PyExc_TypeError, ++ "encoded string too long " ++ "(%zd, maximum length %zd)", ++ (Py_ssize_t)size, (Py_ssize_t)(BUFFER_LEN-1)); ++ return ""; + } + } + memcpy(*buffer, +@@ -1154,7 +1164,7 @@ + != size) { + Py_DECREF(s); + return converterr( +- "encoded string without NULL bytes", ++ "encoded string without null bytes", + arg, msgbuf, bufsize); + } + *buffer = PyMem_NEW(char, size + 1); +@@ -1261,7 +1271,6 @@ + break; + } + +- + case 'w': { /* memory buffer, read-write access */ + void **p = va_arg(*p_va, void **); + void *res; +@@ -1353,7 +1362,7 @@ + } + + default: +- return converterr("impossible", arg, msgbuf, bufsize); ++ return converterr("(impossible)", arg, msgbuf, bufsize); + + } + +diff -r 6d1b6a68f775 Python/getcopyright.c +--- a/Python/getcopyright.c ++++ b/Python/getcopyright.c +@@ -4,7 +4,7 @@ + + static char cprt[] = + "\ +-Copyright (c) 2001-2015 Python Software Foundation.\n\ ++Copyright (c) 2001-2016 Python Software Foundation.\n\ + All Rights Reserved.\n\ + \n\ + Copyright (c) 2000 BeOpen.com.\n\ +diff -r 6d1b6a68f775 Python/import.c +--- a/Python/import.c ++++ b/Python/import.c +@@ -632,25 +632,43 @@ + Because the former action is most common, THIS DOES NOT RETURN A + 'NEW' REFERENCE! */ + ++static PyObject * ++_PyImport_AddModuleObject(PyObject *name) ++{ ++ PyObject *modules = PyImport_GetModuleDict(); ++ PyObject *m; ++ ++ if ((m = _PyDict_GetItemWithError(modules, name)) != NULL && ++ PyModule_Check(m)) { ++ return m; ++ } ++ if (PyErr_Occurred()) { ++ return NULL; ++ } ++ m = PyModule_New(PyString_AS_STRING(name)); ++ if (m == NULL) { ++ return NULL; ++ } ++ if (PyDict_SetItem(modules, name, m) != 0) { ++ Py_DECREF(m); ++ return NULL; ++ } ++ assert(Py_REFCNT(m) > 1); ++ Py_DECREF(m); /* Yes, it still exists, in modules! */ ++ ++ return m; ++} ++ + PyObject * + PyImport_AddModule(const char *name) + { +- PyObject *modules = PyImport_GetModuleDict(); +- PyObject *m; +- +- if ((m = PyDict_GetItemString(modules, name)) != NULL && +- PyModule_Check(m)) +- return m; +- m = PyModule_New(name); +- if (m == NULL) ++ PyObject *nameobj, *module; ++ nameobj = PyString_FromString(name); ++ if (nameobj == NULL) + return NULL; +- if (PyDict_SetItemString(modules, name, m) != 0) { +- Py_DECREF(m); +- return NULL; +- } +- Py_DECREF(m); /* Yes, it still exists, in modules! */ +- +- return m; ++ module = _PyImport_AddModuleObject(nameobj); ++ Py_DECREF(nameobj); ++ return module; + } + + /* Remove name from sys.modules, if it's there. */ +diff -r 6d1b6a68f775 Python/pythonrun.c +--- a/Python/pythonrun.c ++++ b/Python/pythonrun.c +@@ -1299,8 +1299,11 @@ + /* only print colon if the str() of the + object is not the empty string + */ +- if (s == NULL) ++ if (s == NULL) { ++ PyErr_Clear(); + err = -1; ++ PyFile_WriteString(": ", f); ++ } + else if (!PyString_Check(s) || + PyString_GET_SIZE(s) != 0) + err = PyFile_WriteString(": ", f); +@@ -1309,6 +1312,9 @@ + Py_XDECREF(s); + } + /* try to write a newline in any case */ ++ if (err < 0) { ++ PyErr_Clear(); ++ } + err += PyFile_WriteString("\n", f); + } + Py_DECREF(value); +diff -r 6d1b6a68f775 Python/traceback.c +--- a/Python/traceback.c ++++ b/Python/traceback.c +@@ -170,10 +170,6 @@ + + if (xfp == NULL) + return err; +- if (err != 0) { +- fclose(xfp); +- return err; +- } + + for (i = 0; i < lineno; i++) { + char* pLastChar = &linebuf[sizeof(linebuf)-2]; +diff -r 6d1b6a68f775 README +--- a/README ++++ b/README +@@ -2,7 +2,7 @@ + ============================= + + Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, +-2012, 2013, 2014, 2015 Python Software Foundation. All rights reserved. ++2012, 2013, 2014, 2015, 2016 Python Software Foundation. All rights reserved. + + Copyright (c) 2000 BeOpen.com. + All rights reserved. +diff -r 6d1b6a68f775 Tools/msi/msi.py +--- a/Tools/msi/msi.py ++++ b/Tools/msi/msi.py +@@ -1436,6 +1436,7 @@ + if certname: + os.system('signtool sign /n "%s" ' + '/t http://timestamp.verisign.com/scripts/timestamp.dll ' ++ '/fd SHA256 ' + '/d "Python %s" ' + '%s' % (certname, full_current_version, msiname)) + +diff -r 6d1b6a68f775 configure.ac +--- a/configure.ac ++++ b/configure.ac +@@ -573,6 +573,22 @@ + esac]) + AC_MSG_RESULT($without_gcc) + ++AC_MSG_CHECKING(for --with-icc) ++AC_ARG_WITH(icc, ++ AS_HELP_STRING([--with-icc], [build with icc]), ++[ ++ case $withval in ++ no) CC=${CC:-cc} ++ with_icc=no;; ++ yes) CC=icc ++ CXX=icpc ++ with_icc=yes;; ++ *) CC=$withval ++ with_icc=$withval;; ++ esac], [ ++ with_icc=no]) ++AC_MSG_RESULT($with_icc) ++ + # If the user switches compilers, we can't believe the cache + if test ! -z "$ac_cv_prog_CC" -a ! -z "$CC" -a "$CC" != "$ac_cv_prog_CC" + then +@@ -1266,6 +1282,13 @@ + ;; + esac + ++# ICC needs -fp-model strict or floats behave badly ++case "$CC" in ++*icc*) ++ BASECFLAGS="$BASECFLAGS -fp-model strict" ++ ;; ++esac ++ + if test "$Py_DEBUG" = 'true'; then + : + else +@@ -1394,6 +1417,12 @@ + ;; + esac + ;; ++ *icc*) ++ PGO_PROF_GEN_FLAG="-prof-gen" ++ PGO_PROF_USE_FLAG="-prof-use" ++ LLVM_PROF_MERGER="true" ++ LLVM_PROF_FILE="" ++ ;; + esac + + +@@ -3410,7 +3439,7 @@ + AC_CHECK_MEMBERS([struct stat.st_flags]) + AC_CHECK_MEMBERS([struct stat.st_gen]) + AC_CHECK_MEMBERS([struct stat.st_birthtime]) +-AC_STRUCT_ST_BLOCKS ++AC_CHECK_MEMBERS([struct stat.st_blocks]) + + AC_MSG_CHECKING(for time.h that defines altzone) + AC_CACHE_VAL(ac_cv_header_time_altzone,[ +diff -r 6d1b6a68f775 pyconfig.h.in +--- a/pyconfig.h.in ++++ b/pyconfig.h.in +@@ -731,10 +731,6 @@ + /* Define to 1 if `tm_zone' is a member of `struct tm'. */ + #undef HAVE_STRUCT_TM_TM_ZONE + +-/* Define to 1 if your `struct stat' has `st_blocks'. Deprecated, use +- `HAVE_STRUCT_STAT_ST_BLOCKS' instead. */ +-#undef HAVE_ST_BLOCKS +- + /* Define if you have the 'symlink' function. */ + #undef HAVE_SYMLINK + +diff -r 6d1b6a68f775 setup.py +--- a/setup.py ++++ b/setup.py +@@ -117,6 +117,22 @@ + p = p.rstrip(os.sep) + + if host_platform == 'darwin' and is_macosx_sdk_path(p): ++ # Note that, as of Xcode 7, Apple SDKs may contain textual stub ++ # libraries with .tbd extensions rather than the normal .dylib ++ # shared libraries installed in /. The Apple compiler tool ++ # chain handles this transparently but it can cause problems ++ # for programs that are being built with an SDK and searching ++ # for specific libraries. Distutils find_library_file() now ++ # knows to also search for and return .tbd files. But callers ++ # of find_library_file need to keep in mind that the base filename ++ # of the returned SDK library file might have a different extension ++ # from that of the library file installed on the running system, ++ # for example: ++ # /Applications/Xcode.app/Contents/Developer/Platforms/ ++ # MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/ ++ # usr/lib/libedit.tbd ++ # vs ++ # /usr/lib/libedit.dylib + if os.path.join(sysroot, p[1:]) == dirname: + return [ ] + +@@ -568,13 +584,17 @@ + + # array objects + exts.append( Extension('array', ['arraymodule.c']) ) ++ ++ shared_math = 'Modules/_math.o' + # complex math library functions +- exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'], +- depends=['_math.h'], ++ exts.append( Extension('cmath', ['cmathmodule.c'], ++ extra_objects=[shared_math], ++ depends=['_math.h', shared_math], + libraries=math_libs) ) + # math library functions, e.g. sin() +- exts.append( Extension('math', ['mathmodule.c', '_math.c'], +- depends=['_math.h'], ++ exts.append( Extension('math', ['mathmodule.c'], ++ extra_objects=[shared_math], ++ depends=['_math.h', shared_math], + libraries=math_libs) ) + # fast string operations implemented in C + exts.append( Extension('strop', ['stropmodule.c']) ) --- python2.7-2.7.11.orig/debian/patches/hotshot-import.diff +++ python2.7-2.7.11/debian/patches/hotshot-import.diff @@ -0,0 +1,19 @@ +# DP: hotshot: Check for the availability of the profile and pstats modules. + +Index: b/Lib/hotshot/stats.py +=================================================================== +--- 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.11.orig/debian/patches/hurd-disable-nonworking-constants.diff +++ python2.7-2.7.11/debian/patches/hurd-disable-nonworking-constants.diff @@ -0,0 +1,38 @@ +# DP: Comment out constant exposed on the API which are not implemented on +# DP: GNU/Hurd. They would not work at runtime anyway. + +Index: b/Modules/posixmodule.c +=================================================================== +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9303,12 +9303,14 @@ all_ins(PyObject *d) + #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 +Index: b/Modules/socketmodule.c +=================================================================== +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -4930,9 +4930,11 @@ init_socket(void) + #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.11.orig/debian/patches/installed-testsuite.diff +++ python2.7-2.7.11/debian/patches/installed-testsuite.diff @@ -0,0 +1,37 @@ +# DP: Changes needed to run the installed testsuite. +# DP: Also removed: +# DP: - ctypes/test/test_macholib.py +# DP: - distutils/tests/test_bdist_wininst.py + +Index: b/Lib/distutils/tests/test_build_ext.py +=================================================================== +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -83,27 +83,6 @@ class BuildExtTestCase(support.TempdirMa + self.assertIsInstance(xx.Null(), xx.Null) + self.assertIsInstance(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.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): --- python2.7-2.7.11.orig/debian/patches/issue670664.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/issue9012a.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/issue9189.diff +++ python2.7-2.7.11/debian/patches/issue9189.diff @@ -0,0 +1,342 @@ +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -231,11 +231,19 @@ def _parse_makefile(filename, vars=None) + 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 @@ def _parse_makefile(filename, vars=None) + 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): +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -73,12 +73,18 @@ MAKESETUP= $(srcdir)/Modules/makese + # 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@ +@@ -87,7 +93,7 @@ ARFLAGS= @ARFLAGS@ + # 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 +@@ -505,7 +511,7 @@ coverage-report: + + # 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) + +@@ -541,7 +547,7 @@ sharedmods: $(BUILDPYTHON) pybuilddir.tx + *\ -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 + +@@ -559,18 +565,18 @@ $(LIBRARY): $(LIBRARY_OBJS) + + 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 +@@ -609,7 +615,7 @@ $(PYTHONFRAMEWORKDIR)/Versions/$(VERSION + # 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 +@@ -653,7 +659,7 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ + $(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)`\"" \ +@@ -661,7 +667,7 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ + -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)"' \ +@@ -669,7 +675,7 @@ Modules/getpath.o: $(srcdir)/Modules/get + -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 + +@@ -686,7 +692,7 @@ $(GRAMMAR_C): $(GRAMMAR_H) $(GRAMMAR_INP + 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 \ +@@ -708,10 +714,10 @@ $(AST_C): $(AST_ASDL) $(ASDLGEN_FILES) + 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 +@@ -1345,7 +1351,7 @@ config.status: $(srcdir)/configure + + # 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: +Index: b/Modules/makesetup +=================================================================== +--- a/Modules/makesetup ++++ b/Modules/makesetup +@@ -219,7 +219,7 @@ sed -e 's/[ ]*#.*//' -e '/^[ ]*$/d' | + 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 +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -629,14 +629,13 @@ if test "$MACHDEP" = "irix6" && test "$C + 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) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -320,11 +320,19 @@ def parse_makefile(fn, g=None): + 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: +@@ -335,25 +343,47 @@ def parse_makefile(fn, g=None): + 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.11.orig/debian/patches/langpack-gettext.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/lib2to3-no-pickled-grammar.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/libffi-shared.diff +++ python2.7-2.7.11/debian/patches/libffi-shared.diff @@ -0,0 +1,13 @@ +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -2151,7 +2151,7 @@ class PyBuildExt(build_ext): + 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.11.orig/debian/patches/libre.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/link-opt.diff +++ python2.7-2.7.11/debian/patches/link-opt.diff @@ -0,0 +1,26 @@ +# DP: Call the linker with -O1 -Bsymbolic-functions + +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -2110,8 +2110,8 @@ then + 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";; +@@ -2213,7 +2213,7 @@ then + 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.11.orig/debian/patches/link-system-expat.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/link-whole-archive.diff +++ python2.7-2.7.11/debian/patches/link-whole-archive.diff @@ -0,0 +1,15 @@ +# DP: Link libpython with --whole-archive. + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -515,7 +515,7 @@ coverage-report: + $(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.11.orig/debian/patches/locale-module.diff +++ python2.7-2.7.11/debian/patches/locale-module.diff @@ -0,0 +1,19 @@ +# DP: * Lib/locale.py: +# DP: - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding +# DP: for glibc. + +Index: b/Lib/locale.py +=================================================================== +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -1703,8 +1703,8 @@ locale_alias = { + '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', + 'unm_us': 'unm_US.UTF-8', + 'ur': 'ur_PK.CP1256', --- python2.7-2.7.11.orig/debian/patches/lto-link-flags.diff +++ python2.7-2.7.11/debian/patches/lto-link-flags.diff @@ -0,0 +1,24 @@ +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -128,8 +128,8 @@ LIBP= $(LIBDIR)/python$(VERSION) + + # 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 + +@@ -513,7 +513,7 @@ coverage-report: + + # 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.11.orig/debian/patches/makesetup-bashism.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/mangle-fstack-protector.diff +++ python2.7-2.7.11/debian/patches/mangle-fstack-protector.diff @@ -0,0 +1,24 @@ +# DP: When using GCC versions older than 4.9, automagically mangle +# DP: -fstack-protector-strong to -fstack-protector + +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -15,6 +15,7 @@ import os + import re + import string + import sys ++import fnmatch + + from distutils.errors import DistutilsPlatformError + +@@ -197,6 +198,10 @@ def customize_compiler(compiler): + cc = newcc + if 'CXX' in os.environ: + cxx = os.environ['CXX'] ++ if fnmatch.filter([cc, cxx], '*-4.[0-8]'): ++ configure_cflags = configure_cflags.replace('-fstack-protector-strong', '-fstack-protector') ++ ldshared = ldshared.replace('-fstack-protector-strong', '-fstack-protector') ++ cflags = cflags.replace('-fstack-protector-strong', '-fstack-protector') + if 'LDSHARED' in os.environ: + ldshared = os.environ['LDSHARED'] + if 'CPP' in os.environ: --- python2.7-2.7.11.orig/debian/patches/multiarch.diff +++ python2.7-2.7.11/debian/patches/multiarch.diff @@ -0,0 +1,166 @@ +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -333,7 +333,7 @@ def get_makefile_filename(): + """Return the path of the Makefile.""" + 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") + + # Issue #22199: retain undocumented private name for compatibility + _get_makefile_filename = get_makefile_filename +@@ -532,6 +532,12 @@ def get_config_vars(*args): + # 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 + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -102,6 +102,9 @@ MACHDEP= @MACHDEP@ + # Multiarch directory (may be empty) + MULTIARCH= @MULTIARCH@ + ++# Multiarch directory (may be empty) ++MULTIARCH= @MULTIARCH@ ++ + # Install prefix for architecture-independent files + prefix= @prefix@ + +@@ -640,6 +643,10 @@ Makefile Modules/config.c: Makefile.pre + @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 \ +@@ -1193,10 +1200,10 @@ inclinstall: + + # 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); \ +@@ -1475,6 +1482,11 @@ patchcheck: + + 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 +Index: b/Python/dynload_shlib.c +=================================================================== +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -49,6 +49,12 @@ const struct filedescr _PyImport_DynLoad + #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}, +Index: b/configure.ac +=================================================================== +--- a/configure.ac ++++ b/configure.ac +@@ -493,8 +493,16 @@ then + fi + AC_MSG_RESULT($MACHDEP) + ++MULTIARCH=$($CC --print-multiarch 2>/dev/null) ++AC_SUBST(MULTIARCH) ++ ++ + AC_SUBST(PLATDIR) +-PLATDIR=plat-$MACHDEP ++if test -n "$MULTIARCH"; then ++ PLATDIR=plat-$MULTIARCH ++else ++ PLATDIR=plat-$MACHDEP ++fi + + # And add extra plat-mac for darwin + AC_SUBST(EXTRAPLATDIR) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -74,8 +74,6 @@ def get_python_inc(plat_specific=0, pref + If 'prefix' is supplied, use it instead of sys.prefix or + sys.exec_prefix -- i.e., ignore 'plat_specific'. + """ +- if prefix is None: +- prefix = plat_specific and EXEC_PREFIX or PREFIX + + if os.name == "posix": + if python_build: +@@ -90,7 +88,14 @@ def get_python_inc(plat_specific=0, pref + # 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 not (prefix is None): ++ return os.path.join(prefix, "include", ++ "python" + get_python_version())+(sys.pydebug and "_d" or "") ++ 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": +@@ -263,7 +268,7 @@ def get_makefile_filename(): + 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): +Index: b/Python/sysmodule.c +=================================================================== +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1453,6 +1453,8 @@ _PySys_Init(void) + 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.11.orig/debian/patches/no-large-file-support.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/no-zip-on-sys.path.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/plat-gnukfreebsd.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/plat-linux2_alpha.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/plat-linux2_hppa.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/plat-linux2_mips.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/plat-linux2_sparc.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/platform-lsbrelease.diff +++ python2.7-2.7.11/debian/patches/platform-lsbrelease.diff @@ -0,0 +1,52 @@ +# DP: Use /etc/lsb-release to identify the platform. + +Index: b/Lib/platform.py +=================================================================== +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -261,7 +261,7 @@ _release_version = re.compile(r'([^0-9]+ + _supported_dists = ( + 'SuSE', 'debian', 'fedora', 'redhat', 'centos', + 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo', +- 'UnitedLinux', 'turbolinux') ++ 'UnitedLinux', 'turbolinux', 'Ubuntu') + + def _parse_release_file(firstline): + +@@ -290,6 +290,10 @@ def _parse_release_file(firstline): + 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, +@@ -314,6 +318,25 @@ def linux_distribution(distname='', vers + 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.11.orig/debian/patches/profiled-build.diff +++ python2.7-2.7.11/debian/patches/profiled-build.diff @@ -0,0 +1,15 @@ +# DP: Fix profiled build; don't use Python/thread.gc*, gcc complains + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -462,7 +462,7 @@ build_all_generate_profile: + + run_profile_task: + : # FIXME: can't run for a cross build +- $(LLVM_PROF_FILE) ./$(BUILDPYTHON) $(PROFILE_TASK) || true ++ -$(LLVM_PROF_FILE) ./$(BUILDPYTHON) $(PROFILE_TASK) || true + + build_all_merge_profile: + $(LLVM_PROF_MERGER) --- python2.7-2.7.11.orig/debian/patches/pydoc-use-pager.diff +++ python2.7-2.7.11/debian/patches/pydoc-use-pager.diff @@ -0,0 +1,15 @@ +# DP: pydoc: use the pager command if available. + +Index: b/Lib/pydoc.py +=================================================================== +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -1394,6 +1394,8 @@ def getpager(): + return plainpager + if sys.platform == 'win32' or sys.platform.startswith('os2'): + return lambda text: tempfilepager(plain(text), 'more <') ++ if hasattr(os, 'system') and os.system('(pager) 2>/dev/null') == 0: ++ return lambda text: pipepager(text, 'pager') + if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: + return lambda text: pipepager(text, 'less') + --- python2.7-2.7.11.orig/debian/patches/reproducible-buildinfo.diff +++ python2.7-2.7.11/debian/patches/reproducible-buildinfo.diff @@ -0,0 +1,15 @@ +# DP: Build getbuildinfo.o with DATE/TIME values when defined + +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -673,6 +673,8 @@ Modules/getbuildinfo.o: $(PARSER_OBJS) \ + -DHGVERSION="\"`LC_ALL=C $(HGVERSION)`\"" \ + -DHGTAG="\"`LC_ALL=C $(HGTAG)`\"" \ + -DHGBRANCH="\"`LC_ALL=C $(HGBRANCH)`\"" \ ++ $(if $(BUILD_DATE),-DDATE='"$(BUILD_DATE)"') \ ++ $(if $(BUILD_TIME),-DTIME='"$(BUILD_TIME)"') \ + -o $@ $(srcdir)/Modules/getbuildinfo.c + + Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile --- python2.7-2.7.11.orig/debian/patches/revert-unittest-loader-symlinks19352.diff +++ python2.7-2.7.11/debian/patches/revert-unittest-loader-symlinks19352.diff @@ -0,0 +1,68 @@ +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 + +Index: b/Lib/unittest/loader.py +=================================================================== +--- a/Lib/unittest/loader.py ++++ b/Lib/unittest/loader.py +@@ -256,8 +256,8 @@ class TestLoader(object): + 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] +Index: b/Lib/unittest/test/test_discovery.py +=================================================================== +--- a/Lib/unittest/test/test_discovery.py ++++ b/Lib/unittest/test/test_discovery.py +@@ -315,7 +315,7 @@ class TestDiscovery(unittest.TestCase): + 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 +@@ -342,10 +342,7 @@ class TestDiscovery(unittest.TestCase): + 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') +@@ -358,25 +355,6 @@ class TestDiscovery(unittest.TestCase): + ) + 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.11.orig/debian/patches/series.in +++ python2.7-2.7.11/debian/patches/series.in @@ -0,0 +1,69 @@ +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 +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) || defined (arch_mips64) || defined(arch_mips64el) +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 +ctypes-arm.diff +lto-link-flags.diff +multiarch.diff +lib2to3-no-pickled-grammar.diff +add-python-config-sh.diff +ext-no-libpython-link.diff +build-hash.diff +libffi-shared.diff +atomic-pyc-rename.diff +revert-unittest-loader-symlinks19352.diff +enable-sqlite-loadext.diff +installed-testsuite.diff +ensurepip-wheels.diff +ensurepip-disabled.diff +mangle-fstack-protector.diff +reproducible-buildinfo.diff +pydoc-use-pager.diff +fix-sslv3-test.diff --- python2.7-2.7.11.orig/debian/patches/setup-modules-ssl.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/site-locations.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/sphinx-no-refcounting.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/statvfs-f_flag-constants.diff +++ python2.7-2.7.11/debian/patches/statvfs-f_flag-constants.diff @@ -0,0 +1,59 @@ +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(-) + +Index: b/Modules/posixmodule.c +=================================================================== +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9411,6 +9411,43 @@ all_ins(PyObject *d) + 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.11.orig/debian/patches/sys-multiarch.diff +++ python2.7-2.7.11/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.11.orig/debian/patches/test-sundry.diff +++ python2.7-2.7.11/debian/patches/test-sundry.diff @@ -0,0 +1,19 @@ +# DP: test_sundry: Don't fail on import of the profile and pstats module + +Index: b/Lib/test/test_sundry.py +=================================================================== +--- a/Lib/test/test_sundry.py ++++ b/Lib/test/test_sundry.py +@@ -60,7 +60,11 @@ class TestUntestedModules(unittest.TestC + 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.11.orig/debian/patches/tkinter-import.diff +++ python2.7-2.7.11/debian/patches/tkinter-import.diff @@ -0,0 +1,35 @@ +# 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 * +--- a/Demo/turtle/turtleDemo.py ++++ b/Demo/turtle/turtleDemo.py +@@ -3,10 +3,12 @@ + import os + + from Tkinter import * +-from idlelib.Percolator import Percolator +-from idlelib.ColorDelegator import ColorDelegator +-from idlelib.textView import view_file +- ++try: ++ from idlelib.Percolator import Percolator ++ from idlelib.ColorDelegator import ColorDelegator ++ from idlelib.textView import view_file ++except ImportError, msg: ++ raise ImportError, str(msg) + ', please install the idle package' + import turtle + import time + --- python2.7-2.7.11.orig/debian/pdb.1.in +++ python2.7-2.7.11/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.11.orig/debian/pydoc.1.in +++ python2.7-2.7.11/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.11.orig/debian/pygettext.1 +++ python2.7-2.7.11/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.11.orig/debian/pyhtml2devhelp.py +++ python2.7-2.7.11/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.11.orig/debian/pylogo.xpm +++ python2.7-2.7.11/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.11.orig/debian/pymindeps.py +++ python2.7-2.7.11/debian/pymindeps.py @@ -0,0 +1,174 @@ +#! /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 = { + '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(('ctypes', '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.11.orig/debian/python-config.1 +++ python2.7-2.7.11/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.11.orig/debian/rules +++ python2.7-2.7.11/debian/rules @@ -0,0 +1,1427 @@ +#!/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)) + +LAST_CHANGE := $(shell dpkg-parsechangelog -S Date) +export BUILD_DATE := $(shell LC_ALL=C date -u +'%b %e %Y' -d '$(LAST_CHANGE)') +export BUILD_TIME := $(shell LC_ALL=C date -u +'%H:%M:%S' -d '$(LAST_CHANGE)') + +SPHINXOPTS := -D today='$(shell LC_ALL=C date -u +'%B %d, %Y' -d '$(LAST_CHANGE)')' +SPHINXOPTS += -D html_last_updated_fmt='$(shell LC_ALL=C date -u +'%B %d, %Y' -d '$(LAST_CHANGE)')' +export SPHINXOPTS + +on_buildd := $(shell [ -f /CurrentlyBuilding -o "$$LOGNAME" = buildd -o "$$USER" = buildd ] && echo yes) + +dh_compat2 := $(shell dpkg --compare-versions "$$(dpkg-query -f '$${Version}' -W debhelper)" lt 9.20150811ubuntu2 && echo DH_COMPAT=2) + +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) +derivative := $(shell if dpkg-vendor --derives-from Ubuntu; then echo Ubuntu; \ + elif dpkg-vendor --derives-from Debian; then echo Debian; \ + else echo Unknown; fi) + +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 +ifneq (,$(filter $(distrelease),jessie sid experimental)) + bd_gcc = gcc-5 (>= 5.3.1), +endif +ifeq (,$(filter $(distrelease),lenny etch squeeze wheezy lucid maverick natty oneiric precise quantal raring saucy trusty)) + bd_dpkgdev = dpkg-dev (>= 1.17.11), +endif + +CC = $(DEB_HOST_GNU_TYPE)-gcc +CXX=$(DEB_HOST_GNU_TYPE)-g++ + +AR=$(DEB_HOST_GNU_TYPE)-ar +RANLIB=$(DEB_HOST_GNU_TYPE)-ranlib + +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 (,$(filter $(DEB_HOST_ARCH), amd64 arm64 armel armhf i386 powerpc ppc64 ppc64el s390x x32)) + with_pgo := yes + endif +endif +ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE)) + with_pgo := +endif + +ifneq (,$(filter $(DEB_HOST_ARCH), amd64 arm64 armel armhf i386 powerpc ppc64 ppc64el s390x x32)) + 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 + with_fat_lto := $(shell dpkg --compare-versions $$($(CC) --version \ + | sed -n '/^$(CC)/s/.* //p') ge 4.9 && echo yes) + ifeq ($(with_fat_lto),yes) + LTO_CFLAGS += -ffat-lto-objects + endif + EXTRA_OPT_CFLAGS += $(LTO_CFLAGS) + AR=$(DEB_HOST_GNU_TYPE)-gcc-ar + RANLIB=$(DEB_HOST_GNU_TYPE)-gcc-ranlib +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), sparc 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 \ + --with-computed-gotos + +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)" AR="$(AR)" RANLIB="$(RANLIB)" \ + 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)" AR="$(AR)" RANLIB="$(RANLIB)" \ + 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)" AR="$(AR)" RANLIB="$(RANLIB)" \ + 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)" AR="$(AR)" RANLIB="$(RANLIB)" \ + 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 \ + cd $(buildd_static); \ + ./python ../debian/depgraph.py < mindeps.txt > 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) +#TESTOPTS = -v -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 +TEST_EXCLUDES += test_ensurepip +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 sparc)) + TEST_EXCLUDES += test_io +endif +ifneq (,$(filter $(DEB_HOST_ARCH), alpha)) + TEST_EXCLUDES += test_signal +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 +# see http://bugs.python.org/issue25698 +TEST_EXCLUDES += test_cpickle +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" + -tmphome=$$(mktemp -d); export HOME=$$tmphome; \ + cd $(buildd_debug) && time xvfb-run -a -e xvfb-run.log ./run_tests; \ + rm -rf $$tmphome + @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" + -tmphome=$$(mktemp -d); export HOME=$$tmphome; \ + cd $(buildd_static) && time xvfb-run -a -e xvfb-run.log ./run_tests; \ + rm -rf $$tmphome + @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" + -tmphome=$$(mktemp -d); export HOME=$$tmphome; \ + cd $(buildd_shared) && time xvfb-run -a -e xvfb-run.log ./run_tests; \ + rm -rf $$tmphome + @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 + @mkdir -p stamps + 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" \ + -e "s/@bd_gcc@/$(bd_gcc)/g" \ + -e "s/@bd_dpkgdev@/$(bd_dpkgdev)/g" \ + debian/control.in \ + | $(ma_filter) \ + > debian/control.tmp +ifeq ($(derivative),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_autotools-dev_restoreconfig + 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" \ + -e "s,@HOST_QUAL@,:$(DEB_HOST_ARCH),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_prep + 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 DESTDIR=$(CURDIR)/$(d) +else + $(MAKE) -C $(buildd_shared) install DESTDIR=$(CURDIR)/$(d) +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 + + if [ -d $(d)/$(scriptdir)/ensurepip/_bundled ]; then \ + echo "ensurepip/_bundled must not be included in the source package"; \ + exit 1; \ + fi + + : # 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_compat2) 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_compat2) 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_compat2) 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 \ + -e '/^Cflags:/s,$$, -I$${includedir}/$(DEB_HOST_MULTIARCH)/python$(VER),' \ + -e '/^libdir=/d;s/-L\$${libdir} *//' \ + $(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_compat2) 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_compat2) 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_compat2) dh_movefiles -p$(p_gdbm) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/gdbm.so +endif + + : # The test framework into $(p_lbase) + $(dh_compat2) 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_compat2) 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 + + : # 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_compat2) 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/ + + : # 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 \ + 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 + rm -f $(d_exam)/usr/share/doc/python$(VER)/examples/Demo/scripts/newslist.* + + : # 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,' \ + -e '/^libdir=/d;s/-L\$${libdir} *//' \ + $(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 + $(buildd_static)/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 -9nv $(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_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_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 + + find $(d_ldbg) $(d_ldev) -name '*.a' ! -type l \ + | xargs -n 1 $(DEB_HOST_GNU_TYPE)-objcopy -p --remove-section=.gnu.lto_.* + dh_strip -a -N$(p_dbg) -N$(p_ldbg) -Xdebug -Xdbg --dbg-package=$(p_dbg) + mkdir -p $(d_dbg)/usr/share/gdb/auto-load/usr/bin + cp Tools/gdb/libpython.py $(d_dbg)/usr/share/gdb/auto-load/usr/bin/$(PVER)m-gdb.py + ln -sf $(PVER)-gdb.py $(d_dbg)/usr/share/gdb/auto-load/usr/bin/$(PVER)-dbg-gdb.py + mkdir -p $(d_dbg)/usr/share/gdb/auto-load/usr/lib/$(DEB_HOST_MULTIARCH) + ln -sf ../../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/share/gdb/auto-load/usr/lib/$(DEB_HOST_MULTIARCH)/lib$(PVER).so.1.0-gdb.py + ln -sf ../../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/share/gdb/auto-load/usr/lib/$(DEB_HOST_MULTIARCH)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/[^=]*=\(.*\)/\1/p' $(d_min).substvars | awk -v RS=', ' -v ORS=', ' '/^libc6/ { print }'`; \ + echo "shlibs:Pre-Depends=$$dep" >> $(d_min).substvars + sed -i '/^shlibs:Depends/s/libc6[^,]*[, ]*//g' $(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$(derivative) \ + $(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 $@ + + dh_autotools-dev_updateconfig + + : # 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 0.1 + touch Grammar/Grammar + @sleep 0.1 + touch Include/graminit.h + @sleep 0.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 + +.NOTPARALLEL: +.PHONY: control-file configure build clean binary-indep binary-arch binary install + +# Local Variables: +# mode: makefile +# end: --- python2.7-2.7.11.orig/debian/script.py +++ python2.7-2.7.11/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.11.orig/debian/sitecustomize.py.in +++ python2.7-2.7.11/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.11.orig/debian/source.lintian-overrides +++ python2.7-2.7.11/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.11.orig/debian/source.lintian-overrides.in +++ python2.7-2.7.11/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.11.orig/debian/source/format +++ python2.7-2.7.11/debian/source/format @@ -0,0 +1 @@ +1.0 --- python2.7-2.7.11.orig/debian/tests/control +++ python2.7-2.7.11/debian/tests/control @@ -0,0 +1,19 @@ +Tests: testsuite +Depends: build-essential, locales, python2.7-dev, libpython2.7-testsuite, python-gdbm +# test_zipfile wants to write +Restrictions: needs-root + +Tests: testsuite-dbg +Depends: build-essential, locales, 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, locales, 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, locales, 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.11.orig/debian/tests/failing-tests +++ python2.7-2.7.11/debian/tests/failing-tests @@ -0,0 +1,116 @@ +#!/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 + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# 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) +vendor=$(dpkg-vendor --query Vendor) + +TESTPYTHON="python2.7 -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS= + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_gdb: not run for the optimized build +TESTEXCLUSIONS="$TESTEXCLUSIONS test_gdb" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +if [ "$su_user" = nobody ]; then + log=/dev/null +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="HOME=$tmphome python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $tst\"" + else + cmd="HOME=$tmphome $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.11.orig/debian/tests/failing-tests-dbg +++ python2.7-2.7.11/debian/tests/failing-tests-dbg @@ -0,0 +1,108 @@ +#!/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 + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# 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) +vendor=$(dpkg-vendor --query Vendor) + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chown $su_user $tmphome +fi + +TESTPYTHON="python2.7-dbg -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS= + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +if [ "$su_user" = nobody ]; then + log=/dev/null +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="HOME=$tmphome python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $tst\"" + else + cmd="HOME=$tmphome $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.11.orig/debian/tests/testsuite +++ python2.7-2.7.11/debian/tests/testsuite @@ -0,0 +1,113 @@ +#!/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 + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# 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) +vendor=$(dpkg-vendor --query Vendor) + +TESTPYTHON="python2.7 -E -Wd -3 -tt /usr/lib/python2.7/test/regrtest.py" +TESTOPTS="-w -uall,-network,-urlfetch,-gui,-xpickle" +TESTEXCLUSIONS="-x" + +# test_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_ensurepip: module disabled in Debian +TESTEXCLUSIONS="$TESTEXCLUSIONS test_ensurepip" + +# test_gdb: not run for the optimized build +TESTEXCLUSIONS="$TESTEXCLUSIONS test_gdb" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +if [ "$su_user" = nobody ]; then + log=/dev/null +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 + +# several tests fail with configured proxy; we don't need internet access, so +# unset proxy variables +EXTRAENV="env -u https_proxy -u http_proxy -u no_proxy HOME=$tmphome" + +script=$debian_dir/script.py +if [ -f "$script" ]; then + cmd1="$EXTRAENV python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS $SEPARATE_TESTS\"" + cmd2="$EXTRAENV python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $SEPARATE_TESTS\"" +else + cmd1="$EXTRAENV $TESTPYTHON $TESTOPTS $TESTEXCLUSIONS $SEPARATE_TESTS" + cmd2="$EXTRAENV $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.11.orig/debian/tests/testsuite-dbg +++ python2.7-2.7.11/debian/tests/testsuite-dbg @@ -0,0 +1,88 @@ +#!/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 + service apport stop 2>/dev/null || true + sed -i '/^enabled=/s/=.*/=0/' /etc/default/apport 2>/dev/null + fi +fi + +tmphome=$ADTTMP/home +mkdir -p $tmphome +if [ -n "$su_user" ]; then + chmod go+rx $ADTTMP + chown $su_user:nogroup $tmphome +fi +ls -la $ADTTMP + +# 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) +vendor=$(dpkg-vendor --query Vendor) + +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_cpickle: starts to fail with 2.7.11, see http://bugs.python.org/issue25698 +TESTEXCLUSIONS="$TESTEXCLUSIONS test_cpickle" + +# test_curses: error: copywin() returned ERR +TESTEXCLUSIONS="$TESTEXCLUSIONS test_curses" + +# test_distutils: failing tests test_parse_makefile_base, test_parse_makefile_literal_dollar +TESTEXCLUSIONS="$TESTEXCLUSIONS test_distutils" + +# test_ensurepip: module disabled in Debian +TESTEXCLUSIONS="$TESTEXCLUSIONS test_ensurepip" + +# test_threading_local: fails in the Debian CI environment, but even +# succeeds there when re-run. See +# http://ci.debian.net/data/packages/unstable/amd64/p/python2.7/20141121_061940.autopkgtest.log.gz +case "$vendor" in Debian) + TESTEXCLUSIONS="$TESTEXCLUSIONS test_threading_local" +esac + +# test_zipfile: Issue 17753, requires write access to test and email.test +TESTEXCLUSIONS="$TESTEXCLUSIONS test_zipfile" + +if [ "$su_user" = nobody ]; then + log=/dev/null +else + log=testsuite-dbg.log +fi + +# several tests fail with configured proxy; we don't need internet access, so +# unset proxy variables +EXTRAENV="env -u https_proxy -u http_proxy -u no_proxy HOME=$tmphome" + +script=$debian_dir/script.py +if [ -f "$script" ]; then + cmd="$EXTRAENV python2.7 $script \"$log\" \"$TESTPYTHON $TESTOPTS $TESTEXCLUSIONS\"" +else + cmd="$EXTRAENV $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.11.orig/debian/watch +++ python2.7-2.7.11/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