--- python3.2-3.2.2.orig/debian/mkbinfmt.py +++ python3.2-3.2.2/debian/mkbinfmt.py @@ -0,0 +1,18 @@ +# mkbinfmt.py +import imp, sys, os.path + +magic = "".join(["\\x%.2x" % c for c in imp.get_magic()]) + +name = sys.argv[1] + +binfmt = '''\ +package %s +interpreter /usr/bin/%s +magic %s\ +''' % (name, name, magic) + +#filename = '/usr/share/binfmts/' + name +#open(filename,'w+').write(binfmt) + +sys.stdout.write(binfmt) +sys.stdout.write('\n') --- python3.2-3.2.2.orig/debian/PVER-minimal.preinst.in +++ python3.2-3.2.2/debian/PVER-minimal.preinst.in @@ -0,0 +1,26 @@ +#!/bin/sh + +set -e + +case "$1" in + install) + # 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 --- python3.2-3.2.2.orig/debian/README.idle-PVER.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/pyhtml2devhelp.py +++ python3.2-3.2.2/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', 'documenting/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() --- python3.2-3.2.2.orig/debian/pymindeps.py +++ python3.2-3.2.2/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 = { + 'argparse': set(('gettext',)), + 'codecs': set(('encodings',)), + 'collections': set(('cPickle', 'pickle', 'doctest')), + 'copy': set(('reprlib',)), + 'functools': set(('_dummy_thread',)), + 'hashlib': set(('logging',)), + #'hashlib': set(('_hashlib', '_md5', '_sha', '_sha256','_sha512',)), + 'heapq': set(('doctest',)), + 'io': set(('_dummy_thread',)), + 'logging': set(('multiprocessing',)), + 'os': set(('nt', 'ntpath', 'os2', 'os2emxpath', 'mac', 'macpath', + 'riscos', 'riscospath', 'riscosenviron')), + 'optparse': set(('gettext',)), + 'pickle': set(('argparse', 'doctest', 'pprint')), + 'platform': set(('plistlib', 'tempfile')), + #'socket': set(('_ssl',)), + 'subprocess': set(('threading',)), + } + +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:]) --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/pydoc.1.in +++ python3.2-3.2.2/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" --- python3.2-3.2.2.orig/debian/dh_doclink +++ python3.2-3.2.2/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 < + +Last change: 2001-12-14 --- python3.2-3.2.2.orig/debian/PVER.desktop.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/sitecustomize.py.in +++ python3.2-3.2.2/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() --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/pylogo.xpm +++ python3.2-3.2.2/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@ "}; --- python3.2-3.2.2.orig/debian/PVER.overrides.in +++ python3.2-3.2.2/debian/PVER.overrides.in @@ -0,0 +1,11 @@ +# 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 --- python3.2-3.2.2.orig/debian/idle-PVER.prerm.in +++ python3.2-3.2.2/debian/idle-PVER.prerm.in @@ -0,0 +1,31 @@ +#! /bin/sh -e + +remove_bytecode() +{ + pkg=$1 + max=$(LANG=C LC_ALL=C xargs --show-limits < /dev/null 2>&1 | awk '/Maximum/ {print int($NF / 4)}') + dpkg -L $pkg \ + | awk -F/ 'BEGIN {OFS="/"} /\.py$/ {$NF=sprintf("__pycache__/%s.*.py[co]", substr($NF,1,length($NF)-3)); print}' \ + | xargs --max-chars=$max echo \ + | while read files; do rm -f $files; done + find /usr/lib/@PVER@ -name dist-packages -prune -o -name __pycache__ -empty -print \ + | xargs -r rm -rf +} + +case "$1" in + remove|upgrade) + remove_bytecode idle-@PVER@ + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python3.2-3.2.2.orig/debian/PVER.menu.in +++ python3.2-3.2.2/debian/PVER.menu.in @@ -0,0 +1,4 @@ +?package(@PVER@):needs="text" section="Applications/Programming"\ + title="Python (v@VER@)"\ + icon="/usr/share/pixmaps/@PVER@.xpm"\ + command="/usr/bin/python@VER@" --- python3.2-3.2.2.orig/debian/PVER-dbg.symbols.in +++ python3.2-3.2.2/debian/PVER-dbg.symbols.in @@ -0,0 +1,32 @@ +libpython@VER@dmu.so.1.0 python@VER@-dbg #MINVER# +#include "libpython.symbols" + _PyDict_Dummy@Base @SVER@ + _PyMem_DebugFree@Base @SVER@ + _PyMem_DebugMalloc@Base @SVER@ + _PyMem_DebugRealloc@Base @SVER@ + _PyObject_DebugCheckAddress@Base @SVER@ + _PyObject_DebugCheckAddressApi@Base @SVER@ + _PyObject_DebugDumpAddress@Base @SVER@ + _PyObject_DebugFree@Base @SVER@ + _PyObject_DebugFreeApi@Base @SVER@ + _PyObject_DebugMalloc@Base @SVER@ + _PyObject_DebugMallocApi@Base @SVER@ + _PyObject_DebugMallocStats@Base @SVER@ + _PyObject_DebugRealloc@Base @SVER@ + _PyObject_DebugReallocApi@Base @SVER@ + _PySet_Dummy@Base @SVER@ + _Py_AddToAllObjects@Base @SVER@ + _Py_Dealloc@Base @SVER@ + _Py_ForgetReference@Base @SVER@ + _Py_GetObjects@Base @SVER@ + _Py_GetRefTotal@Base @SVER@ + _Py_NegativeRefcount@Base @SVER@ + _Py_NewReference@Base @SVER@ + _Py_PrintReferenceAddresses@Base @SVER@ + _Py_PrintReferences@Base @SVER@ + _Py_RefTotal@Base @SVER@ + _Py_dumptree@Base @SVER@ + _Py_printtree@Base @SVER@ + _Py_showtree@Base @SVER@ + _Py_tok_dump@Base @SVER@ + PyModule_Create2TraceRefs@Base @SVER@ --- python3.2-3.2.2.orig/debian/compat +++ python3.2-3.2.2/debian/compat @@ -0,0 +1 @@ +5 --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-new.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/PVER-minimal.postinst.in +++ python3.2-3.2.2/debian/PVER-minimal.postinst.in @@ -0,0 +1,87 @@ +#! /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 + if [ -d /usr/lib/@PVER@/config ] && [ ! -h /usr/lib/@PVER@/config ]; then + if rmdir /usr/lib/@PVER@/config 2> /dev/null; then + ln -sf config-@VER@mu /usr/lib/@PVER@/config + else + echo >&2 "WARNING: non-empty directory on upgrade: /usr/lib/@PVER@/config" + ls -l /usr/lib/@PVER@/config + fi + fi +fi + +syssite=/usr/lib/@PVER@/site-packages +localsite=/usr/local/lib/@PVER@/dist-packages +syslink=../../${localsite#/usr/*} + +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 + 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 [ ! -h $syssite ]; then + # ln -s $syslink $syssite + #fi + + if which update-binfmts >/dev/null; then + update-binfmts --import @PVER@ + fi + + ;; +esac + +if [ "$1" = configure ]; then + ( + files=$(dpkg -L @PVER@-minimal | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + @PVER@ /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + @PVER@ -O /usr/lib/@PVER@/py_compile.py $files + fi + ) + bc=no + #if [ -z "$2" ] || dpkg --compare-versions "$2" lt 2.5-3 \ + # || [ -f /var/lib/python/@PVER@_installed ]; then + # bc=yes + #fi + if ! grep -sq '^supported-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/python3/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 --- python3.2-3.2.2.orig/debian/PVER-dbg.symbols.i386.in +++ python3.2-3.2.2/debian/PVER-dbg.symbols.i386.in @@ -0,0 +1,35 @@ +libpython@VER@dmu.so.1.0 python@VER@-dbg #MINVER# +#include "libpython.symbols" + _Py_force_double@Base @SVER@ + _Py_get_387controlword@Base @SVER@ + _Py_set_387controlword@Base @SVER@ + _PyDict_Dummy@Base @SVER@ + _PyMem_DebugFree@Base @SVER@ + _PyMem_DebugMalloc@Base @SVER@ + _PyMem_DebugRealloc@Base @SVER@ + _PyObject_DebugCheckAddress@Base @SVER@ + _PyObject_DebugCheckAddressApi@Base @SVER@ + _PyObject_DebugDumpAddress@Base @SVER@ + _PyObject_DebugFree@Base @SVER@ + _PyObject_DebugFreeApi@Base @SVER@ + _PyObject_DebugMalloc@Base @SVER@ + _PyObject_DebugMallocApi@Base @SVER@ + _PyObject_DebugMallocStats@Base @SVER@ + _PyObject_DebugRealloc@Base @SVER@ + _PyObject_DebugReallocApi@Base @SVER@ + _PySet_Dummy@Base @SVER@ + _Py_AddToAllObjects@Base @SVER@ + _Py_Dealloc@Base @SVER@ + _Py_ForgetReference@Base @SVER@ + _Py_GetObjects@Base @SVER@ + _Py_GetRefTotal@Base @SVER@ + _Py_NegativeRefcount@Base @SVER@ + _Py_NewReference@Base @SVER@ + _Py_PrintReferenceAddresses@Base @SVER@ + _Py_PrintReferences@Base @SVER@ + _Py_RefTotal@Base @SVER@ + _Py_dumptree@Base @SVER@ + _Py_printtree@Base @SVER@ + _Py_showtree@Base @SVER@ + _Py_tok_dump@Base @SVER@ + PyModule_Create2TraceRefs@Base @SVER@ --- python3.2-3.2.2.orig/debian/README.dbm +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/README.Debian.in +++ python3.2-3.2.2/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. --- python3.2-3.2.2.orig/debian/PVER-minimal.postrm.in +++ python3.2-3.2.2/debian/PVER-minimal.postrm.in @@ -0,0 +1,29 @@ +#! /bin/sh -e + +if [ "$1" = "remove" ]; then + + (find /usr/lib/@PVER@ -name '*.py[co]' | xargs rm -f {}) 2>/dev/null || true + + 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 + + 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 + + rmdir --parents /usr/local/lib/@PVER@ || true +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 + rm -f /etc/@PVER@/site.py /etc/@PVER@/sitecustomize.py + rmdir --ignore-fail-on-non-empty /etc/@PVER@ 2>/dev/null +fi + +#DEBHELPER# + +exit 0 --- python3.2-3.2.2.orig/debian/watch +++ python3.2-3.2.2/debian/watch @@ -0,0 +1,3 @@ +version=3 +opts=dversionmangle=s/.*\+//,uversionmangle=s/([abcr]+[1-9])$/~$1/ \ + http://www.python.org/ftp/python/3\.2(\.\d)?/Python-(3\.2[.\dabcr]*)\.tgz --- python3.2-3.2.2.orig/debian/libpython.symbols.in +++ python3.2-3.2.2/debian/libpython.symbols.in @@ -0,0 +1,1322 @@ + PyAST_Check@Base @SVER@ + PyAST_Compile@Base @SVER@ + PyAST_CompileEx@Base @SVER@ + PyAST_FromNode@Base @SVER@ + PyAST_mod2obj@Base @SVER@ + PyAST_obj2mod@Base @SVER@ + PyArena_AddPyObject@Base @SVER@ + PyArena_Free@Base @SVER@ + PyArena_Malloc@Base @SVER@ + PyArena_New@Base @SVER@ + PyArg_Parse@Base @SVER@ + PyArg_ParseTuple@Base @SVER@ + PyArg_ParseTupleAndKeywords@Base @SVER@ + PyArg_UnpackTuple@Base @SVER@ + PyArg_VaParse@Base @SVER@ + PyArg_VaParseTupleAndKeywords@Base @SVER@ + PyArg_ValidateKeywordArguments@Base @SVER@ + PyBaseObject_Type@Base @SVER@ + PyBool_FromLong@Base @SVER@ + PyBool_Type@Base @SVER@ + PyBuffer_FillContiguousStrides@Base @SVER@ + PyBuffer_FillInfo@Base @SVER@ + PyBuffer_FromContiguous@Base @SVER@ + PyBuffer_GetPointer@Base @SVER@ + PyBuffer_IsContiguous@Base @SVER@ + PyBuffer_Release@Base @SVER@ + PyBuffer_ToContiguous@Base @SVER@ + PyBufferedIOBase_Type@Base @SVER@ + PyBufferedRWPair_Type@Base @SVER@ + PyBufferedRandom_Type@Base @SVER@ + PyBufferedReader_Type@Base @SVER@ + PyBufferedWriter_Type@Base @SVER@ + PyByteArrayIter_Type@Base @SVER@ + PyByteArray_AsString@Base @SVER@ + PyByteArray_Concat@Base @SVER@ + PyByteArray_Fini@Base @SVER@ + PyByteArray_FromObject@Base @SVER@ + PyByteArray_FromStringAndSize@Base @SVER@ + PyByteArray_Init@Base @SVER@ + PyByteArray_Resize@Base @SVER@ + PyByteArray_Size@Base @SVER@ + PyByteArray_Type@Base @SVER@ + PyBytesIO_Type@Base @SVER@ + PyBytesIter_Type@Base @SVER@ + PyBytes_AsString@Base @SVER@ + PyBytes_AsStringAndSize@Base @SVER@ + PyBytes_Concat@Base @SVER@ + PyBytes_ConcatAndDel@Base @SVER@ + PyBytes_DecodeEscape@Base @SVER@ + PyBytes_Fini@Base @SVER@ + PyBytes_FromFormat@Base @SVER@ + PyBytes_FromFormatV@Base @SVER@ + PyBytes_FromObject@Base @SVER@ + PyBytes_FromString@Base @SVER@ + PyBytes_FromStringAndSize@Base @SVER@ + PyBytes_Repr@Base @SVER@ + PyBytes_Size@Base @SVER@ + PyBytes_Type@Base @SVER@ + PyCArgObject_new@Base @SVER@ + PyCArg_Type@Base @SVER@ + PyCArrayType_Type@Base @SVER@ + PyCArrayType_from_ctype@Base @SVER@ + PyCArray_Type@Base @SVER@ + PyCData_AtAddress@Base @SVER@ + PyCData_FromBaseObj@Base @SVER@ + PyCData_Type@Base @SVER@ + PyCData_get@Base @SVER@ + PyCData_set@Base @SVER@ + PyCField_FromDesc@Base @SVER@ + PyCField_Type@Base @SVER@ + PyCFuncPtrType_Type@Base @SVER@ + PyCFuncPtr_Type@Base @SVER@ + PyCFunction_Call@Base @SVER@ + PyCFunction_ClearFreeList@Base @SVER@ + PyCFunction_Fini@Base @SVER@ + PyCFunction_GetFlags@Base @SVER@ + PyCFunction_GetFunction@Base @SVER@ + PyCFunction_GetSelf@Base @SVER@ + PyCFunction_New@Base @SVER@ + PyCFunction_NewEx@Base @SVER@ + PyCFunction_Type@Base @SVER@ + PyCPointerType_Type@Base @SVER@ + PyCPointer_Type@Base @SVER@ + PyCSimpleType_Type@Base @SVER@ + PyCStgDict_Type@Base @SVER@ + PyCStgDict_clone@Base @SVER@ + PyCStructType_Type@Base @SVER@ + PyCStructUnionType_update_stgdict@Base @SVER@ + PyCThunk_Type@Base @SVER@ + PyCallIter_New@Base @SVER@ + PyCallIter_Type@Base @SVER@ + PyCallable_Check@Base @SVER@ + PyCapsule_GetContext@Base @SVER@ + PyCapsule_GetDestructor@Base @SVER@ + PyCapsule_GetName@Base @SVER@ + PyCapsule_GetPointer@Base @SVER@ + PyCapsule_Import@Base @SVER@ + PyCapsule_IsValid@Base @SVER@ + PyCapsule_New@Base @SVER@ + PyCapsule_SetContext@Base @SVER@ + PyCapsule_SetDestructor@Base @SVER@ + PyCapsule_SetName@Base @SVER@ + PyCapsule_SetPointer@Base @SVER@ + PyCapsule_Type@Base @SVER@ + PyCell_Get@Base @SVER@ + PyCell_New@Base @SVER@ + PyCell_Set@Base @SVER@ + PyCell_Type@Base @SVER@ + PyClassMethodDescr_Type@Base @SVER@ + PyClassMethod_New@Base @SVER@ + PyClassMethod_Type@Base @SVER@ + PyCode_Addr2Line@Base @SVER@ + PyCode_New@Base @SVER@ + PyCode_NewEmpty@Base @SVER@ + PyCode_Optimize@Base @SVER@ + PyCode_Type@Base @SVER@ + PyCodec_BackslashReplaceErrors@Base @SVER@ + PyCodec_Decode@Base @SVER@ + PyCodec_Decoder@Base @SVER@ + PyCodec_Encode@Base @SVER@ + PyCodec_Encoder@Base @SVER@ + PyCodec_IgnoreErrors@Base @SVER@ + PyCodec_IncrementalDecoder@Base @SVER@ + PyCodec_IncrementalEncoder@Base @SVER@ + PyCodec_KnownEncoding@Base @SVER@ + PyCodec_LookupError@Base @SVER@ + PyCodec_Register@Base @SVER@ + PyCodec_RegisterError@Base @SVER@ + PyCodec_ReplaceErrors@Base @SVER@ + PyCodec_StreamReader@Base @SVER@ + PyCodec_StreamWriter@Base @SVER@ + PyCodec_StrictErrors@Base @SVER@ + PyCodec_XMLCharRefReplaceErrors@Base @SVER@ + PyCompileString@Base @SVER@ + PyComplex_AsCComplex@Base @SVER@ + PyComplex_FromCComplex@Base @SVER@ + PyComplex_FromDoubles@Base @SVER@ + PyComplex_ImagAsDouble@Base @SVER@ + PyComplex_RealAsDouble@Base @SVER@ + PyComplex_Type@Base @SVER@ + PyDescr_NewClassMethod@Base @SVER@ + PyDescr_NewGetSet@Base @SVER@ + PyDescr_NewMember@Base @SVER@ + PyDescr_NewMethod@Base @SVER@ + PyDescr_NewWrapper@Base @SVER@ + PyDictItems_Type@Base @SVER@ + PyDictIterItem_Type@Base @SVER@ + PyDictIterKey_Type@Base @SVER@ + PyDictIterValue_Type@Base @SVER@ + PyDictKeys_Type@Base @SVER@ + PyDictProxy_New@Base @SVER@ + PyDictProxy_Type@Base @SVER@ + PyDictValues_Type@Base @SVER@ + PyDict_Clear@Base @SVER@ + PyDict_Contains@Base @SVER@ + PyDict_Copy@Base @SVER@ + PyDict_DelItem@Base @SVER@ + PyDict_DelItemString@Base @SVER@ + PyDict_Fini@Base @SVER@ + PyDict_GetItem@Base @SVER@ + PyDict_GetItemProxy@Base @SVER@ + PyDict_GetItemString@Base @SVER@ + PyDict_GetItemWithError@Base @SVER@ + PyDict_Items@Base @SVER@ + PyDict_Keys@Base @SVER@ + PyDict_Merge@Base @SVER@ + PyDict_MergeFromSeq2@Base @SVER@ + PyDict_New@Base @SVER@ + PyDict_Next@Base @SVER@ + PyDict_SetItem@Base @SVER@ + PyDict_SetItemProxy@Base @SVER@ + PyDict_SetItemString@Base @SVER@ + PyDict_Size@Base @SVER@ + PyDict_Type@Base @SVER@ + PyDict_Update@Base @SVER@ + PyDict_Values@Base @SVER@ + PyEllipsis_Type@Base @SVER@ + PyEnum_Type@Base @SVER@ + PyErr_BadArgument@Base @SVER@ + PyErr_BadInternalCall@Base @SVER@ + PyErr_CheckSignals@Base @SVER@ + PyErr_Clear@Base @SVER@ + PyErr_Display@Base @SVER@ + PyErr_ExceptionMatches@Base @SVER@ + PyErr_Fetch@Base @SVER@ + PyErr_Format@Base @SVER@ + PyErr_GivenExceptionMatches@Base @SVER@ + PyErr_NewException@Base @SVER@ + PyErr_NewExceptionWithDoc@Base @SVER@ + PyErr_NoMemory@Base @SVER@ + PyErr_NormalizeException@Base @SVER@ + PyErr_Occurred@Base @SVER@ + PyErr_Print@Base @SVER@ + PyErr_PrintEx@Base @SVER@ + PyErr_ProgramText@Base @SVER@ + PyErr_Restore@Base @SVER@ + PyErr_SetFromErrno@Base @SVER@ + PyErr_SetFromErrnoWithFilename@Base @SVER@ + PyErr_SetFromErrnoWithFilenameObject@Base @SVER@ + PyErr_SetInterrupt@Base @SVER@ + PyErr_SetNone@Base @SVER@ + PyErr_SetObject@Base @SVER@ + PyErr_SetString@Base @SVER@ + PyErr_SyntaxLocation@Base @SVER@ + PyErr_SyntaxLocationEx@Base @SVER@ + PyErr_Warn@Base @SVER@ + PyErr_WarnEx@Base @SVER@ + PyErr_WarnExplicit@Base @SVER@ + PyErr_WarnFormat@Base @SVER@ + PyErr_WriteUnraisable@Base @SVER@ + PyEval_AcquireLock@Base @SVER@ + PyEval_AcquireThread@Base @SVER@ + PyEval_CallFunction@Base @SVER@ + PyEval_CallMethod@Base @SVER@ + PyEval_CallObjectWithKeywords@Base @SVER@ + PyEval_EvalCode@Base @SVER@ + PyEval_EvalCodeEx@Base @SVER@ + PyEval_EvalFrame@Base @SVER@ + PyEval_EvalFrameEx@Base @SVER@ + PyEval_GetBuiltins@Base @SVER@ + PyEval_GetCallStats@Base @SVER@ + PyEval_GetFrame@Base @SVER@ + PyEval_GetFuncDesc@Base @SVER@ + PyEval_GetFuncName@Base @SVER@ + PyEval_GetGlobals@Base @SVER@ + PyEval_GetLocals@Base @SVER@ + PyEval_InitThreads@Base @SVER@ + PyEval_MergeCompilerFlags@Base @SVER@ + PyEval_ReInitThreads@Base @SVER@ + PyEval_ReleaseLock@Base @SVER@ + PyEval_ReleaseThread@Base @SVER@ + PyEval_RestoreThread@Base @SVER@ + PyEval_SaveThread@Base @SVER@ + PyEval_SetProfile@Base @SVER@ + PyEval_SetTrace@Base @SVER@ + PyEval_ThreadsInitialized@Base @SVER@ + PyExc_ArgError@Base @SVER@ + PyExc_ArithmeticError@Base @SVER@ + PyExc_AssertionError@Base @SVER@ + PyExc_AttributeError@Base @SVER@ + PyExc_BaseException@Base @SVER@ + PyExc_BlockingIOError@Base @SVER@ + PyExc_BufferError@Base @SVER@ + PyExc_BytesWarning@Base @SVER@ + PyExc_DeprecationWarning@Base @SVER@ + PyExc_EOFError@Base @SVER@ + PyExc_EnvironmentError@Base @SVER@ + PyExc_Exception@Base @SVER@ + PyExc_FloatingPointError@Base @SVER@ + PyExc_FutureWarning@Base @SVER@ + PyExc_GeneratorExit@Base @SVER@ + PyExc_IOError@Base @SVER@ + PyExc_ImportError@Base @SVER@ + PyExc_ImportWarning@Base @SVER@ + PyExc_IndentationError@Base @SVER@ + PyExc_IndexError@Base @SVER@ + PyExc_KeyError@Base @SVER@ + PyExc_KeyboardInterrupt@Base @SVER@ + PyExc_LookupError@Base @SVER@ + PyExc_MemoryError@Base @SVER@ + PyExc_NameError@Base @SVER@ + PyExc_NotImplementedError@Base @SVER@ + PyExc_OSError@Base @SVER@ + PyExc_OverflowError@Base @SVER@ + PyExc_PendingDeprecationWarning@Base @SVER@ + PyExc_RecursionErrorInst@Base @SVER@ + PyExc_ReferenceError@Base @SVER@ + PyExc_ResourceWarning@Base @SVER@ + PyExc_RuntimeError@Base @SVER@ + PyExc_RuntimeWarning@Base @SVER@ + PyExc_StopIteration@Base @SVER@ + PyExc_SyntaxError@Base @SVER@ + PyExc_SyntaxWarning@Base @SVER@ + PyExc_SystemError@Base @SVER@ + PyExc_SystemExit@Base @SVER@ + PyExc_TabError@Base @SVER@ + PyExc_TypeError@Base @SVER@ + PyExc_UnboundLocalError@Base @SVER@ + PyExc_UnicodeDecodeError@Base @SVER@ + PyExc_UnicodeEncodeError@Base @SVER@ + PyExc_UnicodeError@Base @SVER@ + PyExc_UnicodeTranslateError@Base @SVER@ + PyExc_UnicodeWarning@Base @SVER@ + PyExc_UserWarning@Base @SVER@ + PyExc_ValueError@Base @SVER@ + PyExc_Warning@Base @SVER@ + PyExc_ZeroDivisionError@Base @SVER@ + PyException_GetCause@Base @SVER@ + PyException_GetContext@Base @SVER@ + PyException_GetTraceback@Base @SVER@ + PyException_SetCause@Base @SVER@ + PyException_SetContext@Base @SVER@ + PyException_SetTraceback@Base @SVER@ + PyFPE_counter@Base @SVER@ + PyFPE_dummy@Base @SVER@ + PyFPE_jbuf@Base @SVER@ + PyFileIO_Type@Base @SVER@ + PyFile_FromFd@Base @SVER@ + PyFile_GetLine@Base @SVER@ + PyFile_NewStdPrinter@Base @SVER@ + PyFile_WriteObject@Base @SVER@ + PyFile_WriteString@Base @SVER@ + PyFilter_Type@Base @SVER@ + PyFloat_AsDouble@Base @SVER@ + PyFloat_ClearFreeList@Base @SVER@ + PyFloat_Fini@Base @SVER@ + PyFloat_FromDouble@Base @SVER@ + PyFloat_FromString@Base @SVER@ + PyFloat_GetInfo@Base @SVER@ + PyFloat_GetMax@Base @SVER@ + PyFloat_GetMin@Base @SVER@ + PyFloat_Type@Base @SVER@ + PyFrame_BlockPop@Base @SVER@ + PyFrame_BlockSetup@Base @SVER@ + PyFrame_ClearFreeList@Base @SVER@ + PyFrame_FastToLocals@Base @SVER@ + PyFrame_Fini@Base @SVER@ + PyFrame_GetLineNumber@Base @SVER@ + PyFrame_LocalsToFast@Base @SVER@ + PyFrame_New@Base @SVER@ + PyFrame_Type@Base @SVER@ + PyFrozenSet_New@Base @SVER@ + PyFrozenSet_Type@Base @SVER@ + PyFunction_GetAnnotations@Base @SVER@ + PyFunction_GetClosure@Base @SVER@ + PyFunction_GetCode@Base @SVER@ + PyFunction_GetDefaults@Base @SVER@ + PyFunction_GetGlobals@Base @SVER@ + PyFunction_GetKwDefaults@Base @SVER@ + PyFunction_GetModule@Base @SVER@ + PyFunction_New@Base @SVER@ + PyFunction_SetAnnotations@Base @SVER@ + PyFunction_SetClosure@Base @SVER@ + PyFunction_SetDefaults@Base @SVER@ + PyFunction_SetKwDefaults@Base @SVER@ + PyFunction_Type@Base @SVER@ + PyFuture_FromAST@Base @SVER@ + PyGC_Collect@Base @SVER@ + PyGILState_Ensure@Base @SVER@ + PyGILState_GetThisThreadState@Base @SVER@ + PyGILState_Release@Base @SVER@ + PyGen_NeedsFinalizing@Base @SVER@ + PyGen_New@Base @SVER@ + PyGen_Type@Base @SVER@ + PyGetSetDescr_Type@Base @SVER@ + PyGrammar_AddAccelerators@Base @SVER@ + PyGrammar_FindDFA@Base @SVER@ + PyGrammar_LabelRepr@Base @SVER@ + PyGrammar_RemoveAccelerators@Base @SVER@ + PyIOBase_Type@Base @SVER@ + PyImport_AddModule@Base @SVER@ + PyImport_AppendInittab@Base @SVER@ + PyImport_Cleanup@Base @SVER@ + PyImport_ExecCodeModule@Base @SVER@ + PyImport_ExecCodeModuleEx@Base @SVER@ + PyImport_ExecCodeModuleWithPathnames@Base @SVER@ + PyImport_ExtendInittab@Base @SVER@ + PyImport_FrozenModules@Base @SVER@ + PyImport_GetImporter@Base @SVER@ + PyImport_GetMagicNumber@Base @SVER@ + PyImport_GetMagicTag@Base @SVER@ + PyImport_GetModuleDict@Base @SVER@ + PyImport_Import@Base @SVER@ + PyImport_ImportFrozenModule@Base @SVER@ + PyImport_ImportModule@Base @SVER@ + PyImport_ImportModuleLevel@Base @SVER@ + PyImport_ImportModuleNoBlock@Base @SVER@ + PyImport_Inittab@Base @SVER@ + PyImport_ReloadModule@Base @SVER@ + PyIncrementalNewlineDecoder_Type@Base @SVER@ + PyInstanceMethod_Function@Base @SVER@ + PyInstanceMethod_New@Base @SVER@ + PyInstanceMethod_Type@Base @SVER@ + PyInterpreterState_Clear@Base @SVER@ + PyInterpreterState_Delete@Base @SVER@ + PyInterpreterState_Head@Base @SVER@ + PyInterpreterState_New@Base @SVER@ + PyInterpreterState_Next@Base @SVER@ + PyInterpreterState_ThreadHead@Base @SVER@ + PyIter_Next@Base @SVER@ + PyListIter_Type@Base @SVER@ + PyListRevIter_Type@Base @SVER@ + PyList_Append@Base @SVER@ + PyList_AsTuple@Base @SVER@ + PyList_Fini@Base @SVER@ + PyList_GetItem@Base @SVER@ + PyList_GetSlice@Base @SVER@ + PyList_Insert@Base @SVER@ + PyList_New@Base @SVER@ + PyList_Reverse@Base @SVER@ + PyList_SetItem@Base @SVER@ + PyList_SetSlice@Base @SVER@ + PyList_Size@Base @SVER@ + PyList_Sort@Base @SVER@ + PyList_Type@Base @SVER@ + PyLongRangeIter_Type@Base @SVER@ + PyLong_AsDouble@Base @SVER@ + PyLong_AsLong@Base @SVER@ + PyLong_AsLongAndOverflow@Base @SVER@ + PyLong_AsLongLong@Base @SVER@ + PyLong_AsLongLongAndOverflow@Base @SVER@ + PyLong_AsSize_t@Base @SVER@ + PyLong_AsSsize_t@Base @SVER@ + PyLong_AsUnsignedLong@Base @SVER@ + PyLong_AsUnsignedLongLong@Base @SVER@ + PyLong_AsUnsignedLongLongMask@Base @SVER@ + PyLong_AsUnsignedLongMask@Base @SVER@ + PyLong_AsVoidPtr@Base @SVER@ + PyLong_Fini@Base @SVER@ + PyLong_FromDouble@Base @SVER@ + PyLong_FromLong@Base @SVER@ + PyLong_FromLongLong@Base @SVER@ + PyLong_FromSize_t@Base @SVER@ + PyLong_FromSsize_t@Base @SVER@ + PyLong_FromString@Base @SVER@ + PyLong_FromUnicode@Base @SVER@ + PyLong_FromUnsignedLong@Base @SVER@ + PyLong_FromUnsignedLongLong@Base @SVER@ + PyLong_FromVoidPtr@Base @SVER@ + PyLong_GetInfo@Base @SVER@ + PyLong_Type@Base @SVER@ + PyMap_Type@Base @SVER@ + PyMapping_Check@Base @SVER@ + PyMapping_GetItemString@Base @SVER@ + PyMapping_HasKey@Base @SVER@ + PyMapping_HasKeyString@Base @SVER@ + PyMapping_Items@Base @SVER@ + PyMapping_Keys@Base @SVER@ + PyMapping_Length@Base @SVER@ + PyMapping_SetItemString@Base @SVER@ + PyMapping_Size@Base @SVER@ + PyMapping_Values@Base @SVER@ + PyMarshal_Init@Base @SVER@ + PyMarshal_ReadLastObjectFromFile@Base @SVER@ + PyMarshal_ReadLongFromFile@Base @SVER@ + PyMarshal_ReadObjectFromFile@Base @SVER@ + PyMarshal_ReadObjectFromString@Base @SVER@ + PyMarshal_ReadShortFromFile@Base @SVER@ + PyMarshal_WriteLongToFile@Base @SVER@ + PyMarshal_WriteObjectToFile@Base @SVER@ + PyMarshal_WriteObjectToString@Base @SVER@ + PyMem_Free@Base @SVER@ + PyMem_Malloc@Base @SVER@ + PyMem_Realloc@Base @SVER@ + PyMemberDescr_Type@Base @SVER@ + PyMember_GetOne@Base @SVER@ + PyMember_SetOne@Base @SVER@ + PyMemoryView_FromBuffer@Base @SVER@ + PyMemoryView_FromObject@Base @SVER@ + PyMemoryView_GetContiguous@Base @SVER@ + PyMemoryView_Type@Base @SVER@ + PyMethodDescr_Type@Base @SVER@ + PyMethod_ClearFreeList@Base @SVER@ + PyMethod_Fini@Base @SVER@ + PyMethod_Function@Base @SVER@ + PyMethod_New@Base @SVER@ + PyMethod_Self@Base @SVER@ + PyMethod_Type@Base @SVER@ + PyModule_AddIntConstant@Base @SVER@ + PyModule_AddObject@Base @SVER@ + PyModule_AddStringConstant@Base @SVER@ + PyModule_GetDef@Base @SVER@ + PyModule_GetDict@Base @SVER@ + PyModule_GetFilename@Base @SVER@ + PyModule_GetFilenameObject@Base @SVER@ + PyModule_GetName@Base @SVER@ + PyModule_GetState@Base @SVER@ + PyModule_GetWarningsModule@Base @SVER@ + PyModule_New@Base @SVER@ + PyModule_Type@Base @SVER@ + PyNode_AddChild@Base @SVER@ + PyNode_Compile@Base @SVER@ + PyNode_Free@Base @SVER@ + PyNode_ListTree@Base @SVER@ + PyNode_New@Base @SVER@ + PyNullImporter_Type@Base @SVER@ + PyNumber_Absolute@Base @SVER@ + PyNumber_Add@Base @SVER@ + PyNumber_And@Base @SVER@ + PyNumber_AsOff_t@Base @SVER@ + PyNumber_AsSsize_t@Base @SVER@ + PyNumber_Check@Base @SVER@ + PyNumber_Divmod@Base @SVER@ + PyNumber_Float@Base @SVER@ + PyNumber_FloorDivide@Base @SVER@ + PyNumber_InPlaceAdd@Base @SVER@ + PyNumber_InPlaceAnd@Base @SVER@ + PyNumber_InPlaceFloorDivide@Base @SVER@ + PyNumber_InPlaceLshift@Base @SVER@ + PyNumber_InPlaceMultiply@Base @SVER@ + PyNumber_InPlaceOr@Base @SVER@ + PyNumber_InPlacePower@Base @SVER@ + PyNumber_InPlaceRemainder@Base @SVER@ + PyNumber_InPlaceRshift@Base @SVER@ + PyNumber_InPlaceSubtract@Base @SVER@ + PyNumber_InPlaceTrueDivide@Base @SVER@ + PyNumber_InPlaceXor@Base @SVER@ + PyNumber_Index@Base @SVER@ + PyNumber_Invert@Base @SVER@ + PyNumber_Long@Base @SVER@ + PyNumber_Lshift@Base @SVER@ + PyNumber_Multiply@Base @SVER@ + PyNumber_Negative@Base @SVER@ + PyNumber_Or@Base @SVER@ + PyNumber_Positive@Base @SVER@ + PyNumber_Power@Base @SVER@ + PyNumber_Remainder@Base @SVER@ + PyNumber_Rshift@Base @SVER@ + PyNumber_Subtract@Base @SVER@ + PyNumber_ToBase@Base @SVER@ + PyNumber_TrueDivide@Base @SVER@ + PyNumber_Xor@Base @SVER@ + PyOS_AfterFork@Base @SVER@ + PyOS_FiniInterrupts@Base @SVER@ + PyOS_InitInterrupts@Base @SVER@ + PyOS_InputHook@Base @SVER@ + PyOS_InterruptOccurred@Base @SVER@ + PyOS_Readline@Base @SVER@ + PyOS_ReadlineFunctionPointer@Base @SVER@ + PyOS_StdioReadline@Base @SVER@ + PyOS_double_to_string@Base @SVER@ + PyOS_getsig@Base @SVER@ + PyOS_mystricmp@Base @SVER@ + PyOS_mystrnicmp@Base @SVER@ + PyOS_setsig@Base @SVER@ + PyOS_snprintf@Base @SVER@ + PyOS_string_to_double@Base @SVER@ + PyOS_strtol@Base @SVER@ + PyOS_strtoul@Base @SVER@ + PyOS_vsnprintf@Base @SVER@ + PyObject_ASCII@Base @SVER@ + PyObject_AsCharBuffer@Base @SVER@ + PyObject_AsFileDescriptor@Base @SVER@ + PyObject_AsReadBuffer@Base @SVER@ + PyObject_AsWriteBuffer@Base @SVER@ + PyObject_Bytes@Base @SVER@ + PyObject_Call@Base @SVER@ + PyObject_CallFunction@Base @SVER@ + PyObject_CallFunctionObjArgs@Base @SVER@ + PyObject_CallMethod@Base @SVER@ + PyObject_CallMethodObjArgs@Base @SVER@ + PyObject_CallObject@Base @SVER@ + PyObject_CheckReadBuffer@Base @SVER@ + PyObject_ClearWeakRefs@Base @SVER@ + PyObject_CopyData@Base @SVER@ + PyObject_DelItem@Base @SVER@ + PyObject_DelItemString@Base @SVER@ + PyObject_Dir@Base @SVER@ + PyObject_Format@Base @SVER@ + PyObject_Free@Base @SVER@ + PyObject_GC_Del@Base @SVER@ + PyObject_GC_Track@Base @SVER@ + PyObject_GC_UnTrack@Base @SVER@ + PyObject_GenericGetAttr@Base @SVER@ + PyObject_GenericSetAttr@Base @SVER@ + PyObject_GetAttr@Base @SVER@ + PyObject_GetAttrString@Base @SVER@ + PyObject_GetBuffer@Base @SVER@ + PyObject_GetItem@Base @SVER@ + PyObject_GetIter@Base @SVER@ + PyObject_HasAttr@Base @SVER@ + PyObject_HasAttrString@Base @SVER@ + PyObject_Hash@Base @SVER@ + PyObject_HashNotImplemented@Base @SVER@ + PyObject_Init@Base @SVER@ + PyObject_InitVar@Base @SVER@ + PyObject_IsInstance@Base @SVER@ + PyObject_IsSubclass@Base @SVER@ + PyObject_IsTrue@Base @SVER@ + PyObject_Length@Base @SVER@ + PyObject_Malloc@Base @SVER@ + PyObject_Not@Base @SVER@ + PyObject_Print@Base @SVER@ + PyObject_Realloc@Base @SVER@ + PyObject_Repr@Base @SVER@ + PyObject_RichCompare@Base @SVER@ + PyObject_RichCompareBool@Base @SVER@ + PyObject_SelfIter@Base @SVER@ + PyObject_SetAttr@Base @SVER@ + PyObject_SetAttrString@Base @SVER@ + PyObject_SetItem@Base @SVER@ + PyObject_Size@Base @SVER@ + PyObject_Str@Base @SVER@ + PyObject_Type@Base @SVER@ + PyObject_stgdict@Base @SVER@ + PyParser_ASTFromFile@Base @SVER@ + PyParser_ASTFromString@Base @SVER@ + PyParser_AddToken@Base @SVER@ + PyParser_Delete@Base @SVER@ + PyParser_New@Base @SVER@ + PyParser_ParseFile@Base @SVER@ + PyParser_ParseFileFlags@Base @SVER@ + PyParser_ParseFileFlagsEx@Base @SVER@ + PyParser_ParseString@Base @SVER@ + PyParser_ParseStringFlags@Base @SVER@ + PyParser_ParseStringFlagsFilename@Base @SVER@ + PyParser_ParseStringFlagsFilenameEx@Base @SVER@ + PyParser_SetError@Base @SVER@ + PyParser_SimpleParseFile@Base @SVER@ + PyParser_SimpleParseFileFlags@Base @SVER@ + PyParser_SimpleParseString@Base @SVER@ + PyParser_SimpleParseStringFilename@Base @SVER@ + PyParser_SimpleParseStringFlags@Base @SVER@ + PyParser_SimpleParseStringFlagsFilename@Base @SVER@ + PyProperty_Type@Base @SVER@ + PyRangeIter_Type@Base @SVER@ + PyRange_Type@Base @SVER@ + PyRawIOBase_Type@Base @SVER@ + PyReversed_Type@Base @SVER@ + PyRun_AnyFile@Base @SVER@ + PyRun_AnyFileEx@Base @SVER@ + PyRun_AnyFileExFlags@Base @SVER@ + PyRun_AnyFileFlags@Base @SVER@ + PyRun_File@Base @SVER@ + PyRun_FileEx@Base @SVER@ + PyRun_FileExFlags@Base @SVER@ + PyRun_FileFlags@Base @SVER@ + PyRun_InteractiveLoop@Base @SVER@ + PyRun_InteractiveLoopFlags@Base @SVER@ + PyRun_InteractiveOne@Base @SVER@ + PyRun_InteractiveOneFlags@Base @SVER@ + PyRun_SimpleFile@Base @SVER@ + PyRun_SimpleFileEx@Base @SVER@ + PyRun_SimpleFileExFlags@Base @SVER@ + PyRun_SimpleString@Base @SVER@ + PyRun_SimpleStringFlags@Base @SVER@ + PyRun_String@Base @SVER@ + PyRun_StringFlags@Base @SVER@ + PySTEntry_Type@Base @SVER@ + PyST_GetScope@Base @SVER@ + PySeqIter_New@Base @SVER@ + PySeqIter_Type@Base @SVER@ + PySequence_Check@Base @SVER@ + PySequence_Concat@Base @SVER@ + PySequence_Contains@Base @SVER@ + PySequence_Count@Base @SVER@ + PySequence_DelItem@Base @SVER@ + PySequence_DelSlice@Base @SVER@ + PySequence_Fast@Base @SVER@ + PySequence_GetItem@Base @SVER@ + PySequence_GetSlice@Base @SVER@ + PySequence_In@Base @SVER@ + PySequence_InPlaceConcat@Base @SVER@ + PySequence_InPlaceRepeat@Base @SVER@ + PySequence_Index@Base @SVER@ + PySequence_Length@Base @SVER@ + PySequence_List@Base @SVER@ + PySequence_Repeat@Base @SVER@ + PySequence_SetItem@Base @SVER@ + PySequence_SetSlice@Base @SVER@ + PySequence_Size@Base @SVER@ + PySequence_Tuple@Base @SVER@ + PySetIter_Type@Base @SVER@ + PySet_Add@Base @SVER@ + PySet_Clear@Base @SVER@ + PySet_Contains@Base @SVER@ + PySet_Discard@Base @SVER@ + PySet_Fini@Base @SVER@ + PySet_New@Base @SVER@ + PySet_Pop@Base @SVER@ + PySet_Size@Base @SVER@ + PySet_Type@Base @SVER@ + PySignal_SetWakeupFd@Base @SVER@ + PySlice_GetIndices@Base @SVER@ + PySlice_GetIndicesEx@Base @SVER@ + PySlice_New@Base @SVER@ + PySlice_Type@Base @SVER@ + PyState_FindModule@Base @SVER@ + PyStaticMethod_New@Base @SVER@ + PyStaticMethod_Type@Base @SVER@ + PyStdPrinter_Type@Base @SVER@ + PyStringIO_Type@Base @SVER@ + PyStructSequence_GetItem@Base @SVER@ + PyStructSequence_InitType@Base @SVER@ + PyStructSequence_New@Base @SVER@ + PyStructSequence_NewType@Base @SVER@ + PyStructSequence_SetItem@Base @SVER@ + PyStructSequence_UnnamedField@Base @SVER@ + PySuper_Type@Base @SVER@ + PySymtable_Build@Base @SVER@ + PySymtable_Free@Base @SVER@ + PySymtable_Lookup@Base @SVER@ + PySys_AddWarnOption@Base @SVER@ + PySys_AddWarnOptionUnicode@Base @SVER@ + PySys_AddXOption@Base @SVER@ + PySys_FormatStderr@Base @SVER@ + PySys_FormatStdout@Base @SVER@ + PySys_GetObject@Base @SVER@ + PySys_GetXOptions@Base @SVER@ + PySys_HasWarnOptions@Base @SVER@ + PySys_ResetWarnOptions@Base @SVER@ + PySys_SetArgv@Base @SVER@ + PySys_SetArgvEx@Base @SVER@ + PySys_SetObject@Base @SVER@ + PySys_SetPath@Base @SVER@ + PySys_WriteStderr@Base @SVER@ + PySys_WriteStdout@Base @SVER@ + PyTextIOBase_Type@Base @SVER@ + PyTextIOWrapper_Type@Base @SVER@ + PyThreadState_Clear@Base @SVER@ + PyThreadState_Delete@Base @SVER@ + PyThreadState_DeleteCurrent@Base @SVER@ + PyThreadState_Get@Base @SVER@ + PyThreadState_GetDict@Base @SVER@ + PyThreadState_New@Base @SVER@ + PyThreadState_Next@Base @SVER@ + PyThreadState_SetAsyncExc@Base @SVER@ + PyThreadState_Swap@Base @SVER@ + PyThread_ReInitTLS@Base @SVER@ + PyThread_acquire_lock@Base @SVER@ + PyThread_acquire_lock_timed@Base @SVER@ + PyThread_allocate_lock@Base @SVER@ + PyThread_create_key@Base @SVER@ + PyThread_delete_key@Base @SVER@ + PyThread_delete_key_value@Base @SVER@ + PyThread_exit_thread@Base @SVER@ + PyThread_free_lock@Base @SVER@ + PyThread_get_key_value@Base @SVER@ + PyThread_get_stacksize@Base @SVER@ + PyThread_get_thread_ident@Base @SVER@ + PyThread_init_thread@Base @SVER@ + PyThread_release_lock@Base @SVER@ + PyThread_set_key_value@Base @SVER@ + PyThread_set_stacksize@Base @SVER@ + PyThread_start_new_thread@Base @SVER@ + PyToken_OneChar@Base @SVER@ + PyToken_ThreeChars@Base @SVER@ + PyToken_TwoChars@Base @SVER@ + PyTokenizer_FindEncoding@Base @SVER@ + PyTokenizer_Free@Base @SVER@ + PyTokenizer_FromFile@Base @SVER@ + PyTokenizer_FromString@Base @SVER@ + PyTokenizer_FromUTF8@Base @SVER@ + PyTokenizer_Get@Base @SVER@ + PyTraceBack_Here@Base @SVER@ + PyTraceBack_Print@Base @SVER@ + PyTraceBack_Type@Base @SVER@ + PyTupleIter_Type@Base @SVER@ + PyTuple_ClearFreeList@Base @SVER@ + PyTuple_Fini@Base @SVER@ + PyTuple_GetItem@Base @SVER@ + PyTuple_GetSlice@Base @SVER@ + PyTuple_New@Base @SVER@ + PyTuple_Pack@Base @SVER@ + PyTuple_SetItem@Base @SVER@ + PyTuple_Size@Base @SVER@ + PyTuple_Type@Base @SVER@ + PyType_ClearCache@Base @SVER@ + PyType_FromSpec@Base @SVER@ + PyType_GenericAlloc@Base @SVER@ + PyType_GenericNew@Base @SVER@ + PyType_GetFlags@Base @SVER@ + PyType_IsSubtype@Base @SVER@ + PyType_Modified@Base @SVER@ + PyType_Ready@Base @SVER@ + PyType_Type@Base @SVER@ + PyType_stgdict@Base @SVER@ + PyUnicodeDecodeError_Create@Base @SVER@ + PyUnicodeDecodeError_GetEncoding@Base @SVER@ + PyUnicodeDecodeError_GetEnd@Base @SVER@ + PyUnicodeDecodeError_GetObject@Base @SVER@ + PyUnicodeDecodeError_GetReason@Base @SVER@ + PyUnicodeDecodeError_GetStart@Base @SVER@ + PyUnicodeDecodeError_SetEnd@Base @SVER@ + PyUnicodeDecodeError_SetReason@Base @SVER@ + PyUnicodeDecodeError_SetStart@Base @SVER@ + PyUnicodeEncodeError_Create@Base @SVER@ + PyUnicodeEncodeError_GetEncoding@Base @SVER@ + PyUnicodeEncodeError_GetEnd@Base @SVER@ + PyUnicodeEncodeError_GetObject@Base @SVER@ + PyUnicodeEncodeError_GetReason@Base @SVER@ + PyUnicodeEncodeError_GetStart@Base @SVER@ + PyUnicodeEncodeError_SetEnd@Base @SVER@ + PyUnicodeEncodeError_SetReason@Base @SVER@ + PyUnicodeEncodeError_SetStart@Base @SVER@ + PyUnicodeIter_Type@Base @SVER@ + PyUnicodeTranslateError_Create@Base @SVER@ + PyUnicodeTranslateError_GetEnd@Base @SVER@ + PyUnicodeTranslateError_GetObject@Base @SVER@ + PyUnicodeTranslateError_GetReason@Base @SVER@ + PyUnicodeTranslateError_GetStart@Base @SVER@ + PyUnicodeTranslateError_SetEnd@Base @SVER@ + PyUnicodeTranslateError_SetReason@Base @SVER@ + PyUnicodeTranslateError_SetStart@Base @SVER@ + PyUnicodeUCS4_Append@Base @SVER@ + PyUnicodeUCS4_AppendAndDel@Base @SVER@ + PyUnicodeUCS4_AsASCIIString@Base @SVER@ + PyUnicodeUCS4_AsCharmapString@Base @SVER@ + PyUnicodeUCS4_AsDecodedObject@Base @SVER@ + PyUnicodeUCS4_AsDecodedUnicode@Base @SVER@ + PyUnicodeUCS4_AsEncodedObject@Base @SVER@ + PyUnicodeUCS4_AsEncodedString@Base @SVER@ + PyUnicodeUCS4_AsEncodedUnicode@Base @SVER@ + PyUnicodeUCS4_AsLatin1String@Base @SVER@ + PyUnicodeUCS4_AsRawUnicodeEscapeString@Base @SVER@ + PyUnicodeUCS4_AsUTF16String@Base @SVER@ + PyUnicodeUCS4_AsUTF32String@Base @SVER@ + PyUnicodeUCS4_AsUTF8String@Base @SVER@ + PyUnicodeUCS4_AsUnicode@Base @SVER@ + PyUnicodeUCS4_AsUnicodeEscapeString@Base @SVER@ + PyUnicodeUCS4_AsWideChar@Base @SVER@ + PyUnicodeUCS4_AsWideCharString@Base @SVER@ + PyUnicodeUCS4_ClearFreelist@Base @SVER@ + PyUnicodeUCS4_Compare@Base @SVER@ + PyUnicodeUCS4_CompareWithASCIIString@Base @SVER@ + PyUnicodeUCS4_Concat@Base @SVER@ + PyUnicodeUCS4_Contains@Base @SVER@ + PyUnicodeUCS4_Count@Base @SVER@ + PyUnicodeUCS4_Decode@Base @SVER@ + PyUnicodeUCS4_DecodeASCII@Base @SVER@ + PyUnicodeUCS4_DecodeCharmap@Base @SVER@ + PyUnicodeUCS4_DecodeFSDefault@Base @SVER@ + PyUnicodeUCS4_DecodeFSDefaultAndSize@Base @SVER@ + PyUnicodeUCS4_DecodeLatin1@Base @SVER@ + PyUnicodeUCS4_DecodeRawUnicodeEscape@Base @SVER@ + PyUnicodeUCS4_DecodeUTF16@Base @SVER@ + PyUnicodeUCS4_DecodeUTF16Stateful@Base @SVER@ + PyUnicodeUCS4_DecodeUTF32@Base @SVER@ + PyUnicodeUCS4_DecodeUTF32Stateful@Base @SVER@ + PyUnicodeUCS4_DecodeUTF8@Base @SVER@ + PyUnicodeUCS4_DecodeUTF8Stateful@Base @SVER@ + PyUnicodeUCS4_DecodeUnicodeEscape@Base @SVER@ + PyUnicodeUCS4_Encode@Base @SVER@ + PyUnicodeUCS4_EncodeASCII@Base @SVER@ + PyUnicodeUCS4_EncodeCharmap@Base @SVER@ + PyUnicodeUCS4_EncodeDecimal@Base @SVER@ + PyUnicodeUCS4_EncodeLatin1@Base @SVER@ + PyUnicodeUCS4_EncodeRawUnicodeEscape@Base @SVER@ + PyUnicodeUCS4_EncodeUTF16@Base @SVER@ + PyUnicodeUCS4_EncodeUTF32@Base @SVER@ + PyUnicodeUCS4_EncodeUTF8@Base @SVER@ + PyUnicodeUCS4_EncodeUnicodeEscape@Base @SVER@ + PyUnicodeUCS4_FSConverter@Base @SVER@ + PyUnicodeUCS4_FSDecoder@Base @SVER@ + PyUnicodeUCS4_Find@Base @SVER@ + PyUnicodeUCS4_Format@Base @SVER@ + PyUnicodeUCS4_FromEncodedObject@Base @SVER@ + PyUnicodeUCS4_FromFormat@Base @SVER@ + PyUnicodeUCS4_FromFormatV@Base @SVER@ + PyUnicodeUCS4_FromObject@Base @SVER@ + PyUnicodeUCS4_FromOrdinal@Base @SVER@ + PyUnicodeUCS4_FromString@Base @SVER@ + PyUnicodeUCS4_FromStringAndSize@Base @SVER@ + PyUnicodeUCS4_FromUnicode@Base @SVER@ + PyUnicodeUCS4_FromWideChar@Base @SVER@ + PyUnicodeUCS4_GetDefaultEncoding@Base @SVER@ + PyUnicodeUCS4_GetMax@Base @SVER@ + PyUnicodeUCS4_GetSize@Base @SVER@ + PyUnicodeUCS4_IsIdentifier@Base @SVER@ + PyUnicodeUCS4_Join@Base @SVER@ + PyUnicodeUCS4_Partition@Base @SVER@ + PyUnicodeUCS4_RPartition@Base @SVER@ + PyUnicodeUCS4_RSplit@Base @SVER@ + PyUnicodeUCS4_Replace@Base @SVER@ + PyUnicodeUCS4_Resize@Base @SVER@ + PyUnicodeUCS4_RichCompare@Base @SVER@ + PyUnicodeUCS4_Split@Base @SVER@ + PyUnicodeUCS4_Splitlines@Base @SVER@ + PyUnicodeUCS4_Tailmatch@Base @SVER@ + PyUnicodeUCS4_Translate@Base @SVER@ + PyUnicodeUCS4_TranslateCharmap@Base @SVER@ + PyUnicode_AsUnicodeCopy@Base @SVER@ + PyUnicode_BuildEncodingMap@Base @SVER@ + PyUnicode_DecodeUTF7@Base @SVER@ + PyUnicode_DecodeUTF7Stateful@Base @SVER@ + PyUnicode_EncodeFSDefault@Base @SVER@ + PyUnicode_EncodeUTF7@Base @SVER@ + PyUnicode_InternFromString@Base @SVER@ + PyUnicode_InternImmortal@Base @SVER@ + PyUnicode_InternInPlace@Base @SVER@ + PyUnicode_TransformDecimalToASCII@Base @SVER@ + PyUnicode_Type@Base @SVER@ + PyWeakref_GetObject@Base @SVER@ + PyWeakref_NewProxy@Base @SVER@ + PyWeakref_NewRef@Base @SVER@ + PyWrapperDescr_Type@Base @SVER@ + PyWrapper_New@Base @SVER@ + PyZip_Type@Base @SVER@ + Py_AddPendingCall@Base @SVER@ + Py_AtExit@Base @SVER@ + Py_BuildValue@Base @SVER@ + Py_BytesWarningFlag@Base @SVER@ + Py_CompileString@Base @SVER@ + Py_CompileStringExFlags@Base @SVER@ + Py_CompileStringFlags@Base @SVER@ + Py_DebugFlag@Base @SVER@ + Py_DecRef@Base @SVER@ + Py_DivisionWarningFlag@Base @SVER@ + Py_DontWriteBytecodeFlag@Base @SVER@ + Py_EndInterpreter@Base @SVER@ + Py_Exit@Base @SVER@ + Py_FatalError@Base @SVER@ + Py_FdIsInteractive@Base @SVER@ + Py_FileSystemDefaultEncoding@Base @SVER@ + Py_Finalize@Base @SVER@ + Py_FrozenFlag@Base @SVER@ + Py_FrozenMain@Base @SVER@ + Py_GetArgcArgv@Base @SVER@ + Py_GetBuildInfo@Base @SVER@ + Py_GetCompiler@Base @SVER@ + Py_GetCopyright@Base @SVER@ + Py_GetExecPrefix@Base @SVER@ + Py_GetPath@Base @SVER@ + Py_GetPlatform@Base @SVER@ + Py_GetPrefix@Base @SVER@ + Py_GetProgramFullPath@Base @SVER@ + Py_GetProgramName@Base @SVER@ + Py_GetPythonHome@Base @SVER@ + Py_GetRecursionLimit@Base @SVER@ + Py_GetVersion@Base @SVER@ + Py_HasFileSystemDefaultEncoding@Base @SVER@ + Py_IgnoreEnvironmentFlag@Base @SVER@ + Py_IncRef@Base @SVER@ + Py_Initialize@Base @SVER@ + Py_InitializeEx@Base @SVER@ + Py_InspectFlag@Base @SVER@ + Py_InteractiveFlag@Base @SVER@ + Py_IsInitialized@Base @SVER@ + Py_Main@Base @SVER@ + Py_MakePendingCalls@Base @SVER@ + Py_NewInterpreter@Base @SVER@ + Py_NoSiteFlag@Base @SVER@ + Py_NoUserSiteDirectory@Base @SVER@ + Py_OptimizeFlag@Base @SVER@ + Py_QuietFlag@Base @SVER@ + Py_ReprEnter@Base @SVER@ + Py_ReprLeave@Base @SVER@ + Py_SetPath@Base @SVER@ + Py_SetProgramName@Base @SVER@ + Py_SetPythonHome@Base @SVER@ + Py_SetRecursionLimit@Base @SVER@ + Py_SubversionRevision@Base @SVER@ + Py_SubversionShortBranch@Base @SVER@ + Py_SymtableString@Base @SVER@ + Py_UNICODE_strcat@Base @SVER@ + Py_UNICODE_strchr@Base @SVER@ + Py_UNICODE_strcmp@Base @SVER@ + Py_UNICODE_strcpy@Base @SVER@ + Py_UNICODE_strlen@Base @SVER@ + Py_UNICODE_strncmp@Base @SVER@ + Py_UNICODE_strncpy@Base @SVER@ + Py_UNICODE_strrchr@Base @SVER@ + Py_UnbufferedStdioFlag@Base @SVER@ + Py_UniversalNewlineFgets@Base @SVER@ + Py_UseClassExceptionsFlag@Base @SVER@ + Py_VaBuildValue@Base @SVER@ + Py_VerboseFlag@Base @SVER@ + Py_meta_grammar@Base @SVER@ + Py_pgen@Base @SVER@ + _PyAccu_Accumulate@Base 3.2.2 + _PyAccu_Destroy@Base 3.2.2 + _PyAccu_Finish@Base 3.2.2 + _PyAccu_FinishAsList@Base 3.2.2 + _PyAccu_Init@Base 3.2.2 + _PyArg_NoKeywords@Base @SVER@ + _PyArg_ParseTupleAndKeywords_SizeT@Base @SVER@ + _PyArg_ParseTuple_SizeT@Base @SVER@ + _PyArg_Parse_SizeT@Base @SVER@ + _PyArg_VaParseTupleAndKeywords_SizeT@Base @SVER@ + _PyArg_VaParse_SizeT@Base @SVER@ + _PyBuiltin_Init@Base @SVER@ + _PyByteArray_empty_string@Base @SVER@ + _PyBytesIOBuffer_Type@Base @SVER@ + _PyBytes_FormatLong@Base @SVER@ + _PyBytes_Join@Base @SVER@ + _PyBytes_Resize@Base @SVER@ + _PyCapsule_hack@Base @SVER@ + _PyCode_CheckLineNumber@Base @SVER@ + _PyCodec_Lookup@Base @SVER@ + _PyComplex_FormatAdvanced@Base @SVER@ + _PyDict_Contains@Base @SVER@ + _PyDict_HasOnlyStringKeys@Base @SVER@ + _PyDict_MaybeUntrack@Base @SVER@ + _PyDict_NewPresized@Base @SVER@ + _PyDict_Next@Base @SVER@ + _PyErr_BadInternalCall@Base @SVER@ + _PyEval_CallTracing@Base @SVER@ + _PyEval_FiniThreads@Base @SVER@ + _PyEval_GetSwitchInterval@Base @SVER@ + _PyEval_SetSwitchInterval@Base @SVER@ + _PyEval_SignalAsyncExc@Base @SVER@ + _PyEval_SliceIndex@Base @SVER@ + _PyExc_Fini@Base @SVER@ + _PyExc_Init@Base @SVER@ + _PyFileIO_closed@Base @SVER@ + _PyFloat_FormatAdvanced@Base @SVER@ + _PyFloat_Init@Base @SVER@ + _PyFloat_Pack4@Base @SVER@ + _PyFloat_Pack8@Base @SVER@ + _PyFloat_Unpack4@Base @SVER@ + _PyFloat_Unpack8@Base @SVER@ + _PyFrame_Init@Base @SVER@ + _PyGC_Dump@Base @SVER@ + _PyGC_Fini@Base @SVER@ + _PyGC_generation0@Base @SVER@ + _PyGILState_Fini@Base @SVER@ + _PyGILState_Init@Base @SVER@ + _PyGILState_Reinit@Base @SVER@ + _PyIOBase_check_closed@Base @SVER@ + _PyIOBase_check_readable@Base @SVER@ + _PyIOBase_check_seekable@Base @SVER@ + _PyIOBase_check_writable@Base @SVER@ + _PyIOBase_finalize@Base @SVER@ + _PyIO_ConvertSsize_t@Base @SVER@ + _PyIO_Module@Base @SVER@ + _PyIO_empty_bytes@Base @SVER@ + _PyIO_empty_str@Base @SVER@ + _PyIO_find_line_ending@Base @SVER@ + _PyIO_str_close@Base @SVER@ + _PyIO_str_closed@Base @SVER@ + _PyIO_str_decode@Base @SVER@ + _PyIO_str_encode@Base @SVER@ + _PyIO_str_fileno@Base @SVER@ + _PyIO_str_flush@Base @SVER@ + _PyIO_str_getstate@Base @SVER@ + _PyIO_str_isatty@Base @SVER@ + _PyIO_str_newlines@Base @SVER@ + _PyIO_str_nl@Base @SVER@ + _PyIO_str_read1@Base @SVER@ + _PyIO_str_read@Base @SVER@ + _PyIO_str_readable@Base @SVER@ + _PyIO_str_readinto@Base @SVER@ + _PyIO_str_readline@Base @SVER@ + _PyIO_str_reset@Base @SVER@ + _PyIO_str_seek@Base @SVER@ + _PyIO_str_seekable@Base @SVER@ + _PyIO_str_setstate@Base @SVER@ + _PyIO_str_tell@Base @SVER@ + _PyIO_str_truncate@Base @SVER@ + _PyIO_str_writable@Base @SVER@ + _PyIO_str_write@Base @SVER@ + _PyIO_zero@Base @SVER@ + _PyImportHooks_Init@Base @SVER@ + _PyImport_AcquireLock@Base @SVER@ + _PyImport_DynLoadFiletab@Base @SVER@ + _PyImport_Filetab@Base @SVER@ + _PyImport_FindBuiltin@Base @SVER@ + _PyImport_FindExtensionUnicode@Base @SVER@ + _PyImport_Fini@Base @SVER@ + _PyImport_FixupBuiltin@Base @SVER@ + _PyImport_FixupExtensionUnicode@Base @SVER@ + _PyImport_GetDynLoadFunc@Base @SVER@ + _PyImport_Init@Base @SVER@ + _PyImport_Inittab@Base @SVER@ + _PyImport_LoadDynamicModule@Base @SVER@ + _PyImport_ReInitLock@Base @SVER@ + _PyImport_ReleaseLock@Base @SVER@ + _PyIncrementalNewlineDecoder_decode@Base @SVER@ + _PyList_Extend@Base @SVER@ + _PyLong_AsByteArray@Base @SVER@ + _PyLong_Copy@Base @SVER@ + _PyLong_DigitValue@Base @SVER@ + _PyLong_DivmodNear@Base @SVER@ + _PyLong_Format@Base @SVER@ + _PyLong_FormatAdvanced@Base @SVER@ + _PyLong_Frexp@Base @SVER@ + _PyLong_FromByteArray@Base @SVER@ + _PyLong_Init@Base @SVER@ + _PyLong_New@Base @SVER@ + _PyLong_NumBits@Base @SVER@ + _PyLong_Sign@Base @SVER@ + _PyMethodWrapper_Type@Base 3.2.2 + _PyModule_Clear@Base @SVER@ + _PyNumber_ConvertIntegralToInt@Base @SVER@ + _PyOS_GetOpt@Base @SVER@ + _PyOS_ReadlineTState@Base @SVER@ + _PyOS_optarg@Base @SVER@ + _PyOS_opterr@Base @SVER@ + _PyOS_optind@Base @SVER@ + _PyObject_CallFunction_SizeT@Base @SVER@ + _PyObject_CallMethod_SizeT@Base @SVER@ + _PyObject_Dump@Base @SVER@ + _PyObject_GC_Malloc@Base @SVER@ + _PyObject_GC_New@Base @SVER@ + _PyObject_GC_NewVar@Base @SVER@ + _PyObject_GC_Resize@Base @SVER@ + _PyObject_GC_Track@Base @SVER@ + _PyObject_GC_UnTrack@Base @SVER@ + _PyObject_GenericGetAttrWithDict@Base @SVER@ + _PyObject_GenericSetAttrWithDict@Base @SVER@ + _PyObject_GetDictPtr@Base @SVER@ + _PyObject_LengthHint@Base @SVER@ + _PyObject_LookupSpecial@Base @SVER@ + _PyObject_New@Base @SVER@ + _PyObject_NewVar@Base @SVER@ + _PyObject_NextNotImplemented@Base @SVER@ + _PyObject_RealIsInstance@Base @SVER@ + _PyObject_RealIsSubclass@Base @SVER@ + _PyParser_Grammar@Base @SVER@ + _PyParser_TokenNames@Base @SVER@ + _PySequence_BytesToCharpArray@Base @SVER@ + _PySequence_IterSearch@Base @SVER@ + _PySet_NextEntry@Base @SVER@ + _PySet_Update@Base @SVER@ + _PySlice_FromIndices@Base @SVER@ + _PyState_AddModule@Base @SVER@ + _PySys_Init@Base @SVER@ + _PyThreadState_Current@Base @SVER@ + _PyThreadState_GetFrame@Base @SVER@ + _PyThreadState_Init@Base @SVER@ + _PyThreadState_Prealloc@Base @SVER@ + _PyThread_CurrentFrames@Base @SVER@ + _PyTime_DoubleToTimet@Base @SVER@ + _PyTime_Init@Base @SVER@ + _PyTime_gettimeofday@Base @SVER@ + _PyTrash_delete_later@Base @SVER@ + _PyTrash_delete_nesting@Base @SVER@ + _PyTrash_deposit_object@Base @SVER@ + _PyTrash_destroy_chain@Base @SVER@ + _PyTuple_MaybeUntrack@Base @SVER@ + _PyTuple_Resize@Base @SVER@ + _PyType_CalculateMetaclass@Base 3.2.2 + _PyType_Lookup@Base @SVER@ + _PyUnicodeUCS4_AsDefaultEncodedString@Base @SVER@ + _PyUnicodeUCS4_Fini@Base @SVER@ + _PyUnicodeUCS4_Init@Base @SVER@ + _PyUnicode_AsString@Base @SVER@ + _PyUnicode_AsStringAndSize@Base @SVER@ + _PyUnicode_BidirectionalNames@Base @SVER@ + _PyUnicode_CategoryNames@Base @SVER@ + _PyUnicode_Database_Records@Base @SVER@ + _PyUnicode_DecodeUnicodeInternal@Base @SVER@ + _PyUnicode_EastAsianWidthNames@Base @SVER@ + _PyUnicode_FormatAdvanced@Base @SVER@ + _PyUnicode_InsertThousandsGrouping@Base @SVER@ + _PyUnicode_InsertThousandsGroupingLocale@Base @SVER@ + _PyUnicode_IsAlpha@Base @SVER@ + _PyUnicode_IsDecimalDigit@Base @SVER@ + _PyUnicode_IsDigit@Base @SVER@ + _PyUnicode_IsLinebreak@Base @SVER@ + _PyUnicode_IsLowercase@Base @SVER@ + _PyUnicode_IsNumeric@Base @SVER@ + _PyUnicode_IsPrintable@Base @SVER@ + _PyUnicode_IsTitlecase@Base @SVER@ + _PyUnicode_IsUppercase@Base @SVER@ + _PyUnicode_IsWhitespace@Base @SVER@ + _PyUnicode_IsXidContinue@Base @SVER@ + _PyUnicode_IsXidStart@Base @SVER@ + _PyUnicode_ToDecimalDigit@Base @SVER@ + _PyUnicode_ToDigit@Base @SVER@ + _PyUnicode_ToLowercase@Base @SVER@ + _PyUnicode_ToNumeric@Base @SVER@ + _PyUnicode_ToTitlecase@Base @SVER@ + _PyUnicode_ToUppercase@Base @SVER@ + _PyUnicode_TypeRecords@Base @SVER@ + _PyUnicode_XStrip@Base @SVER@ + _PyWarnings_Init@Base @SVER@ + _PyWeakref_CallableProxyType@Base @SVER@ + _PyWeakref_ClearRef@Base @SVER@ + _PyWeakref_GetWeakrefCount@Base @SVER@ + _PyWeakref_ProxyType@Base @SVER@ + _PyWeakref_RefType@Base @SVER@ + _Py_Assert@Base @SVER@ + _Py_Assign@Base @SVER@ + _Py_Attribute@Base @SVER@ + _Py_AugAssign@Base @SVER@ + _Py_BinOp@Base @SVER@ + _Py_BoolOp@Base @SVER@ + _Py_Break@Base @SVER@ + _Py_BreakPoint@Base @SVER@ + _Py_BuildValue_SizeT@Base @SVER@ + _Py_Bytes@Base @SVER@ + _Py_Call@Base @SVER@ + _Py_CheckRecursionLimit@Base @SVER@ + _Py_CheckRecursiveCall@Base @SVER@ + _Py_ClassDef@Base @SVER@ + _Py_Compare@Base @SVER@ + _Py_Continue@Base @SVER@ + _Py_Dealloc@Base @SVER@ + _Py_Delete@Base @SVER@ + _Py_Dict@Base @SVER@ + _Py_DictComp@Base @SVER@ + _Py_DisplaySourceLine@Base @SVER@ + _Py_Ellipsis@Base @SVER@ + _Py_EllipsisObject@Base @SVER@ + _Py_ExceptHandler@Base @SVER@ + _Py_Expr@Base @SVER@ + _Py_Expression@Base @SVER@ + _Py_ExtSlice@Base @SVER@ + _Py_FalseStruct@Base @SVER@ + _Py_Finalizing@Base @SVER@ + _Py_For@Base @SVER@ + _Py_FreeCharPArray@Base @SVER@ + _Py_FunctionDef@Base @SVER@ + _Py_GeneratorExp@Base @SVER@ + _Py_Global@Base @SVER@ + _Py_HashDouble@Base @SVER@ + _Py_HashPointer@Base @SVER@ + _Py_If@Base @SVER@ + _Py_IfExp@Base @SVER@ + _Py_Import@Base @SVER@ + _Py_ImportFrom@Base @SVER@ + _Py_Index@Base @SVER@ + _Py_Interactive@Base @SVER@ + _Py_Lambda@Base @SVER@ + _Py_List@Base @SVER@ + _Py_ListComp@Base @SVER@ + _Py_Mangle@Base @SVER@ + _Py_Module@Base @SVER@ + _Py_Name@Base @SVER@ + _Py_NoneStruct@Base @SVER@ + _Py_Nonlocal@Base @SVER@ + _Py_NotImplementedStruct@Base @SVER@ + _Py_Num@Base @SVER@ + _Py_PackageContext@Base @SVER@ + _Py_Pass@Base @SVER@ + _Py_PyAtExit@Base @SVER@ + _Py_Raise@Base @SVER@ + _Py_ReadyTypes@Base @SVER@ + _Py_ReleaseInternedUnicodeStrings@Base @SVER@ + _Py_RestoreSignals@Base @SVER@ + _Py_Return@Base @SVER@ + _Py_Set@Base @SVER@ + _Py_SetComp@Base @SVER@ + _Py_Slice@Base @SVER@ + _Py_Starred@Base @SVER@ + _Py_Str@Base @SVER@ + _Py_Subscript@Base @SVER@ + _Py_Suite@Base @SVER@ + _Py_SwappedOp@Base @SVER@ + _Py_TrueStruct@Base @SVER@ + _Py_TryExcept@Base @SVER@ + _Py_TryFinally@Base @SVER@ + _Py_Tuple@Base @SVER@ + _Py_UnaryOp@Base @SVER@ + _Py_VaBuildValue_SizeT@Base @SVER@ + _Py_While@Base @SVER@ + _Py_With@Base @SVER@ + _Py_Yield@Base @SVER@ + _Py_abstract_hack@Base @SVER@ + _Py_acosh@Base @SVER@ + _Py_add_one_to_index_C@Base @SVER@ + _Py_add_one_to_index_F@Base @SVER@ + _Py_addarc@Base @SVER@ + _Py_addbit@Base @SVER@ + _Py_adddfa@Base @SVER@ + _Py_addfirstsets@Base @SVER@ + _Py_addlabel@Base @SVER@ + _Py_addstate@Base @SVER@ + _Py_alias@Base @SVER@ + _Py_arg@Base @SVER@ + _Py_arguments@Base @SVER@ + _Py_ascii_whitespace@Base @SVER@ + _Py_asinh@Base @SVER@ + _Py_atanh@Base @SVER@ + _Py_bytes_capitalize@Base @SVER@ + _Py_hgidentifier@Base @SVER@ + _Py_hgversion@Base @SVER@ + _Py_bytes_isalnum@Base @SVER@ + _Py_bytes_isalpha@Base @SVER@ + _Py_bytes_isdigit@Base @SVER@ + _Py_bytes_islower@Base @SVER@ + _Py_bytes_isspace@Base @SVER@ + _Py_bytes_istitle@Base @SVER@ + _Py_bytes_isupper@Base @SVER@ + _Py_bytes_lower@Base @SVER@ + _Py_bytes_maketrans@Base @SVER@ + _Py_bytes_swapcase@Base @SVER@ + _Py_bytes_title@Base @SVER@ + _Py_bytes_upper@Base @SVER@ + _Py_c_abs@Base @SVER@ + _Py_c_diff@Base @SVER@ + _Py_c_neg@Base @SVER@ + _Py_c_pow@Base @SVER@ + _Py_c_prod@Base @SVER@ + _Py_c_quot@Base @SVER@ + _Py_c_sum@Base @SVER@ + _Py_capitalize__doc__@Base @SVER@ + _Py_char2wchar@Base @SVER@ + _Py_comprehension@Base @SVER@ + _Py_ctype_table@Base @SVER@ + _Py_ctype_tolower@Base @SVER@ + _Py_ctype_toupper@Base @SVER@ + _Py_delbitset@Base @SVER@ + (arch=!m68k)_Py_dg_dtoa@Base @SVER@ + (arch=!m68k)_Py_dg_freedtoa@Base @SVER@ + (arch=!m68k)_Py_dg_strtod@Base @SVER@ + _Py_expm1@Base @SVER@ + _Py_findlabel@Base @SVER@ + _Py_fopen@Base @SVER@ + (arch=i386 lpia m68k)_Py_force_double@Base @SVER@ + (arch=amd64 i386 lpia)_Py_get_387controlword@Base @SVER@ + _Py_isalnum__doc__@Base @SVER@ + _Py_isalpha__doc__@Base @SVER@ + _Py_isdigit__doc__@Base @SVER@ + _Py_islower__doc__@Base @SVER@ + _Py_isspace__doc__@Base @SVER@ + _Py_istitle__doc__@Base @SVER@ + _Py_isupper__doc__@Base @SVER@ + _Py_keyword@Base @SVER@ + _Py_log1p@Base @SVER@ + _Py_lower__doc__@Base @SVER@ + _Py_maketrans__doc__@Base @SVER@ + _Py_mergebitset@Base @SVER@ + _Py_meta_grammar@Base @SVER@ + _Py_newbitset@Base @SVER@ + _Py_newgrammar@Base @SVER@ + _Py_parse_inf_or_nan@Base @SVER@ + _Py_pgen@Base @SVER@ + _Py_samebitset@Base @SVER@ + (arch=amd64 i386 lpia)_Py_set_387controlword@Base @SVER@ + _Py_stat@Base @SVER@ + _Py_svnversion@Base @SVER@ + _Py_swapcase__doc__@Base @SVER@ + _Py_title__doc__@Base @SVER@ + _Py_translatelabels@Base @SVER@ + _Py_upper__doc__@Base @SVER@ + _Py_wchar2char@Base @SVER@ + _Py_wfopen@Base @SVER@ + _Py_wgetcwd@Base @SVER@ + _Py_wreadlink@Base @SVER@ + _Py_wrealpath@Base @SVER@ + _Py_wstat@Base @SVER@ + + asdl_int_seq_new@Base @SVER@ + asdl_seq_new@Base @SVER@ + + (optional|regex)"^_ctypes_.*@Base$" @SVER@ + (optional|regex)"^ffi_type_.*@Base$" @SVER@ + (optional|regex)"^ffi_closure_.*@Base$" @SVER@ + + (optional|regex)"^PyInit_.*@Base$" @SVER@ --- python3.2-3.2.2.orig/debian/control +++ python3.2-3.2.2/debian/control @@ -0,0 +1,126 @@ +Source: python3.2 +Section: python +Priority: optional +Maintainer: Ubuntu Core Developers +XSBC-Original-Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5.0.51~), quilt, autoconf, libreadline-dev, libncursesw5-dev (>= 5.3), zlib1g-dev, libdb5.1-dev, tk8.5-dev, blt-dev (>= 2.4z), libssl-dev, sharutils, libbz2-dev, libexpat1-dev, libbluetooth-dev [linux-any], locales [!armel !avr32 !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [linux-any], netbase, bzip2, gdb, python +Build-Depends-Indep: python-sphinx +Build-Conflicts: autoconf2.13 +XS-Python-Version: 3.2 +Standards-Version: 3.9.2 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg3.2-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg3.2-debian + +Package: python3.2 +Architecture: any +Priority: optional +Depends: python3.2-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: python3.2-doc, binutils +Provides: python3.2-cjkcodecs, python3.2-ctypes, python3.2-elementtree, python3.2-celementtree, python3.2-wsgiref, python3.2-gdbm, python3.2-profiler +Conflicts: python3-profiler (<= 3.2-2) +Replaces: python3-profiler (<= 3.2-2) +XB-Python-Version: 3.2 +Description: Interactive high-level object-oriented language (version 3.2) + Version 3.2 of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: python3.2-minimal +Architecture: any +Priority: optional +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: python3.2 +Suggests: binfmt-support +Replaces: python3.2 (<< 3.2~b2-1~) +Conflicts: binfmt-support (<< 1.1.2) +XB-Python-Runtime: python3.2 +XB-Python-Version: 3.2 +Description: Minimal subset of the Python language (version 3.2) + 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/python3.2-minimal/README.Debian for a list of the modules + contained in this package. + +Package: libpython3.2 +Architecture: any +Section: libs +Priority: optional +Depends: python3.2 (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: python3.2 (<< 3.0~rc1) +Description: Shared Python runtime library (version 3.2) + Version 3.2 of the high-level, interactive object oriented language, + 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: python3.2-examples +Architecture: all +Depends: python3.2 (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v3.2) + Examples, Demos and Tools for Python (v3.2). These are files included in + the upstream Python distribution (v3.2). + +Package: python3.2-dev +Architecture: any +Depends: python3.2 (= ${binary:Version}), libpython3.2 (= ${binary:Version}), libssl-dev, libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Replaces: python3.2 (<< 3.2~rc1-2) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v3.2) + Header files, a static library and development tools for building + Python (v3.2) modules, extending the Python interpreter or embedding + Python (v3.2) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-python3.2 +Architecture: all +Depends: python3.2, python3-tk, python3.2-tk, ${misc:Depends} +Enhances: python3.2 +XB-Python-Version: 3.2 +Description: IDE for Python (v3.2) using Tkinter + IDLE is an Integrated Development Environment for Python (v3.2). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: python3.2-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: python3.2 +Description: Documentation for the high-level object-oriented language Python (v3.2) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v3.2). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python3.2 + * 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: python3.2-dbg +Section: debug +Architecture: any +Priority: extra +Depends: python3.2 (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends}, python +Suggests: python3-gdbm-dbg, python3-tk-dbg +Description: Debug Build of the Python Interpreter (version 3.2) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/python3.2/lib-dynload/debug first. + +Package: python3.2-udeb +XC-Package-Type: udeb +Section: debian-installer +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +XB-Python-Runtime: python3.2 +XB-Python-Version: 3.2 +Description: A minimal subset of the Python language (version 3.2) + This package contains the interpreter and some essential modules, packaged + for use in the installer. --- python3.2-3.2.2.orig/debian/PVER-dbg.prerm.in +++ python3.2-3.2.2/debian/PVER-dbg.prerm.in @@ -0,0 +1,35 @@ +#! /bin/sh + +set -e + +remove_bytecode() +{ + pkg=$1 + max=$(LANG=C LC_ALL=C xargs --show-limits < /dev/null 2>&1 | awk '/Maximum/ {print int($NF / 4)}') + dpkg -L $pkg \ + | awk -F/ 'BEGIN {OFS="/"} /\.py$/ {$NF=sprintf("__pycache__/%s.*.py[co]", substr($NF,1,length($NF)-3)); print}' \ + | xargs --max-chars=$max echo \ + | while read files; do rm -f $files; done + if [ -d /usr/bin/__pycache__ ]; then + rmdir --ignore-fail-on-non-empty /usr/bin/__pycache__ + fi +} + +case "$1" in + remove) + remove_bytecode @PVER@-dbg + ;; + upgrade) + remove_bytecode @PVER@-dbg + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python3.2-3.2.2.orig/debian/source.lintian-overrides.in +++ python3.2-3.2.2/debian/source.lintian-overrides.in @@ -0,0 +1,2 @@ +# generated during the build +@PVER@ source: quilt-build-dep-but-no-series-file --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/copyright +++ python3.2-3.2.2/debian/copyright @@ -0,0 +1,723 @@ +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 + +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 */ --- python3.2-3.2.2.orig/debian/libPVER.symbols.lpia.in +++ python3.2-3.2.2/debian/libPVER.symbols.lpia.in @@ -0,0 +1,6 @@ +libpython@VER@mu.so.1.0 libpython@VER@ #MINVER# +#include "libpython.symbols" + PyModule_Create2@Base @SVER@ + _Py_force_double@Base @SVER@ + _Py_get_387controlword@Base @SVER@ + _Py_set_387controlword@Base @SVER@ --- python3.2-3.2.2.orig/debian/README.source +++ python3.2-3.2.2/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. --- python3.2-3.2.2.orig/debian/PVER-dbg.overrides.in +++ python3.2-3.2.2/debian/PVER-dbg.overrides.in @@ -0,0 +1,2 @@ +@PVER@-dbg binary: package-name-doesnt-match-sonames +@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/idle-PVER.postrm.in +++ python3.2-3.2.2/debian/idle-PVER.postrm.in @@ -0,0 +1,9 @@ +#! /bin/sh -e + +if [ "$1" = "purge" ]; then + rm -rf /etc/idle-@PVER@ +fi + +#DEBHELPER# + +exit 0 --- python3.2-3.2.2.orig/debian/PVER.pycentral.in +++ python3.2-3.2.2/debian/PVER.pycentral.in @@ -0,0 +1,4 @@ +[@PVER@] +runtime: @PVER@ +interpreter: /usr/bin/@PVER@ +prefix: /usr/lib/@PVER@ --- python3.2-3.2.2.orig/debian/PVER.postinst.in +++ python3.2-3.2.2/debian/PVER.postinst.in @@ -0,0 +1,30 @@ +#! /bin/sh -e + +if [ "$1" = configure ]; then + ( + files=$(dpkg -L @PVER@ | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + @PVER@ /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + @PVER@ -O /usr/lib/@PVER@/py_compile.py $files + fi + ) +fi + +oldlocalsite=/usr/local/lib/@PVER@/site-packages +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + # issue #623057 + if [ -d $oldlocalsite -a ! -h $oldlocalsite ]; then + rmdir --ignore-fail-on-non-empty $oldlocalsite 2>/dev/null || true + fi + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python3.2-3.2.2.orig/debian/README.python +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/pdb.1.in +++ python3.2-3.2.2/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. --- python3.2-3.2.2.orig/debian/locale-gen +++ python3.2-3.2.2/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 <&1 | awk '/Maximum/ {print int($NF / 4)}') + dpkg -L $pkg \ + | awk -F/ 'BEGIN {OFS="/"} /\.py$/ {$NF=sprintf("__pycache__/%s.*.py[co]", substr($NF,1,length($NF)-3)); print}' \ + | xargs --max-chars="$max" echo \ + | while read files; do rm -f $files; done + find /usr/lib/python3 /usr/lib/@PVER@ -name dist-packages -prune -o -name __pycache__ -empty -print \ + | xargs -r rm -rf +} + +case "$1" in + remove) + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Unlinking and removing bytecode for runtime @PVER@" + fi + for hook in /usr/share/python3/runtime.d/*.rtremove; do + [ -x $hook ] || continue + $hook rtremove @PVER@ || continue + done + + remove_bytecode @PVER@-minimal + + if which update-binfmts >/dev/null; then + update-binfmts --package @PVER@ --remove @PVER@ /usr/bin/@PVER@ + fi + + if [ -h $syssite ]; then + rm -f $syssite + fi + [ -d $localsite ] && rmdir $localsite 2>/dev/null || true + [ -d $(dirname $localsite) ] && rmdir $(dirname $localsite) 2>/dev/null || true + ;; + upgrade) + remove_bytecode @PVER@-minimal + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python3.2-3.2.2.orig/debian/idle.desktop.in +++ python3.2-3.2.2/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@ -n +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=false +Type=Application +Categories=Application;Development; +StartupNotify=true --- python3.2-3.2.2.orig/debian/idle-PVER.overrides.in +++ python3.2-3.2.2/debian/idle-PVER.overrides.in @@ -0,0 +1,2 @@ +# icon in dependent package +idle-@PVER@ binary: menu-icon-missing --- python3.2-3.2.2.orig/debian/PVER-dbg.README.Debian.in +++ python3.2-3.2.2/debian/PVER-dbg.README.Debian.in @@ -0,0 +1,51 @@ +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 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. + + * 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. --- python3.2-3.2.2.orig/debian/libPVER.overrides.in +++ python3.2-3.2.2/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python3.2-3.2.2.orig/debian/FAQ.html +++ python3.2-3.2.2/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
+ + --- python3.2-3.2.2.orig/debian/libPVER.symbols.in +++ python3.2-3.2.2/debian/libPVER.symbols.in @@ -0,0 +1,3 @@ +libpython@VER@mu.so.1.0 libpython@VER@ #MINVER# +#include "libpython.symbols" + PyModule_Create2@Base @SVER@ --- python3.2-3.2.2.orig/debian/rules +++ python3.2-3.2.2/debian/rules @@ -0,0 +1,1075 @@ +#!/usr/bin/make -f +# Sample debian/rules that uses debhelper. GNU copyright 1997 by Joey Hess. + +unexport LANG LC_ALL LC_CTYPE LC_COLLATE LC_TIME LC_NUMERIC LC_MESSAGES +unexport CFLAGS CXXFLAGS CPPFLAGS + +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_HOST_ARCH ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH) +DEB_HOST_ARCH_OS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_OS) + +CHANGELOG_VARS := $(shell dpkg-parsechangelog | \ + sed -n 's/ /_/g;/^[^_]/s/^\([^:]*\):_\(.*\)/\1=\2/p') +PKGSOURCE := $(call vafilt,$(CHANGELOG_VARS),Source) +PKGVERSION := $(call vafilt,$(CHANGELOG_VARS),Version) + +on_buildd := $(shell [ -f /CurrentlyBuilding -o "$$LOGNAME" = buildd ] && echo yes) + +ifneq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS))) + WITHOUT_CHECK := yes +endif +WITHOUT_BENCH := +ifneq (,$(findstring nobench, $(DEB_BUILD_OPTIONS))) + WITHOUT_BENCH := yes +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + WITHOUT_BENCH := disabled on $(DEB_HOST_ARCH) +endif +ifeq ($(on_buildd),yes) + ifneq (,$(findstring $(DEB_HOST_ARCH), armel hppa mips mipsel s390)) + WITHOUT_CHECK := yes + endif + ifneq (,$(findstring $(DEB_HOST_ARCH), armel hppa mips mipsel s390)) + WITHOUT_BENCH := yes + endif +endif + WITHOUT_CHECK := yes + WITHOUT_BENCH := yes + +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) +distribution := Ubuntu + +export VER=3.2 +export SVER=3.2~a4 +export NVER=3.3 +export PVER=python3.2 +export 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 = no +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_interp := static +#with_interp := shared + +build_target := build-all +install_target := install + +PY_INTERPRETER = /usr/bin/python$(VER) + +ifeq ($(DEFAULT_VERSION),yes) + PY_PRIO = standard + #PYSTDDEP = , python (>= $(VER)) +else + PY_PRIO = optional +endif +ifeq ($(distribution),Ubuntu) + PY_MINPRIO = required + PY_MINPRIO = optional + with_fpectl = yes +else + PY_MINPRIO = $(PY_PRIO) + with_fpectl = yes +endif + +CC = gcc + +# on alpha, use -O2 only, use -mieee +ifeq ($(DEB_HOST_ARCH),alpha) + OPTSETTINGS = OPT="-g -O2 -fwrapv -mieee -Wall -Wstrict-prototypes" + OPTDEBUGSETTINGS = OPT="-g -O0 -fwrapv -mieee -Wall -Wstrict-prototypes" +endif +ifeq ($(DEB_HOST_ARCH),m68k) + OPTSETTINGS = OPT="-g -O2 -fwrapv -Wall -Wstrict-prototypes" +endif + +PWD := $(shell pwd) +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_dev := $(PVER)-dev +p_exam := $(PVER)-examples +p_idle := idle-$(PVER) +p_doc := $(PVER)-doc +p_dbg := $(PVER)-dbg +p_udeb := $(PVER)-udeb + +d_base := debian/$(p_base) +d_min := debian/$(p_min) +d_lib := debian/$(p_lib) +d_tk := debian/$(p_tk) +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_udeb := debian/$(p_udeb) + +ifneq (,$(findstring $(DEB_HOST_ARCH), alpha hppa ia64 m68k sparc sparc64)) + make_build_target = +else + make_build_target = profile-opt +endif + +build: $(build_target) +build-arch: $(build_target) +build-indep: build-doc +build-all: stamps/stamp-build +stamps/stamp-build: stamps/stamp-build-static stamps/stamp-build-shared stamps/stamp-build-debug stamps/stamp-build-shared-debug stamps/stamp-mincheck stamps/stamp-check stamps/stamp-pystone stamps/stamp-pybench + touch stamps/stamp-build + +PROFILE_EXCLUDES = test_compiler test_distutils test_platform test_subprocess \ + test_multiprocessing test_socketserver \ + test_thread test_threaded_import test_threadedtempfile \ + test_threading test_threading_local test_threadsignals \ + test_dbm_dumb test_dbm_ndbm test_pydoc test_sundry \ + test_signal test_ioctl test_gdb +# FIXME: test_mailxbox breaks, 20090703 +PROFILE_EXCLUDES += test_mailbox +# FIXME: test_xmlrpc breaks, 20090818 +PROFILE_EXCLUDES += test_xmlrpc +# FIXME: test_telnetlib uses network resources +PROFILE_EXCLUDES += test_telnetlib + +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) \ + PROFILE_TASK='$(PROFILE_TASK)' $(make_build_target) + touch stamps/stamp-build-static + +stamps/stamp-build-shared: stamps/stamp-configure-shared + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_shared) +# : # build the shared library +# $(MAKE) $(NJOBS) -C $(buildd_shared) \ +# libpython$(VER).so + : # build a static library with PIC objects + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + LIBRARY=libpython$(VER)mu-pic.a libpython$(VER)mu-pic.a + touch stamps/stamp-build-shared + +stamps/stamp-build-debug: stamps/stamp-configure-debug + dh_testdir +# not building with $(NJOBS), see issue #4279 + $(MAKE) -C $(buildd_debug) + touch stamps/stamp-build-debug + +stamps/stamp-build-shared-debug: stamps/stamp-configure-shared-debug + dh_testdir + : # build the shared debug library +# not building with $(NJOBS), see issue #4279 + $(MAKE) -C $(buildd_shdebug) \ + libpython$(VER)dmu.so + touch stamps/stamp-build-shared-debug + +common_configure_args = \ + --prefix=/usr \ + --enable-ipv6 \ + --enable-loadable-sqlite-extensions \ + --with-dbmliborder=bdb \ + --with-wide-unicode \ + --with-computed-gotos \ + --with-system-expat \ + +ifeq ($(DEB_HOST_ARCH), avr32) + common_configure_args += --without-ffi +else + common_configure_args += --with-system-ffi +endif + +ifeq ($(with_fpectl),yes) + common_configure_args += \ + --with-fpectl +endif + +stamps/stamp-configure-shared: stamps/stamp-patch + rm -rf $(buildd_shared) + mkdir -p $(buildd_shared) + cd $(buildd_shared) && \ + CC="$(CC)" $(OPTSETTINGS) \ + ../configure \ + --enable-shared \ + $(common_configure_args) + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(buildd_shared)/Modules/Setup.local + cd $(buildd_shared) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(buildd_shared)/config.c $(buildd_shared)/Modules/ + + @echo XXXXXXX pyconfig.h + -cat $(buildd_shared)/pyconfig.h + 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)" $(OPTSETTINGS) \ + ../configure \ + $(common_configure_args) + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist | sed 's/^#//' \ + >> $(buildd_static)/Modules/Setup.local + cd $(buildd_static) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(buildd_static)/pyconfig.h \ + > $(buildd_static)/pyconfig.h.new + touch -r $(buildd_static)/pyconfig.h $(buildd_static)/pyconfig.h.new + mv -f $(buildd_static)/pyconfig.h.new $(buildd_static)/pyconfig.h + mv $(buildd_static)/config.c $(buildd_static)/Modules/ + + 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)" $(OPTDEBUGSETTINGS) CFLAGS="" CXXFLAGS="" \ + ../configure \ + $(common_configure_args) \ + --with-pydebug + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist | sed 's/^#//' \ + >> $(buildd_debug)/Modules/Setup.local + cd $(buildd_debug) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(buildd_debug)/config.c $(buildd_debug)/Modules/ + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(buildd_debug)/pyconfig.h \ + > $(buildd_debug)/pyconfig.h.new + touch -r $(buildd_debug)/pyconfig.h $(buildd_debug)/pyconfig.h.new + mv -f $(buildd_debug)/pyconfig.h.new $(buildd_debug)/pyconfig.h + + 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)" $(OPTDEBUGSETTINGS) CFLAGS="" CXXFLAGS="" \ + ../configure \ + $(common_configure_args) \ + --enable-shared \ + --with-pydebug + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(buildd_shdebug)/Modules/Setup.local + cd $(buildd_shdebug) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(buildd_shdebug)/config.c $(buildd_shdebug)/Modules/ + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(buildd_shdebug)/pyconfig.h \ + > $(buildd_shdebug)/pyconfig.h.new + touch -r $(buildd_shdebug)/pyconfig.h $(buildd_shdebug)/pyconfig.h.new + mv -f $(buildd_shdebug)/pyconfig.h.new $(buildd_shdebug)/pyconfig.h + + touch stamps/stamp-configure-shared-debug + +stamps/stamp-mincheck: stamps/stamp-build-static debian/PVER-minimal.README.Debian.in + for m in $(MIN_MODS) $(MIN_PACKAGES) $(MIN_EXTS) $(MIN_BUILTINS); do \ + echo "import $$m"; \ + done > $(buildd_static)/minmods.py + cd $(buildd_static) && ./python ../debian/pymindeps.py minmods.py \ + > $(buildd_static)/mindeps.txt + if [ -x /usr/bin/dot ]; then \ + python debian/depgraph.py < $(buildd_static)/mindeps.txt \ + > $(buildd_static)/mindeps.dot; \ + dot -Tpng -o $(buildd_static)/mindeps.png \ + $(buildd_static)/mindeps.dot; \ + else true; fi + cd $(buildd_static) && ./python ../debian/mincheck.py \ + minmods.py mindeps.txt + touch stamps/stamp-mincheck + +TEST_RESOURCES = all +ifeq ($(on_buildd),yes) + TEST_RESOURCES := $(TEST_RESOURCES),-network,-urlfetch +endif +TESTOPTS = $(NJOBS) -w -u$(TEST_RESOURCES) +TEST_EXCLUDES = +ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_tcl test_codecmaps_cn test_codecmaps_hk \ + test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw \ + test_normalization test_ossaudiodev +endif +ifeq (,$(wildcard /dev/dsp)) + TEST_EXCLUDES += test_linuxaudiodev test_ossaudiodev +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hppa)) + TEST_EXCLUDES += test_fork1 test_multiprocessing test_socketserver test_threading test_wait3 test_wait4 test_gdb +endif +ifneq (,$(filter $(DEB_HOST_ARCH), arm avr32)) + TEST_EXCLUDES += test_ctypes +endif +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 m68k)) + ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_compiler + endif +endif +ifneq (,$(filter $(DEB_HOST_ARCH), sparc sparc64)) + TEST_EXCLUDES += test_gdb +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + TEST_EXCLUDES += test_imaplib test_io test_logging test_random test_signal test_socket test_socketserver test_ssl test_threading test_threadsignals test_threadedtempfile +endif +# issues with 3.2~a4 +TEST_EXCLUDES += test_sysconfig + +ifneq (,$(TEST_EXCLUDES)) + TESTOPTS += -x $(sort $(TEST_EXCLUDES)) +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 ======================================== + + @echo "BEGIN test static" + -time \ + $(SET_LOCPATH) \ + $(MAKE) -C $(buildd_static) test \ + TESTOPTS="$(TESTOPTS)" 2>&1 \ + | tee $(buildd_static)/test_results + @echo "END test static" + @echo "BEGIN test shared" + -time \ + $(SET_LOCPATH) \ + $(MAKE) -C $(buildd_shared) test \ + TESTOPTS="$(TESTOPTS)" 2>&1 \ + | tee $(buildd_shared)/test_results + @echo "END test shared" + ifeq (,$(findstring $(DEB_HOST_ARCH), alpha)) + @echo "BEGIN test debug" + -time \ + $(SET_LOCPATH) \ + $(MAKE) -C $(buildd_debug) test \ + TESTOPTS="$(TESTOPTS)" 2>&1 \ + | tee $(buildd_debug)/test_results + @echo "END test debug" + endif +endif + cp -p $(buildd_static)/test_results debian/ + touch stamps/stamp-check + +stamps/stamp-pystone: + @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=. ./python ../Lib/test/pystone.py + cd $(buildd_shared) \ + && 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" + touch stamps/stamp-pystone + +stamps/stamp-pybench: + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log + +#ifeq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 hppa mips mipsel m68k)) + pybench_options = -C 2 -n 5 -w 4 +#endif + +stamps/stamp-pybenchx: +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=. ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_shared) \ + && 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 $(foreach i,$(MIN_EXTS),$(buildd_static)/build/lib*/$(i).so) \ +# mintest/dynlib/ + cp -p Lib/unittest.py mintest/lib/ + cp -pr Lib/test mintest/lib/ + cp -pr Lib mintest/all-lib + cp -p $(buildd_static)/build/lib*/*.so mintest/all-lib/ + ( \ + echo "import sys"; \ + echo "sys.path = ["; \ + echo " '$(CURDIR)/mintest/lib',"; \ + echo " '$(CURDIR)/mintest/dynlib',"; \ + echo "]"; \ + cat Lib/test/regrtest.py; \ + ) > mintest/lib/test/mintest.py + cd mintest && ./python -E -S lib/test/mintest.py \ + -x test_codecencodings_cn test_codecencodings_hk \ + test_codecencodings_jp test_codecencodings_kr \ + test_codecencodings_tw test_codecs test_multibytecodec \ + +stamps/stamp-doc-html: + dh_testdir + $(MAKE) -C Doc html + touch stamps/stamp-doc-html + +build-doc: stamps/stamp-patch stamps/stamp-build-doc +stamps/stamp-build-doc: stamps/stamp-doc-html + touch stamps/stamp-build-doc + +control-file: + sed -e "s/@PVER@/$(PVER)/g" \ + -e "s/@VER@/$(VER)/g" \ + -e "s/@PYSTDDEP@/$(PYSTDDEP)/g" \ + -e "s/@PRIO@/$(PY_PRIO)/g" \ + -e "s/@MINPRIO@/$(PY_MINPRIO)/g" \ + debian/control.in > debian/control.tmp +ifeq ($(distribution),Ubuntu) + ifneq (,$(findstring ubuntu, $(PKGVERSION))) + m='Ubuntu Core Developers '; \ + sed -i "/^Maintainer:/s/\(.*\)/Maintainer: $$m\nXSBC-Original-\1/" \ + debian/control.tmp + endif +endif + [ -e debian/control ] \ + && cmp -s debian/control debian/control.tmp \ + && rm -f debian/control.tmp && exit 0; \ + mv debian/control.tmp debian/control + + + +clean: control-file + dh_testdir + dh_testroot + $(MAKE) -f debian/rules unpatch + rm -rf stamps .pc + rm -f debian/test_results + + $(MAKE) -C Doc clean + sed 's/^@/#/' Makefile.pre.in | $(MAKE) -f - srcdir=. distclean + rm -rf $(buildd_static) $(buildd_shared) $(buildd_debug) $(buildd_shdebug) + find -name '*.py[co]' | xargs -r rm -f + rm -f Lib/lib2to3/*.pickle + rm -rf locales + rm -rf $(d)-dbg + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ] && [ $$f2 != debian/source.lintian-overrides ]; then \ + rm -f $$f2; \ + fi; \ + done + dh_clean + +stamps/stamp-control: + : # We have to prepare the various control files + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ]; then \ + sed -e "s/@PVER@/$(PVER)/g;s/@VER@/$(VER)/g;s/@SVER@/$(SVER)/g" \ + -e "s/@PRIORITY@/$(PRIORITY)/g" \ + -e "s,@SCRIPTDIR@,/$(scriptdir),g" \ + -e "s,@INFO@,$(info_docs),g" \ + <$$f >$$f2; \ + fi; \ + done + +install: $(build_target) stamps/stamp-install +stamps/stamp-install: stamps/stamp-build control-file stamps/stamp-control + dh_testdir + dh_testroot + dh_clean -k + dh_installdirs + + : # make install into tmp and subsequently move the files into + : # their packages' directories. + install -d $(d)/usr +ifeq ($(with_interp),static) + $(MAKE) -C $(buildd_static) install prefix=$(CURDIR)/$(d)/usr +else + $(MAKE) -C $(buildd_shared) install prefix=$(CURDIR)/$(d)/usr +endif + -find $(d)/usr/lib/python$(VER) -name '*_failed*.so' + find $(d)/usr/lib/python$(VER) -name '*_failed*.so' | xargs -r rm -f + + mkdir -p $(d)/usr/lib/python3 + mv $(d)/usr/lib/python$(VER)/site-packages \ + $(d)/usr/lib/python3/dist-packages + rm -f $(d)/usr/lib/python3/dist-packages/README + + : # remove files, which are not packaged + rm -rf $(d)/usr/lib/python$(VER)/ctypes/macholib + + : # fix some file permissions + chmod a-x $(d)/$(scriptdir)/{runpy,fractions,lib2to3/refactor,tkinter/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 + + mkdir -p $(d)/usr/share/man/man1 + cp -p Misc/python.man $(d)/usr/share/man/man1/python$(VER).1 + 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/{2to3,idle3,pydoc3,python3,python3-config} + rm -f $(d)/usr/lib/pkgconfig/python3.pc + + : # Remove version information from the egg-info file + mv $(d)/$(scriptdir)/lib-dynload/Python-3*.egg-info \ + $(d)/$(scriptdir)/lib-dynload/Python.egg-info + + dh_installdirs -p$(p_lib) \ + $(scriptdir)/config-$(VER)mu \ + usr/share/doc + : # install the shared library + cp -p $(buildd_shared)/libpython$(VER)mu.so.1.0 $(d_lib)/usr/lib/ + ln -sf libpython$(VER)mu.so.1.0 $(d_lib)/usr/lib/libpython$(VER)mu.so.1 + ln -sf ../../libpython$(VER)mu.so \ + $(d_lib)/$(scriptdir)/config-$(VER)mu/libpython$(VER)mu.so + ln -sf libpython$(VER)mu.so \ + $(d_lib)/$(scriptdir)/config-$(VER)mu/libpython$(VER).so + ln -sf $(p_base) $(d_lib)/usr/share/doc/$(p_lib) + + ln -sf libpython$(VER)mu.so.1 $(d)/usr/lib/libpython$(VER)mu.so + +ifeq ($(with_interp),shared) + : # install the statically linked runtime + install -m755 $(buildd_static)/python $(d)/usr/bin/python$(VER)-static +endif + + 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,^RUNSHARED *=.*,RUNSHARED=,' \ + build-shared/Makefile > $(d)/$(scriptdir)/config-$(VER)mu/Makefile + + : # Move the binary and the minimal libraries into $(p_min). + dh_installdirs -p$(p_min) \ + etc/$(PVER) \ + usr/bin \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload \ + $(scriptdir)/config-$(VER)mu \ + usr/include/python$(VER)mu + DH_COMPAT=2 dh_movefiles -p$(p_min) --sourcedir=$(d) \ + usr/bin/python$(VER) \ + usr/bin/python$(VER)mu \ + usr/share/man/man1/python$(VER).1 \ + $(foreach i,$(MIN_MODS),$(scriptdir)/$(i).py) \ + $(foreach i,$(MIN_PACKAGES),$(scriptdir)/$(i)) \ + $(foreach i,$(MIN_ENCODINGS),$(scriptdir)/$(i)) \ + $(scriptdir)/config-$(VER)mu/Makefile \ + $(scriptdir)/site.py \ + usr/include/python$(VER)mu/pyconfig.h + +# $(foreach i,$(MIN_EXTS),$(scriptdir)/lib-dynload/$(i).so) \ +# usr/share/man/man1/python$(VER).1 \ + + ln -sf python$(VER)mu $(d_min)/usr/bin/python$(VER) + : # symlinks for the "old" config directory name + ln -sf config-$(VER)mu $(d_min)/$(scriptdir)/config + + rv=0; \ + for i in $(MIN_EXTS); do \ + if [ -f $(d)/$(scriptdir)/lib-dynload/$$i.so ]; then \ + echo >&2 "extension $$i not mentioned in Setup.dist"; \ + rv=1; \ + fi; \ + done; \ + exit $$rv; + + : # Install sitecustomize.py. + cp -p debian/sitecustomize.py $(d_min)/etc/$(PVER)/ + dh_link -p$(p_min) /etc/$(PVER)/sitecustomize.py \ + /$(scriptdir)/sitecustomize.py + + : # Move the static library and the header files into $(p_dev). +# mv $(d)/usr/share/include/python$(VER)/* $(d)/usr/include/python$(VER)/. +# rm -rf $(d)/usr/share/include + dh_installdirs -p$(p_dev) \ + usr/share/doc/python$(VER) \ + $(scriptdir) \ + $(scriptdir)/doc/html \ + usr/include \ + usr/lib + cp -p Misc/HISTORY Misc/README.valgrind Misc/gdbinit \ + debian/README.maintainers \ + debian/test_results $(buildd_static)/pybench.log \ + $(d_dev)/usr/share/doc/python$(VER)/ + + DH_COMPAT=2 dh_movefiles -p$(p_dev) --sourcedir=$(d) \ + usr/lib/python$(VER)/config-$(VER)mu \ + usr/include/python$(VER)mu \ + usr/lib/libpython$(VER)mu.so \ + usr/lib/pkgconfig/python-$(VER)*.pc \ + usr/bin/python$(VER)*-config \ + usr/lib/python$(VER)/distutils/command/wininst-*.exe + + cp -p $(buildd_shared)/libpython$(VER)mu-pic.a \ + $(d_dev)/usr/lib/python$(VER)/config-$(VER)mu/ + + : # symlinks for the "old" include directory name + ln -sf python$(VER)mu $(d_dev)/usr/include/python$(VER) + +ifeq ($(with_tk),yes) + : # Move the Tkinter files into $(p_tk). + dh_installdirs -p$(p_tk) \ + $(scriptdir) \ + usr/lib/python$(VER)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_tk) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/_tkinter*.so +endif + +# : # The test framework into $(p_base), regression tests dropped + DH_COMPAT=2 dh_movefiles -p$(p_base) --sourcedir=$(d) \ + $(scriptdir)/test/{regrtest.py,support.py,__init__.py,pystone.py} + rm -rf $(d)/$(scriptdir)/test + rm -rf $(d)/$(scriptdir)/ctypes/test + rm -rf $(d)/$(scriptdir)/bsddb/test + rm -rf $(d)/$(scriptdir)/distutils/tests + rm -rf $(d)/$(scriptdir)/email/test + rm -rf $(d)/$(scriptdir)/importlib/test + rm -rf $(d)/$(scriptdir)/json/tests + rm -rf $(d)/$(scriptdir)/lib2to3/tests + rm -rf $(d)/$(scriptdir)/sqlite3/test + rm -rf $(d)/$(scriptdir)/distutils/tests + rm -rf $(d)/$(scriptdir)/lib2to3/tests + rm -rf $(d)/$(scriptdir)/tkinter/test + rm -rf $(d)/$(scriptdir)/unittest/test + + : # IDLE + mv $(d)/usr/bin/idle$(VER) $(d)/usr/bin/idle-python$(VER) + rm -f $(d)/usr/lib/python$(VER)/idlelib/idle.bat + dh_installdirs -p$(p_idle) \ + usr/bin \ + usr/share/man/man1 + DH_COMPAT=2 dh_movefiles -p$(p_idle) \ + 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 Tools/* $(d_exam)/usr/share/doc/python$(VER)/examples/ + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/{buildbot,msi} + : # 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 + + : # 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 + + : # The rest goes into $(p_base) + mkdir -p $(d)/usr/lib/python3/dist-packages + (cd $(d) && tar cf - .) | (cd $(d_base) && tar xpf -) + rm -f $(d_base)/usr/bin/python + + : # 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 + $(buildd_static)/python debian/mkbinfmt.py $(PVER) \ + > $(d_min)/usr/share/binfmts/$(PVER) + + : # 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 ! -name dist-packages -type d -empty -delete + + : # install debug package + rm -rf $(d)-dbg + $(MAKE) -C $(buildd_debug) install DESTDIR=$(CURDIR)/$(d)-dbg + + dh_installdirs -p$(p_dbg) \ + usr/bin \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload \ + usr/include/$(PVER)dmu \ + usr/lib/pkgconfig \ + 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)dmu + ln -sf python$(VER)dmu $(d_dbg)/usr/bin/$(PVER)-dbg + sed '1s,#!.*python[^ ]*\(.*\),#! $(PY_INTERPRETER)-dbg\1,' \ + $(d)-dbg/usr/bin/$(PVER)-config \ + > $(d_dbg)/usr/bin/$(PVER)dmu-config + chmod 755 $(d_dbg)/usr/bin/$(PVER)dmu-config + ln -sf $(PVER)dmu-config $(d_dbg)/usr/bin/$(PVER)-dbg-config + cp -p $(buildd_debug)/build/lib*/*.so \ + $(d_dbg)/$(scriptdir)/lib-dynload/ + cp -p $(buildd_shdebug)/libpython$(VER)dmu.so.1.0 $(d_dbg)/usr/lib/ + ln -sf libpython$(VER)dmu.so.1.0 $(d_dbg)/usr/lib/libpython$(VER)dmu.so.1 + ln -sf libpython$(VER)dmu.so.1 $(d_dbg)/usr/lib/libpython$(VER)dmu.so + sed -e '/^Libs:/s,-lpython$(VER),-lpython$(VER)dmu,' \ + -e '/^Cflags:/s,python$(VER),python$(VER)_d,' \ + $(d)-dbg/usr/lib/pkgconfig/python-$(VER).pc \ + > $(d_dbg)/usr/lib/pkgconfig/python-$(VER)-dbg.pc +ifneq ($(with_tk),yes) + rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_tkinter*.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_tkinter*.so +endif +ifneq ($(with_gdbm),yes) + rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_gdbm*.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_gdbm*.so +endif + + cp -a $(d)-dbg/$(scriptdir)/config-$(VER)dmu $(d_dbg)/$(scriptdir)/ + ln -sf ../../libpython$(VER)dmu.so \ + $(d_dbg)/$(scriptdir)/config-$(VER)dmu/libpython$(VER)dmu.so + ln -sf libpython$(VER)dmu.so \ + $(d_dbg)/$(scriptdir)/config-$(VER)dmu/libpython$(VER).so + ln -sf libpython$(VER)dmu.a \ + $(d_dbg)/$(scriptdir)/config-$(VER)dmu/libpython$(VER).a + + for i in $(d_dev)/usr/include/$(PVER)mu/*; do \ + i=$$(basename $$i); \ + case $$i in pyconfig.h) continue; esac; \ + ln -sf ../$(PVER)mu/$$i $(d_dbg)/usr/include/$(PVER)dmu/$$i; \ + done + cp -p $(buildd_debug)/pyconfig.h $(d_dbg)/usr/include/$(PVER)dmu/ + ln -sf $(PVER).1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg.1.gz + + : # Copy the most important files from $(p_min) into $(p_udeb). + dh_installdirs -p$(p_udeb) \ + etc/$(PVER) \ + usr/bin \ + usr/include/$(PVER)mu \ + $(scriptdir)/lib-dynload \ + $(scriptdir)/config-$(VER)mu + cp -p $(d_min)/usr/bin/python$(VER) $(d_udeb)/usr/bin/ + ln -sf python$(VER)mu $(d_udeb)/usr/bin/python$(VER) + ln -sf python$(VER) $(d_udeb)/usr/bin/python3 + cp -p $(foreach i,$(MIN_MODS),$(d_min)/$(scriptdir)/$(i).py) \ + $(d_udeb)/$(scriptdir)/ + cp -a $(foreach i,$(MIN_PACKAGES),$(d_min)/$(scriptdir)/$(i)) \ + $(d_udeb)/$(scriptdir)/ + cp -p $(foreach i,$(MIN_ENCODINGS),$(d_min)/$(scriptdir)/$(i)) \ + $(d_udeb)/$(scriptdir)/ + cp -p $(d_min)/$(scriptdir)/config-$(VER)mu/Makefile \ + $(d_udeb)/$(scriptdir)/config-$(VER)mu/ + cp -p $(d_min)/usr/include/$(PVER)mu/pyconfig.h \ + $(d_udeb)/usr/include/$(PVER)mu/ + cp -p $(d_min)/$(scriptdir)/site.py $(d_udeb)/$(scriptdir)/ + cp -p debian/sitecustomize.py $(d_udeb)/etc/$(PVER)/ + dh_link -p$(p_udeb) /etc/$(PVER)/sitecustomize.py \ + /$(scriptdir)/sitecustomize.py + + : # symlinks for the "old" include / config directory names + ln -sf python$(VER)dmu $(d_dbg)/usr/include/python$(VER)_d + ln -sf config-$(VER)dmu $(d_dbg)/$(scriptdir)/config_d + + 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: $(install_target) $(build_target) stamps/stamp-build-doc 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 + 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 + + : # devhelp docs + python debian/pyhtml2devhelp.py \ + $(d_doc)/usr/share/doc/$(p_base)/html index.html $(VER) \ + > $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + gzip -9v $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html /usr/share/devhelp/books/$(PVER) + + dh_installdebconf -i $(dh_args) + dh_installexamples -i $(dh_args) + dh_installmenu -i $(dh_args) + -dh_icons -i $(dh_args) || dh_iconcache -i $(dh_args) + dh_installchangelogs -i $(dh_args) + dh_link -i $(dh_args) + dh_compress -i $(dh_args) -X.py -X.cls -X.css -X.txt -X.json -X.js -Xobjects.inv -Xgdbinit + dh_fixperms -i $(dh_args) + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + -find $(d_doc) -name '*.txt' -perm 755 -exec chmod 644 {} \; + + dh_installdeb -i $(dh_args) + dh_gencontrol -i $(dh_args) + dh_md5sums -i $(dh_args) + dh_builddeb -i $(dh_args) + +# Build architecture-dependent files here. +binary-arch: build install + dh_testdir -a + dh_testroot -a +# dh_installdebconf -a + dh_installexamples -a + dh_installmenu -a + -dh_icons -a || dh_iconcache -a +# dh_installmime -a + dh_installchangelogs -a + for i in $(p_dev) $(p_dbg) $(p_lib); do \ + rm -rf debian/$$i/usr/share/doc/$$i; \ + ln -s $(p_base) debian/$$i/usr/share/doc/$$i; \ + done + -find debian ! -perm -200 -print -exec chmod +w {} \; +ifneq ($(with_tk),yes) + rm -f $(d_base)/$(scriptdir)/lib-dynload/_tkinter*.so +endif +ifneq ($(with_gdbm),yes) + rm -f $(d_base)/$(scriptdir)/lib-dynload/_gdbm*.so +endif + + dh_strip -a -N$(p_dbg) -Xdebug -Xdbg --dbg-package=$(p_dbg) + cp Tools/gdb/libpython.py $(d_dbg)/usr/lib/debug/usr/bin/$(PVER)mu-gdb.py + ln -sf $(PVER)-gdb.py $(d_dbg)/usr/lib/debug/usr/bin/$(PVER)-dbg-gdb.py + ln -sf ../bin/$(PVER)mu-gdb.py \ + $(d_dbg)/usr/lib/debug/usr/lib/lib$(PVER)mu.so.1.0-gdb.py + ln -sf ../bin/$(PVER)mu-gdb.py \ + $(d_dbg)/usr/lib/lib$(PVER)dmu.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_dbg) -V '$(p_dbg)' +# don't include the following symbols, found in extensions +# which either can be built as builtin or extension. + sed -ri \ + -e '/^ (PyInit_|_add_one_to_index|asdl_)/d' \ + -e '/^ (PyExpat_XML_|PyExpat_Xml)/d' \ + -e '/^ (ffi_type_|_ctypes_)/d' \ + $(d_lib)/DEBIAN/symbols $(d_dbg)/DEBIAN/symbols + dh_installdeb -a + dh_shlibdeps -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) +old_sphinx := $(shell dpkg --compare-versions $$(dpkg -l python-sphinx | awk '/^ii *python-sphinx/ {print $$3}') lt 1 && echo yes || echo no) + +$(patchdir)/series: $(patchdir)/series.in + cpp -E \ + -D$(distribution) \ + $(if $(filter $(broken_utimes),yes),-DBROKEN_UTIMES) \ + $(if $(filter $(old_sphinx),yes),-DOLD_SPHINX) \ + -Darch_os_$(DEB_HOST_ARCH_OS) -Darch_$(DEB_HOST_ARCH) \ + -o - $(patchdir)/series.in \ + | egrep -v '^(#.*|$$)' > $(patchdir)/series + +patch-stamp: stamps/stamp-patch +patch: stamps/stamp-patch +stamps/stamp-patch: $(patchdir)/series + dh_testdir + 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 $@ + +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 + +update-patches: $(patchdir)/series + export QUILT_PATCHES=$(patchdir); \ + export QUILT_REFRESH_ARGS="--no-timestamps --no-index -pab"; \ + export QUILT_DIFF_ARGS="--no-timestamps --no-index -pab"; \ + while quilt push; do quilt refresh; done + +binary: binary-indep binary-arch + +.PHONY: control-file configure build clean binary-indep binary-arch binary install + +# Local Variables: +# mode: makefile +# end: --- python3.2-3.2.2.orig/debian/libPVER.symbols.i386.in +++ python3.2-3.2.2/debian/libPVER.symbols.i386.in @@ -0,0 +1,6 @@ +libpython@VER@mu.so.1.0 libpython@VER@ #MINVER# +#include "libpython.symbols" + PyModule_Create2@Base @SVER@ + _Py_force_double@Base @SVER@ + _Py_get_387controlword@Base @SVER@ + _Py_set_387controlword@Base @SVER@ --- python3.2-3.2.2.orig/debian/PVER-dbg.postinst.in +++ python3.2-3.2.2/debian/PVER-dbg.postinst.in @@ -0,0 +1,24 @@ +#! /bin/sh -e + +if [ "$1" = configure ]; then + if [ -d /usr/include/@PVER@_d ] && [ ! -h /usr/include/@PVER@_d ]; then + if rmdir /usr/include/@PVER@_d 2> /dev/null; then + ln -sf @PVER@dmu /usr/include/@PVER@_d + else + echo >&2 "WARNING: non-empty directory on upgrade: /usr/include/@PVER@_d" + ls -l /usr/include/@PVER@_d + fi + fi + if [ -d /usr/lib/@PVER@/config_d ] && [ ! -h /usr/lib/@PVER@/config_d ]; then + if rmdir /usr/lib/@PVER@/config_d 2> /dev/null; then + ln -sf config-dmu /usr/lib/@PVER@/config_d + else + echo >&2 "WARNING: non-empty directory on upgrade: /usr/lib/@PVER@/config_d" + ls -l /usr/lib/@PVER@/config_d + fi + fi +fi + +#DEBHELPER# + +exit 0 --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-doc.in +++ python3.2-3.2.2/debian/PVER-doc.doc-base.PVER-doc.in @@ -0,0 +1,19 @@ +Document: @PVER@-doc +Title: Documenting Python (v@VER@) +Author: Fred L. Drake, Jr. +Abstract: The Python language has a substantial body of documentation, much + of it contributed by various authors. The markup used for the Python + documentation is based on LATEX and requires a significant set of + macros written specifically for documenting Python. This document + describes the macros introduced to support Python documentation and + how they should be used to support a wide range of output formats. + . + This document describes the document classes and special markup used + in the Python documentation. Authors may use this guide, in + conjunction with the template files provided with the distribution, + to create or maintain whole documents or sections. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/documenting/index.html +Files: /usr/share/doc/@PVER@/html/documenting/*.html --- python3.2-3.2.2.orig/debian/changelog.shared +++ python3.2-3.2.2/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%. --- python3.2-3.2.2.orig/debian/source.lintian-overrides +++ python3.2-3.2.2/debian/source.lintian-overrides @@ -0,0 +1,2 @@ +# generated during the build +python3.2 source: quilt-build-dep-but-no-series-file --- python3.2-3.2.2.orig/debian/PVER.prerm.in +++ python3.2-3.2.2/debian/PVER.prerm.in @@ -0,0 +1,38 @@ +#! /bin/sh -e +# +# prerm script for the Debian @PVER@-base package. +# Written 1998 by Gregor Hoffleit . +# + +remove_bytecode() +{ + pkg=$1 + max=$(LANG=C LC_ALL=C xargs --show-limits < /dev/null 2>&1 | awk '/Maximum/ {print int($NF / 4)}') + dpkg -L $pkg \ + | awk -F/ 'BEGIN {OFS="/"} /\.py$/ {$NF=sprintf("__pycache__/%s.*.py[co]", substr($NF,1,length($NF)-3)); print}' \ + | xargs --max-chars="$max" echo \ + | while read files; do rm -f $files; done + find /usr/lib/python3 /usr/lib/@PVER@ -name dist-packages -prune -o -name __pycache__ -empty -print \ + | xargs -r rm -rf +} + +case "$1" in + remove|upgrade) + remove_bytecode @PVER@ + oldlocalsite=/usr/local/lib/@PVER@/site-packages + # issue #623057 + if [ -d $oldlocalsite -a ! -h $oldlocalsite ]; then + rmdir --ignore-fail-on-non-empty $oldlocalsite 2>/dev/null || true + fi + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python3.2-3.2.2.orig/debian/control.in +++ python3.2-3.2.2/debian/control.in @@ -0,0 +1,125 @@ +Source: @PVER@ +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5.0.51~), quilt, autoconf, libreadline-dev, libncursesw5-dev (>= 5.3), zlib1g-dev, libdb5.1-dev, tk8.5-dev, blt-dev (>= 2.4z), libssl-dev, sharutils, libbz2-dev, libexpat1-dev, libbluetooth-dev [linux-any], locales [!armel !avr32 !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [linux-any], netbase, bzip2, gdb, python +Build-Depends-Indep: python-sphinx +Build-Conflicts: autoconf2.13 +XS-Python-Version: @VER@ +Standards-Version: 3.9.2 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg@VER@-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg@VER@-debian + +Package: @PVER@ +Architecture: any +Priority: @PRIO@ +Depends: @PVER@-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: @PVER@-doc, binutils +Provides: python@VER@-cjkcodecs, python@VER@-ctypes, python@VER@-elementtree, python@VER@-celementtree, python@VER@-wsgiref, @PVER@-gdbm, @PVER@-profiler +Conflicts: python3-profiler (<= 3.2-2) +Replaces: python3-profiler (<= 3.2-2) +XB-Python-Version: @VER@ +Description: Interactive high-level object-oriented language (version @VER@) + Version @VER@ of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: @PVER@-minimal +Architecture: any +Priority: @MINPRIO@ +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: @PVER@ +Suggests: binfmt-support +Replaces: @PVER@ (<< 3.2~b2-1~) +Conflicts: binfmt-support (<< 1.1.2) +XB-Python-Runtime: @PVER@ +XB-Python-Version: @VER@ +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@ +Architecture: any +Section: libs +Priority: @PRIO@ +Depends: @PVER@ (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 3.0~rc1) +Description: Shared Python runtime library (version @VER@) + Version @VER@ of the high-level, interactive object oriented language, + 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 +Depends: @PVER@ (= ${binary:Version}), lib@PVER@ (= ${binary:Version}), libssl-dev, libexpat1-dev, ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 3.2~rc1-2) +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. + +Package: idle-@PVER@ +Architecture: all +Depends: @PVER@, python3-tk, @PVER@-tk, ${misc:Depends} +Enhances: @PVER@ +XB-Python-Version: @VER@ +Description: IDE for Python (v@VER@) using Tkinter + IDLE is an Integrated Development Environment for Python (v@VER@). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: @PVER@-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: @PVER@ +Description: Documentation for the high-level object-oriented language Python (v@VER@) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v@VER@). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python@VER@ + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: @PVER@-dbg +Section: debug +Architecture: any +Priority: extra +Depends: @PVER@ (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends}, python +Suggests: python3-gdbm-dbg, python3-tk-dbg +Description: Debug Build of the Python Interpreter (version @VER@) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/@PVER@/lib-dynload/debug first. + +Package: @PVER@-udeb +XC-Package-Type: udeb +Section: debian-installer +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +XB-Python-Runtime: @PVER@ +XB-Python-Version: @VER@ +Description: A minimal subset of the Python language (version @VER@) + This package contains the interpreter and some essential modules, packaged + for use in the installer. --- python3.2-3.2.2.orig/debian/PVER-examples.overrides.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/PVER-dev.postinst.in +++ python3.2-3.2.2/debian/PVER-dev.postinst.in @@ -0,0 +1,24 @@ +#! /bin/sh -e + +if [ "$1" = configure ]; then + if [ -d /usr/include/@PVER@ ] && [ ! -h /usr/include/@PVER@ ]; then + if rmdir /usr/include/@PVER@ 2> /dev/null; then + ln -sf @PVER@mu /usr/include/@PVER@ + else + echo >&2 "WARNING: non-empty directory on upgrade: /usr/include/@PVER@" + ls -l /usr/include/@PVER@ + fi + fi + if [ -d /usr/lib/@PVER@/config ] && [ ! -h /usr/lib/@PVER@/config ]; then + if rmdir /usr/lib/@PVER@/config 2> /dev/null; then + ln -sf config-@VER@mu /usr/lib/@PVER@/config + else + echo >&2 "WARNING: non-empty directory on upgrade: /usr/lib/@PVER@/config" + ls -l /usr/lib/@PVER@/config + fi + fi +fi + +#DEBHELPER# + +exit 0 --- python3.2-3.2.2.orig/debian/idle-PVER.postinst.in +++ python3.2-3.2.2/debian/idle-PVER.postinst.in @@ -0,0 +1,30 @@ +#! /bin/sh -e +# +# postinst script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +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 --- python3.2-3.2.2.orig/debian/README.maintainers.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/control.stdlib +++ python3.2-3.2.2/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. + --- python3.2-3.2.2.orig/debian/depgraph.py +++ python3.2-3.2.2/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() + + + --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/changelog +++ python3.2-3.2.2/debian/changelog @@ -0,0 +1,2265 @@ +python3.2 (3.2.2-2ubuntu3) precise; urgency=low + + * Avoid python3 in the build dependencies. + + -- Matthias Klose Mon, 19 Dec 2011 12:31:21 +0100 + +python3.2 (3.2.2-2ubuntu2) precise; urgency=low + + * Fix python3 symlinks in the udeb. + + -- Matthias Klose Mon, 19 Dec 2011 12:15:06 +0100 + +python3.2 (3.2.2-2ubuntu1) precise; urgency=low + + * Update to 20111218 from the 3.2 branch. + * Add an udeb (Colin Watson). + + -- Matthias Klose Mon, 19 Dec 2011 00:25:38 +0100 + +python3.2 (3.2.2-2) unstable; urgency=low + + * Update platform patches (alpha, hppa, mips, sparc). + + -- Matthias Klose Fri, 02 Dec 2011 10:24:05 +0100 + +python3.2 (3.2.2-1) unstable; urgency=low + + * Python 3.2.2 release. + * Update to 20111201 from the 3.2 branch. + * Search headers in /usr/include/ncursesw for the curses/panel extensions. + * New patch, ctypes-arm, allow for ",hard-float" after libc6 in ldconfig -p + output (Loic Minier). LP: #898172. + + -- Matthias Klose Thu, 01 Dec 2011 13:19:16 +0100 + +python3.2 (3.2.2~rc1-1) unstable; urgency=low + + * Python 3.2.2 release candidate 1. + + -- Matthias Klose Sun, 14 Aug 2011 20:25:35 +0200 + +python3.2 (3.2.1-2) unstable; urgency=low + + * Update to 20110803 from the 3.2 branch. + * Revert previous change to treat Linux 3.x as Linux 2. Use the + plat-linux3 directory instead. + * Use linux-any for some build dependencies. Closes: #634310. + + -- Matthias Klose Wed, 03 Aug 2011 15:16:05 +0200 + +python3.2 (3.2.1-1) unstable; urgency=medium + + * Python 3.2.1 release. + * Update lib-argparse patch (Pino Toscano). Closes: #631635. + * Treat Linux 3.x as Linux 2. Closes: #633015. + + -- Matthias Klose Sun, 10 Jul 2011 21:46:36 +0200 + +python3.2 (3.2.1~rc2-1) unstable; urgency=low + + * Python 3.2.1 release candidate 2. + * Add profile/pstats to the python3.2 package, update debian copyright. + * Don't run the benchmark on hurd-i386. + * Disable threading tests on hurd-i386. Closes: #631634. + * Don't add the bsddb multilib path, if already in the standard lib path. + + -- Matthias Klose Mon, 04 Jul 2011 20:27:52 +0200 + +python3.2 (3.2.1~rc1-1) unstable; urgency=low + + * Python 3.2.1 release candidate 1. + * Only enable sphinx-0.x patches when building with sphinx-0.x. + + -- Matthias Klose Wed, 18 May 2011 12:15:47 +0200 + +python3.2 (3.2-4) unstable; urgency=low + + * Update to 20110504 from the 3.2 branch. + * Disable the profiled build on ia64 and m68k. + * Update symbols file for m68k (Thorsten Glaser). + + -- Matthias Klose Wed, 04 May 2011 21:32:08 +0200 + +python3.2 (3.2-3) unstable; urgency=low + + * Update to 20110427 from the 3.2 branch. + - Fix argparse import. Closes: #624277. + * Keep the ssl.PROTOCOL_SSLv2 module constant , just raise an exception + when trying to create a PySSL object. #624127. + * Don't depend on the locale and specific awk implementations in prerm. + Closes: #623466, #620836. + * Remove the old local site directory. Closes: #623057. + + -- Matthias Klose Wed, 27 Apr 2011 20:40:29 +0200 + +python3.2 (3.2-2) unstable; urgency=low + + * Update to 20110419 from the 3.2 branch. + * Re-enable profile-guided builds. + * Build without OpenSSL v2 support. Closes: #622004. + * Force linking the curses module against libncursesw. Closes: #622064. + * Re-enable running the testsuite during the build. + + -- Matthias Klose Tue, 19 Apr 2011 17:54:36 +0200 + +python3.2 (3.2-1) unstable; urgency=low + + * Python 3.2 final release. + + -- Matthias Klose Sun, 20 Feb 2011 19:22:24 +0100 + +python3.2 (3.2~rc3-1) experimental; urgency=low + + * Python 3.2 release candidate 3. + + -- Matthias Klose Mon, 14 Feb 2011 16:12:14 +0100 + +python3.2 (3.2~rc1-2) experimental; urgency=low + + * Fix upgrade of the python3.2-dev package. Closes: #610370. + + -- Matthias Klose Wed, 19 Jan 2011 02:21:19 +0100 + +python3.2 (3.2~rc1-1) experimental; urgency=low + + * Python 3.2 release candidate 1. + + -- Matthias Klose Sun, 16 Jan 2011 22:17:09 +0100 + +python3.2 (3.2~b2-1) experimental; urgency=low + + * Python 3.2 beta2 release. + * Fix FTBFS on hurd-i386 (Pino Toscano). Closes: #606152). + + -- Matthias Klose Tue, 21 Dec 2010 21:23:21 +0100 + +python3.2 (3.2~b1-1) experimental; urgency=low + + * Python 3.2 beta1 release. + * Configure with --enable-loadable-sqlite-extensions. + + -- Matthias Klose Mon, 06 Dec 2010 12:19:09 +0100 + +python3.2 (3.2~a4-2) experimental; urgency=low + + * Fix build failure on the hurd. + + -- Matthias Klose Fri, 26 Nov 2010 06:38:41 +0100 + +python3.2 (3.2~a4-1) experimental; urgency=low + + * Python 3.2 alpha4 release. + * Update to the py3k branch (20101124). + * Move the Makefile into the -min package, required by sysconfig. + Addresses: #603237. + + -- Matthias Klose Wed, 24 Nov 2010 22:20:32 +0100 + +python3.2 (3.2~a3-2) experimental; urgency=low + + * Update to the py3k branch (20101018). + - Issue #10094: Use versioned .so files on GNU/kfreeBSD and the GNU Hurd. + Closes: #600183. + + -- Matthias Klose Mon, 18 Oct 2010 19:34:39 +0200 + +python3.2 (3.2~a3-1) experimental; urgency=low + + * Python 3.2 alpha3 release. + * Make Lib/plat-gnukfreebsd[78] ready for python3. Closes: #597874. + + -- Matthias Klose Tue, 12 Oct 2010 16:13:15 +0200 + +python3.2 (3.2~a2-7) experimental; urgency=low + + * Update to the py3k branch (20100926). + + -- Matthias Klose Sun, 26 Sep 2010 14:41:18 +0200 + +python3.2 (3.2~a2-6) experimental; urgency=low + + * Update to the py3k branch (20100919). + * Update GNU/Hurd patches (Pino Toscano). Closes: #597320. + + -- Matthias Klose Sun, 19 Sep 2010 12:45:14 +0200 + +python3.2 (3.2~a2-5) experimental; urgency=low + + * Update to the py3k branch (20100916). + * Provide Lib/plat-gnukfreebsd[78] (Jakub Wilk). Addresses: #593818. + * Assume working semaphores, don't rely on running kernel for the check. + LP: #630511. + + -- Matthias Klose Thu, 16 Sep 2010 14:41:58 +0200 + +python3.2 (3.2~a2-4) experimental; urgency=low + + * Update to the py3k branch (20100911). + * Add the sysconfig module to python3.2-minimal. + * Remove dist-packages/README. + * Make xargs --show-limits in the maintainer scripts independent from + the locale. + + -- Matthias Klose Sat, 11 Sep 2010 20:59:47 +0200 + +python3.2 (3.2~a2-3) experimental; urgency=low + + * Update to the py3k branch (20100910). + * Disable profile feedback based optimization on armel. + * Add copyright information for expat, libffi and zlib. Sources + for the wininst-* files are in PC/bdist_wininst. Closes: #596276. + * Run the testsuite in parallel, when parallel= is set in DEB_BUILD_OPTIONS. + + -- Matthias Klose Fri, 10 Sep 2010 20:28:16 +0200 + +python3.2 (3.2~a2-2) experimental; urgency=low + + * Fix distutils.sysconfig.get_makefile_name for debug builds. + + -- Matthias Klose Thu, 09 Sep 2010 02:40:11 +0200 + +python3.2 (3.2~a2-1) experimental; urgency=low + + * Python 3.2 alpha2 release. + * Update to the py3k branch (20100908). + * Provide /usr/lib/python3/dist-packages as location for public python + packages. + + -- Matthias Klose Wed, 08 Sep 2010 17:36:06 +0200 + +python3.2 (3.2~a1-1) experimental; urgency=low + + * Python 3.2 alpha1 release. + - Files removed: Lib/profile.py, Lib/pstats.py, PC/icons/source.xar. + * Update to the py3k branch (20100827). + * Fix detection of ffi.h header file. Closes: #591408. + * python3.1-dev: Depend on libssl-dev. LP: #611845. + + -- Matthias Klose Fri, 27 Aug 2010 21:40:31 +0200 + +python3.2 (3.2~~20100707-0ubuntu1) maverick; urgency=low + + * Move the pkgconfig file into the -dev package. + * Update preremoval scripts for __pycache__ layout. + * Run hooks from /usr/share/python3/runtime.d/ + * Update distutils-install-layout and debug-build patches. + + -- Matthias Klose Wed, 07 Jul 2010 12:38:52 +0200 + +python3.2 (3.2~~20100706-0ubuntu1) maverick; urgency=low + + * Test build, taken from the py3k branch (20100706). + * Merge with the python3.1 packaging. + + -- Matthias Klose Tue, 06 Jul 2010 17:10:51 +0200 + +python3.2 (3.2~~20100704-0ubuntu1) maverick; urgency=low + + * Test build, taken from the py3k branch (20100704). + + -- Matthias Klose Sun, 04 Jul 2010 16:04:45 +0200 + +python3.2 (3.2~~20100421-0ubuntu1) lucid; urgency=low + + * Test build, taken from the py3k branch (20100421). + + -- Matthias Klose Wed, 21 Apr 2010 22:04:14 +0200 + +python3.1 (3.1.2+20100703-1) unstable; urgency=low + + * Update to the 3.1 release branch, 20100703. + * Convert internal dpatch system to quilt. + * Update module list for python3-minimal. + + -- Matthias Klose Sat, 03 Jul 2010 14:18:18 +0200 + +python3.1 (3.1.2-3) unstable; urgency=low + + * Update to the 3.1 release branch, 20100508. + * Fix backport of issue #8140. Closes: #578896. + + -- Matthias Klose Sat, 08 May 2010 15:37:35 +0200 + +python3.1 (3.1.2-2) unstable; urgency=low + + * Update to the 3.1 release branch, 20100421. + * Update patch for issue #8032, gdb7 hooks for debugging. + * Fix issue #8233: When run as a script, py_compile.py optionally + takes a single argument `-`. + * Don't build-depend on locales on avr32. + + -- Matthias Klose Wed, 21 Apr 2010 21:12:37 +0200 + +python3.1 (3.1.2-1) unstable; urgency=low + + * Python 3.1.2 release. + * Fix issue #4961: Inconsistent/wrong result of askyesno function in + tkMessageBox with Tcl8.5. LP: #462950. + * Don't complain when /usr/local is not writable on installation. + * Apply proposed patch for issue #8032, gdb7 hooks for debugging. + + -- Matthias Klose Sun, 21 Mar 2010 17:59:49 +0100 + +python3.1 (3.1.2~rc1-2) unstable; urgency=low + + * Update to the 3.1 release branch, 20100316. + * Backport issue #8140: Extend compileall to compile single files. + Add -i option. + + -- Matthias Klose Tue, 16 Mar 2010 02:38:45 +0100 + +python3.1 (3.1.2~rc1-1) unstable; urgency=low + + * Python 3.1.2 release candidate 1. + - Replace the Monty Python audio test file. Closes: #568676. + * Build using libdb4.8-dev. Only used for the dbm extension; the bsddb3 + extension isn't built from the core packages anymore. + + -- Matthias Klose Thu, 11 Mar 2010 17:26:17 +0100 + +python3.1 (3.1.1-3) unstable; urgency=low + + * Update to the 3.1 release branch, 20100119. + * Hurd fixes (Pino Toscano): + - 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). + - hurd-path_max.dpatch (hurd only): change few PATH_MAX occurrences to + MAXPATHLEN (which is defined by the python lib if not defined by the OS). + - cthreads.dpatch: Refresh. + - Exclude the profiled build for hurd. + - Disable six blocking tests from the test suite. + * Don't run the testsuite on armel and hppa until someone figures out + the blocking tests. + + -- Matthias Klose Tue, 19 Jan 2010 22:02:14 +0100 + +python3.1 (3.1.1-2) unstable; urgency=low + + * Update to the 3.1 release branch, 20100116. + * 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. + + -- Matthias Klose Sat, 16 Jan 2010 23:28:05 +0100 + +python3.1 (3.1.1-1) experimental; urgency=low + + * Python 3.1.1 final release. + * Update to the 3.1 release branch, 20091011. + * Remove /usr/local/lib/python3.1 on package removal, if empty. + * Build _hashlib as a builtin. LP: #445530. + * python3.1-doc: Don't compress the sphinx inventory. + * python3.1-doc: Fix jquery.js symlink. LP: #447370. + * Run the benchmark with -C 2 -n 5 -w 4 on all architectures. + * python3.1-dbg: Don't create debug subdirectory in /usr/local. No + separate debug directory needed anymore. + * Fix title of devhelp document. LP: #423551. + + -- Matthias Klose Sun, 11 Oct 2009 22:01:57 +0200 + +python3.1 (3.1-1) experimental; urgency=low + + * Python 3.1 final release. + * Update to the 3.1 release branch, 20090723. + * Add explicit build dependency on tk8.5-dev. + + -- Matthias Klose Thu, 23 Jul 2009 15:20:35 +0200 + +python3.1 (3.1-0ubuntu2) karmic; urgency=low + + * Disable profile feedback based optimization on amd64 (GCC + PR gcov-profile/38292). + + -- Matthias Klose Fri, 24 Jul 2009 16:27:22 +0200 + +python3.1 (3.1-0ubuntu1) karmic; urgency=low + + * Python 3.1 final release. + * Update to the 3.1 release branch, 20090723. + * Add explicit build dependency on tk8.5-dev. + + -- Matthias Klose Thu, 23 Jul 2009 18:52:17 +0200 + +python3.1 (3.1~rc2+20090622-1) experimental; urgency=low + + [Matthias Klose] + * Python 3.1 rc2 release. Closes: #529320. + * Update to the trunk, 20090622, remove patches integrated upstream. + * Configure with --with-fpectl --with-dbmliborder=bdb --with-wide-unicode. + NOTE: The --with-wide-unicode configuration will break most extensions + built with 3.1~a1, but is consistent with python2.x configurations. + * Add symbols files for libpython3.1 and python3.1-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python3.1-minimal to avoid a warning on + startup. + * python3.1-doc: Depend on libjs-jquery, use jquery.js from this package. + Closes: #523485. + * Do not add /usr/lib/pythonXY.zip on sys.path. + * Add symbols files for libpython3.1 and python3.1-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python3.1-minimal to avoid a warning on + startup. + * 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. + * Don't build a profiled binary. Closes: #521811. + + * 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/python3.1/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. + + [Marc Deslauriers] + * debian/pyhtml2devhelp.py: update for sphinx generated documentation. + * debian/rules: re-enable documentation files for devhelp. + + -- Matthias Klose Mon, 22 Jun 2009 16:18:39 +0200 + +python3.1 (3.1~a1+20090322-1) experimental; urgency=low + + * Python 3.1 alpha1 release. + * Update to the trunk, 20090322. + * Update installation schemes: LP: #338395. + - 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. + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * pydoc: Fix detection of local documentation files. + * Build a shared library configured --with-pydebug. LP: #322580. + * Fix some lintian warnings. + + -- Matthias Klose Mon, 23 Mar 2009 00:01:27 +0100 + +python3.1 (3.1~~20090226-1) experimental; urgency=low + + * Python-3.1 snapshot (20090226), upload to experimental. + + -- Matthias Klose Thu, 26 Feb 2009 16:18:41 +0100 + +python3.1 (3.1~~20090222-0ubuntu1) jaunty; urgency=low + + * Python-3.1 snapshot (20090222). + * Build the _dbm extension using the Berkeley DB backend. + + -- Matthias Klose Sun, 22 Feb 2009 12:58:58 +0100 + +python3.0 (3.0.1-0ubuntu4) jaunty; urgency=low + + * Don't build-depend on locales on sparc. Currently not installable. + + -- Matthias Klose Sun, 22 Feb 2009 12:48:38 +0100 + +python3.0 (3.0.1-0ubuntu3) jaunty; urgency=low + + * Update to 20090222 from the release30-maint branch. + + -- Matthias Klose Sun, 22 Feb 2009 11:09:58 +0100 + +python3.0 (3.0.1-0ubuntu2) jaunty; urgency=low + + * Allow docs to be built with Sphinx 0.5.x. + + -- Matthias Klose Tue, 17 Feb 2009 12:58:02 +0100 + +python3.0 (3.0.1-0ubuntu1) jaunty; urgency=low + + * New upstream version. + + -- Matthias Klose Mon, 16 Feb 2009 17:18:23 +0100 + +python3.0 (3.0-0ubuntu2) jaunty; urgency=low + + * Update to 20090213 from the release30-maint branch. + + -- Matthias Klose Fri, 13 Feb 2009 15:49:12 +0100 + +python3.0 (3.0-0ubuntu1) jaunty; urgency=low + + * Final Python-3.0 release. + + -- Matthias Klose Thu, 04 Dec 2008 09:00:09 +0100 + +python3.0 (3.0~rc3-0ubuntu4) jaunty; urgency=low + + * Update to 20081127 from the py3k branch. + * Ensure that all extensions from the -minimal package are statically + linked into the interpreter. LP: #301597. + * Include expat, _elementtree, datetime in -minimal to link + these extensions statically. + + -- Matthias Klose Thu, 27 Nov 2008 08:49:02 +0100 + +python3.0 (3.0~rc3-0ubuntu3) jaunty; urgency=low + + * Ignore errors when running the profile task. + + -- Matthias Klose Sun, 23 Nov 2008 15:50:17 +0100 + +python3.0 (3.0~rc3-0ubuntu2) jaunty; urgency=low + + * Don't run test_ioctl on the buildd, before the buildd chroot is fixed: + Unable to open /dev/tty. + + -- Matthias Klose Sun, 23 Nov 2008 15:28:02 +0100 + +python3.0 (3.0~rc3-0ubuntu1) jaunty; urgency=low + + * Update to the python-3.0 release candidate 3. + + -- Matthias Klose Sun, 23 Nov 2008 13:14:20 +0100 + +python3.0 (3.0~rc1+20081027-0ubuntu1) intrepid; urgency=low + + * Update to 20081027 from the py3k branch. LP: #279227. + * Fix typos and section names in doc-base files. LP: #273344. + * Build a new package libpython3.0. + * For locally installed packages, create a directory + /usr/local/lib/python3.0/dist-packages. This is the default for + installations done with distutils and setuptools. Third party stuff + packaged within the distribution goes to /usr/lib/python3.0/dist-packages. + There is no /usr/lib/python3.0/site-packages in the file system and + on sys.path. No package within the distribution must not install + anything in this location. + * 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 Mon, 27 Oct 2008 23:38:42 +0100 + +python3.0 (3.0~b3+20080915-0ubuntu1) intrepid; urgency=low + + * Update to 20080915 from the py3k branch. + * Build gdbm + + -- Matthias Klose Mon, 15 Sep 2008 23:56:44 +0200 + +python3.0 (3.0~b3-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 3.0 beta3 release. + + -- Matthias Klose Sun, 24 Aug 2008 03:49:26 +0200 + +python3.0 (3.0~b2-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 3.0 beta2 release. + + -- Matthias Klose Thu, 07 Aug 2008 14:57:02 +0000 + +python3.0 (3.0~b1-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 3.0 beta1 release. + + -- Matthias Klose Tue, 15 Jul 2008 16:10:52 +0200 + +python3.0 (3.0~a5+0530-0ubuntu1) intrepid; urgency=low + + * Update to snapshot taken from the py3k branch. + + -- Matthias Klose Thu, 29 May 2008 15:50:55 +0200 + +python3.0 (3.0~a1-0ubuntu2) gutsy; urgency=low + + * Disable running the benchmark. + + -- Matthias Klose Fri, 31 Aug 2007 23:22:34 +0000 + +python3.0 (3.0~a1-0ubuntu1) gutsy; urgency=low + + * First Python-3.0 alpha release. + + -- Matthias Klose Fri, 31 Aug 2007 21:26:21 +0200 + +python2.6 (2.6~alpha~pre1-~0ubuntu1~ppa1) gutsy; urgency=low + + * Snapshot build, an "how to use tilde in version numbers" upload. + * SVN 20070831. + + -- Matthias Klose Fri, 31 Aug 2007 15:56:09 +0200 + +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 --- python3.2-3.2.2.orig/debian/pygettext.1 +++ python3.2-3.2.2/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". --- python3.2-3.2.2.orig/debian/patches/disable-utimes.diff +++ python3.2-3.2.2/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.in ++++ b/configure.in +@@ -2588,7 +2588,7 @@ + setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setuid setvbuf \ + sigaction siginterrupt sigrelse snprintf strftime strlcpy \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ +- truncate uname unsetenv utimes waitpid wait3 wait4 \ ++ truncate uname unsetenv waitpid wait3 wait4 \ + wcscoll wcsftime wcsxfrm _getpty) + + # For some functions, having a definition is not sufficient, since --- python3.2-3.2.2.orig/debian/patches/link-system-expat.diff +++ python3.2-3.2.2/debian/patches/link-system-expat.diff @@ -0,0 +1,22 @@ +# DP: Link with the system expat + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -168,7 +168,7 @@ + #_testcapi _testcapimodule.c # Python C API test module + #_random _randommodule.c # Random number generator + #atexit atexitmodule.c # Register functions to be run at interpreter-shutdown +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H _elementtree.c # elementtree accelerator ++#_elementtree -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #_datetime _datetimemodule.c # datetime accelerator + #_bisect _bisectmodule.c # Bisection algorithms +@@ -364,7 +364,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 ++#pyexpat pyexpat.c -lexpat + + # Hye-Shik Chang's CJKCodecs + --- python3.2-3.2.2.orig/debian/patches/site-locations.diff +++ python3.2-3.2.2/debian/patches/site-locations.diff @@ -0,0 +1,46 @@ +# DP: Set site-packages/dist-packages + +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -6,13 +6,19 @@ + + This will append site-specific paths to the module search path. On + Unix (including Mac OSX), it starts with sys.prefix and +-sys.exec_prefix (if different) and appends +-lib/python/site-packages as well as lib/site-python. ++sys.exec_prefix (if different) and appends lib/python3/dist-packages, ++lib/python/dist-packages as well as lib/site-python. + On other platforms (such as Windows), it tries each of the + prefixes directly, as well as with lib/site-packages appended. The + 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/python3/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 +@@ -285,10 +291,17 @@ + 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", ++ "python3", ++ "dist-packages")) ++ # this one is deprecated for Debian + sitepackages.append(os.path.join(prefix, "lib", + "python" + sys.version[:3], +- "site-packages")) +- sitepackages.append(os.path.join(prefix, "lib", "site-python")) ++ "dist-packages")) ++ sitepackages.append(os.path.join(prefix, "lib", "dist-python")) + else: + sitepackages.append(prefix) + sitepackages.append(os.path.join(prefix, "lib", "site-packages")) --- python3.2-3.2.2.orig/debian/patches/statvfs-f_flag-constants.diff +++ python3.2-3.2.2/debian/patches/statvfs-f_flag-constants.diff @@ -0,0 +1,55 @@ +# DP: Modules/posixmodule.c: Add flags for statvfs.f_flag to constant list. + +From: Peter Jones +Date: Wed, 6 Jan 2010 15:22:38 -0500 +Subject: [PATCH] Add flags for statvfs.f_flag to constant list. + + Modules/posixmodule.c | 37 +++++++++++++++++++++++++++++++++++++ + 1 files changed, 37 insertions(+), 0 deletions(-) + +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -8364,6 +8364,43 @@ + if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1; + #endif /* ST_NOSUID */ + ++ /* 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; --- python3.2-3.2.2.orig/debian/patches/deb-locations.diff +++ python3.2-3.2.2/debian/patches/deb-locations.diff @@ -0,0 +1,26 @@ +# DP: adjust locations of directories to debian policy + +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -32,6 +32,10 @@ + + Module docs for core modules are assumed to be in + ++ /usr/share/doc/pythonX.Y/html/library ++ ++if the pythonX.Y-doc package is installed or in ++ + http://docs.python.org/X.Y/library/ + + This can be overridden by setting the PYTHONDOCS environment variable +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -316,7 +316,7 @@ + These are subject to difference depending on local installation + conventions; ${prefix} and ${exec_prefix} are installation-dependent + and should be interpreted as for GNU software; they may be the same. +-The default for both is \fI/usr/local\fP. ++On Debian GNU/{Hurd,Linux} the default for both is \fI/usr\fP. + .IP \fI${exec_prefix}/bin/python\fP + Recommended location of the interpreter. + .PP --- python3.2-3.2.2.orig/debian/patches/doc-build.diff +++ python3.2-3.2.2/debian/patches/doc-build.diff @@ -0,0 +1,38 @@ +# DP: Allow docs to be built with Sphinx 0.5.x. + +--- a/Doc/tools/sphinxext/pyspecific.py ++++ b/Doc/tools/sphinxext/pyspecific.py +@@ -171,8 +171,15 @@ + from docutils.io import StringOutput + from docutils.utils import new_document + +-from sphinx.builders import Builder +-from sphinx.writers.text import TextWriter ++try: ++ from sphinx.builders import Builder ++except ImportError: ++ from sphinx.builder import Builder ++ ++try: ++ from sphinx.writers.text import TextWriter ++except ImportError: ++ from sphinx.textwriter import TextWriter + + + class PydocTopicsBuilder(Builder): +--- a/Doc/tools/sphinxext/suspicious.py ++++ b/Doc/tools/sphinxext/suspicious.py +@@ -47,7 +47,12 @@ + import sys + + from docutils import nodes +-from sphinx.builders import Builder ++ ++try: ++ from sphinx.builders import Builder ++except ImportError: ++ from sphinx.builder import Builder ++ + + detect_all = re.compile(r''' + ::(?=[^=])| # two :: (but NOT ::=) --- python3.2-3.2.2.orig/debian/patches/plat-linux2_sparc.diff +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/patches/bdist-wininst-notfound.diff +++ python3.2-3.2.2/debian/patches/bdist-wininst-notfound.diff @@ -0,0 +1,17 @@ +# DP: suggest installation of the pythonX.Y-dev package, if bdist_wininst +# DP: cannot find the wininst-* files. + +--- a/Lib/distutils/command/bdist_wininst.py ++++ b/Lib/distutils/command/bdist_wininst.py +@@ -340,7 +340,10 @@ + sfix = '' + + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) +- f = open(filename, "rb") ++ try: ++ f = open(filename, "rb") ++ except IOError as e: ++ raise DistutilsFileError(str(e) + ', please install the python%s-dev package' % sys.version[:3]) + try: + return f.read() + finally: --- python3.2-3.2.2.orig/debian/patches/doc-faq.dpatch +++ python3.2-3.2.2/debian/patches/doc-faq.dpatch @@ -0,0 +1,52 @@ +#! /bin/sh -e + +# DP: Mention the FAQ on the documentation index page. + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Doc/html/index.html.in~ 2002-04-01 18:11:27.000000000 +0200 ++++ Doc/html/index.html.in 2003-04-05 13:33:35.000000000 +0200 +@@ -123,6 +123,24 @@ + + + ++ ++ ++   ++

++ ++ ++   ++ ++ ++ + + +

--- python3.2-3.2.2.orig/debian/patches/hurd-path_max.diff +++ python3.2-3.2.2/debian/patches/hurd-path_max.diff @@ -0,0 +1,89 @@ +# DP: Replace PATH_MAX with MAXPATHLEN. + +--- a/Python/pythonrun.c ++++ b/Python/pythonrun.c +@@ -680,7 +680,7 @@ + } + + static wchar_t *default_home = NULL; +-static wchar_t env_home[PATH_MAX+1]; ++static wchar_t env_home[MAXPATHLEN+1]; + + void + Py_SetPythonHome(wchar_t *home) +@@ -695,8 +695,8 @@ + if (home == NULL && !Py_IgnoreEnvironmentFlag) { + char* chome = Py_GETENV("PYTHONHOME"); + if (chome) { +- size_t r = mbstowcs(env_home, chome, PATH_MAX+1); +- if (r != (size_t)-1 && r <= PATH_MAX) ++ size_t r = mbstowcs(env_home, chome, MAXPATHLEN+1); ++ if (r != (size_t)-1 && r <= MAXPATHLEN) + home = env_home; + } + +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1804,7 +1804,7 @@ + #else /* All other filename syntaxes */ + if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) { + #if defined(HAVE_REALPATH) +- if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) { ++ if (_Py_wrealpath(argv0, fullpath, MAXPATHLEN)) { + argv0 = fullpath; + } + #endif +--- a/Python/fileutils.c ++++ b/Python/fileutils.c +@@ -1,4 +1,5 @@ + #include "Python.h" ++#include "osdefs.h" + #ifdef MS_WINDOWS + # include + #endif +@@ -325,7 +326,7 @@ + _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) + { + char *cpath; +- char cbuf[PATH_MAX]; ++ char cbuf[MAXPATHLEN]; + wchar_t *wbuf; + int res; + size_t r1; +@@ -335,11 +336,11 @@ + errno = EINVAL; + return -1; + } +- res = (int)readlink(cpath, cbuf, PATH_MAX); ++ res = (int)readlink(cpath, cbuf, MAXPATHLEN); + PyMem_Free(cpath); + if (res == -1) + return -1; +- if (res == PATH_MAX) { ++ if (res == MAXPATHLEN) { + errno = EINVAL; + return -1; + } +@@ -370,7 +371,7 @@ + wchar_t *resolved_path, size_t resolved_path_size) + { + char *cpath; +- char cresolved_path[PATH_MAX]; ++ char cresolved_path[MAXPATHLEN]; + wchar_t *wresolved_path; + char *res; + size_t r; +@@ -409,11 +410,11 @@ + #ifdef MS_WINDOWS + return _wgetcwd(buf, size); + #else +- char fname[PATH_MAX]; ++ char fname[MAXPATHLEN]; + wchar_t *wname; + size_t len; + +- if (getcwd(fname, PATH_MAX) == NULL) ++ if (getcwd(fname, MAXPATHLEN) == NULL) + return NULL; + wname = _Py_char2wchar(fname, &len); + if (wname == NULL) --- python3.2-3.2.2.orig/debian/patches/plat-linux2_mips.diff +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/patches/platform-lsbrelease.diff +++ python3.2-3.2.2/debian/patches/platform-lsbrelease.diff @@ -0,0 +1,41 @@ +# DP: Use /etc/lsb-release to identify the platform. + +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -284,6 +284,10 @@ + id = l[1] + return '', version, id + ++_distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I) ++_release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I) ++_codename_file_re = re.compile("(?:DISTRIB_CODENAME\s*=)\s*(.*)", re.I) ++ + def linux_distribution(distname='', version='', id='', + + supported_dists=_supported_dists, +@@ -308,6 +312,25 @@ + args given as parameters. + + """ ++ # check for the Debian/Ubuntu /etc/lsb-release file first, needed so ++ # that the distribution doesn't get identified as Debian. ++ try: ++ etclsbrel = open("/etc/lsb-release", "rU") ++ 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: --- python3.2-3.2.2.orig/debian/patches/distutils-link.diff +++ python3.2-3.2.2/debian/patches/distutils-link.diff @@ -0,0 +1,18 @@ +# DP: Don't add standard library dirs to library_dirs and runtime_library_dirs. + +--- a/Lib/distutils/unixccompiler.py ++++ b/Lib/distutils/unixccompiler.py +@@ -213,6 +213,13 @@ + runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + ++ # 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 not isinstance(output_dir, (str, type(None))): --- python3.2-3.2.2.orig/debian/patches/plat-gnukfreebsd.diff +++ python3.2-3.2.2/debian/patches/plat-gnukfreebsd.diff @@ -0,0 +1,2480 @@ +# DP: Provide Lib/plat-gnukfreebsd[78]. + +--- /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 = 200809 ++_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 = 199506 ++_POSIX_C_SOURCE = 200112 ++_POSIX_C_SOURCE = 200809 ++__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__ = 200009 ++__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-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 = 200809 ++_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 = 199506 ++_POSIX_C_SOURCE = 200112 ++_POSIX_C_SOURCE = 200809 ++__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__ = 200009 ++__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 = (-9223372036854775807-1) ++INT_FAST32_MIN = (-9223372036854775807-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807) ++INT_FAST32_MAX = (9223372036854775807) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807-1) ++INTPTR_MAX = (9223372036854775807) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807-1) ++PTRDIFF_MAX = (9223372036854775807) ++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 = 9223372036854775807 ++LONG_MAX = 2147483647 ++LONG_MIN = (-LONG_MAX - 1) ++ ++# 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 = 200809 ++_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 = 199506 ++_POSIX_C_SOURCE = 200112 ++_POSIX_C_SOURCE = 200809 ++__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__ = 200009 ++__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 = 1000000 ++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 = 200809 ++_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 = 199506 ++_POSIX_C_SOURCE = 200112 ++_POSIX_C_SOURCE = 200809 ++__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__ = 200009 ++__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 = 200809 ++_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 = 199506 ++_POSIX_C_SOURCE = 200112 ++_POSIX_C_SOURCE = 200809 ++__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__ = 200009 ++__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 = (-9223372036854775807-1) ++INT_FAST32_MIN = (-9223372036854775807-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807) ++INT_FAST32_MAX = (9223372036854775807) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807-1) ++INTPTR_MAX = (9223372036854775807) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807-1) ++PTRDIFF_MAX = (9223372036854775807) ++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 = 9223372036854775807 ++LONG_MAX = 2147483647 ++LONG_MIN = (-LONG_MAX - 1) ++ ++# 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 = 200809 ++_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 = 199506 ++_POSIX_C_SOURCE = 200112 ++_POSIX_C_SOURCE = 200809 ++__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__ = 200009 ++__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 = 1000000 ++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) ++ --- python3.2-3.2.2.orig/debian/patches/ctypes-arm.diff +++ python3.2-3.2.2/debian/patches/ctypes-arm.diff @@ -0,0 +1,32 @@ +--- a/Lib/ctypes/util.py ++++ b/Lib/ctypes/util.py +@@ -206,16 +206,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') + --- python3.2-3.2.2.orig/debian/patches/apport-support.dpatch +++ python3.2-3.2.2/debian/patches/apport-support.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/site.py 2004-07-20 12:28:28.000000000 +1000 ++++ Lib/site.py 2006-11-09 09:28:32.000000000 +1100 +@@ -393,6 +393,14 @@ + # this module is run as a script, because this code is executed twice. + if hasattr(sys, "setdefaultencoding"): + del sys.setdefaultencoding ++ # install the apport exception handler if available ++ try: ++ import apport_python_hook ++ except ImportError: ++ pass ++ else: ++ apport_python_hook.install() ++ + + main() + --- python3.2-3.2.2.orig/debian/patches/no-zip-on-sys.path.diff +++ python3.2-3.2.2/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 +@@ -413,7 +413,9 @@ + wchar_t *path = NULL; + wchar_t *prog = Py_GetProgramName(); + wchar_t argv0_path[MAXPATHLEN+1]; ++#ifdef WITH_ZIP_PATH + wchar_t zip_path[MAXPATHLEN+1]; ++#endif + int pfound, efound; /* 1 if found; -1 if found build directory */ + wchar_t *buf; + size_t bufsz; +@@ -575,6 +577,7 @@ + else + reduce(prefix); + ++#ifdef WITH_ZIP_PATH + wcsncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = L'\0'; + if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ +@@ -587,6 +590,7 @@ + bufsz = wcslen(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, _exec_prefix))) { + if (!Py_FrozenFlag) +@@ -632,7 +636,9 @@ + defpath = delim + 1; + } + ++#ifdef WITH_ZIP_PATH + bufsz += wcslen(zip_path) + 1; ++#endif + bufsz += wcslen(exec_prefix) + 1; + + buf = (wchar_t *)PyMem_Malloc(bufsz*sizeof(wchar_t)); +@@ -652,9 +658,11 @@ + else + buf[0] = '\0'; + ++#ifdef WITH_ZIP_PATH + /* Next is the default zip path */ + wcscat(buf, zip_path); + wcscat(buf, delimiter); ++#endif + + /* Next goes merge of compile-time $PYTHONPATH with + * dynamically located prefix. --- python3.2-3.2.2.orig/debian/patches/doc-nodownload.diff +++ python3.2-3.2.2/debian/patches/doc-nodownload.diff @@ -0,0 +1,13 @@ +# DP: Don't try to download documentation tools + +--- a/Doc/Makefile ++++ b/Doc/Makefile +@@ -58,7 +58,7 @@ + + update: clean checkout + +-build: checkout ++build: + mkdir -p build/$(BUILDER) build/doctrees + $(PYTHON) tools/sphinx-build.py $(ALLSPHINXOPTS) + @echo --- python3.2-3.2.2.orig/debian/patches/cthreads.diff +++ python3.2-3.2.2/debian/patches/cthreads.diff @@ -0,0 +1,39 @@ +# DP: Remove cthreads detection + +--- a/configure.in ++++ b/configure.in +@@ -2046,7 +2046,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, +@@ -2128,17 +2127,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"],[ + # Just looking for pthread_create in libpthread is not enough: + # on HP/UX, pthread.h renames pthread_create to a different symbol name. + # So we really have to include pthread.h, and then link. +@@ -2174,7 +2162,7 @@ + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o"],[ + USE_THREAD_MODULE="#"]) +- ])])])])])])]) ++ ])])])])]) + + AC_CHECK_LIB(mpc, usconfig, [AC_DEFINE(WITH_THREAD) + LIBS="$LIBS -lmpc" --- python3.2-3.2.2.orig/debian/patches/profiled-build.diff +++ python3.2-3.2.2/debian/patches/profiled-build.diff @@ -0,0 +1,17 @@ +# DP: Ignore errors in the profile task. + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -412,10 +412,10 @@ + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" + + run_profile_task: +- ./$(BUILDPYTHON) $(PROFILE_TASK) ++ -./$(BUILDPYTHON) $(PROFILE_TASK) + + build_all_use_profile: +- $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" ++ $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use -fprofile-correction" + + coverage: + @echo "Building with support for coverage checking:" --- python3.2-3.2.2.orig/debian/patches/autoconf-version.diff +++ python3.2-3.2.2/debian/patches/autoconf-version.diff @@ -0,0 +1,18 @@ +# DP: Remove autoconf version check + +--- a/configure.in ++++ b/configure.in +@@ -5,13 +5,6 @@ + # Set VERSION so we only need to edit in one place (i.e., here) + m4_define(PYTHON_VERSION, 3.2) + +-dnl Some m4 magic to ensure that the configure script is generated +-dnl by the correct autoconf version. +-m4_define([version_required], +-[m4_if(m4_version_compare(m4_defn([m4_PACKAGE_VERSION]), [$1]), 0, +- [], +- [m4_fatal([Autoconf version $1 is required for Python], 63)]) +-]) + AC_PREREQ(2.65) + + AC_REVISION($Revision: 88440 $) --- python3.2-3.2.2.orig/debian/patches/revert-r83274.diff +++ python3.2-3.2.2/debian/patches/revert-r83274.diff @@ -0,0 +1,12 @@ +--- a/Doc/conf.py ++++ b/Doc/conf.py +@@ -65,9 +65,6 @@ + # Options for HTML output + # ----------------------- + +-html_theme = 'default' +-html_theme_options = {'collapsiblesidebar': True} +- + # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, + # using the given strftime format. + html_last_updated_fmt = '%b %d, %Y' --- python3.2-3.2.2.orig/debian/patches/revert-r83234.diff +++ python3.2-3.2.2/debian/patches/revert-r83234.diff @@ -0,0 +1,227 @@ +--- a/Doc/conf.py ++++ b/Doc/conf.py +@@ -13,7 +13,7 @@ + # --------------------- + + extensions = ['sphinx.ext.refcounting', 'sphinx.ext.coverage', +- 'sphinx.ext.doctest', 'pyspecific'] ++ 'sphinx.ext.doctest'] + templates_path = ['tools/sphinxext'] + + # General substitutions. +--- a/Doc/tools/sphinxext/pyspecific.py ++++ b/Doc/tools/sphinxext/pyspecific.py +@@ -84,32 +84,6 @@ + return [pnode] + + +-# Support for documenting decorators +- +-from sphinx import addnodes +-from sphinx.domains.python import PyModulelevel, PyClassmember +- +-class PyDecoratorMixin(object): +- def handle_signature(self, sig, signode): +- ret = super(PyDecoratorMixin, self).handle_signature(sig, signode) +- signode.insert(0, addnodes.desc_addname('@', '@')) +- return ret +- +- def needs_arglist(self): +- return False +- +-class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel): +- def run(self): +- # a decorator function is a function after all +- self.name = 'py:function' +- return PyModulelevel.run(self) +- +-class PyDecoratorMethod(PyDecoratorMixin, PyClassmember): +- def run(self): +- self.name = 'py:method' +- return PyClassmember.run(self) +- +- + # Support for documenting version of removal in deprecations + + from sphinx.locale import versionlabels +@@ -227,6 +201,7 @@ + # Support for documenting Opcodes + + import re ++from sphinx import addnodes + + opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?') + +@@ -280,5 +255,3 @@ + app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)', + parse_pdb_command) + app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)') +- app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction) +- app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod) +--- a/Doc/library/contextlib.rst ++++ b/Doc/library/contextlib.rst +@@ -15,7 +15,7 @@ + Functions provided: + + +-.. decorator:: contextmanager ++.. function:: contextmanager(func) + + This function is a :term:`decorator` that can be used to define a factory + function for :keyword:`with` statement context managers, without needing to +--- a/Doc/library/abc.rst ++++ b/Doc/library/abc.rst +@@ -126,7 +126,7 @@ + + It also provides the following decorators: + +-.. decorator:: abstractmethod(function) ++.. function:: abstractmethod(function) + + A decorator indicating abstract methods. + +--- a/Doc/library/unittest.rst ++++ b/Doc/library/unittest.rst +@@ -666,20 +666,20 @@ + + The following decorators implement test skipping and expected failures: + +-.. decorator:: skip(reason) ++.. function:: skip(reason) + + Unconditionally skip the decorated test. *reason* should describe why the + test is being skipped. + +-.. decorator:: skipIf(condition, reason) ++.. function:: skipIf(condition, reason) + + Skip the decorated test if *condition* is true. + +-.. decorator:: skipUnless(condition, reason) ++.. function:: skipUnless(condition, reason) + + Skip the decorated test unless *condition* is true. + +-.. decorator:: expectedFailure ++.. function:: expectedFailure + + Mark the test as an expected failure. If the test fails when run, the test + is not counted as a failure. +@@ -973,11 +973,11 @@ + :attr:`exception` attribute. This can be useful if the intention + is to perform additional checks on the exception raised:: + +- with self.assertRaises(SomeException) as cm: +- do_something() ++ with self.assertRaises(SomeException) as cm: ++ do_something() + +- the_exception = cm.exception +- self.assertEqual(the_exception.error_code, 3) ++ the_exception = cm.exception ++ self.assertEqual(the_exception.error_code, 3) + + .. versionchanged:: 3.1 + Added the ability to use :meth:`assertRaises` as a context manager. +--- a/Doc/library/importlib.rst ++++ b/Doc/library/importlib.rst +@@ -469,7 +469,7 @@ + This module contains the various objects that help in the construction of + an :term:`importer`. + +-.. decorator:: module_for_loader ++.. function:: module_for_loader(method) + + A :term:`decorator` for a :term:`loader` method, + to handle selecting the proper +@@ -494,7 +494,7 @@ + Use of this decorator handles all the details of which module object a + loader should initialize as specified by :pep:`302`. + +-.. decorator:: set_loader ++.. function:: set_loader(fxn) + + A :term:`decorator` for a :term:`loader` method, + to set the :attr:`__loader__` +@@ -502,7 +502,7 @@ + does nothing. It is assumed that the first positional argument to the + wrapped method is what :attr:`__loader__` should be set to. + +-.. decorator:: set_package ++.. function:: set_package(fxn) + + A :term:`decorator` for a :term:`loader` to set the :attr:`__package__` + attribute on the module returned by the loader. If :attr:`__package__` is +--- a/Doc/library/functools.rst ++++ b/Doc/library/functools.rst +@@ -111,7 +111,7 @@ + + .. versionadded:: 3.2 + +-.. decorator:: total_ordering ++.. function:: total_ordering(cls) + + Given a class defining one or more rich comparison ordering methods, this + class decorator supplies the rest. This simplifies the effort involved +@@ -217,7 +217,7 @@ + Missing attributes no longer trigger an :exc:`AttributeError`. + + +-.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) ++.. function:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) + + This is a convenience function for invoking ``partial(update_wrapper, + wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator +--- a/Doc/documenting/markup.rst ++++ b/Doc/documenting/markup.rst +@@ -177,37 +177,6 @@ + are modified), side effects, and possible exceptions. A small example may be + provided. + +-.. describe:: decorator +- +- Describes a decorator function. The signature should *not* represent the +- signature of the actual function, but the usage as a decorator. For example, +- given the functions +- +- .. code-block:: python +- +- def removename(func): +- func.__name__ = '' +- return func +- +- def setnewname(name): +- def decorator(func): +- func.__name__ = name +- return func +- return decorator +- +- the descriptions should look like this:: +- +- .. decorator:: removename +- +- Remove name of the decorated function. +- +- .. decorator:: setnewname(name) +- +- Set name of the decorated function to *name*. +- +- There is no ``deco`` role to link to a decorator that is marked up with +- this directive; rather, use the ``:func:`` role. +- + .. describe:: class + + Describes a class. The signature can include parentheses with parameters +@@ -225,12 +194,6 @@ + parameter. The description should include similar information to that + described for ``function``. + +-.. describe:: decoratormethod +- +- Same as ``decorator``, but for decorators that are methods. +- +- Refer to a decorator method using the ``:meth:`` role. +- + .. describe:: opcode + + Describes a Python :term:`bytecode` instruction. --- python3.2-3.2.2.orig/debian/patches/lib-argparse.diff +++ python3.2-3.2.2/debian/patches/lib-argparse.diff @@ -0,0 +1,23 @@ +# DP: argparse.py: Make the gettext import conditional + +--- a/Lib/argparse.py ++++ b/Lib/argparse.py +@@ -89,7 +89,17 @@ + import sys as _sys + import textwrap as _textwrap + +-from gettext import gettext as _, ngettext ++try: ++ from gettext import gettext as _, ngettext ++except ImportError: ++ def gettext(message): ++ return message ++ _ = gettext ++ def ngettext(msgid1, msgid2, n): ++ if n == 1: ++ return msgid1 ++ else: ++ return msgid2 + + + def _callable(obj): --- python3.2-3.2.2.orig/debian/patches/link-opt.diff +++ python3.2-3.2.2/debian/patches/link-opt.diff @@ -0,0 +1,24 @@ +# DP: Call the linker with -O1 -Bsymbolic-functions + +--- a/configure.in ++++ b/configure.in +@@ -1733,8 +1733,8 @@ + fi + ;; + Linux*|GNU*|QNX*) +- LDSHARED='$(CC) -shared' +- LDCXXSHARED='$(CXX) -shared';; ++ LDSHARED='$(CC) -shared -Wl,-O1 -Wl,-Bsymbolic-functions' ++ LDCXXSHARED='$(CXX) -shared -Wl,-O1 -Wl,-Bsymbolic-functions';; + BSD/OS*/4*) + LDSHARED="gcc -shared" + LDCXXSHARED="g++ -shared";; +@@ -1832,7 +1832,7 @@ + LINKFORSHARED="-Wl,-E -Wl,+s";; + # LINKFORSHARED="-Wl,-E -Wl,+s -Wl,+b\$(BINLIBDEST)/lib-dynload";; + BSD/OS/4*) LINKFORSHARED="-Xlinker -export-dynamic";; +- Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic";; ++ Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + LINKFORSHARED="$extra_undefs -framework CoreFoundation" --- python3.2-3.2.2.orig/debian/patches/setup-modules.diff +++ python3.2-3.2.2/debian/patches/setup-modules.diff @@ -0,0 +1,64 @@ +# DP: Modules/Setup.dist: patches to build some extensions statically + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -168,7 +168,7 @@ + #_testcapi _testcapimodule.c # Python C API test module + #_random _randommodule.c # Random number generator + #atexit atexitmodule.c # Register functions to be run at interpreter-shutdown +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #_datetime _datetimemodule.c # datetime accelerator + #_bisect _bisectmodule.c # Bisection algorithms +@@ -197,10 +197,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). +@@ -243,6 +240,7 @@ + #_sha256 sha256module.c + #_sha512 sha512module.c + ++#_hashlib _hashopenssl.c -lssl -lcrypto + + # The _tkinter module. + # +@@ -331,6 +329,7 @@ + # Fred Drake's interface to the Python parser + #parser parsermodule.c + ++#_ctypes _ctypes/_ctypes.c _ctypes/callbacks.c _ctypes/callproc.c _ctypes/stgdict.c _ctypes/cfield.c _ctypes/malloc_closure.c -Wl,-Bstatic -lffi -Wl,-Bdynamic + + # Lee Busby's SIGFPE modules. + # The library to link fpectl with is platform specific. +@@ -365,7 +364,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 expat/xmlparse.c expat/xmlrole.c expat/xmltok.c pyexpat.c -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H + + # Hye-Shik Chang's CJKCodecs + +--- a/Modules/_elementtree.c ++++ b/Modules/_elementtree.c +@@ -2040,7 +2040,10 @@ + static struct PyExpat_CAPI* expat_capi; + #define EXPAT(func) (expat_capi->func) + #else +-#define EXPAT(func) (XML_##func) ++#define EXPAT(func) (PyExpat_XML_##func) ++#define PyExpat_XML_GetErrorLineNumber PyExpat_XML_GetCurrentLineNumber ++#define PyExpat_XML_GetErrorColumnNumber PyExpat_XML_GetCurrentColumnNumber ++#define PyExpat_XML_GetErrorByteIndex PyExpat_XML_GetCurrentByteIndex + #endif + + typedef struct { --- python3.2-3.2.2.orig/debian/patches/disable-sem-check.diff +++ python3.2-3.2.2/debian/patches/disable-sem-check.diff @@ -0,0 +1,36 @@ +# DP: Assume working semaphores, don't rely on running kernel for the check. + +--- a/configure.in ++++ b/configure.in +@@ -3488,8 +3488,13 @@ + AC_MSG_RESULT($ac_cv_posix_semaphores_enabled) + if test $ac_cv_posix_semaphores_enabled = no + then +- AC_DEFINE(POSIX_SEMAPHORES_NOT_ENABLED, 1, +- [Define if POSIX semaphores aren't enabled on your system]) ++ case $ac_sys_system in ++ Linux*) # assume yes, see https://launchpad.net/bugs/630511 ++ ;; ++ *) ++ AC_DEFINE(POSIX_SEMAPHORES_NOT_ENABLED, 1, ++ [Define if POSIX semaphores aren't enabled on your system]) ++ esac + fi + + # Multiprocessing check for broken sem_getvalue +@@ -3524,8 +3529,13 @@ + AC_MSG_RESULT($ac_cv_broken_sem_getvalue) + if test $ac_cv_broken_sem_getvalue = yes + then +- AC_DEFINE(HAVE_BROKEN_SEM_GETVALUE, 1, +- [define to 1 if your sem_getvalue is broken.]) ++ case $ac_sys_system in ++ Linux*) # assume yes, see https://launchpad.net/bugs/630511 ++ ;; ++ *) ++ AC_DEFINE(HAVE_BROKEN_SEM_GETVALUE, 1, ++ [define to 1 if your sem_getvalue is broken.]) ++ esac + fi + + # determine what size digit to use for Python's longs --- python3.2-3.2.2.orig/debian/patches/no-large-file-support.diff +++ python3.2-3.2.2/debian/patches/no-large-file-support.diff @@ -0,0 +1,14 @@ +# DP: disable large file support for GNU/Hurd + +--- a/configure.in ++++ b/configure.in +@@ -1402,6 +1402,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 --- python3.2-3.2.2.orig/debian/patches/ncursesw-include.diff +++ python3.2-3.2.2/debian/patches/ncursesw-include.diff @@ -0,0 +1,18 @@ +--- a/setup.py ++++ b/setup.py +@@ -1168,6 +1168,7 @@ + panel_library = 'panelw' + curses_libs = [curses_library] + exts.append( Extension('_curses', ['_cursesmodule.c'], ++ include_dirs=['/usr/include/ncursesw'], + libraries = curses_libs) ) + elif curses_library == 'curses' and platform != 'darwin': + # OSX has an old Berkeley curses, not good enough for +@@ -1188,6 +1189,7 @@ + if (module_enabled(exts, '_curses') and + self.compiler.find_library_file(lib_dirs, panel_library)): + exts.append( Extension('_curses_panel', ['_curses_panel.c'], ++ include_dirs=['/usr/include/ncursesw'], + libraries = [panel_library] + curses_libs) ) + else: + missing.append('_curses_panel') --- python3.2-3.2.2.orig/debian/patches/test-sundry.diff +++ python3.2-3.2.2/debian/patches/test-sundry.diff @@ -0,0 +1,17 @@ +# DP: test_sundry: Don't fail on import of the profile and pstats module + +--- a/Lib/test/test_sundry.py ++++ b/Lib/test/test_sundry.py +@@ -50,7 +50,11 @@ + import mailcap + import nturl2path + import os2emxpath +- 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 sndhdr + import tabnanny --- python3.2-3.2.2.orig/debian/patches/linecache.diff +++ python3.2-3.2.2/debian/patches/linecache.diff @@ -0,0 +1,16 @@ +# DP: Proper handling of packages in linecache.py + +--- a/Lib/linecache.py ++++ b/Lib/linecache.py +@@ -109,6 +109,11 @@ + if os.path.isabs(filename): + return [] + ++ # Take care to handle packages. ++ if basename == '__init__.py': ++ # filename referes to a package ++ basename = filename ++ + for dirname in sys.path: + try: + fullname = os.path.join(dirname, basename) --- python3.2-3.2.2.orig/debian/patches/tkinter-import.diff +++ python3.2-3.2.2/debian/patches/tkinter-import.diff @@ -0,0 +1,16 @@ +# DP: suggest installation of python-tk package on failing _tkinter import + +--- a/Lib/tkinter/__init__.py ++++ b/Lib/tkinter/__init__.py +@@ -36,7 +36,10 @@ + if sys.platform == "win32": + # Attempt to configure Tcl/Tk without requiring PATH + from tkinter import _fix +-import _tkinter # If this fails your Python may not be configured for Tk ++try: ++ import _tkinter ++except ImportError as msg: ++ raise ImportError(str(msg) + ', please install the python-tk package') + TclError = _tkinter.TclError + from tkinter.constants import * + --- python3.2-3.2.2.orig/debian/patches/distutils-sysconfig.diff +++ python3.2-3.2.2/debian/patches/distutils-sysconfig.diff @@ -0,0 +1,31 @@ +# DP: Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, +# DP: CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -163,8 +163,9 @@ + varies across Unices and is stored in Python's Makefile. + """ + if compiler.compiler_type == "unix": +- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ ++ (cc, cxx, opt, cflags, extra_cflags, basecflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ + get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', ++ 'EXTRA_CFLAGS', 'BASECFLAGS', + 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS') + + if 'CC' in os.environ: +@@ -179,8 +180,13 @@ + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ if 'BASECFLAGS' in os.environ: ++ basecflags = os.environ['BASECFLAGS'] ++ if 'OPT' in os.environ: ++ opt = os.environ['OPT'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, extra_cflags) if x) + if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] --- python3.2-3.2.2.orig/debian/patches/distutils-install-layout.diff +++ python3.2-3.2.2/debian/patches/distutils-install-layout.diff @@ -0,0 +1,261 @@ +# DP: distutils: Add an option --install-layout=deb, which +# DP: - installs into $prefix/dist-packages instead of $prefix/site-packages. +# DP: - doesn't encode the python version into the egg name. + +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -237,6 +237,8 @@ + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Platform | Standard installation location | Default value | Notes | + +=================+=====================================================+==================================================+=======+ ++| Debian/Ubuntu | :file:`{prefix}/lib/python3/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) | +@@ -246,6 +248,17 @@ + + 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`). ++ ++ Starting with Python3, Debian/Ubuntu use a common installation directory for ++ all Python3 versions. ++ + (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 +@@ -364,6 +377,15 @@ + + /usr/bin/python setup.py install --prefix=/usr/local + ++Starting with Python3 Debian/Ubuntu does use ++:file:`/usr/lib/python3/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 +@@ -602,6 +624,17 @@ + import them, this directory must be added to ``sys.path``. There are several + different ways to add the directory. + ++On Debian/Ubuntu, starting with Python3 the convention for system ++installed packages is to put then in the ++:file:`/usr/lib/python3/dist-packages/` directory, and for locally ++installed packages is to put them in the ++:file:`/usr/local/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/local/lib/python{X.Y}/dist-packages/` a symbolic link to the ++:file:`{...}/site-packages/` directory of your local python ++installation. ++ + The most convenient way is to add a path configuration file to a directory + that's already on Python's path, usually to the :file:`.../site-packages/` + directory. Path configuration files have an extension of :file:`.pth`, and each +--- a/Lib/distutils/command/install_egg_info.py ++++ b/Lib/distutils/command/install_egg_info.py +@@ -14,18 +14,38 @@ + 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: ++ if not self.install_layout.lower() in ['deb', 'unix']: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ no_pyver = (self.install_layout.lower() == 'deb') ++ elif self.prefix_option: ++ no_pyver = False ++ else: ++ no_pyver = True ++ if no_pyver: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) ++ else: ++ 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.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + +--- a/Lib/distutils/command/install.py ++++ b/Lib/distutils/command/install.py +@@ -52,6 +52,20 @@ + 'scripts': '$base/bin', + 'data' : '$base', + }, ++ 'unix_local': { ++ 'purelib': '$base/local/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/local/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/local/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/local/bin', ++ 'data' : '$base/local', ++ }, ++ 'deb_system': { ++ 'purelib': '$base/lib/python3/dist-packages', ++ 'platlib': '$platbase/lib/python3/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', +@@ -163,6 +177,9 @@ + + ('record=', None, + "filename in which to record list of installed files"), ++ ++ ('install-layout=', None, ++ "installation layout to choose (known values: deb, unix)"), + ] + + boolean_options = ['compile', 'force', 'skip-build'] +@@ -183,6 +200,7 @@ + self.exec_prefix = None + self.home = None + self.user = 0 ++ self.prefix_option = None + + # These select only the installation base; it's up to the user to + # specify the installation scheme (currently, that means supplying +@@ -204,6 +222,9 @@ + self.install_userbase = USER_BASE + self.install_usersite = USER_SITE + ++ # enable custom installation, known values: deb ++ self.install_layout = None ++ + self.compile = None + self.optimize = None + +@@ -443,6 +464,7 @@ + self.install_base = self.install_platbase = self.home + self.select_scheme("unix_home") + else: ++ self.prefix_option = self.prefix + if self.prefix is None: + if self.exec_prefix is not None: + raise DistutilsOptionError( +@@ -457,7 +479,23 @@ + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix +- self.select_scheme("unix_prefix") ++ if self.install_layout: ++ if self.install_layout.lower() in ['deb']: ++ self.select_scheme("deb_system") ++ elif self.install_layout.lower() in ['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.prefix = self.exec_prefix = '/usr' ++ self.install_base = self.install_platbase = '/usr' ++ self.select_scheme("unix_local") + + def finalize_other(self): + """Finalizes options for non-posix platforms""" +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -120,6 +120,7 @@ + If 'prefix' is supplied, use it instead of sys.prefix or + sys.exec_prefix -- i.e., ignore 'plat_specific'. + """ ++ is_default_prefix = not prefix or os.path.normpath(prefix) in ('/usr', '/usr/local') + if prefix is None: + prefix = plat_specific and EXEC_PREFIX or PREFIX + +@@ -128,6 +129,8 @@ + "lib", "python" + get_python_version()) + if standard_lib: + return libpython ++ elif is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__: ++ return os.path.join(prefix, "lib", "python3", "dist-packages") + else: + return os.path.join(libpython, "site-packages") + elif os.name == "nt": +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -270,6 +270,13 @@ + + if ENABLE_USER_SITE and os.path.isdir(user_site): + addsitedir(user_site, known_paths) ++ if ENABLE_USER_SITE: ++ for dist_libdir in ("lib", "local/lib"): ++ user_site = os.path.join(USER_BASE, dist_libdir, ++ "python" + sys.version[:3], ++ "dist-packages") ++ if os.path.isdir(user_site): ++ addsitedir(user_site, known_paths) + return known_paths + + def getsitepackages(): +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -32,6 +32,26 @@ + 'scripts': '{base}/bin', + 'data': '{base}', + }, ++ 'posix_local': { ++ 'stdlib': '{base}/local/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/local/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/python3/dist-packages', ++ 'platlib': '{platbase}/lib/python3/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', --- python3.2-3.2.2.orig/debian/patches/plat-linux2_hppa.diff +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/patches/hg-updates.diff +++ python3.2-3.2.2/debian/patches/hg-updates.diff @@ -0,0 +1,24291 @@ +# DP: hg updates of the 3.2 release branch (until 2011-12-18). + +# hg diff -r v3.2.2 | filterdiff --exclude=Lib/pstats.py --exclude=Lib/profile.py --exclude=.hgignore --exclude=.hgeol --exclude=.hgtags --remove-timestamps + +diff -r 137e45f15c0b Doc/ACKS.txt +--- a/Doc/ACKS.txt ++++ b/Doc/ACKS.txt +@@ -33,6 +33,7 @@ + * Keith Briggs + * Ian Bruntlett + * Lee Busby ++ * Arnaud Calmettes + * Lorenzo M. Catucci + * Carl Cerecke + * Mauro Cicognini +@@ -57,6 +58,7 @@ + * Carl Feynman + * Dan Finnie + * Hernán Martínez Foffani ++ * Michael Foord + * Stefan Franke + * Jim Fulton + * Peter Funk +@@ -144,6 +146,7 @@ + * Ross Moore + * Sjoerd Mullender + * Dale Nagata ++ * Trent Nelson + * Michal Nowikowski + * Steffen Daode Nurpmeso + * Ng Pheng Siong +@@ -186,6 +189,7 @@ + * Joakim Sernbrant + * Justin Sheehy + * Charlie Shepherd ++ * Yue Shuaijie + * SilentGhost + * Michael Simcich + * Ionel Simionescu +@@ -222,6 +226,7 @@ + * Collin Winter + * Blake Winton + * Dan Wolfe ++ * Adam Woodbeck + * Steven Work + * Thomas Wouters + * Ka-Ping Yee +@@ -229,5 +234,3 @@ + * Moshe Zadka + * Milan Zamazal + * Cheng Zhang +- * Trent Nelson +- * Michael Foord +diff -r 137e45f15c0b Doc/bugs.rst +--- a/Doc/bugs.rst ++++ b/Doc/bugs.rst +@@ -57,12 +57,14 @@ + + Each bug report will be assigned to a developer who will determine what needs to + be done to correct the problem. You will receive an update each time action is +-taken on the bug. See http://www.python.org/dev/workflow/ for a detailed +-description of the issue workflow. ++taken on the bug. + + + .. seealso:: + ++ `Python Developer's Guide `_ ++ Detailed description of the issue workflow and developers tools. ++ + `How to Report Bugs Effectively `_ + Article which goes into some detail about how to create a useful bug report. + This describes what kind of information is useful and why it is useful. +diff -r 137e45f15c0b Doc/c-api/complex.rst +--- a/Doc/c-api/complex.rst ++++ b/Doc/c-api/complex.rst +@@ -63,12 +63,18 @@ + Return the quotient of two complex numbers, using the C :c:type:`Py_complex` + representation. + ++ If *divisor* is null, this method returns zero and sets ++ :c:data:`errno` to :c:data:`EDOM`. ++ + + .. c:function:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp) + + Return the exponentiation of *num* by *exp*, using the C :c:type:`Py_complex` + representation. + ++ If *num* is null and *exp* is not a positive real number, ++ this method returns zero and sets :c:data:`errno` to :c:data:`EDOM`. ++ + + Complex Numbers as Python Objects + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +@@ -123,4 +129,4 @@ + + If *op* is not a Python complex number object but has a :meth:`__complex__` + method, this method will first be called to convert *op* to a Python complex +- number object. ++ number object. Upon failure, this method returns ``-1.0`` as a real value. +diff -r 137e45f15c0b Doc/c-api/float.rst +--- a/Doc/c-api/float.rst ++++ b/Doc/c-api/float.rst +@@ -47,6 +47,8 @@ + Return a C :c:type:`double` representation of the contents of *pyfloat*. If + *pyfloat* is not a Python floating point object but has a :meth:`__float__` + method, this method will first be called to convert *pyfloat* into a float. ++ This method returns ``-1.0`` upon failure, so one should call ++ :c:func:`PyErr_Occurred` to check for errors. + + + .. c:function:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) +diff -r 137e45f15c0b Doc/c-api/memoryview.rst +--- a/Doc/c-api/memoryview.rst ++++ b/Doc/c-api/memoryview.rst +@@ -17,7 +17,7 @@ + + Create a memoryview object from an object that provides the buffer interface. + If *obj* supports writable buffer exports, the memoryview object will be +- readable and writable, other it will be read-only. ++ readable and writable, otherwise it will be read-only. + + + .. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view) +@@ -33,7 +33,7 @@ + Create a memoryview object to a contiguous chunk of memory (in either + 'C' or 'F'ortran *order*) from an object that defines the buffer + interface. If memory is contiguous, the memoryview object points to the +- original memory. Otherwise copy is made and the memoryview points to a ++ original memory. Otherwise, a copy is made and the memoryview points to a + new bytes object. + + +diff -r 137e45f15c0b Doc/c-api/method.rst +--- a/Doc/c-api/method.rst ++++ b/Doc/c-api/method.rst +@@ -27,7 +27,7 @@ + .. c:function:: PyObject* PyInstanceMethod_New(PyObject *func) + + Return a new instance method object, with *func* being any callable object +- *func* is is the function that will be called when the instance method is ++ *func* is the function that will be called when the instance method is + called. + + +@@ -70,7 +70,7 @@ + .. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self) + + Return a new method object, with *func* being any callable object and *self* +- the instance the method should be bound. *func* is is the function that will ++ the instance the method should be bound. *func* is the function that will + be called when the method is called. *self* must not be *NULL*. + + +diff -r 137e45f15c0b Doc/c-api/number.rst +--- a/Doc/c-api/number.rst ++++ b/Doc/c-api/number.rst +@@ -239,10 +239,10 @@ + + .. c:function:: PyObject* PyNumber_ToBase(PyObject *n, int base) + +- Returns the integer *n* converted to *base* as a string with a base +- marker of ``'0b'``, ``'0o'``, or ``'0x'`` if applicable. When +- *base* is not 2, 8, 10, or 16, the format is ``'x#num'`` where x is the +- base. If *n* is not an int object, it is converted with ++ Returns the integer *n* converted to base *base* as a string. The *base* ++ argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the ++ returned string is prefixed with a base marker of ``'0b'``, ``'0o'``, or ++ ``'0x'``, respectively. If *n* is not a Python int, it is converted with + :c:func:`PyNumber_Index` first. + + +diff -r 137e45f15c0b Doc/c-api/unicode.rst +--- a/Doc/c-api/unicode.rst ++++ b/Doc/c-api/unicode.rst +@@ -338,16 +338,21 @@ + + .. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) + +- Return a read-only pointer to the Unicode object's internal :c:type:`Py_UNICODE` +- buffer, *NULL* if *unicode* is not a Unicode object. ++ Return a read-only pointer to the Unicode object's internal ++ :c:type:`Py_UNICODE` buffer, *NULL* if *unicode* is not a Unicode object. ++ Note that the resulting :c:type:`Py_UNICODE*` string may contain embedded ++ null characters, which would cause the string to be truncated when used in ++ most C functions. + + + .. c:function:: Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode) + + Create a copy of a Unicode string ending with a nul character. Return *NULL* + and raise a :exc:`MemoryError` exception on memory allocation failure, +- otherwise return a new allocated buffer (use :c:func:`PyMem_Free` to free the +- buffer). ++ otherwise return a new allocated buffer (use :c:func:`PyMem_Free` to free ++ the buffer). Note that the resulting :c:type:`Py_UNICODE*` string may contain ++ embedded null characters, which would cause the string to be truncated when ++ used in most C functions. + + .. versionadded:: 3.2 + +@@ -447,7 +452,8 @@ + + Encode a Unicode object to :c:data:`Py_FileSystemDefaultEncoding` with the + ``'surrogateescape'`` error handler, or ``'strict'`` on Windows, and return +- :class:`bytes`. ++ :class:`bytes`. Note that the resulting :class:`bytes` object may contain ++ null bytes. + + If :c:data:`Py_FileSystemDefaultEncoding` is not set, fall back to the + locale encoding. +@@ -476,7 +482,9 @@ + copied or -1 in case of an error. Note that the resulting :c:type:`wchar_t` + string may or may not be 0-terminated. It is the responsibility of the caller + to make sure that the :c:type:`wchar_t` string is 0-terminated in case this is +- required by the application. ++ required by the application. Also, note that the :c:type:`wchar_t*` string ++ might contain null characters, which would cause the string to be truncated ++ when used with most C functions. + + + .. c:function:: wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size) +@@ -486,9 +494,11 @@ + of wide characters (excluding the trailing 0-termination character) into + *\*size*. + +- Returns a buffer allocated by :c:func:`PyMem_Alloc` (use :c:func:`PyMem_Free` +- to free it) on success. On error, returns *NULL*, *\*size* is undefined and +- raises a :exc:`MemoryError`. ++ Returns a buffer allocated by :c:func:`PyMem_Alloc` (use ++ :c:func:`PyMem_Free` to free it) on success. On error, returns *NULL*, ++ *\*size* is undefined and raises a :exc:`MemoryError`. Note that the ++ resulting :c:type:`wchar_t*` string might contain null characters, which ++ would cause the string to be truncated when used with most C functions. + + .. versionadded:: 3.2 + +diff -r 137e45f15c0b Doc/data/refcounts.dat +--- a/Doc/data/refcounts.dat ++++ b/Doc/data/refcounts.dat +@@ -376,6 +376,8 @@ + PyEval_EvalCode:PyObject*:globals:0: + PyEval_EvalCode:PyObject*:locals:0: + ++PyException_GetTraceback:PyObject*::+1: ++ + PyFile_AsFile:FILE*::: + PyFile_AsFile:PyFileObject*:p:0: + +diff -r 137e45f15c0b Doc/distutils/apiref.rst +--- a/Doc/distutils/apiref.rst ++++ b/Doc/distutils/apiref.rst +@@ -31,8 +31,9 @@ + +====================+================================+=============================================================+ + | *name* | The name of the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *version* | The version number of the | See :mod:`distutils.version` | +- | | package | | ++ | *version* | The version number of the | a string | ++ | | package; see | | ++ | | :mod:`distutils.version` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *description* | A single line describing the | a string | + | | package | | +@@ -49,14 +50,14 @@ + | | maintainer, if different from | | + | | the author | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *maintainer_email* | The email address of the | | ++ | *maintainer_email* | The email address of the | a string | + | | current maintainer, if | | + | | different from the author | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *url* | A URL for the package | a URL | ++ | *url* | A URL for the package | a string | + | | (homepage) | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *download_url* | A URL to download the package | a URL | ++ | *download_url* | A URL to download the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *packages* | A list of Python packages that | a list of strings | + | | distutils will manipulate | | +@@ -68,14 +69,13 @@ + | | files to be built and | | + | | installed | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *ext_modules* | A list of Python extensions to | A list of instances of | ++ | *ext_modules* | A list of Python extensions to | a list of instances of | + | | be built | :class:`distutils.core.Extension` | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *classifiers* | A list of categories for the | The list of available | +- | | package | categorizations is available on `PyPI | +- | | | `_. | ++ | *classifiers* | A list of categories for the | a list of strings; valid classifiers are listed on `PyPI | ++ | | package | `_. | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *distclass* | the :class:`Distribution` | A subclass of | ++ | *distclass* | the :class:`Distribution` | a subclass of | + | | class to use | :class:`distutils.core.Distribution` | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *script_name* | The name of the setup.py | a string | +@@ -85,15 +85,15 @@ + | *script_args* | Arguments to supply to the | a list of strings | + | | setup script | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *options* | default options for the setup | a string | ++ | *options* | default options for the setup | a dictionary | + | | script | | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *license* | The license for the package | a string | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *keywords* | Descriptive meta-data, see | | ++ | *keywords* | Descriptive meta-data, see | a list of strings or a comma-separated string | + | | :pep:`314` | | + +--------------------+--------------------------------+-------------------------------------------------------------+ +- | *platforms* | | | ++ | *platforms* | | a list of strings or a comma-separated string | + +--------------------+--------------------------------+-------------------------------------------------------------+ + | *cmdclass* | A mapping of command names to | a dictionary | + | | :class:`Command` subclasses | | +@@ -165,13 +165,13 @@ + +------------------------+--------------------------------+---------------------------+ + | argument name | value | type | + +========================+================================+===========================+ +- | *name* | the full name of the | string | ++ | *name* | the full name of the | a string | + | | extension, including any | | + | | packages --- ie. *not* a | | + | | filename or pathname, but | | + | | Python dotted name | | + +------------------------+--------------------------------+---------------------------+ +- | *sources* | list of source filenames, | string | ++ | *sources* | list of source filenames, | a list of strings | + | | relative to the distribution | | + | | root (where the setup script | | + | | lives), in Unix form (slash- | | +@@ -184,12 +184,12 @@ + | | as source for a Python | | + | | extension. | | + +------------------------+--------------------------------+---------------------------+ +- | *include_dirs* | list of directories to search | string | ++ | *include_dirs* | list of directories to search | a list of strings | + | | for C/C++ header files (in | | + | | Unix form for portability) | | + +------------------------+--------------------------------+---------------------------+ +- | *define_macros* | list of macros to define; each | (string, string) tuple or | +- | | macro is defined using a | (name, ``None``) | ++ | *define_macros* | list of macros to define; each | a list of tuples | ++ | | macro is defined using a | | + | | 2-tuple ``(name, value)``, | | + | | where *value* is | | + | | either the string to define it | | +@@ -200,31 +200,31 @@ + | | on Unix C compiler command | | + | | line) | | + +------------------------+--------------------------------+---------------------------+ +- | *undef_macros* | list of macros to undefine | string | ++ | *undef_macros* | list of macros to undefine | a list of strings | + | | explicitly | | + +------------------------+--------------------------------+---------------------------+ +- | *library_dirs* | list of directories to search | string | ++ | *library_dirs* | list of directories to search | a list of strings | + | | for C/C++ libraries at link | | + | | time | | + +------------------------+--------------------------------+---------------------------+ +- | *libraries* | list of library names (not | string | ++ | *libraries* | list of library names (not | a list of strings | + | | filenames or paths) to link | | + | | against | | + +------------------------+--------------------------------+---------------------------+ +- | *runtime_library_dirs* | list of directories to search | string | ++ | *runtime_library_dirs* | list of directories to search | a list of strings | + | | for C/C++ libraries at run | | + | | time (for shared extensions, | | + | | this is when the extension is | | + | | loaded) | | + +------------------------+--------------------------------+---------------------------+ +- | *extra_objects* | list of extra files to link | string | ++ | *extra_objects* | list of extra files to link | a list of strings | + | | with (eg. object files not | | + | | implied by 'sources', static | | + | | library that must be | | + | | explicitly specified, binary | | + | | resource files, etc.) | | + +------------------------+--------------------------------+---------------------------+ +- | *extra_compile_args* | any extra platform- and | string | ++ | *extra_compile_args* | any extra platform- and | a list of strings | + | | compiler-specific information | | + | | to use when compiling the | | + | | source files in 'sources'. For | | +@@ -235,7 +235,7 @@ + | | for other platforms it could | | + | | be anything. | | + +------------------------+--------------------------------+---------------------------+ +- | *extra_link_args* | any extra platform- and | string | ++ | *extra_link_args* | any extra platform- and | a list of strings | + | | compiler-specific information | | + | | to use when linking object | | + | | files together to create the | | +@@ -244,7 +244,7 @@ + | | Similar interpretation as for | | + | | 'extra_compile_args'. | | + +------------------------+--------------------------------+---------------------------+ +- | *export_symbols* | list of symbols to be exported | string | ++ | *export_symbols* | list of symbols to be exported | a list of strings | + | | from a shared extension. Not | | + | | used on all platforms, and not | | + | | generally necessary for Python | | +@@ -252,10 +252,10 @@ + | | export exactly one symbol: | | + | | ``init`` + extension_name. | | + +------------------------+--------------------------------+---------------------------+ +- | *depends* | list of files that the | string | ++ | *depends* | list of files that the | a list of strings | + | | extension depends on | | + +------------------------+--------------------------------+---------------------------+ +- | *language* | extension language (i.e. | string | ++ | *language* | extension language (i.e. | a string | + | | ``'c'``, ``'c++'``, | | + | | ``'objc'``). Will be detected | | + | | from the source extensions if | | +@@ -1204,9 +1204,9 @@ + .. function:: byte_compile(py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None]) + + Byte-compile a collection of Python source files to either :file:`.pyc` or +- :file:`.pyo` files in the same directory. *py_files* is a list of files to +- compile; any files that don't end in :file:`.py` are silently skipped. +- *optimize* must be one of the following: ++ :file:`.pyo` files in a :file:`__pycache__` subdirectory (see :pep:`3147`). ++ *py_files* is a list of files to compile; any files that don't end in ++ :file:`.py` are silently skipped. *optimize* must be one of the following: + + * ``0`` - don't optimize (generate :file:`.pyc`) + * ``1`` - normal optimization (like ``python -O``) +@@ -1231,6 +1231,11 @@ + is used by the script generated in indirect mode; unless you know what you're + doing, leave it set to ``None``. + ++ .. versionchanged:: 3.2.3 ++ Create ``.pyc`` or ``.pyo`` files with an :func:`import magic tag ++ ` in their name, in a :file:`__pycache__` subdirectory ++ instead of files without tag in the current directory. ++ + + .. function:: rfc822_escape(header) + +@@ -1740,7 +1745,7 @@ + Set final values for all the options that this command supports. This is + always called as late as possible, ie. after any option assignments from the + command-line or from other commands have been done. Thus, this is the place +- to to code option dependencies: if *foo* depends on *bar*, then it is safe to ++ to code option dependencies: if *foo* depends on *bar*, then it is safe to + set *foo* from *bar* as long as *foo* still has the same value it was + assigned in :meth:`initialize_options`. + +diff -r 137e45f15c0b Doc/distutils/introduction.rst +--- a/Doc/distutils/introduction.rst ++++ b/Doc/distutils/introduction.rst +@@ -84,8 +84,8 @@ + + python setup.py sdist + +-For Windows, open a command prompt windows ("DOS box") and change the command +-to:: ++For Windows, open a command prompt window (:menuselection:`Start --> ++Accessories`) and change the command to:: + + setup.py sdist + +diff -r 137e45f15c0b Doc/distutils/setupscript.rst +--- a/Doc/distutils/setupscript.rst ++++ b/Doc/distutils/setupscript.rst +@@ -254,7 +254,7 @@ + + If you need to include header files from some other Python extension, you can + take advantage of the fact that header files are installed in a consistent way +-by the Distutils :command:`install_header` command. For example, the Numerical ++by the Distutils :command:`install_headers` command. For example, the Numerical + Python header files are installed (on a standard Unix installation) to + :file:`/usr/local/include/python1.5/Numerical`. (The exact location will differ + according to your platform and Python installation.) Since the Python include +diff -r 137e45f15c0b Doc/documenting/markup.rst +--- a/Doc/documenting/markup.rst ++++ b/Doc/documenting/markup.rst +@@ -513,7 +513,10 @@ + + .. describe:: keyword + +- The name of a keyword in Python. ++ The name of a Python keyword. Using this role will generate a link to the ++ documentation of the keyword. ``True``, ``False`` and ``None`` do not use ++ this role, but simple code markup (````True````), given that they're ++ fundamental to the language and should be known to any programmer. + + .. describe:: mailheader + +diff -r 137e45f15c0b Doc/extending/embedding.rst +--- a/Doc/extending/embedding.rst ++++ b/Doc/extending/embedding.rst +@@ -133,8 +133,9 @@ + + This code loads a Python script using ``argv[1]``, and calls the function named + in ``argv[2]``. Its integer arguments are the other values of the ``argv`` +-array. If you compile and link this program (let's call the finished executable +-:program:`call`), and use it to execute a Python script, such as:: ++array. If you :ref:`compile and link ` this program (let's call ++the finished executable :program:`call`), and use it to execute a Python ++script, such as:: + + def multiply(a,b): + print("Will compute", a, "times", b) +@@ -257,37 +258,52 @@ + program. There is no need to recompile Python itself using C++. + + +-.. _link-reqs: ++.. _compiling: + +-Linking Requirements +-==================== ++Compiling and Linking under Unix-like systems ++============================================= + +-While the :program:`configure` script shipped with the Python sources will +-correctly build Python to export the symbols needed by dynamically linked +-extensions, this is not automatically inherited by applications which embed the +-Python library statically, at least on Unix. This is an issue when the +-application is linked to the static runtime library (:file:`libpython.a`) and +-needs to load dynamic extensions (implemented as :file:`.so` files). ++It is not necessarily trivial to find the right flags to pass to your ++compiler (and linker) in order to embed the Python interpreter into your ++application, particularly because Python needs to load library modules ++implemented as C dynamic extensions (:file:`.so` files) linked against ++it. + +-The problem is that some entry points are defined by the Python runtime solely +-for extension modules to use. If the embedding application does not use any of +-these entry points, some linkers will not include those entries in the symbol +-table of the finished executable. Some additional options are needed to inform +-the linker not to remove these symbols. ++To find out the required compiler and linker flags, you can execute the ++:file:`python{X.Y}-config` script which is generated as part of the ++installation process (a generic :file:`python3-config` script is also ++available). This script has several options, of which the following will ++be directly useful to you: + +-Determining the right options to use for any given platform can be quite +-difficult, but fortunately the Python configuration already has those values. +-To retrieve them from an installed Python interpreter, start an interactive +-interpreter and have a short session like this:: ++* ``pythonX.Y-config --cflags`` will give you the recommended flags when ++ compiling:: + +- >>> import distutils.sysconfig +- >>> distutils.sysconfig.get_config_var('LINKFORSHARED') ++ $ /opt/bin/python3.2-config --cflags ++ -I/opt/include/python3.2m -I/opt/include/python3.2m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes ++ ++* ``pythonX.Y-config --ldflags`` will give you the recommended flags when ++ linking:: ++ ++ $ /opt/bin/python3.2-config --ldflags ++ -I/opt/lib/python3.2/config-3.2m -lpthread -ldl -lutil -lm -lpython3.2m -Xlinker -export-dynamic ++ ++.. note:: ++ To avoid confusion between several Python installations (and especially ++ between the system Python and your own compiled Python), it is recommended ++ that you use the absolute path to :file:`python{X.Y}-config`, as in the above ++ example. ++ ++If this procedure doesn't work for you (it is not guaranteed to work for ++all Unix-like platforms; however, we welcome bug reports at ++http://bugs.python.org), you will have to read your system's documentation ++about dynamic linking and/or examine Python's Makefile and compilation ++options. In this case, the :mod:`sysconfig` module is a useful tool to ++programmatically extract the configuration values that you will want to ++combine together:: ++ ++ >>> import sysconfig ++ >>> sysconfig.get_config_var('LINKFORSHARED') + '-Xlinker -export-dynamic' + +-.. index:: module: distutils.sysconfig + +-The contents of the string presented will be the options that should be used. +-If the string is empty, there's no need to add any additional options. The +-:const:`LINKFORSHARED` definition corresponds to the variable of the same name +-in Python's top-level :file:`Makefile`. +- ++.. XXX similar documentation for Windows missing +diff -r 137e45f15c0b Doc/faq/design.rst +--- a/Doc/faq/design.rst ++++ b/Doc/faq/design.rst +@@ -380,11 +380,24 @@ + 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 ++Practical answer: ++ ++`Cython `_ and `Pyrex `_ ++compile a modified version of Python with optional annotations into C ++extensions. `Weave `_ makes it easy to ++intermingle Python and C code in various ways to increase performance. ++`Nuitka `_ is an up-and-coming compiler of Python ++into C++ code, aiming to support the full Python language. ++ ++Theoretical answer: ++ ++ .. XXX not sure what to make of this ++ ++Not trivially. Python's high level data types, dynamic typing of objects and + run-time invocation of the interpreter (using :func:`eval` or :func:`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``. ++together mean that a naïvely "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 +@@ -395,99 +408,64 @@ + from the `1997 Python conference + `_ for more information.) + +-Internally, Python source code is always translated into a bytecode +-representation, and this bytecode is then executed by the Python virtual +-machine. In order to avoid the overhead of repeatedly parsing and translating +-modules that rarely change, this byte code is written into a file whose name +-ends in ".pyc" whenever a module is parsed. 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, as 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 improves the start-up time of Python scripts. If +-desired, the Lib/compileall.py module can be used to create 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. Usually main scripts are quite short, so this doesn't cost +-much speed. +- +-.. XXX check which of these projects are still alive +- +-There are also several programs which make it easier to intermingle Python and C +-code in various ways to increase performance. See, for example, `Cython +-`_, `Pyrex +-`_ and `Weave +-`_. +- + + How does Python manage memory? + ------------------------------ + + The details of Python memory management depend on the implementation. The +-standard C implementation of Python uses reference counting to detect +-inaccessible objects, and another mechanism to collect reference cycles, ++standard implementation of Python, :term:`CPython`, uses reference counting to ++detect inaccessible objects, and another mechanism to collect reference cycles, + periodically executing a cycle detection algorithm which looks for inaccessible + cycles and deletes the objects involved. The :mod:`gc` module provides functions + to perform a garbage collection, obtain debugging statistics, and tune the + collector's parameters. + +-Jython relies on the Java runtime so the JVM's garbage collector is used. This +-difference can cause some subtle porting problems if your Python code depends on +-the behavior of the reference counting implementation. ++Other implementations (such as `Jython `_ or ++`PyPy `_), however, can rely on a different mechanism ++such as a full-blown garbage collector. This difference can cause some ++subtle porting problems if your Python code depends on the behavior of the ++reference counting implementation. + +-.. XXX relevant for Python 3? ++In some Python implementations, the following code (which is fine in CPython) ++will probably run out of file descriptors:: + +- Sometimes objects get stuck in traceback temporarily and hence are not +- deallocated when you might expect. Clear the traceback with:: ++ for file in very_long_list_of_files: ++ f = open(file) ++ c = f.read(1) + +- import sys +- sys.last_traceback = None ++Indeed, using CPython's reference counting and destructor scheme, each new ++assignment to *f* closes the previous file. With a traditional GC, however, ++those file objects will only get collected (and closed) at varying and possibly ++long intervals. + +- Tracebacks are used for reporting errors, 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). ++If you want to write code that will work with any Python implementation, ++you should explicitly close the file or use the :keyword:`with` statement; ++this will work regardless of memory management scheme:: + +-In the absence of circularities, Python programs do not need to manage memory +-explicitly. ++ for file in very_long_list_of_files: ++ with open(file) as f: ++ c = f.read(1) + +-Why doesn't Python use a more traditional garbage collection scheme? For one +-thing, this is not a C standard feature and hence it's not portable. (Yes, we +-know about the Boehm GC library. It has bits of assembler code for *most* +-common platforms, not for all of them, and although it is mostly transparent, it +-isn't completely transparent; patches are required to get Python to work with +-it.) ++ ++Why doesn't CPython use a more traditional garbage collection scheme? ++--------------------------------------------------------------------- ++ ++For one thing, this is not a C standard feature and hence it's not portable. ++(Yes, we know about the Boehm GC library. It has bits of assembler code for ++*most* common platforms, not for all of them, and although it is mostly ++transparent, it isn't completely transparent; patches are required to get ++Python to work with it.) + + Traditional GC also becomes a problem when Python is embedded into other + applications. While in a standalone Python it's 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 ++and may not want Python's. Right now, CPython works with anything that + implements malloc() and free() properly. + +-In Jython, the following code (which is fine in CPython) 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. If you want +-to write code that will work with any Python implementation, you should +-explicitly close the file or use the :keyword:`with` statement; this will work +-regardless of GC:: +- +- for file in very_long_list_of_files: +- with open(file) as f: +- c = f.read(1) +- +- +-Why isn't all memory freed when Python exits? +---------------------------------------------- ++Why isn't all memory freed when CPython exits? ++---------------------------------------------- + + Objects referenced from the global namespaces of Python modules are not always + deallocated when Python exits. This may happen if there are circular +@@ -647,10 +625,10 @@ + 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. + +-In Python 2.4 a new built-in function -- :func:`sorted` -- has been added. +-This function creates a new list from a provided iterable, sorts it and returns +-it. For example, here's how to iterate over the keys of a dictionary in sorted +-order:: ++If you want to return a new list, use the built-in :func:`sorted` function ++instead. This function creates a new list from a provided iterable, sorts ++it and returns it. For example, here's how to iterate over the keys of a ++dictionary in sorted order:: + + for key in sorted(mydict): + ... # do whatever with mydict[key]... +diff -r 137e45f15c0b Doc/faq/extending.rst +--- a/Doc/faq/extending.rst ++++ b/Doc/faq/extending.rst +@@ -37,13 +37,7 @@ + There are a number of alternatives to writing your own C extensions, depending + on what you're trying to do. + +-.. XXX make sure these all work; mention Cython +- +-If you need more speed, `Psyco `_ generates x86 +-assembly code from Python bytecode. You can use Psyco to compile the most +-time-critical functions in your code, and gain a significant improvement with +-very little effort, as long as you're running on a machine with an +-x86-compatible processor. ++.. XXX make sure these all work + + `Cython `_ and its relative `Pyrex + `_ are compilers +@@ -105,12 +99,7 @@ + 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``, so you have to :c:func:`Py_INCREF` it. Lists have similar functions +-``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. ++You can't. Use :c:func:`PyTuple_Pack` instead. + + + How do I call an object's method from C? +@@ -153,21 +142,30 @@ + 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. ++The easiest way to do this is to use the :class:`io.StringIO` class:: + +-Sample code and use for catching stdout: ++ >>> import io, sys ++ >>> sys.stdout = io.StringIO() ++ >>> print('foo') ++ >>> print('hello world!') ++ >>> sys.stderr.write(sys.stdout.getvalue()) ++ foo ++ hello world! + +- >>> class StdoutCatcher: ++A custom object to do the same would look like this:: ++ ++ >>> import io, sys ++ >>> class StdoutCatcher(io.TextIOBase): + ... def __init__(self): +- ... self.data = '' ++ ... self.data = [] + ... def write(self, stuff): +- ... self.data = self.data + stuff ++ ... self.data.append(stuff) + ... + >>> import sys + >>> sys.stdout = StdoutCatcher() + >>> print('foo') + >>> print('hello world!') +- >>> sys.stderr.write(sys.stdout.data) ++ >>> sys.stderr.write(''.join(sys.stdout.data)) + foo + hello world! + +diff -r 137e45f15c0b Doc/faq/general.rst +--- a/Doc/faq/general.rst ++++ b/Doc/faq/general.rst +@@ -19,7 +19,7 @@ + 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 Unix variants, on the Mac, and on +-PCs under MS-DOS, Windows, Windows NT, and OS/2. ++Windows 2000 and later. + + To find out more, start with :ref:`tutorial-index`. The `Beginner's Guide to + Python `_ links to other +@@ -164,9 +164,7 @@ + several useful pieces of freely distributable software. The source will compile + and run out of the box on most UNIX platforms. + +-.. XXX update link once the dev faq is relocated +- +-Consult the `Developer FAQ `__ for more ++Consult the `Developer FAQ `__ for more + information on getting the source code and compiling it. + + +@@ -221,10 +219,8 @@ + newsgroups and on the Python home page at http://www.python.org/; an RSS feed of + news is available. + +-.. XXX update link once the dev faq is relocated +- + You can also access the development version of Python through Subversion. See +-http://www.python.org/dev/faq/ for details. ++http://docs.python.org/devguide/faq for details. + + + How do I submit bug reports and patches for Python? +@@ -239,10 +235,8 @@ + report bugs to Python, you can obtain your Roundup password through Roundup's + `password reset procedure `_. + +-.. XXX adapt link to dev guide +- + For more information on how Python is developed, consult `the Python Developer's +-Guide `_. ++Guide `_. + + + Are there any published articles about Python that I can reference? +@@ -475,38 +469,3 @@ + If you want to discuss Python's use in education, you may be interested in + joining `the edu-sig mailing list + `_. +- +- +-Upgrading Python +-================ +- +-What is this bsddb185 module my application keeps complaining about? +--------------------------------------------------------------------- +- +-.. XXX remove this question? +- +-Starting with Python2.3, the distribution includes the `PyBSDDB package +-` as a replacement for the old bsddb module. It +-includes functions which provide backward compatibility at the API level, but +-requires a newer version of the underlying `Berkeley DB +-`_ library. Files created with the older bsddb module +-can't be opened directly using the new module. +- +-Using your old version of Python and a pair of scripts which are part of Python +-2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory) you can +-convert your old database files to the new format. Using your old Python +-version, run the db2pickle.py script to convert it to a pickle, e.g.:: +- +- python2.2 /db2pickley.py database.db database.pck +- +-Rename your database file:: +- +- mv database.db olddatabase.db +- +-Now convert the pickle file to a new format database:: +- +- python /pickle2db.py database.db database.pck +- +-The precise commands you use will vary depending on the particulars of your +-installation. For full details about operation of these two scripts check the +-doc string at the start of each one. +diff -r 137e45f15c0b Doc/faq/gui.rst +--- a/Doc/faq/gui.rst ++++ b/Doc/faq/gui.rst +@@ -68,8 +68,12 @@ + Gtk+ + ---- + +-PyGtk bindings for the `Gtk+ toolkit `_ have been +-implemented by James Henstridge; see . ++The `GObject introspection bindings `_ ++for Python allow you to write GTK+ 3 applications. There is also a ++`Python GTK+ 3 Tutorial `_. ++ ++The older PyGtk bindings for the `Gtk+ 2 toolkit `_ have ++been implemented by James Henstridge; see . + + FLTK + ---- +diff -r 137e45f15c0b Doc/faq/library.rst +--- a/Doc/faq/library.rst ++++ b/Doc/faq/library.rst +@@ -814,52 +814,6 @@ + general such as using gdbm with pickle/shelve. + + +-If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come? +------------------------------------------------------------------------------------------- +- +-.. XXX move this FAQ entry elsewhere? +- +-.. note:: +- +- The bsddb module is now available as a standalone package `pybsddb +- `_. +- +-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 library caches database +-contents which need to be converted to on-disk form and written. +- +-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. +- +- +-I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data? +----------------------------------------------------------------------------------------------------------------------------- +- +-.. XXX move this FAQ entry elsewhere? +- +-.. note:: +- +- The bsddb module is now available as a standalone package `pybsddb +- `_. +- +-Don't panic! Your data is 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 move away from Berkeley DB version 1 files because the hash file code +-contains known bugs that can corrupt your data. +- +- + Mathematics and Numerics + ======================== + +diff -r 137e45f15c0b Doc/faq/programming.rst +--- a/Doc/faq/programming.rst ++++ b/Doc/faq/programming.rst +@@ -115,167 +115,6 @@ + :pep:`8`. + + +-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; +-consider rewriting parts in C as a last resort. +- +-In some cases it's possible to automatically translate Python to C or x86 +-assembly language, meaning that you don't have to modify your code to gain +-increased speed. +- +-.. XXX seems to have overlap with other questions! +- +-`Cython `_ and `Pyrex `_ +-can compile a slightly modified version of Python code into a C extension, and +-can be used on many different platforms. +- +-`Psyco `_ is a just-in-time compiler that +-translates Python code into x86 assembly language. If you can use it, Psyco can +-provide dramatic speedups for critical functions. +- +-The rest of this answer will discuss various tricks for squeezing a bit more +-speed out of Python code. *Never* apply any optimization tricks unless you know +-you need them, after profiling has indicated that a particular function is the +-heavily executed hot spot in the code. Optimizations almost always make the +-code less clear, and you shouldn't pay the costs of reduced clarity (increased +-development time, greater likelihood of bugs) unless the resulting performance +-benefit is worth it. +- +-There is a page on the wiki devoted to `performance tips +-`_. +- +-Guido van Rossum has written up an anecdote related to optimization at +-http://www.python.org/doc/essays/list2str.html. +- +-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 might consider using a more direct way such as directly +-accessing instance variables. Also see the standard module :mod:`profile` 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 reduce the overhead of kernel system calls. Thus CGI scripts that +-write all output in "one shot" may be faster than those that write lots of small +-pieces of output. +- +-Also, be sure to use Python's core features where appropriate. For example, +-slicing allows programs to chop up lists and other sequence objects in a single +-tick of the interpreter's 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 functionally-oriented built-in functions such as :func:`map`, +-:func:`zip`, and friends can be a convenient accelerator for loops that +-perform a single task. For example to pair the elements of two lists +-together:: +- +- >>> list(zip([1, 2, 3], [4, 5, 6])) +- [(1, 4), (2, 5), (3, 6)] +- +-or to compute a number of sines:: +- +- >>> list(map(math.sin, (1, 2, 3, 4))) +- [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308] +- +-The operation completes very quickly in such cases. +- +-Other examples include the ``join()`` and ``split()`` :ref:`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 the copying in one pass. For +-manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods +-on string objects `. Use regular expressions only when you're +-not dealing with constant string patterns. +- +-Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the +-`sorting mini-HOWTO `_ for examples +-of moderately advanced usage. :meth:`list.sort` beats other techniques for +-sorting in all but the most extreme circumstances. +- +-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 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:: +- +- list = map(ff, oldlist) +- +-or:: +- +- 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 the two examples to ``list = ffseq(oldlist)`` and to:: +- +- for value in ffseq(sequence): +- ... # do something with value... +- +-Single calls to ``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 +-slightly 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. +- +- + Core Language + ============= + +@@ -687,61 +526,21 @@ + Is there an equivalent of C's "?:" ternary operator? + ---------------------------------------------------- + +-Yes, this feature was added in Python 2.5. The syntax would be as follows:: ++Yes, there is. The syntax is as follows:: + + [on_true] if [expression] else [on_false] + + x, y = 50, 25 +- + small = x if x < y else y + +-For versions previous to 2.5 the answer would be 'No'. ++Before this syntax was introduced in Python 2.5, a common idiom was to use ++logical operators:: + +-.. XXX remove rest? ++ [expression] and [on_true] or [on_false] + +-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'. +- +-The best course is usually to write a simple ``if...else`` statement. Another +-solution is to implement the ``?:`` operator as a function:: +- +- def q(cond, on_true, on_false): +- if cond: +- if not isfunction(on_true): +- return on_true +- else: +- return on_true() +- else: +- if not isfunction(on_false): +- return on_false +- else: +- return 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. There are +-several answers: 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. +- +-In 2002, :pep:`308` was written proposing several possible syntaxes and the +-community was asked to vote on the issue. The vote was inconclusive. Most +-people liked one of the syntaxes, but also hated other syntaxes; many votes +-implied that people preferred no ternary operator rather than having a syntax +-they hated. ++However, this idiom is unsafe, as it can give wrong results when *on_true* ++has a false boolean value. Therefore, it is always better to use ++the ``... if ... else ...`` form. + + + Is it possible to write obfuscated one-liners in Python? +@@ -860,15 +659,21 @@ + How do I modify a string in place? + ---------------------------------- + +-You can't, because strings are immutable. If you need an object with this +-ability, try converting the string to a list or use the array module:: ++You can't, because strings are immutable. In most situations, you should ++simply construct a new string from the various parts you want to assemble ++it from. However, if you need an object with the ability to modify in-place ++unicode data, try using a :class:`io.StringIO` object or the :mod:`array` ++module:: + + >>> s = "Hello, world" +- >>> a = list(s) +- >>> print(a) +- ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] +- >>> a[7:] = list("there!") +- >>> ''.join(a) ++ >>> sio = io.StringIO(s) ++ >>> sio.getvalue() ++ 'Hello, world' ++ >>> sio.seek(7) ++ 7 ++ >>> sio.write("there!") ++ 6 ++ >>> sio.getvalue() + 'Hello, there!' + + >>> import array +@@ -943,11 +748,11 @@ + Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? + ------------------------------------------------------------------------------------- + +-Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all +-occurrences of any line terminator from the end of the string ``S`` without +-removing other trailing whitespace. If the string ``S`` represents more than +-one line, with several empty lines at the end, the line terminators for all the +-blank lines will be removed:: ++You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line ++terminator from the end of the string ``S`` without removing other trailing ++whitespace. If the string ``S`` represents more than one line, with several ++empty lines at the end, the line terminators for all the blank lines will ++be removed:: + + >>> lines = ("line 1 \r\n" + ... "\r\n" +@@ -958,15 +763,6 @@ + Since this is typically only desired when reading text one line at a time, using + ``S.rstrip()`` this way works well. + +-For older versions of Python, there are two partial substitutes: +- +-- If you want to remove all trailing whitespace, use the ``rstrip()`` method of +- string objects. This removes all trailing whitespace, not just a single +- newline. +- +-- Otherwise, if there is only one line in the string ``S``, use +- ``S.splitlines()[0]``. +- + + Is there a scanf() or sscanf() equivalent? + ------------------------------------------ +@@ -989,6 +785,94 @@ + See the :ref:`unicode-howto`. + + ++Performance ++=========== ++ ++My program is too slow. How do I speed it up? ++--------------------------------------------- ++ ++That's a tough one, in general. First, here are a list of things to ++remember before diving further: ++ ++* Performance characteristics vary accross Python implementations. This FAQ ++ focusses on :term:`CPython`. ++* Behaviour can vary accross operating systems, especially when talking about ++ I/O or multi-threading. ++* You should always find the hot spots in your program *before* attempting to ++ optimize any code (see the :mod:`profile` module). ++* Writing benchmark scripts will allow you to iterate quickly when searching ++ for improvements (see the :mod:`timeit` module). ++* It is highly recommended to have good code coverage (through unit testing ++ or any other technique) before potentially introducing regressions hidden ++ in sophisticated optimizations. ++ ++That being said, there are many tricks to speed up Python code. Here are ++some general principles which go a long way towards reaching acceptable ++performance levels: ++ ++* Making your algorithms faster (or changing to faster ones) can yield ++ much larger benefits than trying to sprinkle micro-optimization tricks ++ all over your code. ++ ++* Use the right data structures. Study documentation for the :ref:`bltin-types` ++ and the :mod:`collections` module. ++ ++* When the standard library provides a primitive for doing something, it is ++ likely (although not guaranteed) to be faster than any alternative you ++ may come up with. This is doubly true for primitives written in C, such ++ as builtins and some extension types. For example, be sure to use ++ either the :meth:`list.sort` built-in method or the related :func:`sorted` ++ function to do sorting (and see the ++ `sorting mini-HOWTO `_ for examples ++ of moderately advanced usage). ++ ++* Abstractions tend to create indirections and force the interpreter to work ++ more. If the levels of indirection outweigh the amount of useful work ++ done, your program will be slower. You should avoid excessive abstraction, ++ especially under the form of tiny functions or methods (which are also often ++ detrimental to readability). ++ ++If you have reached the limit of what pure Python can allow, there are tools ++to take you further away. For example, `Cython `_ can ++compile a slightly modified version of Python code into a C extension, and ++can be used on many different platforms. Cython can take advantage of ++compilation (and optional type annotations) to make your code significantly ++faster than when interpreted. If you are confident in your C programming ++skills, you can also :ref:`write a C extension module ` ++yourself. ++ ++.. seealso:: ++ The wiki page devoted to `performance tips ++ `_. ++ ++.. _efficient_string_concatenation: ++ ++What is the most efficient way to concatenate many strings together? ++-------------------------------------------------------------------- ++ ++:class:`str` and :class:`bytes` objects are immutable, therefore concatenating ++many strings together is inefficient as each concatenation creates a new ++object. In the general case, the total runtime cost is quadratic in the ++total string length. ++ ++To accumulate many :class:`str` objects, the recommended idiom is to place ++them into a list and call :meth:`str.join` at the end:: ++ ++ chunks = [] ++ for s in my_strings: ++ chunks.append(s) ++ result = ''.join(chunks) ++ ++(another reasonably efficient idiom is to use :class:`io.StringIO`) ++ ++To accumulate many :class:`bytes` objects, the recommended idiom is to extend ++a :class:`bytearray` object using in-place concatenation (the ``+=`` operator):: ++ ++ result = bytearray() ++ for b in my_bytes_objects: ++ result += b ++ ++ + Sequences (Tuples/Lists) + ======================== + +@@ -1058,15 +942,8 @@ + else: + last = mylist[i] + +-If all elements of the list may be used as dictionary keys (i.e. they are all +-hashable) this is often faster :: +- +- d = {} +- for x in mylist: +- d[x] = 1 +- mylist = list(d.keys()) +- +-In Python 2.5 and later, the following is possible instead:: ++If all elements of the list may be used as set keys (i.e. they are all ++:term:`hashable`) this is often faster :: + + mylist = list(set(mylist)) + +@@ -1436,15 +1313,7 @@ + + C.count = 314 + +-Static methods are possible since Python 2.2:: +- +- class C: +- def static(arg1, arg2, arg3): +- # No 'self' parameter! +- ... +- static = staticmethod(static) +- +-With Python 2.4's decorators, this can also be written as :: ++Static methods are possible:: + + class C: + @staticmethod +diff -r 137e45f15c0b Doc/glossary.rst +--- a/Doc/glossary.rst ++++ b/Doc/glossary.rst +@@ -30,7 +30,10 @@ + Abstract base classes complement :term:`duck-typing` by + providing a way to define interfaces when other techniques like + :func:`hasattr` would be clumsy or subtly wrong (for example with +- :ref:`magic methods `). Python comes with many built-in ABCs for ++ :ref:`magic methods `). ABCs introduce virtual ++ subclasses, which are classes that don't inherit from a class but are ++ still recognized by :func:`isinstance` and :func:`issubclass`; see the ++ :mod:`abc` module documentation. Python comes with many built-in ABCs for + data structures (in the :mod:`collections` module), numbers (in the + :mod:`numbers` module), streams (in the :mod:`io` module), import finders + and loaders (in the :mod:`importlib.abc` module). You can create your own +@@ -163,8 +166,8 @@ + well-designed code improves its flexibility by allowing polymorphic + substitution. Duck-typing avoids tests using :func:`type` or + :func:`isinstance`. (Note, however, that duck-typing can be complemented +- with :term:`abstract base class`\ es.) Instead, it typically employs +- :func:`hasattr` tests or :term:`EAFP` programming. ++ with :term:`abstract base classes `.) Instead, it ++ typically employs :func:`hasattr` tests or :term:`EAFP` programming. + + EAFP + Easier to ask for forgiveness than permission. This common Python coding +diff -r 137e45f15c0b Doc/howto/functional.rst +--- a/Doc/howto/functional.rst ++++ b/Doc/howto/functional.rst +@@ -1010,135 +1010,6 @@ + Consult the operator module's documentation for a complete list. + + +- +-The functional module +---------------------- +- +-Collin Winter's `functional module `__ +-provides a number of more advanced tools for functional programming. It also +-reimplements several Python built-ins, trying to make them more intuitive to +-those used to functional programming in other languages. +- +-This section contains an introduction to some of the most important functions in +-``functional``; full documentation can be found at `the project's website +-`__. +- +-``compose(outer, inner, unpack=False)`` +- +-The ``compose()`` function implements function composition. In other words, it +-returns a wrapper around the ``outer`` and ``inner`` callables, such that the +-return value from ``inner`` is fed directly to ``outer``. That is, :: +- +- >>> def add(a, b): +- ... return a + b +- ... +- >>> def double(a): +- ... return 2 * a +- ... +- >>> compose(double, add)(5, 6) +- 22 +- +-is equivalent to :: +- +- >>> double(add(5, 6)) +- 22 +- +-The ``unpack`` keyword is provided to work around the fact that Python functions +-are not always `fully curried `__. By +-default, it is expected that the ``inner`` function will return a single object +-and that the ``outer`` function will take a single argument. Setting the +-``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which +-will be expanded before being passed to ``outer``. Put simply, :: +- +- compose(f, g)(5, 6) +- +-is equivalent to:: +- +- f(g(5, 6)) +- +-while :: +- +- compose(f, g, unpack=True)(5, 6) +- +-is equivalent to:: +- +- f(*g(5, 6)) +- +-Even though ``compose()`` only accepts two functions, it's trivial to build up a +-version that will compose any number of functions. We'll use +-:func:`functools.reduce`, ``compose()`` and ``partial()`` (the last of which is +-provided by both ``functional`` and ``functools``). :: +- +- from functional import compose, partial +- import functools +- +- +- multi_compose = partial(functools.reduce, compose) +- +- +-We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of +-``"".join(...)`` that converts its arguments to string:: +- +- from functional import compose, partial +- +- join = compose("".join, partial(map, str)) +- +- +-``flip(func)`` +- +-``flip()`` wraps the callable in ``func`` and causes it to receive its +-non-keyword arguments in reverse order. :: +- +- >>> def triple(a, b, c): +- ... return (a, b, c) +- ... +- >>> triple(5, 6, 7) +- (5, 6, 7) +- >>> +- >>> flipped_triple = flip(triple) +- >>> flipped_triple(5, 6, 7) +- (7, 6, 5) +- +-``foldl(func, start, iterable)`` +- +-``foldl()`` takes a binary function, a starting value (usually some kind of +-'zero'), and an iterable. The function is applied to the starting value and the +-first element of the list, then the result of that and the second element of the +-list, then the result of that and the third element of the list, and so on. +- +-This means that a call such as:: +- +- foldl(f, 0, [1, 2, 3]) +- +-is equivalent to:: +- +- f(f(f(0, 1), 2), 3) +- +- +-``foldl()`` is roughly equivalent to the following recursive function:: +- +- def foldl(func, start, seq): +- if len(seq) == 0: +- return start +- +- return foldl(func, func(start, seq[0]), seq[1:]) +- +-Speaking of equivalence, the above ``foldl`` call can be expressed in terms of +-the built-in :func:`functools.reduce` like so:: +- +- import functools +- functools.reduce(f, [1, 2, 3], 0) +- +- +-We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a +-cleaner, more aesthetically-pleasing version of Python's ``"".join(...)`` +-idiom:: +- +- from functional import foldl, partial from operator import concat +- +- join = partial(foldl, concat, "") +- +- + Small functions and the lambda expression + ========================================= + +diff -r 137e45f15c0b Doc/howto/logging-cookbook.rst +--- a/Doc/howto/logging-cookbook.rst ++++ b/Doc/howto/logging-cookbook.rst +@@ -674,9 +674,10 @@ + to have all the processes log to a :class:`SocketHandler`, and have a separate + process which implements a socket server which reads from the socket and logs + to file. (If you prefer, you can dedicate one thread in one of the existing +-processes to perform this function.) The following section documents this +-approach in more detail and includes a working socket receiver which can be +-used as a starting point for you to adapt in your own applications. ++processes to perform this function.) :ref:`This section ` ++documents this approach in more detail and includes a working socket receiver ++which can be used as a starting point for you to adapt in your own ++applications. + + If you are using a recent version of Python which includes the + :mod:`multiprocessing` module, you could write your own handler which uses the +@@ -960,7 +961,7 @@ + ``.1``. Each of the existing backup files is renamed to increment the suffix + (``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased. + +-Obviously this example sets the log length much much too small as an extreme ++Obviously this example sets the log length much too small as an extreme + example. You would want to set *maxBytes* to an appropriate value. + + .. _zeromq-handlers: +@@ -1037,3 +1038,67 @@ + :ref:`A basic logging tutorial ` + + :ref:`A more advanced logging tutorial ` ++ ++ ++An example dictionary-based configuration ++----------------------------------------- ++ ++Below is an example of a logging configuration dictionary - it's taken from ++the `documentation on the Django project `_. ++This dictionary is passed to :func:`~logging.config.dictConfig` to put the configuration into effect:: ++ ++ LOGGING = { ++ 'version': 1, ++ 'disable_existing_loggers': True, ++ 'formatters': { ++ 'verbose': { ++ 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' ++ }, ++ 'simple': { ++ 'format': '%(levelname)s %(message)s' ++ }, ++ }, ++ 'filters': { ++ 'special': { ++ '()': 'project.logging.SpecialFilter', ++ 'foo': 'bar', ++ } ++ }, ++ 'handlers': { ++ 'null': { ++ 'level':'DEBUG', ++ 'class':'django.utils.log.NullHandler', ++ }, ++ 'console':{ ++ 'level':'DEBUG', ++ 'class':'logging.StreamHandler', ++ 'formatter': 'simple' ++ }, ++ 'mail_admins': { ++ 'level': 'ERROR', ++ 'class': 'django.utils.log.AdminEmailHandler', ++ 'filters': ['special'] ++ } ++ }, ++ 'loggers': { ++ 'django': { ++ 'handlers':['null'], ++ 'propagate': True, ++ 'level':'INFO', ++ }, ++ 'django.request': { ++ 'handlers': ['mail_admins'], ++ 'level': 'ERROR', ++ 'propagate': False, ++ }, ++ 'myproject.custom': { ++ 'handlers': ['console', 'mail_admins'], ++ 'level': 'INFO', ++ 'filters': ['special'] ++ } ++ } ++ } ++ ++For more information about this configuration, you can see the `relevant ++section `_ ++of the Django documentation. +diff -r 137e45f15c0b Doc/howto/logging.rst +--- a/Doc/howto/logging.rst ++++ b/Doc/howto/logging.rst +@@ -679,7 +679,7 @@ + version: 1 + formatters: + simple: +- format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s ++ format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + handlers: + console: + class: logging.StreamHandler +diff -r 137e45f15c0b Doc/howto/pyporting.rst +--- a/Doc/howto/pyporting.rst ++++ b/Doc/howto/pyporting.rst +@@ -328,7 +328,7 @@ + textual data, people have over the years been rather loose in their delineation + of what ``str`` instances held text compared to bytes. In Python 3 you cannot + be so care-free anymore and need to properly handle the difference. The key +-handling this issue to to make sure that **every** string literal in your ++handling this issue to make sure that **every** string literal in your + Python 2 code is either syntactically of functionally marked as either bytes or + text data. After this is done you then need to make sure your APIs are designed + to either handle a specific type or made to be properly polymorphic. +@@ -505,6 +505,18 @@ + to :mod:`unittest`. + + ++Update `map` for imbalanced input sequences ++''''''''''''''''''''''''''''''''''''''''''' ++ ++With Python 2, `map` would pad input sequences of unequal length with ++`None` values, returning a sequence as long as the longest input sequence. ++ ++With Python 3, if the input sequences to `map` are of unequal length, `map` ++will stop at the termination of the shortest of the sequences. For full ++compatibility with `map` from Python 2.x, also wrap the sequences in ++:func:`itertools.zip_longest`, e.g. ``map(func, *sequences)`` becomes ++``list(map(func, itertools.zip_longest(*sequences)))``. ++ + Eliminate ``-3`` Warnings + ------------------------- + +diff -r 137e45f15c0b Doc/howto/sockets.rst +--- a/Doc/howto/sockets.rst ++++ b/Doc/howto/sockets.rst +@@ -60,11 +60,10 @@ + Roughly speaking, when you clicked on the link that brought you to this page, + your browser did something like the following:: + +- #create an INET, STREAMing socket ++ # create an INET, STREAMing socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +- #now connect to the web server on port 80 +- # - the normal http port +- s.connect(("www.mcmillan-inc.com", 80)) ++ # now connect to the web server on port 80 - the normal http port ++ s.connect(("www.python.org", 80)) + + When the ``connect`` completes, the socket ``s`` can be used to send + in a request for the text of the page. The same socket will read the +@@ -75,13 +74,11 @@ + What happens in the web server is a bit more complex. First, the web server + creates a "server socket":: + +- #create an INET, STREAMing socket +- serversocket = socket.socket( +- socket.AF_INET, socket.SOCK_STREAM) +- #bind the socket to a public host, +- # and a well-known port ++ # create an INET, STREAMing socket ++ serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ++ # bind the socket to a public host, and a well-known port + serversocket.bind((socket.gethostname(), 80)) +- #become a server socket ++ # become a server socket + serversocket.listen(5) + + A couple things to notice: we used ``socket.gethostname()`` so that the socket +@@ -101,10 +98,10 @@ + mainloop of the web server:: + + while True: +- #accept connections from outside ++ # accept connections from outside + (clientsocket, address) = serversocket.accept() +- #now do something with the clientsocket +- #in this case, we'll pretend this is a threaded server ++ # now do something with the clientsocket ++ # in this case, we'll pretend this is a threaded server + ct = client_thread(clientsocket) + ct.run() + +@@ -126,12 +123,13 @@ + --- + + If you need fast IPC between two processes on one machine, you should look into +-whatever form of shared memory the platform offers. A simple protocol based +-around shared memory and locks or semaphores is by far the fastest technique. ++pipes or shared memory. If you do decide to use AF_INET sockets, bind the ++"server" socket to ``'localhost'``. On most platforms, this will take a ++shortcut around a couple of layers of network code and be quite a bit faster. + +-If you do decide to use sockets, bind the "server" socket to ``'localhost'``. On +-most platforms, this will take a shortcut around a couple of layers of network +-code and be quite a bit faster. ++.. seealso:: ++ The :mod:`multiprocessing` integrates cross-platform IPC into a higher-level ++ API. + + + Using a Socket +@@ -300,7 +298,7 @@ + + Probably the worst thing about using blocking sockets is what happens when the + other side comes down hard (without doing a ``close``). Your socket is likely to +-hang. SOCKSTREAM is a reliable protocol, and it will wait a long, long time ++hang. TCP is a reliable protocol, and it will wait a long, long time + before giving up on a connection. If you're using threads, the entire thread is + essentially dead. There's not much you can do about it. As long as you aren't + doing something dumb, like holding a lock while doing a blocking read, the +@@ -395,19 +393,13 @@ + + There's no question that the fastest sockets code uses non-blocking sockets and + select to multiplex them. You can put together something that will saturate a +-LAN connection without putting any strain on the CPU. The trouble is that an app +-written this way can't do much of anything else - it needs to be ready to +-shuffle bytes around at all times. ++LAN connection without putting any strain on the CPU. + +-Assuming that your app is actually supposed to do something more than that, +-threading is the optimal solution, (and using non-blocking sockets will be +-faster than using blocking sockets). Unfortunately, threading support in Unixes +-varies both in API and quality. So the normal Unix solution is to fork a +-subprocess to deal with each connection. The overhead for this is significant +-(and don't do this on Windows - the overhead of process creation is enormous +-there). It also means that unless each subprocess is completely independent, +-you'll need to use another form of IPC, say a pipe, or shared memory and +-semaphores, to communicate between the parent and child processes. ++The trouble is that an app written this way can't do much of anything else - ++it needs to be ready to shuffle bytes around at all times. Assuming that your ++app is actually supposed to do something more than that, threading is the ++optimal solution, (and using non-blocking sockets will be faster than using ++blocking sockets). + + Finally, remember that even though blocking sockets are somewhat slower than + non-blocking, in many cases they are the "right" solution. After all, if your +diff -r 137e45f15c0b Doc/howto/unicode.rst +--- a/Doc/howto/unicode.rst ++++ b/Doc/howto/unicode.rst +@@ -552,7 +552,6 @@ + i.e. Unix systems. + + +- + Tips for Writing Unicode-aware Programs + --------------------------------------- + +@@ -572,28 +571,12 @@ + When using data coming from a web browser or some other untrusted source, a + common technique is to check for illegal characters in a string before using the + string in a generated command line or storing it in a database. If you're doing +-this, be careful to check the string once it's in the form that will be used or +-stored; it's possible for encodings to be used to disguise characters. This is +-especially true if the input data also specifies the encoding; many encodings +-leave the commonly checked-for characters alone, but Python includes some +-encodings such as ``'base64'`` that modify every single character. ++this, be careful to check the decoded string, not the encoded bytes data; ++some encodings may have interesting properties, such as not being bijective ++or not being fully ASCII-compatible. This is especially true if the input ++data also specifies the encoding, since the attacker can then choose a ++clever way to hide malicious text in the encoded bytestream. + +-For example, let's say you have a content management system that takes a Unicode +-filename, and you want to disallow paths with a '/' character. You might write +-this code:: +- +- def read_file(filename, encoding): +- if '/' in filename: +- raise ValueError("'/' not allowed in filenames") +- unicode_name = filename.decode(encoding) +- with open(unicode_name, 'r') as f: +- # ... return contents of file ... +- +-However, if an attacker could specify the ``'base64'`` encoding, they could pass +-``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string +-``'/etc/passwd'``, to read a system file. The above code looks for ``'/'`` +-characters in the encoded form and misses the dangerous character in the +-resulting decoded form. + + References + ---------- +diff -r 137e45f15c0b Doc/howto/webservers.rst +--- a/Doc/howto/webservers.rst ++++ b/Doc/howto/webservers.rst +@@ -264,7 +264,7 @@ + + * `FastCGI, SCGI, and Apache: Background and Future + `_ +- is a discussion on why the concept of FastCGI and SCGI is better that that ++ is a discussion on why the concept of FastCGI and SCGI is better than that + of mod_python. + + +diff -r 137e45f15c0b Doc/includes/sqlite3/ctx_manager.py +--- a/Doc/includes/sqlite3/ctx_manager.py ++++ b/Doc/includes/sqlite3/ctx_manager.py +@@ -8,7 +8,7 @@ + con.execute("insert into person(firstname) values (?)", ("Joe",)) + + # con.rollback() is called after the with block finishes with an exception, the +-# exception is still raised and must be catched ++# exception is still raised and must be caught + try: + with con: + con.execute("insert into person(firstname) values (?)", ("Joe",)) +diff -r 137e45f15c0b Doc/install/index.rst +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -101,8 +101,8 @@ + + python setup.py install + +-For Windows, this command should be run from a command prompt windows ("DOS +-box"):: ++For Windows, this command should be run from a command prompt window ++(:menuselection:`Start --> Accessories`):: + + setup.py install + +@@ -144,7 +144,7 @@ + :file:`C:\\Temp\\foo-1.0`; you can use either a archive manipulator with a + graphical user interface (such as WinZip) or a command-line tool (such as + :program:`unzip` or :program:`pkunzip`) to unpack the archive. Then, open a +-command prompt window ("DOS box"), and run:: ++command prompt window and run:: + + cd c:\Temp\foo-1.0 + python setup.py install +diff -r 137e45f15c0b Doc/library/2to3.rst +--- a/Doc/library/2to3.rst ++++ b/Doc/library/2to3.rst +@@ -123,7 +123,9 @@ + .. 2to3fixer:: callable + + Converts ``callable(x)`` to ``isinstance(x, collections.Callable)``, adding +- an import to :mod:`collections` if needed. ++ an import to :mod:`collections` if needed. Note ``callable(x)`` has returned ++ in Python 3.2, so if you do not intend to support Python 3.1, you can disable ++ this fixer. + + .. 2to3fixer:: dict + +diff -r 137e45f15c0b Doc/library/argparse.rst +--- a/Doc/library/argparse.rst ++++ b/Doc/library/argparse.rst +@@ -6,10 +6,10 @@ + .. moduleauthor:: Steven Bethard + .. sectionauthor:: Steven Bethard + ++.. versionadded:: 3.2 ++ + **Source code:** :source:`Lib/argparse.py` + +-.. versionadded:: 3.2 +- + -------------- + + The :mod:`argparse` module makes it easy to write user-friendly command-line +@@ -109,7 +109,7 @@ + + :class:`ArgumentParser` parses arguments through the + :meth:`~ArgumentParser.parse_args` method. This will inspect the command line, +-convert each arg to the appropriate type and then invoke the appropriate action. ++convert each argument to the appropriate type and then invoke the appropriate action. + In most cases, this means a simple :class:`Namespace` object will be built up from + attributes parsed out of the command line:: + +@@ -244,7 +244,7 @@ + --foo FOO foo help + + The help option is typically ``-h/--help``. The exception to this is +-if the ``prefix_chars=`` is specified and does not include ``'-'``, in ++if the ``prefix_chars=`` is specified and does not include ``-``, in + which case ``-h`` and ``--help`` are not valid options. In + this case, the first character in ``prefix_chars`` is used to prefix + the help options:: +@@ -260,7 +260,7 @@ + prefix_chars + ^^^^^^^^^^^^ + +-Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``. ++Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``. + Parsers that need to support different or additional prefix + characters, e.g. for options + like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument +@@ -273,7 +273,7 @@ + Namespace(bar='Y', f='X') + + The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of +-characters that does not include ``'-'`` will cause ``-f/--foo`` options to be ++characters that does not include ``-`` will cause ``-f/--foo`` options to be + disallowed. + + +@@ -395,7 +395,7 @@ + likewise for this epilog whose whitespace will be cleaned up and whose words + will be wrapped across a couple lines + +-Passing :class:`~argparse.RawDescriptionHelpFormatter` as ``formatter_class=`` ++Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=`` + indicates that description_ and epilog_ are already correctly formatted and + should not be line-wrapped:: + +@@ -421,7 +421,7 @@ + optional arguments: + -h, --help show this help message and exit + +-:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text ++:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text, + including argument descriptions. + + The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`, +@@ -703,7 +703,7 @@ + >>> parser.add_argument('--str', dest='types', action='append_const', const=str) + >>> parser.add_argument('--int', dest='types', action='append_const', const=int) + >>> parser.parse_args('--str --int'.split()) +- Namespace(types=[, ]) ++ Namespace(types=[, ]) + + * ``'version'`` - This expects a ``version=`` keyword argument in the + :meth:`~ArgumentParser.add_argument` call, and prints version information +@@ -759,7 +759,7 @@ + different number of command-line arguments with a single action. The supported + values are: + +-* N (an integer). N arguments from the command line will be gathered together into a ++* ``N`` (an integer). ``N`` arguments from the command line will be gathered together into a + list. For example:: + + >>> parser = argparse.ArgumentParser() +@@ -771,11 +771,11 @@ + Note that ``nargs=1`` produces a list of one item. This is different from + the default, in which the item is produced by itself. + +-* ``'?'``. One arg will be consumed from the command line if possible, and +- produced as a single item. If no command-line arg is present, the value from ++* ``'?'``. One argument will be consumed from the command line if possible, and ++ produced as a single item. If no command-line argument is present, the value from + default_ will be produced. Note that for optional arguments, there is an + additional case - the option string is present but not followed by a +- command-line arg. In this case the value from const_ will be produced. Some ++ command-line argument. In this case the value from const_ will be produced. Some + examples to illustrate this:: + + >>> parser = argparse.ArgumentParser() +@@ -817,7 +817,7 @@ + + * ``'+'``. Just like ``'*'``, all command-line args present are gathered into a + list. Additionally, an error message will be generated if there wasn't at +- least one command-line arg present. For example:: ++ least one command-line argument present. For example:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('foo', nargs='+') +@@ -828,7 +828,7 @@ + PROG: error: too few arguments + + If the ``nargs`` keyword argument is not provided, the number of arguments consumed +-is determined by the action_. Generally this means a single command-line arg ++is determined by the action_. Generally this means a single command-line argument + will be consumed and a single item (not a list) will be produced. + + +@@ -847,7 +847,7 @@ + (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional + argument that can be followed by zero or one command-line arguments. + When parsing the command line, if the option string is encountered with no +- command-line arg following it, the value of ``const`` will be assumed instead. ++ command-line argument following it, the value of ``const`` will be assumed instead. + See the nargs_ description for examples. + + The ``const`` keyword argument defaults to ``None``. +@@ -859,7 +859,7 @@ + All optional arguments and some positional arguments may be omitted at the + command line. The ``default`` keyword argument of + :meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``, +-specifies what value should be used if the command-line arg is not present. ++specifies what value should be used if the command-line argument is not present. + For optional arguments, the ``default`` value is used when the option string + was not present at the command line:: + +@@ -870,8 +870,8 @@ + >>> parser.parse_args(''.split()) + Namespace(foo=42) + +-For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value +-is used when no command-line arg was present:: ++For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value ++is used when no command-line argument was present:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('foo', nargs='?', default=42) +@@ -957,8 +957,8 @@ + Some command-line arguments should be selected from a restricted set of values. + These can be handled by passing a container object as the ``choices`` keyword + argument to :meth:`~ArgumentParser.add_argument`. When the command line is +-parsed, arg values will be checked, and an error message will be displayed if +-the arg was not one of the acceptable values:: ++parsed, argument values will be checked, and an error message will be displayed if ++the argument was not one of the acceptable values:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('foo', choices='abc') +@@ -1060,8 +1060,8 @@ + value as the "name" of each object. By default, for positional argument + actions, the dest_ value is used directly, and for optional argument actions, + the dest_ value is uppercased. So, a single positional argument with +-``dest='bar'`` will that argument will be referred to as ``bar``. A single +-optional argument ``--foo`` that should be followed by a single command-line arg ++``dest='bar'`` will be referred to as ``bar``. A single ++optional argument ``--foo`` that should be followed by a single command-line argument + will be referred to as ``FOO``. An example:: + + >>> parser = argparse.ArgumentParser() +@@ -1133,10 +1133,10 @@ + + For optional argument actions, the value of ``dest`` is normally inferred from + the option strings. :class:`ArgumentParser` generates the value of ``dest`` by +-taking the first long option string and stripping away the initial ``'--'`` ++taking the first long option string and stripping away the initial ``--`` + string. If no long option strings were supplied, ``dest`` will be derived from +-the first short option string by stripping the initial ``'-'`` character. Any +-internal ``'-'`` characters will be converted to ``'_'`` characters to make sure ++the first short option string by stripping the initial ``-`` character. Any ++internal ``-`` characters will be converted to ``_`` characters to make sure + the string is a valid attribute name. The examples below illustrate this + behavior:: + +@@ -1168,7 +1168,7 @@ + created and how they are assigned. See the documentation for + :meth:`add_argument` for details. + +- By default, the arg strings are taken from :data:`sys.argv`, and a new empty ++ By default, the argument strings are taken from :data:`sys.argv`, and a new empty + :class:`Namespace` object is created for the attributes. + + +@@ -1239,15 +1239,15 @@ + PROG: error: extra arguments found: badger + + +-Arguments containing ``"-"`` +-^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ++Arguments containing ``-`` ++^^^^^^^^^^^^^^^^^^^^^^^^^^ + + The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever + the user has clearly made a mistake, but some situations are inherently +-ambiguous. For example, the command-line arg ``'-1'`` could either be an ++ambiguous. For example, the command-line argument ``-1`` could either be an + attempt to specify an option or an attempt to provide a positional argument. + The :meth:`~ArgumentParser.parse_args` method is cautious here: positional +-arguments may only begin with ``'-'`` if they look like negative numbers and ++arguments may only begin with ``-`` if they look like negative numbers and + there are no options in the parser that look like negative numbers:: + + >>> parser = argparse.ArgumentParser(prog='PROG') +@@ -1280,7 +1280,7 @@ + usage: PROG [-h] [-1 ONE] [foo] + PROG: error: argument -1: expected one argument + +-If you have positional arguments that must begin with ``'-'`` and don't look ++If you have positional arguments that must begin with ``-`` and don't look + like negative numbers, you can insert the pseudo-argument ``'--'`` which tells + :meth:`~ArgumentParser.parse_args` that everything after that is a positional + argument:: +@@ -1398,7 +1398,7 @@ + >>> parser_b = subparsers.add_parser('b', help='b help') + >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') + >>> +- >>> # parse some arg lists ++ >>> # parse some argument lists + >>> parser.parse_args(['a', '12']) + Namespace(bar=12, foo=False) + >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) +@@ -1407,8 +1407,8 @@ + Note that the object returned by :meth:`parse_args` will only contain + attributes for the main parser and the subparser that was selected by the + command line (and not any other subparsers). So in the example above, when +- the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are +- present, and when the ``"b"`` command is specified, only the ``foo`` and ++ the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are ++ present, and when the ``b`` command is specified, only the ``foo`` and + ``baz`` attributes are present. + + Similarly, when a help message is requested from a subparser, only the help +diff -r 137e45f15c0b Doc/library/atexit.rst +--- a/Doc/library/atexit.rst ++++ b/Doc/library/atexit.rst +@@ -6,6 +6,9 @@ + .. moduleauthor:: Skip Montanaro + .. sectionauthor:: Skip Montanaro + ++**Source code:** :source:`Lib/atexit.py` ++ ++-------------- + + The :mod:`atexit` module defines functions to register and unregister cleanup + functions. Functions thus registered are automatically executed upon normal +diff -r 137e45f15c0b Doc/library/base64.rst +--- a/Doc/library/base64.rst ++++ b/Doc/library/base64.rst +@@ -45,8 +45,8 @@ + at least length 2 (additional characters are ignored) which specifies the + alternative alphabet used instead of the ``+`` and ``/`` characters. + +- The decoded string is returned. A `binascii.Error` is raised if *s* is +- incorrectly padded. ++ The decoded string is returned. A :exc:`binascii.Error` exception is raised ++ if *s* is incorrectly padded. + + If *validate* is ``False`` (the default), non-base64-alphabet characters are + discarded prior to the padding check. If *validate* is ``True``, +diff -r 137e45f15c0b Doc/library/builtins.rst +--- a/Doc/library/builtins.rst ++++ b/Doc/library/builtins.rst +@@ -36,6 +36,6 @@ + + As an implementation detail, most modules have the name ``__builtins__`` made + available as part of their globals. The value of ``__builtins__`` is normally +-either this module or the value of this modules's :attr:`__dict__` attribute. ++either this module or the value of this module's :attr:`__dict__` attribute. + Since this is an implementation detail, it may not be used by alternate + implementations of Python. +diff -r 137e45f15c0b Doc/library/cmd.rst +--- a/Doc/library/cmd.rst ++++ b/Doc/library/cmd.rst +@@ -205,6 +205,9 @@ + :mod:`readline`, on systems that support it, the interpreter will automatically + support :program:`Emacs`\ -like line editing and command-history keystrokes.) + ++ ++.. _cmd-example: ++ + Cmd Example + ----------- + +@@ -244,7 +247,7 @@ + right(*parse(arg)) + def do_left(self, arg): + 'Turn turtle left by given number of degrees: LEFT 90' +- right(*parse(arg)) ++ left(*parse(arg)) + def do_goto(self, arg): + 'Move turtle to an absolute position with changing orientation. GOTO 100 200' + goto(*parse(arg)) +diff -r 137e45f15c0b Doc/library/codecs.rst +--- a/Doc/library/codecs.rst ++++ b/Doc/library/codecs.rst +@@ -810,27 +810,28 @@ + Windows). There's a string constant with 256 characters that shows you which + character is mapped to which byte value. + +-All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints ++All of these encodings can only encode 256 of the 1114112 codepoints + defined in Unicode. A simple and straightforward way that can store each Unicode +-code point, is to store each codepoint as two consecutive bytes. There are two +-possibilities: Store the bytes in big endian or in little endian order. These +-two encodings are called UTF-16-BE and UTF-16-LE respectively. Their +-disadvantage is that if e.g. you use UTF-16-BE on a little endian machine you +-will always have to swap bytes on encoding and decoding. UTF-16 avoids this +-problem: Bytes will always be in natural endianness. When these bytes are read ++code point, is to store each codepoint as four consecutive bytes. There are two ++possibilities: store the bytes in big endian or in little endian order. These ++two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their ++disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you ++will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this ++problem: bytes will always be in natural endianness. When these bytes are read + by a CPU with a different endianness, then bytes have to be swapped though. To +-be able to detect the endianness of a UTF-16 byte sequence, there's the so +-called BOM (the "Byte Order Mark"). This is the Unicode character ``U+FEFF``. +-This character will be prepended to every UTF-16 byte sequence. The byte swapped +-version of this character (``0xFFFE``) is an illegal character that may not +-appear in a Unicode text. So when the first character in an UTF-16 byte sequence ++be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence, ++there's the so called BOM ("Byte Order Mark"). This is the Unicode character ++``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32`` ++byte sequence. The byte swapped version of this character (``0xFFFE``) is an ++illegal character that may not appear in a Unicode text. So when the ++first character in an ``UTF-16`` or ``UTF-32`` byte sequence + appears to be a ``U+FFFE`` the bytes have to be swapped on decoding. +-Unfortunately upto Unicode 4.0 the character ``U+FEFF`` had a second purpose as +-a ``ZERO WIDTH NO-BREAK SPACE``: A character that has no width and doesn't allow ++Unfortunately the character ``U+FEFF`` had a second purpose as ++a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow + a word to be split. It can e.g. be used to give hints to a ligature algorithm. + With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been + deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless +-Unicode software still must be able to handle ``U+FEFF`` in both roles: As a BOM ++Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM + it's a device to determine the storage layout of the encoded bytes, and vanishes + once the byte sequence has been decoded into a string; as a ``ZERO WIDTH + NO-BREAK SPACE`` it's a normal character that will be decoded like any other. +@@ -838,8 +839,8 @@ + There's another encoding that is able to encoding the full range of Unicode + characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues + with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two +-parts: Marker bits (the most significant bits) and payload bits. The marker bits +-are a sequence of zero to six 1 bits followed by a 0 bit. Unicode characters are ++parts: marker bits (the most significant bits) and payload bits. The marker bits ++are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are + encoded like this (with x being payload bits, which when concatenated give the + Unicode character): + +@@ -852,12 +853,7 @@ + +-----------------------------------+----------------------------------------------+ + | ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx | + +-----------------------------------+----------------------------------------------+ +-| ``U-00010000`` ... ``U-001FFFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | +-+-----------------------------------+----------------------------------------------+ +-| ``U-00200000`` ... ``U-03FFFFFF`` | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx | +-+-----------------------------------+----------------------------------------------+ +-| ``U-04000000`` ... ``U-7FFFFFFF`` | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx | +-| | 10xxxxxx | ++| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | + +-----------------------------------+----------------------------------------------+ + + The least significant bit of the Unicode character is the rightmost x bit. +@@ -882,13 +878,14 @@ + | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK + | INVERTED QUESTION MARK + +-in iso-8859-1), this increases the probability that a utf-8-sig encoding can be ++in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be + correctly guessed from the byte sequence. So here the BOM is not used to be able + to determine the byte order used for generating the byte sequence, but as a + signature that helps in guessing the encoding. On encoding the utf-8-sig codec + will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On +-decoding utf-8-sig will skip those three bytes if they appear as the first three +-bytes in the file. ++decoding ``utf-8-sig`` will skip those three bytes if they appear as the first ++three bytes in the file. In UTF-8, the use of the BOM is discouraged and ++should generally be avoided. + + + .. _standard-encodings: +diff -r 137e45f15c0b Doc/library/collections.rst +--- a/Doc/library/collections.rst ++++ b/Doc/library/collections.rst +@@ -1,4 +1,3 @@ +- + :mod:`collections` --- Container datatypes + ========================================== + +@@ -192,7 +191,7 @@ + * The multiset methods are designed only for use cases with positive values. + The inputs may be negative or zero, but only outputs with positive values + are created. There are no type restrictions, but the value type needs to +- support support addition, subtraction, and comparison. ++ support addition, subtraction, and comparison. + + * The :meth:`elements` method requires integer counts. It ignores zero and + negative counts. +@@ -886,7 +885,7 @@ + del self[key] + OrderedDict.__setitem__(self, key, value) + +-An ordered dictionary can combined with the :class:`Counter` class ++An ordered dictionary can be combined with the :class:`Counter` class + so that the counter remembers the order elements are first encountered:: + + class OrderedCounter(Counter, OrderedDict): +@@ -985,6 +984,7 @@ + subclass) or an arbitrary sequence which can be converted into a string using + the built-in :func:`str` function. + ++ + .. _collections-abstract-base-classes: + + ABCs - abstract base classes +diff -r 137e45f15c0b Doc/library/concurrent.futures.rst +--- a/Doc/library/concurrent.futures.rst ++++ b/Doc/library/concurrent.futures.rst +@@ -4,17 +4,17 @@ + .. module:: concurrent.futures + :synopsis: Execute computations concurrently using threads or processes. + ++.. versionadded:: 3.2 ++ + **Source code:** :source:`Lib/concurrent/futures/thread.py` + and :source:`Lib/concurrent/futures/process.py` + +-.. versionadded:: 3.2 +- + -------------- + + The :mod:`concurrent.futures` module provides a high-level interface for + asynchronously executing callables. + +-The asynchronous execution can be be performed with threads, using ++The asynchronous execution can be performed with threads, using + :class:`ThreadPoolExecutor`, or separate processes, using + :class:`ProcessPoolExecutor`. Both implement the same interface, which is + defined by the abstract :class:`Executor` class. +diff -r 137e45f15c0b Doc/library/configparser.rst +--- a/Doc/library/configparser.rst ++++ b/Doc/library/configparser.rst +@@ -806,17 +806,17 @@ + cfg = configparser.ConfigParser() + cfg.read('example.cfg') + +- # Set the optional `raw` argument of get() to True if you wish to disable ++ # Set the optional *raw* argument of get() to True if you wish to disable + # interpolation in a single get operation. + print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" + print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" + +- # The optional `vars` argument is a dict with members that will take ++ # The optional *vars* argument is a dict with members that will take + # precedence in interpolation. + print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation', + 'baz': 'evil'})) + +- # The optional `fallback` argument can be used to provide a fallback value ++ # The optional *fallback* argument can be used to provide a fallback value + print(cfg.get('Section1', 'foo')) + # -> "Python is fun!" + +diff -r 137e45f15c0b Doc/library/ctypes.rst +--- a/Doc/library/ctypes.rst ++++ b/Doc/library/ctypes.rst +@@ -1958,7 +1958,7 @@ + + .. function:: string_at(address, size=-1) + +- This function returns the C string starting at memory address address as a bytes ++ This function returns the C string starting at memory address *address* as a bytes + object. If size is specified, it is used as size, otherwise the string is assumed + to be zero-terminated. + +diff -r 137e45f15c0b Doc/library/curses.rst +--- a/Doc/library/curses.rst ++++ b/Doc/library/curses.rst +@@ -566,7 +566,7 @@ + + Instantiate the string *str* with the supplied parameters, where *str* should + be a parameterized string obtained from the terminfo database. E.g. +- ``tparm(tigetstr("cup"), 5, 3)`` could result in ``'\033[6;4H'``, the exact ++ ``tparm(tigetstr("cup"), 5, 3)`` could result in ``b'\033[6;4H'``, the exact + result depending on terminal type. + + +diff -r 137e45f15c0b Doc/library/datetime.rst +--- a/Doc/library/datetime.rst ++++ b/Doc/library/datetime.rst +@@ -18,19 +18,19 @@ + There are two kinds of date and time objects: "naive" and "aware". This + distinction refers to whether the object has any notion of time zone, daylight + saving time, or other kind of algorithmic or political time adjustment. Whether +-a naive :class:`datetime` object represents Coordinated Universal Time (UTC), ++a naive :class:`.datetime` object represents Coordinated Universal Time (UTC), + local time, or time in some other timezone is purely up to the program, just + like it's up to the program whether a particular number represents metres, +-miles, or mass. Naive :class:`datetime` objects are easy to understand and to ++miles, or mass. Naive :class:`.datetime` objects are easy to understand and to + work with, at the cost of ignoring some aspects of reality. + +-For applications requiring more, :class:`datetime` and :class:`time` objects ++For applications requiring more, :class:`.datetime` and :class:`.time` objects + have an optional time zone information attribute, :attr:`tzinfo`, that can be + set to an instance of a subclass of the abstract :class:`tzinfo` class. These + :class:`tzinfo` objects capture information about the offset from UTC time, the + time zone name, and whether Daylight Saving Time is in effect. Note that only + one concrete :class:`tzinfo` class, the :class:`timezone` class, is supplied by the +-:mod:`datetime` module. The :class:`timezone` class can reprsent simple ++:mod:`datetime` module. The :class:`timezone` class can represent simple + timezones with fixed offset from UTC such as UTC itself or North American EST and + EDT timezones. Supporting timezones at whatever level of detail is + required is up to the application. The rules for time adjustment across the +@@ -41,13 +41,13 @@ + + .. data:: MINYEAR + +- The smallest year number allowed in a :class:`date` or :class:`datetime` object. ++ The smallest year number allowed in a :class:`date` or :class:`.datetime` object. + :const:`MINYEAR` is ``1``. + + + .. data:: MAXYEAR + +- The largest year number allowed in a :class:`date` or :class:`datetime` object. ++ The largest year number allowed in a :class:`date` or :class:`.datetime` object. + :const:`MAXYEAR` is ``9999``. + + +@@ -91,14 +91,14 @@ + .. class:: timedelta + :noindex: + +- A duration expressing the difference between two :class:`date`, :class:`time`, +- or :class:`datetime` instances to microsecond resolution. ++ A duration expressing the difference between two :class:`date`, :class:`.time`, ++ or :class:`.datetime` instances to microsecond resolution. + + + .. class:: tzinfo + + An abstract base class for time zone information objects. These are used by the +- :class:`datetime` and :class:`time` classes to provide a customizable notion of ++ :class:`.datetime` and :class:`.time` classes to provide a customizable notion of + time adjustment (for example, to account for time zone and/or daylight saving + time). + +@@ -114,7 +114,7 @@ + + Objects of the :class:`date` type are always naive. + +-An object *d* of type :class:`time` or :class:`datetime` may be naive or aware. ++An object *d* of type :class:`.time` or :class:`.datetime` may be naive or aware. + *d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does + not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not + ``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive. +@@ -299,7 +299,7 @@ + -1 day, 19:00:00 + + In addition to the operations listed above :class:`timedelta` objects support +-certain additions and subtractions with :class:`date` and :class:`datetime` ++certain additions and subtractions with :class:`date` and :class:`.datetime` + objects (see below). + + .. versionchanged:: 3.2 +@@ -638,10 +638,10 @@ + :class:`datetime` Objects + ------------------------- + +-A :class:`datetime` object is a single object containing all the information +-from a :class:`date` object and a :class:`time` object. Like a :class:`date` +-object, :class:`datetime` assumes the current Gregorian calendar extended in +-both directions; like a time object, :class:`datetime` assumes there are exactly ++A :class:`.datetime` object is a single object containing all the information ++from a :class:`date` object and a :class:`.time` object. Like a :class:`date` ++object, :class:`.datetime` assumes the current Gregorian calendar extended in ++both directions; like a time object, :class:`.datetime` assumes there are exactly + 3600\*24 seconds in every day. + + Constructor: +@@ -689,7 +689,7 @@ + + Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like + :meth:`now`, but returns the current UTC date and time, as a naive +- :class:`datetime` object. An aware current UTC datetime can be obtained by ++ :class:`.datetime` object. An aware current UTC datetime can be obtained by + calling ``datetime.now(timezone.utc)``. See also :meth:`now`. + + .. classmethod:: datetime.fromtimestamp(timestamp, tz=None) +@@ -697,7 +697,7 @@ + Return the local date and time corresponding to the POSIX timestamp, such as is + returned by :func:`time.time`. If optional argument *tz* is ``None`` or not + specified, the timestamp is converted to the platform's local date and time, and +- the returned :class:`datetime` object is naive. ++ the returned :class:`.datetime` object is naive. + + Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the + timestamp is converted to *tz*'s time zone. In this case the result is +@@ -710,12 +710,12 @@ + 1970 through 2038. Note that on non-POSIX systems that include leap seconds in + their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, + and then it's possible to have two timestamps differing by a second that yield +- identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`. ++ identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`. + + + .. classmethod:: datetime.utcfromtimestamp(timestamp) + +- Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with ++ Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with + :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is + out of the range of values supported by the platform C :c:func:`gmtime` function. + It's common for this to be restricted to years in 1970 through 2038. See also +@@ -724,7 +724,7 @@ + + .. classmethod:: datetime.fromordinal(ordinal) + +- Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal, ++ Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal, + where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 + <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and + microsecond of the result are all 0, and :attr:`tzinfo` is ``None``. +@@ -732,18 +732,18 @@ + + .. classmethod:: datetime.combine(date, time) + +- Return a new :class:`datetime` object whose date components are equal to the ++ Return a new :class:`.datetime` object whose date components are equal to the + given :class:`date` object's, and whose time components and :attr:`tzinfo` +- attributes are equal to the given :class:`time` object's. For any +- :class:`datetime` object *d*, ++ attributes are equal to the given :class:`.time` object's. For any ++ :class:`.datetime` object *d*, + ``d == datetime.combine(d.date(), d.timetz())``. If date is a +- :class:`datetime` object, its time components and :attr:`tzinfo` attributes ++ :class:`.datetime` object, its time components and :attr:`tzinfo` attributes + are ignored. + + + .. classmethod:: datetime.strptime(date_string, format) + +- Return a :class:`datetime` corresponding to *date_string*, parsed according to ++ Return a :class:`.datetime` corresponding to *date_string*, parsed according to + *format*. This is equivalent to ``datetime(*(time.strptime(date_string, + format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format + can't be parsed by :func:`time.strptime` or if it returns a value which isn't a +@@ -755,19 +755,19 @@ + + .. attribute:: datetime.min + +- The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1, ++ The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1, + tzinfo=None)``. + + + .. attribute:: datetime.max + +- The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59, ++ The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59, + 59, 999999, tzinfo=None)``. + + + .. attribute:: datetime.resolution + +- The smallest possible difference between non-equal :class:`datetime` objects, ++ The smallest possible difference between non-equal :class:`.datetime` objects, + ``timedelta(microseconds=1)``. + + +@@ -810,24 +810,24 @@ + + .. attribute:: datetime.tzinfo + +- The object passed as the *tzinfo* argument to the :class:`datetime` constructor, ++ The object passed as the *tzinfo* argument to the :class:`.datetime` constructor, + or ``None`` if none was passed. + + + Supported operations: + +-+---------------------------------------+-------------------------------+ +-| Operation | Result | +-+=======================================+===============================+ +-| ``datetime2 = datetime1 + timedelta`` | \(1) | +-+---------------------------------------+-------------------------------+ +-| ``datetime2 = datetime1 - timedelta`` | \(2) | +-+---------------------------------------+-------------------------------+ +-| ``timedelta = datetime1 - datetime2`` | \(3) | +-+---------------------------------------+-------------------------------+ +-| ``datetime1 < datetime2`` | Compares :class:`datetime` to | +-| | :class:`datetime`. (4) | +-+---------------------------------------+-------------------------------+ +++---------------------------------------+--------------------------------+ ++| Operation | Result | +++=======================================+================================+ ++| ``datetime2 = datetime1 + timedelta`` | \(1) | +++---------------------------------------+--------------------------------+ ++| ``datetime2 = datetime1 - timedelta`` | \(2) | +++---------------------------------------+--------------------------------+ ++| ``timedelta = datetime1 - datetime2`` | \(3) | +++---------------------------------------+--------------------------------+ ++| ``datetime1 < datetime2`` | Compares :class:`.datetime` to | ++| | :class:`.datetime`. (4) | +++---------------------------------------+--------------------------------+ + + (1) + datetime2 is a duration of timedelta removed from datetime1, moving forward in +@@ -846,7 +846,7 @@ + in isolation can overflow in cases where datetime1 - timedelta does not. + + (3) +- Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if ++ Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if + both operands are naive, or if both are aware. If one is aware and the other is + naive, :exc:`TypeError` is raised. + +@@ -875,16 +875,16 @@ + + In order to stop comparison from falling back to the default scheme of comparing + object addresses, datetime comparison normally raises :exc:`TypeError` if the +- other comparand isn't also a :class:`datetime` object. However, ++ other comparand isn't also a :class:`.datetime` object. However, + ``NotImplemented`` is returned instead if the other comparand has a + :meth:`timetuple` attribute. This hook gives other kinds of date objects a +- chance at implementing mixed-type comparison. If not, when a :class:`datetime` ++ chance at implementing mixed-type comparison. If not, when a :class:`.datetime` + object is compared to an object of a different type, :exc:`TypeError` is raised + unless the comparison is ``==`` or ``!=``. The latter cases return + :const:`False` or :const:`True`, respectively. + +-:class:`datetime` objects can be used as dictionary keys. In Boolean contexts, +-all :class:`datetime` objects are considered to be true. ++:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts, ++all :class:`.datetime` objects are considered to be true. + + Instance methods: + +@@ -895,13 +895,13 @@ + + .. method:: datetime.time() + +- Return :class:`time` object with same hour, minute, second and microsecond. ++ Return :class:`.time` object with same hour, minute, second and microsecond. + :attr:`tzinfo` is ``None``. See also method :meth:`timetz`. + + + .. method:: datetime.timetz() + +- Return :class:`time` object with same hour, minute, second, microsecond, and ++ Return :class:`.time` object with same hour, minute, second, microsecond, and + tzinfo attributes. See also method :meth:`time`. + + +@@ -915,7 +915,7 @@ + + .. method:: datetime.astimezone(tz) + +- Return a :class:`datetime` object with new :attr:`tzinfo` attribute *tz*, ++ Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*, + adjusting the date and time data so the result is the same UTC time as + *self*, but in *tz*'s local time. + +@@ -989,7 +989,7 @@ + + .. method:: datetime.utctimetuple() + +- If :class:`datetime` instance *d* is naive, this is the same as ++ If :class:`.datetime` instance *d* is naive, this is the same as + ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what + ``d.dst()`` returns. DST is never in effect for a UTC time. + +@@ -1050,7 +1050,7 @@ + + .. method:: datetime.__str__() + +- For a :class:`datetime` instance *d*, ``str(d)`` is equivalent to ++ For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to + ``d.isoformat(' ')``. + + +@@ -1199,19 +1199,19 @@ + + .. attribute:: time.min + +- The earliest representable :class:`time`, ``time(0, 0, 0, 0)``. ++ The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``. + + + .. attribute:: time.max + +- The latest representable :class:`time`, ``time(23, 59, 59, 999999)``. ++ The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``. + + + .. attribute:: time.resolution + +- The smallest possible difference between non-equal :class:`time` objects, +- ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time` +- objects is not supported. ++ The smallest possible difference between non-equal :class:`.time` objects, ++ ``timedelta(microseconds=1)``, although note that arithmetic on ++ :class:`.time` objects is not supported. + + + Instance attributes (read-only): +@@ -1238,13 +1238,13 @@ + + .. attribute:: time.tzinfo + +- The object passed as the tzinfo argument to the :class:`time` constructor, or ++ The object passed as the tzinfo argument to the :class:`.time` constructor, or + ``None`` if none was passed. + + + Supported operations: + +-* comparison of :class:`time` to :class:`time`, where *a* is considered less ++* comparison of :class:`.time` to :class:`.time`, where *a* is considered less + than *b* when *a* precedes *b* in time. If one comparand is naive and the other + is aware, :exc:`TypeError` is raised. If both comparands are aware, and have + the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is +@@ -1252,7 +1252,7 @@ + have different :attr:`tzinfo` attributes, the comparands are first adjusted by + subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order + to stop mixed-type comparisons from falling back to the default comparison by +- object address, when a :class:`time` object is compared to an object of a ++ object address, when a :class:`.time` object is compared to an object of a + different type, :exc:`TypeError` is raised unless the comparison is ``==`` or + ``!=``. The latter cases return :const:`False` or :const:`True`, respectively. + +@@ -1260,7 +1260,7 @@ + + * efficient pickling + +-* in Boolean contexts, a :class:`time` object is considered to be true if and ++* in Boolean contexts, a :class:`.time` object is considered to be true if and + only if, after converting it to minutes and subtracting :meth:`utcoffset` (or + ``0`` if that's ``None``), the result is non-zero. + +@@ -1269,10 +1269,10 @@ + + .. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]) + +- Return a :class:`time` with the same value, except for those attributes given ++ Return a :class:`.time` with the same value, except for those attributes given + new values by whichever keyword arguments are specified. Note that +- ``tzinfo=None`` can be specified to create a naive :class:`time` from an +- aware :class:`time`, without conversion of the time data. ++ ``tzinfo=None`` can be specified to create a naive :class:`.time` from an ++ aware :class:`.time`, without conversion of the time data. + + + .. method:: time.isoformat() +@@ -1350,13 +1350,13 @@ + :class:`tzinfo` is an abstract base class, meaning that this class should not be + instantiated directly. You need to derive a concrete subclass, and (at least) + supply implementations of the standard :class:`tzinfo` methods needed by the +-:class:`datetime` methods you use. The :mod:`datetime` module supplies ++:class:`.datetime` methods you use. The :mod:`datetime` module supplies + a simple concrete subclass of :class:`tzinfo` :class:`timezone` which can reprsent + timezones with fixed offset from UTC such as UTC itself or North American EST and + EDT. + + An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the +-constructors for :class:`datetime` and :class:`time` objects. The latter objects ++constructors for :class:`.datetime` and :class:`.time` objects. The latter objects + view their attributes as being in local time, and the :class:`tzinfo` object + supports methods revealing offset of local time from UTC, the name of the time + zone, and DST offset, all relative to a date or time object passed to them. +@@ -1411,7 +1411,7 @@ + + ``tz.utcoffset(dt) - tz.dst(dt)`` + +- must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo == ++ must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo == + tz`` For sane :class:`tzinfo` subclasses, this expression yields the time + zone's "standard offset", which should not depend on the date or the time, but + only on geographic location. The implementation of :meth:`datetime.astimezone` +@@ -1422,13 +1422,13 @@ + + Most implementations of :meth:`dst` will probably look like one of these two:: + +- def dst(self): ++ def dst(self, dt): + # a fixed-offset class: doesn't account for DST + return timedelta(0) + + or :: + +- def dst(self): ++ def dst(self, dt): + # Code to set dston and dstoff to the time zone's DST + # transition times based on the input dt.year, and expressed + # in standard local time. Then +@@ -1443,7 +1443,7 @@ + + .. method:: tzinfo.tzname(dt) + +- Return the time zone name corresponding to the :class:`datetime` object *dt*, as ++ Return the time zone name corresponding to the :class:`.datetime` object *dt*, as + a string. Nothing about string names is defined by the :mod:`datetime` module, + and there's no requirement that it mean anything in particular. For example, + "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all +@@ -1456,11 +1456,11 @@ + The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`. + + +-These methods are called by a :class:`datetime` or :class:`time` object, in +-response to their methods of the same names. A :class:`datetime` object passes +-itself as the argument, and a :class:`time` object passes ``None`` as the ++These methods are called by a :class:`.datetime` or :class:`.time` object, in ++response to their methods of the same names. A :class:`.datetime` object passes ++itself as the argument, and a :class:`.time` object passes ``None`` as the + argument. A :class:`tzinfo` subclass's methods should therefore be prepared to +-accept a *dt* argument of ``None``, or of class :class:`datetime`. ++accept a *dt* argument of ``None``, or of class :class:`.datetime`. + + When ``None`` is passed, it's up to the class designer to decide the best + response. For example, returning ``None`` is appropriate if the class wishes to +@@ -1468,7 +1468,7 @@ + may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as + there is no other convention for discovering the standard offset. + +-When a :class:`datetime` object is passed in response to a :class:`datetime` ++When a :class:`.datetime` object is passed in response to a :class:`.datetime` + method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can + rely on this, unless user code calls :class:`tzinfo` methods directly. The + intent is that the :class:`tzinfo` methods interpret *dt* as being in local +@@ -1606,7 +1606,7 @@ + .. method:: timezone.fromutc(dt) + + Return ``dt + offset``. The *dt* argument must be an aware +- :class:`datetime` instance, with ``tzinfo`` set to ``self``. ++ :class:`.datetime` instance, with ``tzinfo`` set to ``self``. + + Class attributes: + +@@ -1620,18 +1620,18 @@ + :meth:`strftime` and :meth:`strptime` Behavior + ---------------------------------------------- + +-:class:`date`, :class:`datetime`, and :class:`time` objects all support a ++:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a + ``strftime(format)`` method, to create a string representing the time under the + control of an explicit format string. Broadly speaking, ``d.strftime(fmt)`` + acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())`` + although not all objects support a :meth:`timetuple` method. + + Conversely, the :meth:`datetime.strptime` class method creates a +-:class:`datetime` object from a string representing a date and time and a ++:class:`.datetime` object from a string representing a date and time and a + corresponding format string. ``datetime.strptime(date_string, format)`` is + equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``. + +-For :class:`time` objects, the format codes for year, month, and day should not ++For :class:`.time` objects, the format codes for year, month, and day should not + be used, as time objects have no such values. If they're used anyway, ``1900`` + is substituted for the year, and ``1`` for the month and day. + +@@ -1789,5 +1789,5 @@ + + .. versionchanged:: 3.2 + When the ``%z`` directive is provided to the :meth:`strptime` method, an +- aware :class:`datetime` object will be produced. The ``tzinfo`` of the ++ aware :class:`.datetime` object will be produced. The ``tzinfo`` of the + result will be set to a :class:`timezone` instance. +diff -r 137e45f15c0b Doc/library/email.header.rst +--- a/Doc/library/email.header.rst ++++ b/Doc/library/email.header.rst +@@ -141,11 +141,11 @@ + Returns an approximation of the :class:`Header` as a string, using an + unlimited line length. All pieces are converted to unicode using the + specified encoding and joined together appropriately. Any pieces with a +- charset of `unknown-8bit` are decoded as `ASCII` using the `replace` ++ charset of ``'unknown-8bit'`` are decoded as ASCII using the ``'replace'`` + error handler. + + .. versionchanged:: 3.2 +- Added handling for the `unknown-8bit` charset. ++ Added handling for the ``'unknown-8bit'`` charset. + + + .. method:: __eq__(other) +diff -r 137e45f15c0b Doc/library/email.message.rst +--- a/Doc/library/email.message.rst ++++ b/Doc/library/email.message.rst +@@ -291,7 +291,7 @@ + + Content-Disposition: attachment; filename="bud.gif" + +- An example with with non-ASCII characters:: ++ An example with non-ASCII characters:: + + msg.add_header('Content-Disposition', 'attachment', + filename=('iso-8859-1', '', 'Fußballer.ppt')) +diff -r 137e45f15c0b Doc/library/exceptions.rst +--- a/Doc/library/exceptions.rst ++++ b/Doc/library/exceptions.rst +@@ -40,9 +40,9 @@ + + The base class for all built-in exceptions. It is not meant to be directly + inherited by user-defined classes (for that, use :exc:`Exception`). If +- :func:`bytes` or :func:`str` is called on an instance of this class, the +- representation of the argument(s) to the instance are returned, or the empty +- string when there were no arguments. ++ :func:`str` is called on an instance of this class, the representation of ++ the argument(s) to the instance are returned, or the empty string when ++ there were no arguments. + + .. attribute:: args + +diff -r 137e45f15c0b Doc/library/functions.rst +--- a/Doc/library/functions.rst ++++ b/Doc/library/functions.rst +@@ -10,7 +10,7 @@ + =================== ================= ================== ================ ==================== + .. .. Built-in Functions .. .. + =================== ================= ================== ================ ==================== +-:func:`abs` :func:`dict` :func:`help` :func:`min` :func:`setattr` ++:func:`abs` |func-dict|_ :func:`help` :func:`min` :func:`setattr` + :func:`all` :func:`dir` :func:`hex` :func:`next` :func:`slice` + :func:`any` :func:`divmod` :func:`id` :func:`object` :func:`sorted` + :func:`ascii` :func:`enumerate` :func:`input` :func:`oct` :func:`staticmethod` +@@ -19,13 +19,22 @@ + :func:`bytearray` :func:`filter` :func:`issubclass` :func:`pow` :func:`super` + :func:`bytes` :func:`float` :func:`iter` :func:`print` :func:`tuple` + :func:`callable` :func:`format` :func:`len` :func:`property` :func:`type` +-:func:`chr` :func:`frozenset` :func:`list` :func:`range` :func:`vars` ++:func:`chr` |func-frozenset|_ :func:`list` :func:`range` :func:`vars` + :func:`classmethod` :func:`getattr` :func:`locals` :func:`repr` :func:`zip` + :func:`compile` :func:`globals` :func:`map` :func:`reversed` :func:`__import__` + :func:`complex` :func:`hasattr` :func:`max` :func:`round` +-:func:`delattr` :func:`hash` :func:`memoryview` :func:`set` ++:func:`delattr` :func:`hash` |func-memoryview|_ |func-set|_ + =================== ================= ================== ================ ==================== + ++.. using :func:`dict` would create a link to another page, so local targets are ++ used, with replacement texts to make the output in the table consistent ++ ++.. |func-dict| replace:: ``dict()`` ++.. |func-frozenset| replace:: ``frozenset()`` ++.. |func-memoryview| replace:: ``memoryview()`` ++.. |func-set| replace:: ``set()`` ++ ++ + .. function:: abs(x) + + Return the absolute value of a number. The argument may be an +@@ -74,11 +83,12 @@ + + .. function:: bool([x]) + +- Convert a value to a Boolean, using the standard truth testing procedure. If +- *x* is false or omitted, this returns :const:`False`; otherwise it returns +- :const:`True`. :class:`bool` is also a class, which is a subclass of +- :class:`int`. Class :class:`bool` cannot be subclassed further. Its only +- instances are :const:`False` and :const:`True`. ++ Convert a value to a Boolean, using the standard :ref:`truth testing ++ procedure `. If *x* is false or omitted, this returns ``False``; ++ otherwise it returns ``True``. :class:`bool` is also a class, which is a ++ subclass of :class:`int` (see :ref:`typesnumeric`). Class :class:`bool` ++ cannot be subclassed further. Its only instances are ``False`` and ++ ``True`` (see :ref:`bltin-boolean-values`). + + .. index:: pair: Boolean; type + +@@ -248,6 +258,7 @@ + example, ``delattr(x, 'foobar')`` is equivalent to ``del x.foobar``. + + ++.. _func-dict: + .. function:: dict([arg]) + :noindex: + +@@ -491,6 +502,7 @@ + + The float type is described in :ref:`typesnumeric`. + ++ + .. function:: format(value[, format_spec]) + + .. index:: +@@ -511,6 +523,8 @@ + :exc:`TypeError` exception is raised if the method is not found or if either + the *format_spec* or the return value are not strings. + ++ ++.. _func-frozenset: + .. function:: frozenset([iterable]) + :noindex: + +@@ -624,7 +638,8 @@ + .. function:: isinstance(object, classinfo) + + Return true if the *object* argument is an instance of the *classinfo* +- argument, or of a (direct or indirect) subclass thereof. If *object* is not ++ argument, or of a (direct, indirect or :term:`virtual `) subclass thereof. If *object* is not + an object of the given type, the function always returns false. If + *classinfo* is not a class (type object), it may be a tuple of type objects, + or may recursively contain other such tuples (other sequence types are not +@@ -634,7 +649,8 @@ + + .. function:: issubclass(class, classinfo) + +- Return true if *class* is a subclass (direct or indirect) of *classinfo*. A ++ Return true if *class* is a subclass (direct, indirect or :term:`virtual ++ `) of *classinfo*. A + class is considered a subclass of itself. *classinfo* may be a tuple of class + objects, in which case every entry in *classinfo* will be checked. In any other + case, a :exc:`TypeError` exception is raised. +@@ -715,6 +731,8 @@ + such as ``sorted(iterable, key=keyfunc, reverse=True)[0]`` and + ``heapq.nlargest(1, iterable, key=keyfunc)``. + ++ ++.. _func-memoryview: + .. function:: memoryview(obj) + :noindex: + +@@ -810,7 +828,7 @@ + .. note:: + + Python doesn't depend on the underlying operating system's notion of text +- files; all the the processing is done by Python itself, and is therefore ++ files; all the processing is done by Python itself, and is therefore + platform-independent. + + *buffering* is an optional integer used to set the buffering policy. Pass 0 +@@ -898,7 +916,7 @@ + .. XXX works for bytes too, but should it? + .. function:: ord(c) + +- Given a string representing one Uncicode character, return an integer ++ Given a string representing one Unicode character, return an integer + representing the Unicode code + point of that character. For example, ``ord('a')`` returns the integer ``97`` + and ``ord('\u2020')`` returns ``8224``. This is the inverse of :func:`chr`. +@@ -1038,7 +1056,7 @@ + + Range objects implement the :class:`collections.Sequence` ABC, and provide + features such as containment tests, element index lookup, slicing and +- support for negative indices: ++ support for negative indices (see :ref:`typesseq`): + + >>> r = range(0, 20, 2) + >>> r +@@ -1106,6 +1124,8 @@ + can't be represented exactly as a float. See :ref:`tut-fp-issues` for + more information. + ++ ++.. _func-set: + .. function:: set([iterable]) + :noindex: + +@@ -1347,10 +1367,10 @@ + def zip(*iterables): + # zip('ABCD', 'xy') --> Ax By + sentinel = object() +- iterables = [iter(it) for it in iterables] +- while iterables: ++ iterators = [iter(it) for it in iterables] ++ while iterators: + result = [] +- for it in iterables: ++ for it in iterators: + elem = next(it, sentinel) + if elem is sentinel: + return +diff -r 137e45f15c0b Doc/library/gettext.rst +--- a/Doc/library/gettext.rst ++++ b/Doc/library/gettext.rst +@@ -263,7 +263,7 @@ + + .. method:: lngettext(singular, plural, n) + +- If a fallback has been set, forward :meth:`ngettext` to the fallback. ++ If a fallback has been set, forward :meth:`lngettext` to the fallback. + Otherwise, return the translated message. Overridden in derived classes. + + +@@ -644,8 +644,8 @@ + .. [#] See the footnote for :func:`bindtextdomain` above. + + .. [#] François Pinard has written a program called :program:`xpot` which does a +- similar job. It is available as part of his :program:`po-utils` package at http +- ://po-utils.progiciels-bpi.ca/. ++ similar job. It is available as part of his `po-utils package ++ `_. + + .. [#] :program:`msgfmt.py` is binary compatible with GNU :program:`msgfmt` except that + it provides a simpler, all-Python implementation. With this and +diff -r 137e45f15c0b Doc/library/heapq.rst +--- a/Doc/library/heapq.rst ++++ b/Doc/library/heapq.rst +@@ -173,36 +173,36 @@ + with a dictionary pointing to an entry in the queue. + + Removing the entry or changing its priority is more difficult because it would +-break the heap structure invariants. So, a possible solution is to mark an +-entry as invalid and optionally add a new entry with the revised priority:: ++break the heap structure invariants. So, a possible solution is to mark the ++entry as removed and add a new entry with the revised priority:: + +- pq = [] # the priority queue list +- counter = itertools.count(1) # unique sequence count +- task_finder = {} # mapping of tasks to entries +- INVALID = 0 # mark an entry as deleted ++ pq = [] # list of entries arranged in a heap ++ entry_finder = {} # mapping of tasks to entries ++ REMOVED = '' # placeholder for a removed task ++ counter = itertools.count() # unique sequence count + +- def add_task(priority, task, count=None): +- if count is None: +- count = next(counter) ++ def add_task(task, priority=0): ++ 'Add a new task or update the priority of an existing task' ++ if task in entry_finder: ++ remove_task(task) ++ count = next(counter) + entry = [priority, count, task] +- task_finder[task] = entry ++ entry_finder[task] = entry + heappush(pq, entry) + +- def get_top_priority(): +- while True: ++ def remove_task(task): ++ 'Mark an existing task as REMOVED. Raise KeyError if not found.' ++ entry = entry_finder.pop(task) ++ entry[-1] = REMOVED ++ ++ def pop_task(): ++ 'Remove and return the lowest priority task. Raise KeyError if empty.' ++ while pq: + priority, count, task = heappop(pq) +- del task_finder[task] +- if count is not INVALID: ++ if task is not REMOVED: ++ del entry_finder[task] + return task +- +- def delete_task(task): +- entry = task_finder[task] +- entry[1] = INVALID +- +- def reprioritize(priority, task): +- entry = task_finder[task] +- add_task(priority, task, entry[1]) +- entry[1] = INVALID ++ raise KeyError('pop from an empty priority queue') + + + Theory +diff -r 137e45f15c0b Doc/library/html.parser.rst +--- a/Doc/library/html.parser.rst ++++ b/Doc/library/html.parser.rst +@@ -101,9 +101,9 @@ + .. method:: HTMLParser.handle_startendtag(tag, attrs) + + Similar to :meth:`handle_starttag`, but called when the parser encounters an +- XHTML-style empty tag (````). This method may be overridden by ++ XHTML-style empty tag (````). This method may be overridden by + subclasses which require this particular lexical information; the default +- implementation simple calls :meth:`handle_starttag` and :meth:`handle_endtag`. ++ implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`. + + + .. method:: HTMLParser.handle_endtag(tag) +@@ -115,7 +115,8 @@ + + .. method:: HTMLParser.handle_data(data) + +- This method is called to process arbitrary data. It is intended to be ++ This method is called to process arbitrary data (e.g. the content of ++ ```` and ````). It is intended to be + overridden by a derived class; the base class implementation does nothing. + + +@@ -178,27 +179,23 @@ + Example HTML Parser Application + ------------------------------- + +-As a basic example, below is a very basic HTML parser that uses the +-:class:`HTMLParser` class to print out tags as they are encountered:: ++As a basic example, below is a simple HTML parser that uses the ++:class:`HTMLParser` class to print out start tags, end tags, and data ++as they are encountered:: + +- >>> from html.parser import HTMLParser +- >>> +- >>> class MyHTMLParser(HTMLParser): +- ... def handle_starttag(self, tag, attrs): +- ... print("Encountered a {} start tag".format(tag)) +- ... def handle_endtag(self, tag): +- ... print("Encountered a {} end tag".format(tag)) +- ... +- >>> page = """

Title

I'm a paragraph!

""" +- >>> +- >>> myparser = MyHTMLParser() +- >>> myparser.feed(page) +- Encountered a html start tag +- Encountered a h1 start tag +- Encountered a h1 end tag +- Encountered a p start tag +- Encountered a p end tag +- Encountered a html end tag ++ from html.parser import HTMLParser ++ ++ class MyHTMLParser(HTMLParser): ++ def handle_starttag(self, tag, attrs): ++ print("Encountered a start tag:", tag) ++ def handle_endtag(self, tag): ++ print("Encountered an end tag:", tag) ++ def handle_data(self, data): ++ print("Encountered some data:", data) ++ ++ parser = MyHTMLParser() ++ parser.feed('Test' ++ '

Parse me!

') + + + .. rubric:: Footnotes +diff -r 137e45f15c0b Doc/library/http.client.rst +--- a/Doc/library/http.client.rst ++++ b/Doc/library/http.client.rst +@@ -435,7 +435,7 @@ + Set the host and the port for HTTP Connect Tunnelling. Normally used when it + is required to a HTTPS Connection through a proxy server. + +- The headers argument should be a mapping of extra HTTP headers to to sent ++ The headers argument should be a mapping of extra HTTP headers to sent + with the CONNECT request. + + .. versionadded:: 3.2 +@@ -472,10 +472,13 @@ + an argument. + + +-.. method:: HTTPConnection.endheaders() ++.. method:: HTTPConnection.endheaders(message_body=None) + +- Send a blank line to the server, signalling the end of the headers. +- ++ Send a blank line to the server, signalling the end of the headers. The ++ optional *message_body* argument can be used to pass a message body ++ associated with the request. The message body will be sent in the same ++ packet as the message headers if it is string, otherwise it is sent in a ++ separate packet. + + .. method:: HTTPConnection.send(data) + +diff -r 137e45f15c0b Doc/library/imaplib.rst +--- a/Doc/library/imaplib.rst ++++ b/Doc/library/imaplib.rst +@@ -109,7 +109,7 @@ + Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation. The + return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS + +HHMM"`` (including double-quotes). The *date_time* argument can be a +- number (int or float) represening seconds since epoch (as returned ++ number (int or float) representing seconds since epoch (as returned + by :func:`time.time`), a 9-tuple representing local time (as returned by + :func:`time.localtime`), or a double-quoted string. In the last case, it + is assumed to already be in the correct format. +diff -r 137e45f15c0b Doc/library/inspect.rst +--- a/Doc/library/inspect.rst ++++ b/Doc/library/inspect.rst +@@ -575,13 +575,13 @@ + may be called. + + For cases where you want passive introspection, like documentation tools, this +-can be inconvenient. `getattr_static` has the same signature as :func:`getattr` ++can be inconvenient. :func:`getattr_static` has the same signature as :func:`getattr` + but avoids executing code when it fetches attributes. + + .. function:: getattr_static(obj, attr, default=None) + + Retrieve attributes without triggering dynamic lookup via the +- descriptor protocol, `__getattr__` or `__getattribute__`. ++ descriptor protocol, :meth:`__getattr__` or :meth:`__getattribute__`. + + Note: this function may not be able to retrieve all attributes + that getattr can fetch (like dynamically created attributes) +@@ -589,12 +589,12 @@ + that raise AttributeError). It can also return descriptors objects + instead of instance members. + +- If the instance `__dict__` is shadowed by another member (for example a ++ If the instance :attr:`__dict__` is shadowed by another member (for example a + property) then this function will be unable to find instance members. + + .. versionadded:: 3.2 + +-`getattr_static` does not resolve descriptors, for example slot descriptors or ++:func:`getattr_static` does not resolve descriptors, for example slot descriptors or + getset descriptors on objects implemented in C. The descriptor object + is returned instead of the underlying attribute. + +diff -r 137e45f15c0b Doc/library/io.rst +--- a/Doc/library/io.rst ++++ b/Doc/library/io.rst +@@ -217,7 +217,7 @@ + :class:`IOBase` object can be iterated over yielding the lines in a stream. + Lines are defined slightly differently depending on whether the stream is + a binary stream (yielding bytes), or a text stream (yielding character +- strings). See :meth:`readline` below. ++ strings). See :meth:`~IOBase.readline` below. + + IOBase is also a context manager and therefore supports the + :keyword:`with` statement. In this example, *file* is closed after the +diff -r 137e45f15c0b Doc/library/itertools.rst +--- a/Doc/library/itertools.rst ++++ b/Doc/library/itertools.rst +@@ -557,16 +557,25 @@ + iterables are of uneven length, missing values are filled-in with *fillvalue*. + Iteration continues until the longest iterable is exhausted. Equivalent to:: + +- def zip_longest(*args, fillvalue=None): ++ class ZipExhausted(Exception): ++ pass ++ ++ def zip_longest(*args, **kwds): + # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- +- def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): +- yield counter() # yields the fillvalue, or raises IndexError ++ fillvalue = kwds.get('fillvalue') ++ counter = len(args) - 1 ++ def sentinel(): ++ nonlocal counter ++ if not counter: ++ raise ZipExhausted ++ counter -= 1 ++ yield fillvalue + fillers = repeat(fillvalue) +- iters = [chain(it, sentinel(), fillers) for it in args] ++ iterators = [chain(it, sentinel(), fillers) for it in args] + try: +- for tup in zip(*iters): +- yield tup +- except IndexError: ++ while iterators: ++ yield tuple(map(next, iterators)) ++ except ZipExhausted: + pass + + If one of the iterables is potentially infinite, then the :func:`zip_longest` +diff -r 137e45f15c0b Doc/library/locale.rst +--- a/Doc/library/locale.rst ++++ b/Doc/library/locale.rst +@@ -22,19 +22,19 @@ + + .. exception:: Error + +- Exception raised when :func:`setlocale` fails. ++ Exception raised when the locale passed to :func:`setlocale` is not ++ recognized. + + + .. function:: setlocale(category, locale=None) + +- If *locale* is specified, it may be a string, a tuple of the form ``(language +- code, encoding)``, or ``None``. If it is a tuple, it is converted to a string +- using the locale aliasing engine. If *locale* is given and not ``None``, +- :func:`setlocale` modifies the locale setting for the *category*. The available +- categories are listed in the data description below. The value is the name of a +- locale. An empty string specifies the user's default settings. If the +- modification of the locale fails, the exception :exc:`Error` is raised. If +- successful, the new locale setting is returned. ++ If *locale* is given and not ``None``, :func:`setlocale` modifies the locale ++ setting for the *category*. The available categories are listed in the data ++ description below. *locale* may be a string, or an iterable of two strings ++ (language code and encoding). If it's an iterable, it's converted to a locale ++ name using the locale aliasing engine. An empty string specifies the user's ++ default settings. If the modification of the locale fails, the exception ++ :exc:`Error` is raised. If successful, the new locale setting is returned. + + If *locale* is omitted or ``None``, the current setting for *category* is + returned. +diff -r 137e45f15c0b Doc/library/logging.handlers.rst +--- a/Doc/library/logging.handlers.rst ++++ b/Doc/library/logging.handlers.rst +@@ -790,7 +790,7 @@ + + + +-.. queue-listener: ++.. _queue-listener: + + QueueListener + ^^^^^^^^^^^^^ +diff -r 137e45f15c0b Doc/library/logging.rst +--- a/Doc/library/logging.rst ++++ b/Doc/library/logging.rst +@@ -57,9 +57,15 @@ + + .. attribute:: Logger.propagate + +- If this evaluates to false, logging messages are not passed by this logger or by +- its child loggers to the handlers of higher level (ancestor) loggers. The +- constructor sets this attribute to 1. ++ If this evaluates to true, logging messages are passed by this logger and by ++ its child loggers to the handlers of higher level (ancestor) loggers. ++ Messages are passed directly to the ancestor loggers' handlers - neither the ++ level nor filters of the ancestor loggers in question are considered. ++ ++ If this evaluates to false, logging messages are not passed to the handlers ++ of ancestor loggers. ++ ++ The constructor sets this attribute to 1. + + + .. method:: Logger.setLevel(lvl) +@@ -137,7 +143,7 @@ + + Stack (most recent call last): + +- This mimics the `Traceback (most recent call last):` which is used when ++ This mimics the ``Traceback (most recent call last):`` which is used when + displaying exception frames. + + The third keyword argument is *extra* which can be used to pass a +@@ -820,7 +826,7 @@ + + Stack (most recent call last): + +- This mimics the `Traceback (most recent call last):` which is used when ++ This mimics the ``Traceback (most recent call last):`` which is used when + displaying exception frames. + + The third optional keyword argument is *extra* which can be used to pass a +@@ -1059,11 +1065,11 @@ + If *capture* is ``True``, warnings issued by the :mod:`warnings` module will + be redirected to the logging system. Specifically, a warning will be + formatted using :func:`warnings.formatwarning` and the resulting string +- logged to a logger named 'py.warnings' with a severity of `WARNING`. ++ logged to a logger named ``'py.warnings'`` with a severity of ``'WARNING'``. + + If *capture* is ``False``, the redirection of warnings to the logging system + will stop, and warnings will be redirected to their original destinations +- (i.e. those in effect before `captureWarnings(True)` was called). ++ (i.e. those in effect before ``captureWarnings(True)`` was called). + + + .. seealso:: +diff -r 137e45f15c0b Doc/library/mailbox.rst +--- a/Doc/library/mailbox.rst ++++ b/Doc/library/mailbox.rst +@@ -780,7 +780,7 @@ + There is no requirement that :class:`Message` instances be used to represent + messages retrieved using :class:`Mailbox` instances. In some situations, the + time and memory required to generate :class:`Message` representations might +- not not acceptable. For such situations, :class:`Mailbox` instances also ++ not be acceptable. For such situations, :class:`Mailbox` instances also + offer string and file-like representations, and a custom message factory may + be specified when a :class:`Mailbox` instance is initialized. + +diff -r 137e45f15c0b Doc/library/mmap.rst +--- a/Doc/library/mmap.rst ++++ b/Doc/library/mmap.rst +@@ -259,7 +259,7 @@ + + .. method:: write_byte(byte) + +- Write the the integer *byte* into memory at the current ++ Write the integer *byte* into memory at the current + position of the file pointer; the file position is advanced by ``1``. If + the mmap was created with :const:`ACCESS_READ`, then writing to it will + raise a :exc:`TypeError` exception. +diff -r 137e45f15c0b Doc/library/multiprocessing.rst +--- a/Doc/library/multiprocessing.rst ++++ b/Doc/library/multiprocessing.rst +@@ -552,9 +552,9 @@ + Return ``True`` if the queue is full, ``False`` otherwise. Because of + multithreading/multiprocessing semantics, this is not reliable. + +- .. method:: put(item[, block[, timeout]]) +- +- Put item into the queue. If the optional argument *block* is ``True`` ++ .. method:: put(obj[, block[, timeout]]) ++ ++ Put obj into the queue. If the optional argument *block* is ``True`` + (the default) and *timeout* is ``None`` (the default), block if necessary until + a free slot is available. If *timeout* is a positive number, it blocks at + most *timeout* seconds and raises the :exc:`queue.Full` exception if no +@@ -563,9 +563,9 @@ + available, else raise the :exc:`queue.Full` exception (*timeout* is + ignored in that case). + +- .. method:: put_nowait(item) +- +- Equivalent to ``put(item, False)``. ++ .. method:: put_nowait(obj) ++ ++ Equivalent to ``put(obj, False)``. + + .. method:: get([block[, timeout]]) + +@@ -1494,7 +1494,7 @@ + a new shared object -- see documentation for the *method_to_typeid* + argument of :meth:`BaseManager.register`. + +- If an exception is raised by the call, then then is re-raised by ++ If an exception is raised by the call, then is re-raised by + :meth:`_callmethod`. If some other exception is raised in the manager's + process then this is converted into a :exc:`RemoteError` exception and is + raised by :meth:`_callmethod`. +@@ -1631,7 +1631,7 @@ + + The *chunksize* argument is the same as the one used by the :meth:`.map` + method. For very long iterables using a large value for *chunksize* can +- make make the job complete **much** faster than using the default value of ++ make the job complete **much** faster than using the default value of + ``1``. + + Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator +diff -r 137e45f15c0b Doc/library/operator.rst +--- a/Doc/library/operator.rst ++++ b/Doc/library/operator.rst +@@ -378,8 +378,6 @@ + +-----------------------+-------------------------+---------------------------------------+ + | Right Shift | ``a >> b`` | ``rshift(a, b)`` | + +-----------------------+-------------------------+---------------------------------------+ +-| Sequence Repetition | ``seq * i`` | ``repeat(seq, i)`` | +-+-----------------------+-------------------------+---------------------------------------+ + | Slice Assignment | ``seq[i:j] = values`` | ``setitem(seq, slice(i, j), values)`` | + +-----------------------+-------------------------+---------------------------------------+ + | Slice Deletion | ``del seq[i:j]`` | ``delitem(seq, slice(i, j))`` | +diff -r 137e45f15c0b Doc/library/optparse.rst +--- a/Doc/library/optparse.rst ++++ b/Doc/library/optparse.rst +@@ -7,14 +7,14 @@ + .. moduleauthor:: Greg Ward + .. sectionauthor:: Greg Ward + +-**Source code:** :source:`Lib/optparse.py` +- +--------------- +- +-.. deprecated:: 2.7 ++.. deprecated:: 3.2 + The :mod:`optparse` module is deprecated and will not be developed further; + development will continue with the :mod:`argparse` module. + ++**Source code:** :source:`Lib/optparse.py` ++ ++-------------- ++ + :mod:`optparse` is a more convenient, flexible, and powerful library for parsing + command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a + more declarative style of command-line parsing: you create an instance of +@@ -607,8 +607,8 @@ + + -g Group option. + +-A bit more complete example might invole using more than one group: still +-extendind the previous example:: ++A bit more complete example might involve using more than one group: still ++extending the previous example:: + + group = OptionGroup(parser, "Dangerous Options", + "Caution: use these options at your own risk. " +diff -r 137e45f15c0b Doc/library/os.rst +--- a/Doc/library/os.rst ++++ b/Doc/library/os.rst +@@ -29,11 +29,6 @@ + objects, and result in an object of the same type, if a path or file name is + returned. + +-.. note:: +- +- If not separately noted, all functions that claim "Availability: Unix" are +- supported on Mac OS X, which builds on a Unix core. +- + * An "Availability: Unix" note means that this function is commonly found on + Unix systems. It does not make any claims about its existence on a specific + operating system. +@@ -711,7 +706,7 @@ + by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the + beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the + current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of +- the file. ++ the file. Return the new cursor position in bytes, starting from the beginning. + + Availability: Unix, Windows. + +@@ -915,7 +910,7 @@ + try: + fp = open("myfile") + except IOError as e: +- if e.errno == errno.EACCESS: ++ if e.errno == errno.EACCES: + return "some default data" + # Not a permission error. + raise +@@ -1519,7 +1514,7 @@ + ineffective, because in bottom-up mode the directories in *dirnames* are + generated before *dirpath* itself is generated. + +- By default errors from the :func:`listdir` call are ignored. If optional ++ By default, errors from the :func:`listdir` call are ignored. If optional + argument *onerror* is specified, it should be a function; it will be called with + one argument, an :exc:`OSError` instance. It can report the error to continue + with the walk, or raise the exception to abort the walk. Note that the filename +diff -r 137e45f15c0b Doc/library/othergui.rst +--- a/Doc/library/othergui.rst ++++ b/Doc/library/othergui.rst +@@ -3,42 +3,22 @@ + Other Graphical User Interface Packages + ======================================= + +-There are an number of extension widget sets to :mod:`tkinter`. ++Major cross-platform (Windows, Mac OS X, Unix-like) GUI toolkits are ++available for Python: + + .. seealso:: + +- `Python megawidgets `_ +- is a toolkit for building high-level compound widgets in Python using the +- :mod:`tkinter` package. It consists of a set of base classes and a library of +- flexible and extensible megawidgets built on this foundation. These megawidgets +- include notebooks, comboboxes, selection widgets, paned widgets, scrolled +- widgets, dialog windows, etc. Also, with the Pmw.Blt interface to BLT, the +- busy, graph, stripchart, tabset and vector commands are be available. ++ `PyGObject `_ ++ provides introspection bindings for C libraries using ++ `GObject `_. One of ++ these libraries is the `GTK+ 3 `_ widget set. ++ GTK+ comes with many more widgets than Tkinter provides. An online ++ `Python GTK+ 3 Tutorial `_ ++ is available. + +- The initial ideas for Pmw were taken from the Tk ``itcl`` extensions ``[incr +- Tk]`` by Michael McLennan and ``[incr Widgets]`` by Mark Ulferts. Several of the +- megawidgets are direct translations from the itcl to Python. It offers most of +- the range of widgets that ``[incr Widgets]`` does, and is almost as complete as +- Tix, lacking however Tix's fast :class:`HList` widget for drawing trees. +- +- `Tkinter3000 Widget Construction Kit (WCK) `_ +- is a library that allows you to write new Tkinter widgets in pure Python. The +- WCK framework gives you full control over widget creation, configuration, screen +- appearance, and event handling. WCK widgets can be very fast and light-weight, +- since they can operate directly on Python data structures, without having to +- transfer data through the Tk/Tcl layer. +- +- +-The major cross-platform (Windows, Mac OS X, Unix-like) GUI toolkits that are +-also available for Python: +- +-.. seealso:: +- +- `PyGTK `_ +- is a set of bindings for the `GTK `_ widget set. It +- provides an object oriented interface that is slightly higher level than +- the C one. It comes with many more widgets than Tkinter provides, and has +- good Python-specific reference documentation. There are also bindings to ++ `PyGTK `_ provides bindings for an older version ++ of the library, GTK+ 2. It provides an object oriented interface that ++ is slightly higher level than the C one. There are also bindings to + `GNOME `_. One well known PyGTK application is + `PythonCAD `_. An online `tutorial + `_ is available. +@@ -55,6 +35,11 @@ + with Python and Qt `_, by Mark + Summerfield. + ++ `PySide `_ ++ is a newer binding to the Qt toolkit, provided by Nokia. ++ Compared to PyQt, its licensing scheme is friendlier to non-open source ++ applications. ++ + `wxPython `_ + wxPython is a cross-platform GUI toolkit for Python that is built around + the popular `wxWidgets `_ (formerly wxWindows) +diff -r 137e45f15c0b Doc/library/pickle.rst +--- a/Doc/library/pickle.rst ++++ b/Doc/library/pickle.rst +@@ -237,7 +237,7 @@ + + .. exception:: UnpicklingError + +- Error raised when there a problem unpickling an object, such as a data ++ Error raised when there is a problem unpickling an object, such as a data + corruption or a security violation. It inherits :exc:`PickleError`. + + Note that other exceptions may also be raised during unpickling, including +@@ -324,11 +324,11 @@ + + .. method:: persistent_load(pid) + +- Raise an :exc:`UnpickingError` by default. ++ Raise an :exc:`UnpicklingError` by default. + + If defined, :meth:`persistent_load` should return the object specified by + the persistent ID *pid*. If an invalid persistent ID is encountered, an +- :exc:`UnpickingError` should be raised. ++ :exc:`UnpicklingError` should be raised. + + See :ref:`pickle-persistent` for details and examples of uses. + +@@ -377,7 +377,7 @@ + + Note that functions (built-in and user-defined) are pickled by "fully qualified" + name reference, not by value. This means that only the function name is +-pickled, along with the name of module the function is defined in. Neither the ++pickled, along with the name of the module the function is defined in. Neither the + function's code, nor any of its function attributes are pickled. Thus the + defining module must be importable in the unpickling environment, and the module + must contain the named object, otherwise an exception will be raised. [#]_ +@@ -668,7 +668,7 @@ + For this reason, you may want to control what gets unpickled by customizing + :meth:`Unpickler.find_class`. Unlike its name suggests, :meth:`find_class` is + called whenever a global (i.e., a class or a function) is requested. Thus it is +-possible to either forbid completely globals or restrict them to a safe subset. ++possible to either completely forbid globals or restrict them to a safe subset. + + Here is an example of an unpickler allowing only few safe classes from the + :mod:`builtins` module to be loaded:: +diff -r 137e45f15c0b Doc/library/random.rst +--- a/Doc/library/random.rst ++++ b/Doc/library/random.rst +@@ -163,6 +163,7 @@ + The end-point value ``b`` may or may not be included in the range + depending on floating-point rounding in the equation ``a + (b-a) * random()``. + ++ + .. function:: triangular(low, high, mode) + + Return a random floating point number *N* such that ``low <= N <= high`` and +@@ -191,6 +192,12 @@ + Gamma distribution. (*Not* the gamma function!) Conditions on the + parameters are ``alpha > 0`` and ``beta > 0``. + ++ The probability distribution function is:: ++ ++ x ** (alpha - 1) * math.exp(-x / beta) ++ pdf(x) = -------------------------------------- ++ math.gamma(alpha) * beta ** alpha ++ + + .. function:: gauss(mu, sigma) + +diff -r 137e45f15c0b Doc/library/re.rst +--- a/Doc/library/re.rst ++++ b/Doc/library/re.rst +@@ -80,7 +80,7 @@ + characters either stand for classes of ordinary characters, or affect + how the regular expressions around them are interpreted. Regular + expression pattern strings may not contain null bytes, but can specify +-the null byte using the ``\number`` notation, e.g., ``'\x00'``. ++the null byte using a ``\number`` notation such as ``'\x00'``. + + + The special characters are: +@@ -161,30 +161,36 @@ + raw strings for all but the simplest expressions. + + ``[]`` +- Used to indicate a set of characters. Characters can be listed individually, or +- a range of characters can be indicated by giving two characters and separating +- them by a ``'-'``. Special characters are not active inside sets. For example, +- ``[akm$]`` will match any of the characters ``'a'``, ``'k'``, +- ``'m'``, or ``'$'``; ``[a-z]`` will match any lowercase letter, and +- ``[a-zA-Z0-9]`` matches any letter or digit. Character classes such +- as ``\w`` or ``\S`` (defined below) are also acceptable inside a +- range, although the characters they match depends on whether +- :const:`ASCII` or :const:`LOCALE` mode is in force. If you want to +- include a ``']'`` or a ``'-'`` inside a set, precede it with a +- backslash, or place it as the first character. The pattern ``[]]`` +- will match ``']'``, for example. ++ Used to indicate a set of characters. In a set: + +- You can match the characters not within a range by :dfn:`complementing` the set. +- This is indicated by including a ``'^'`` as the first character of the set; +- ``'^'`` elsewhere will simply match the ``'^'`` character. For example, +- ``[^5]`` will match any character except ``'5'``, and ``[^^]`` will match any +- character except ``'^'``. ++ * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``, ++ ``'m'``, or ``'k'``. + +- Note that inside ``[]`` the special forms and special characters lose +- their meanings and only the syntaxes described here are valid. For +- example, ``+``, ``*``, ``(``, ``)``, and so on are treated as +- literals inside ``[]``, and backreferences cannot be used inside +- ``[]``. ++ * Ranges of characters can be indicated by giving two characters and separating ++ them by a ``'-'``, for example ``[a-z]`` will match any lowercase ASCII letter, ++ ``[0-5][0-9]`` will match all the two-digits numbers from ``00`` to ``59``, and ++ ``[0-9A-Fa-f]`` will match any hexadecimal digit. If ``-`` is escaped (e.g. ++ ``[a\-z]``) or if it's placed as the first or last character (e.g. ``[a-]``), ++ it will match a literal ``'-'``. ++ ++ * Special characters lose their special meaning inside sets. For example, ++ ``[(+*)]`` will match any of the literal characters ``'('``, ``'+'``, ++ ``'*'``, or ``')'``. ++ ++ * Character classes such as ``\w`` or ``\S`` (defined below) are also accepted ++ inside a set, although the characters they match depends on whether ++ :const:`ASCII` or :const:`LOCALE` mode is in force. ++ ++ * Characters that are not within a range can be matched by :dfn:`complementing` ++ the set. If the first character of the set is ``'^'``, all the characters ++ that are *not* in the set will be matched. For example, ``[^5]`` will match ++ any character except ``'5'``, and ``[^^]`` will match any character except ++ ``'^'``. ``^`` has no special meaning if it's not the first character in ++ the set. ++ ++ * To match a literal ``']'`` inside a set, precede it with a backslash, or ++ place it at the beginning of the set. For example, both ``[()[\]{}]`` and ++ ``[]()[{}]`` will both match a parenthesis. + + ``'|'`` + ``A|B``, where A and B can be arbitrary REs, creates a regular expression that +@@ -405,7 +411,7 @@ + \r \t \v \x + \\ + +-Octal escapes are included in a limited form: If the first digit is a 0, or if ++Octal escapes are included in a limited form. If the first digit is a 0, or if + there are three octal digits, it is considered an octal escape. Otherwise, it is + a group reference. As for string literals, octal escapes are always at most + three digits in length. +@@ -413,8 +419,8 @@ + + .. _matching-searching: + +-Matching vs Searching +---------------------- ++Matching vs. Searching ++---------------------- + + .. sectionauthor:: Fred L. Drake, Jr. + +@@ -595,8 +601,7 @@ + ['', '...', 'words', ', ', 'words', '...', ''] + + That way, separator components are always found at the same relative +- indices within the result list (e.g., if there's one capturing group +- in the separator, the 0th, the 2nd and so forth). ++ indices within the result list. + + Note that *split* will never split a string on an empty pattern match. + For example: +@@ -713,7 +718,7 @@ + -------------------------- + + Compiled regular expression objects support the following methods and +-attributes. ++attributes: + + .. method:: regex.search(string[, pos[, endpos]]) + +@@ -732,7 +737,7 @@ + The optional parameter *endpos* limits how far the string will be searched; it + will be as if the string is *endpos* characters long, so only the characters + from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less +- than *pos*, no match will be found, otherwise, if *rx* is a compiled regular ++ than *pos*, no match will be found; otherwise, if *rx* is a compiled regular + expression object, ``rx.search(string, 0, 50)`` is equivalent to + ``rx.search(string[:50], 0)``. + +@@ -820,8 +825,8 @@ + Match Objects + ------------- + +-Match objects always have a boolean value of :const:`True`, so that you can test +-whether e.g. :func:`match` resulted in a match with a simple if statement. They ++Match objects always have a boolean value of :const:`True`. This lets you ++use a simple if-statement to test whether a match was found. Match objects + support the following methods and attributes: + + +@@ -998,7 +1003,7 @@ + --------------------------- + + +-Checking For a Pair ++Checking for a Pair + ^^^^^^^^^^^^^^^^^^^ + + In this example, we'll use the following helper function to display match +@@ -1013,16 +1018,16 @@ + + Suppose you are writing a poker program where a player's hand is represented as + a 5-character string with each character representing a card, "a" for ace, "k" +-for king, "q" for queen, j for jack, "0" for 10, and "1" through "9" ++for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9" + representing the card with that value. + + To see if a given string is a valid hand, one could do the following: + +- >>> valid = re.compile(r"[0-9akqj]{5}$") +- >>> displaymatch(valid.match("ak05q")) # Valid. +- "" +- >>> displaymatch(valid.match("ak05e")) # Invalid. +- >>> displaymatch(valid.match("ak0")) # Invalid. ++ >>> valid = re.compile(r"^[a2-9tjqk]{5}$") ++ >>> displaymatch(valid.match("akt5q")) # Valid. ++ "" ++ >>> displaymatch(valid.match("akt5e")) # Invalid. ++ >>> displaymatch(valid.match("akt")) # Invalid. + >>> displaymatch(valid.match("727ak")) # Valid. + "" + +@@ -1106,7 +1111,7 @@ + + If you create regular expressions that require the engine to perform a lot of + recursion, you may encounter a :exc:`RuntimeError` exception with the message +-``maximum recursion limit`` exceeded. For example, :: ++``maximum recursion limit exceeded``. For example, :: + + >>> s = 'Begin ' + 1000*'a very long string ' + 'end' + >>> re.match('Begin (\w| )*? end', s).end() +diff -r 137e45f15c0b Doc/library/sched.rst +--- a/Doc/library/sched.rst ++++ b/Doc/library/sched.rst +@@ -95,7 +95,7 @@ + + .. method:: scheduler.enter(delay, priority, action, argument) + +- Schedule an event for *delay* more time units. Other then the relative time, the ++ Schedule an event for *delay* more time units. Other than the relative time, the + other arguments, the effect and the return value are the same as those for + :meth:`enterabs`. + +diff -r 137e45f15c0b Doc/library/shutil.rst +--- a/Doc/library/shutil.rst ++++ b/Doc/library/shutil.rst +@@ -269,7 +269,8 @@ + *owner* and *group* are used when creating a tar archive. By default, + uses the current owner and group. + +- *logger* is an instance of :class:`logging.Logger`. ++ *logger* must be an object compatible with :pep:`282`, usually an instance of ++ :class:`logging.Logger`. + + .. versionadded:: 3.2 + +diff -r 137e45f15c0b Doc/library/socket.rst +--- a/Doc/library/socket.rst ++++ b/Doc/library/socket.rst +@@ -64,20 +64,20 @@ + tuple, and the fields depend on the address type. The general tuple form is + ``(addr_type, v1, v2, v3 [, scope])``, where: + +- - *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or +- TIPC_ADDR_ID. +- - *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and +- TIPC_NODE_SCOPE. +- - If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is ++ - *addr_type* is one of :const:`TIPC_ADDR_NAMESEQ`, :const:`TIPC_ADDR_NAME`, ++ or :const:`TIPC_ADDR_ID`. ++ - *scope* is one of :const:`TIPC_ZONE_SCOPE`, :const:`TIPC_CLUSTER_SCOPE`, and ++ :const:`TIPC_NODE_SCOPE`. ++ - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2* is + the port identifier, and *v3* should be 0. + +- If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2* ++ If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2* + is the lower port number, and *v3* is the upper port number. + +- If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the ++ If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the + reference, and *v3* should be set to 0. + +- If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the ++ If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the + reference, and *v3* should be set to 0. + + - Certain other address families (:const:`AF_BLUETOOTH`, :const:`AF_PACKET`) +diff -r 137e45f15c0b Doc/library/socketserver.rst +--- a/Doc/library/socketserver.rst ++++ b/Doc/library/socketserver.rst +@@ -39,11 +39,12 @@ + + When inheriting from :class:`ThreadingMixIn` for threaded connection behavior, + you should explicitly declare how you want your threads to behave on an abrupt +-shutdown. The :class:`ThreadingMixIn` class defines an attribute ++shutdown. The :class:`ThreadingMixIn` class defines an attribute + *daemon_threads*, which indicates whether or not the server should wait for +-thread termination. You should set the flag explicitly if you would like threads +-to behave autonomously; the default is :const:`False`, meaning that Python will +-not exit until all threads created by :class:`ThreadingMixIn` have exited. ++thread termination. You should set the flag explicitly if you would like ++threads to behave autonomously; the default is :const:`False`, meaning that ++Python will not exit until all threads created by :class:`ThreadingMixIn` have ++exited. + + Server classes have the same external methods and attributes, no matter what + network protocol they use. +@@ -115,8 +116,8 @@ + finished requests and to use :func:`select` to decide which request to work on + next (or whether to handle a new incoming request). This is particularly + important for stream services where each client can potentially be connected for +-a long time (if threads or subprocesses cannot be used). See :mod:`asyncore` for +-another way to manage this. ++a long time (if threads or subprocesses cannot be used). See :mod:`asyncore` ++for another way to manage this. + + .. XXX should data and methods be intermingled, or separate? + how should the distinction between class and instance variables be drawn? +@@ -192,7 +193,7 @@ + + .. attribute:: BaseServer.allow_reuse_address + +- Whether the server will allow the reuse of an address. This defaults to ++ 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. + + +@@ -269,7 +270,7 @@ + .. method:: BaseServer.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. ++ just :meth:`listen`\ s to the server's socket. May be overridden. + + + .. method:: BaseServer.server_bind() +@@ -280,10 +281,10 @@ + + .. method:: BaseServer.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 +@@ -348,7 +349,7 @@ + def handle(self): + # self.request is the TCP socket connected to the client + self.data = self.request.recv(1024).strip() +- print("%s wrote:" % self.client_address[0]) ++ print("{} wrote:".format(self.client_address[0])) + print(self.data) + # just send back the same data, but upper-cased + self.request.send(self.data.upper()) +@@ -372,7 +373,7 @@ + # self.rfile is a file-like object created by the handler; + # we can now use e.g. readline() instead of raw recv() calls + self.data = self.rfile.readline().strip() +- print("%s wrote:" % self.client_address[0]) ++ print("{} wrote:".format(self.client_address[0])) + print(self.data) + # Likewise, self.wfile is a file-like object used to write back + # to the client +@@ -395,16 +396,18 @@ + # Create a socket (SOCK_STREAM means a TCP socket) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + +- # Connect to server and send data +- sock.connect((HOST, PORT)) +- sock.send(bytes(data + "\n","utf8")) ++ try: ++ # Connect to server and send data ++ sock.connect((HOST, PORT)) ++ sock.send(bytes(data + "\n", "utf-8")) + +- # Receive data from the server and shut down +- received = sock.recv(1024) +- sock.close() ++ # Receive data from the server and shut down ++ received = str(sock.recv(1024), "utf-8") ++ finally: ++ sock.close() + +- print("Sent: %s" % data) +- print("Received: %s" % received) ++ print("Sent: {}".format(data)) ++ print("Received: {}".format(received)) + + + The output of the example should look something like this: +@@ -421,10 +424,10 @@ + + $ python TCPClient.py hello world with TCP + Sent: hello world with TCP +- Received: b'HELLO WORLD WITH TCP' ++ Received: HELLO WORLD WITH TCP + $ python TCPClient.py python is nice + Sent: python is nice +- Received: b'PYTHON IS NICE' ++ Received: PYTHON IS NICE + + + :class:`socketserver.UDPServer` Example +@@ -445,7 +448,7 @@ + def handle(self): + data = self.request[0].strip() + socket = self.request[1] +- print("%s wrote:" % self.client_address[0]) ++ print("{} wrote:".format(self.client_address[0])) + print(data) + socket.sendto(data.upper(), self.client_address) + +@@ -467,11 +470,11 @@ + + # As you can see, there is no connect() call; UDP has no connections. + # Instead, data is directly sent to the recipient via sendto(). +- sock.sendto(bytes(data + "\n","utf8"), (HOST, PORT)) +- received = sock.recv(1024) ++ sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT)) ++ received = str(sock.recv(1024), "utf-8") + +- print("Sent: %s" % data) +- print("Received: %s" % received) ++ print("Sent: {}".format(data)) ++ print("Received: {}".format(received)) + + The output of the example should look exactly like for the TCP server example. + +@@ -491,9 +494,9 @@ + class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler): + + def handle(self): +- data = self.request.recv(1024) ++ data = str(self.request.recv(1024), 'ascii') + cur_thread = threading.current_thread() +- response = bytes("%s: %s" % (cur_thread.getName(), data),'ascii') ++ response = bytes("{}: {}".format(cur_thread.name, data), 'ascii') + self.request.send(response) + + class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): +@@ -502,10 +505,12 @@ + def client(ip, port, message): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((ip, port)) +- sock.send(message) +- response = sock.recv(1024) +- print("Received: %s" % response) +- sock.close() ++ try: ++ sock.send(bytes(message, 'ascii')) ++ response = str(sock.recv(1024), 'ascii') ++ print("Received: {}".format(response)) ++ finally: ++ sock.close() + + if __name__ == "__main__": + # Port 0 means to select an arbitrary unused port +@@ -518,13 +523,13 @@ + # more thread for each request + server_thread = threading.Thread(target=server.serve_forever) + # Exit the server thread when the main thread terminates +- server_thread.setDaemon(True) ++ server_thread.daemon = True + server_thread.start() + print("Server loop running in thread:", server_thread.name) + +- client(ip, port, b"Hello World 1") +- client(ip, port, b"Hello World 2") +- client(ip, port, b"Hello World 3") ++ client(ip, port, "Hello World 1") ++ client(ip, port, "Hello World 2") ++ client(ip, port, "Hello World 3") + + server.shutdown() + +@@ -533,9 +538,9 @@ + + $ python ThreadedTCPServer.py + Server loop running in thread: Thread-1 +- Received: b"Thread-2: b'Hello World 1'" +- Received: b"Thread-3: b'Hello World 2'" +- Received: b"Thread-4: b'Hello World 3'" ++ Received: Thread-2: Hello World 1 ++ Received: Thread-3: Hello World 2 ++ Received: Thread-4: Hello World 3 + + + The :class:`ForkingMixIn` class is used in the same way, except that the server +diff -r 137e45f15c0b Doc/library/sqlite3.rst +--- a/Doc/library/sqlite3.rst ++++ b/Doc/library/sqlite3.rst +@@ -243,7 +243,7 @@ + .. method:: Connection.commit() + + This method commits the current transaction. If you don't call this method, +- anything you did since the last call to ``commit()`` is not visible from from ++ anything you did since the last call to ``commit()`` is not visible from + other database connections. If you wonder why you don't see the data you've + written to the database, please check you didn't forget to call this method. + +diff -r 137e45f15c0b Doc/library/ssl.rst +--- a/Doc/library/ssl.rst ++++ b/Doc/library/ssl.rst +@@ -990,8 +990,8 @@ + Class :class:`socket.socket` + Documentation of underlying :mod:`socket` class + +- `Introducing SSL and Certificates using OpenSSL `_ +- Frederick J. Hirsch ++ `TLS (Transport Layer Security) and SSL (Secure Socket Layer) `_ ++ Debby Koren + + `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management `_ + Steve Kent +diff -r 137e45f15c0b Doc/library/stdtypes.rst +--- a/Doc/library/stdtypes.rst ++++ b/Doc/library/stdtypes.rst +@@ -54,7 +54,7 @@ + + * instances of user-defined classes, if the class defines a :meth:`__bool__` or + :meth:`__len__` method, when that method returns the integer zero or +- :class:`bool` value ``False``. [#]_ ++ :class:`bool` value ``False``. [1]_ + + .. index:: single: true + +@@ -261,7 +261,7 @@ + operands of different numeric types, the operand with the "narrower" type is + widened to that of the other, where integer is narrower than floating point, + which is narrower than complex. Comparisons between numbers of mixed type use +-the same rule. [#]_ The constructors :func:`int`, :func:`float`, and ++the same rule. [2]_ The constructors :func:`int`, :func:`float`, and + :func:`complex` can be used to produce numbers of a specific type. + + All numeric types (except complex) support the following operations, sorted by +@@ -852,7 +852,7 @@ + Most sequence types support the following operations. The ``in`` and ``not in`` + operations have the same priorities as the comparison operations. The ``+`` and + ``*`` operations have the same priority as the corresponding numeric operations. +-[#]_ Additional methods are provided for :ref:`typesseq-mutable`. ++[3]_ Additional methods are provided for :ref:`typesseq-mutable`. + + This table lists the sequence operations sorted in ascending priority + (operations in the same box have the same priority). In the table, *s* and *t* +@@ -964,15 +964,18 @@ + If *k* is ``None``, it is treated like ``1``. + + (6) +- .. impl-detail:: +- +- If *s* and *t* are both strings, some Python implementations such as +- CPython can usually perform an in-place optimization for assignments of +- the form ``s = s + t`` or ``s += t``. When applicable, this optimization +- makes quadratic run-time much less likely. This optimization is both +- version and implementation dependent. For performance sensitive code, it +- is preferable to use the :meth:`str.join` method which assures consistent +- linear concatenation performance across versions and implementations. ++ Concatenating immutable strings always results in a new object. This means ++ that building up a string by repeated concatenation will have a quadratic ++ runtime cost in the total string length. To get a linear runtime cost, ++ you must switch to one of the alternatives below: ++ ++ * if concatenating :class:`str` objects, you can build a list and use ++ :meth:`str.join` at the end; ++ ++ * if concatenating :class:`bytes` objects, you can similarly use ++ :meth:`bytes.join`, or you can do in-place concatenation with a ++ :class:`bytearray` object. :class:`bytearray` objects are mutable and ++ have an efficient overallocation mechanism. + + + .. _string-methods: +@@ -1033,7 +1036,7 @@ + + .. method:: str.expandtabs([tabsize]) + +- Return a copy of the string where all tab characters are replaced by one or ++ Return a copy of the string where all tab characters are replaced by zero or + more spaces, depending on the current column and the given tab size. The + column number is reset to zero after each newline occurring in the string. + If *tabsize* is not given, a tab size of ``8`` characters is assumed. This +@@ -1117,7 +1120,7 @@ + characters and there is at least one character, false + otherwise. Decimal characters are those from general category "Nd". This category + includes digit characters, and all characters +- that that can be used to form decimal-radix numbers, e.g. U+0660, ++ that can be used to form decimal-radix numbers, e.g. U+0660, + ARABIC-INDIC DIGIT ZERO. + + +@@ -1137,10 +1140,8 @@ + + .. method:: str.islower() + +- Return true if all cased characters in the string are lowercase and there is at +- least one cased character, false otherwise. Cased characters are those with +- general category property being one of "Lu", "Ll", or "Lt" and lowercase characters +- are those with general category property "Ll". ++ Return true if all cased characters [4]_ in the string are lowercase and ++ there is at least one cased character, false otherwise. + + + .. method:: str.isnumeric() +@@ -1180,10 +1181,8 @@ + + .. method:: str.isupper() + +- Return true if all cased characters in the string are uppercase and there is at +- least one cased character, false otherwise. Cased characters are those with +- general category property being one of "Lu", "Ll", or "Lt" and uppercase characters +- are those with general category property "Lu". ++ Return true if all cased characters [4]_ in the string are uppercase and ++ there is at least one cased character, false otherwise. + + + .. method:: str.join(iterable) +@@ -1203,7 +1202,8 @@ + + .. method:: str.lower() + +- Return a copy of the string converted to lowercase. ++ Return a copy of the string with all the cased characters [4]_ converted to ++ lowercase. + + + .. method:: str.lstrip([chars]) +@@ -1404,7 +1404,10 @@ + + .. method:: str.upper() + +- Return a copy of the string converted to uppercase. ++ Return a copy of the string with all the cased characters [4]_ converted to ++ uppercase. Note that ``str.upper().isupper()`` might be ``False`` if ``s`` ++ contains uncased characters or if the Unicode category of the resulting ++ character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase). + + + .. method:: str.zfill(width) +@@ -1444,7 +1447,7 @@ + The effect is similar to the using :c:func:`sprintf` in the C language. + + If *format* requires a single argument, *values* may be a single non-tuple +-object. [#]_ Otherwise, *values* must be a tuple with exactly the number of ++object. [5]_ Otherwise, *values* must be a tuple with exactly the number of + items specified by the format string, or a single mapping object (for example, a + dictionary). + +@@ -2712,6 +2715,8 @@ + It is written as ``Ellipsis`` or ``...``. + + ++.. _bltin-notimplemented-object: ++ + The NotImplemented Object + ------------------------- + +@@ -2722,6 +2727,8 @@ + It is written as ``NotImplemented``. + + ++.. _bltin-boolean-values: ++ + Boolean Values + -------------- + +@@ -2729,9 +2736,9 @@ + used to represent truth values (although other values can also be considered + false or true). In numeric contexts (for example when used as the argument to + an arithmetic operator), they behave like the integers 0 and 1, respectively. +-The built-in function :func:`bool` can be used to cast any value to a Boolean, +-if the value can be interpreted as a truth value (see section Truth Value +-Testing above). ++The built-in function :func:`bool` can be used to convert any value to a ++Boolean, if the value can be interpreted as a truth value (see section ++:ref:`truth` above). + + .. index:: + single: False +@@ -2781,8 +2788,6 @@ + The name of the class or type. + + +-The following attributes are only supported by :term:`new-style class`\ es. +- + .. attribute:: class.__mro__ + + This attribute is a tuple of classes that are considered when looking for +@@ -2798,23 +2803,26 @@ + + .. method:: class.__subclasses__ + +- Each new-style class keeps a list of weak references to its immediate +- subclasses. This method returns a list of all those references still alive. ++ Each class keeps a list of weak references to its immediate subclasses. This ++ method returns a list of all those references still alive. + Example:: + + >>> int.__subclasses__() +- [] ++ [] + + + .. rubric:: Footnotes + +-.. [#] Additional information on these special methods may be found in the Python ++.. [1] Additional information on these special methods may be found in the Python + Reference Manual (:ref:`customization`). + +-.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and ++.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and + similarly for tuples. + +-.. [#] They must have since the parser can't tell the type of the operands. +- +-.. [#] To format only a tuple you should therefore provide a singleton tuple whose only ++.. [3] They must have since the parser can't tell the type of the operands. ++ ++.. [4] Cased characters are those with general category property being one of ++ "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase). ++ ++.. [5] To format only a tuple you should therefore provide a singleton tuple whose only + element is the tuple to be formatted. +diff -r 137e45f15c0b Doc/library/string.rst +--- a/Doc/library/string.rst ++++ b/Doc/library/string.rst +@@ -4,6 +4,9 @@ + .. module:: string + :synopsis: Common string operations. + ++**Source code:** :source:`Lib/string.py` ++ ++-------------- + + .. seealso:: + +@@ -11,10 +14,6 @@ + + :ref:`string-methods` + +-**Source code:** :source:`Lib/string.py` +- +--------------- +- + String constants + ---------------- + +@@ -212,7 +211,7 @@ + + See also the :ref:`formatspec` section. + +-The *field_name* itself begins with an *arg_name* that is either either a number or a ++The *field_name* itself begins with an *arg_name* that is either a number or a + keyword. If it's a number, it refers to a positional argument, and if it's a keyword, + it refers to a named keyword argument. If the numerical arg_names in a format string + are 0, 1, 2, ... in sequence, they can all be omitted (not just some) +diff -r 137e45f15c0b Doc/library/subprocess.rst +--- a/Doc/library/subprocess.rst ++++ b/Doc/library/subprocess.rst +@@ -25,7 +25,227 @@ + Using the subprocess Module + --------------------------- + +-This module defines one class called :class:`Popen`: ++The recommended approach to invoking subprocesses is to use the following ++convenience functions for all use cases they can handle. For more advanced ++use cases, the underlying :class:`Popen` interface can be used directly. ++ ++ ++.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False) ++ ++ Run the command described by *args*. Wait for command to complete, then ++ return the :attr:`returncode` attribute. ++ ++ The arguments shown above are merely the most common ones, described below ++ in :ref:`frequently-used-arguments` (hence the slightly odd notation in ++ the abbreviated signature). The full function signature is the same as ++ that of the :class:`Popen` constructor - this functions passes all ++ supplied arguments directly through to that interface. ++ ++ Examples:: ++ ++ >>> subprocess.call(["ls", "-l"]) ++ 0 ++ ++ >>> subprocess.call("exit 1", shell=True) ++ 1 ++ ++ .. warning:: ++ ++ Invoking the system shell with ``shell=True`` can be a security hazard ++ if combined with untrusted input. See the warning under ++ :ref:`frequently-used-arguments` for details. ++ ++ .. note:: ++ ++ Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As ++ the pipes are not being read in the current process, the child ++ process may block if it generates enough output to a pipe to fill up ++ the OS pipe buffer. ++ ++ ++.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) ++ ++ Run command with arguments. Wait for command to complete. If the return ++ code was zero then return, otherwise raise :exc:`CalledProcessError`. The ++ :exc:`CalledProcessError` object will have the return code in the ++ :attr:`returncode` attribute. ++ ++ The arguments shown above are merely the most common ones, described below ++ in :ref:`frequently-used-arguments` (hence the slightly odd notation in ++ the abbreviated signature). The full function signature is the same as ++ that of the :class:`Popen` constructor - this functions passes all ++ supplied arguments directly through to that interface. ++ ++ Examples:: ++ ++ >>> subprocess.check_call(["ls", "-l"]) ++ 0 ++ ++ >>> subprocess.check_call("exit 1", shell=True) ++ Traceback (most recent call last): ++ ... ++ subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 ++ ++ .. versionadded:: 2.5 ++ ++ .. warning:: ++ ++ Invoking the system shell with ``shell=True`` can be a security hazard ++ if combined with untrusted input. See the warning under ++ :ref:`frequently-used-arguments` for details. ++ ++ .. note:: ++ ++ Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As ++ the pipes are not being read in the current process, the child ++ process may block if it generates enough output to a pipe to fill up ++ the OS pipe buffer. ++ ++ ++.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) ++ ++ Run command with arguments and return its output as a byte string. ++ ++ If the return code was non-zero it raises a :exc:`CalledProcessError`. The ++ :exc:`CalledProcessError` object will have the return code in the ++ :attr:`returncode` attribute and any output in the :attr:`output` ++ attribute. ++ ++ The arguments shown above are merely the most common ones, described below ++ in :ref:`frequently-used-arguments` (hence the slightly odd notation in ++ the abbreviated signature). The full function signature is largely the ++ same as that of the :class:`Popen` constructor, except that *stdout* is ++ not permitted as it is used internally. All other supplied arguments are ++ passed directly through to the :class:`Popen` constructor. ++ ++ Examples:: ++ ++ >>> subprocess.check_output(["echo", "Hello World!"]) ++ b'Hello World!\n' ++ ++ >>> subprocess.check_output(["echo", "Hello World!"], universal_newlines=True) ++ 'Hello World!\n' ++ ++ >>> subprocess.check_output("exit 1", shell=True) ++ Traceback (most recent call last): ++ ... ++ subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 ++ ++ By default, this function will return the data as encoded bytes. The actual ++ encoding of the output data may depend on the command being invoked, so the ++ decoding to text will often need to be handled at the application level. ++ ++ This behaviour may be overridden by setting *universal_newlines* to ++ :const:`True` as described below in :ref:`frequently-used-arguments`. ++ ++ To also capture standard error in the result, use ++ ``stderr=subprocess.STDOUT``:: ++ ++ >>> subprocess.check_output( ++ ... "ls non_existent_file; exit 0", ++ ... stderr=subprocess.STDOUT, ++ ... shell=True) ++ 'ls: non_existent_file: No such file or directory\n' ++ ++ .. versionadded:: 2.7 ++ ++ .. warning:: ++ ++ Invoking the system shell with ``shell=True`` can be a security hazard ++ if combined with untrusted input. See the warning under ++ :ref:`frequently-used-arguments` for details. ++ ++ .. note:: ++ ++ Do not use ``stderr=PIPE`` with this function. As the pipe is not being ++ read in the current process, the child process may block if it ++ generates enough output to the pipe to fill up the OS pipe buffer. ++ ++ ++.. data:: PIPE ++ ++ Special value that can be used as the *stdin*, *stdout* or *stderr* argument ++ to :class:`Popen` and indicates that a pipe to the standard stream should be ++ opened. ++ ++ ++.. data:: STDOUT ++ ++ Special value that can be used as the *stderr* argument to :class:`Popen` and ++ indicates that standard error should go into the same handle as standard ++ output. ++ ++ ++.. _frequently-used-arguments: ++ ++Frequently Used Arguments ++^^^^^^^^^^^^^^^^^^^^^^^^^ ++ ++To support a wide variety of use cases, the :class:`Popen` constructor (and ++the convenience functions) accept a large number of optional arguments. For ++most typical use cases, many of these arguments can be safely left at their ++default values. The arguments that are most commonly needed are: ++ ++ *args* is required for all calls and should be a string, or a sequence of ++ program arguments. Providing a sequence of arguments is generally ++ preferred, as it allows the module to take care of any required escaping ++ and quoting of arguments (e.g. to permit spaces in file names). If passing ++ a single string, either *shell* must be :const:`True` (see below) or else ++ the string must simply name the program to be executed without specifying ++ any arguments. ++ ++ *stdin*, *stdout* and *stderr* specify the executed program's standard input, ++ standard output and standard error file handles, respectively. Valid values ++ are :data:`PIPE`, an existing file descriptor (a positive integer), an ++ existing file object, and ``None``. :data:`PIPE` indicates that a new pipe ++ to the child should be created. With the default settings of ``None``, no ++ redirection will occur; the child's file handles will be inherited from the ++ parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that ++ the stderr data from the child process should be captured into the same file ++ handle as for stdout. ++ ++ When *stdout* or *stderr* are pipes and *universal_newlines* is ++ :const:`True` then the output data is assumed to be encoded as UTF-8 and ++ will automatically be decoded to text. All line endings will be converted ++ to ``'\n'`` as described for the universal newlines `'U'`` mode argument ++ to :func:`open`. ++ ++ If *shell* is :const:`True`, the specified command will be executed through ++ the shell. This can be useful if you are using Python primarily for the ++ enhanced control flow it offers over most system shells and still want ++ access to other shell features such as filename wildcards, shell pipes and ++ environment variable expansion. ++ ++ .. warning:: ++ ++ Executing shell commands that incorporate unsanitized input from an ++ untrusted source makes a program vulnerable to `shell injection ++ `_, ++ a serious security flaw which can result in arbitrary command execution. ++ For this reason, the use of *shell=True* is **strongly discouraged** in cases ++ where the command string is constructed from external input:: ++ ++ >>> from subprocess import call ++ >>> filename = input("What file would you like to display?\n") ++ What file would you like to display? ++ non_existent; rm -rf / # ++ >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly... ++ ++ ``shell=False`` disables all shell based features, but does not suffer ++ from this vulnerability; see the Note in the :class:`Popen` constructor ++ documentation for helpful hints in getting ``shell=False`` to work. ++ ++These options, along with all of the other options, are described in more ++detail in the :class:`Popen` constructor documentation. ++ ++ ++Popen Constuctor ++^^^^^^^^^^^^^^^^ ++ ++The underlying process creation and management in this module is handled by ++the :class:`Popen` class. It offers a lot of flexibility so that developers ++are able to handle the less common cases not covered by the convenience ++functions. + + + .. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=()) +@@ -78,21 +298,9 @@ + + .. warning:: + +- Executing shell commands that incorporate unsanitized input from an +- untrusted source makes a program vulnerable to `shell injection +- `_, +- a serious security flaw which can result in arbitrary command execution. +- For this reason, the use of *shell=True* is **strongly discouraged** in cases +- where the command string is constructed from external input:: +- +- >>> from subprocess import call +- >>> filename = input("What file would you like to display?\n") +- What file would you like to display? +- non_existent; rm -rf / # +- >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly... +- +- *shell=False* does not suffer from this vulnerability; the above Note may be +- helpful in getting code using *shell=False* to work. ++ Enabling this option can be a security hazard if combined with untrusted ++ input. See the warning under :ref:`frequently-used-arguments` ++ for details. + + On Windows: the :class:`Popen` class uses CreateProcess() to execute the + child program, which operates on strings. If *args* is a sequence, it will +@@ -121,14 +329,15 @@ + You don't need ``shell=True`` to run a batch file, nor to run a console-based + executable. + +- *stdin*, *stdout* and *stderr* specify the executed programs' standard input, ++ *stdin*, *stdout* and *stderr* specify the executed program's standard input, + standard output and standard error file handles, respectively. Valid values + are :data:`PIPE`, an existing file descriptor (a positive integer), an + existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a +- new pipe to the child should be created. With ``None``, no redirection will +- occur; the child's file handles will be inherited from the parent. Additionally, +- *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the +- applications should be captured into the same file handle as for stdout. ++ new pipe to the child should be created. With the default settings of ++ ``None``, no redirection will occur; the child's file handles will be ++ inherited from the parent. Additionally, *stderr* can be :data:`STDOUT`, ++ which indicates that the stderr data from the applications should be ++ captured into the same file handle as for stdout. + + If *preexec_fn* is set to a callable object, this object will be called in the + child process just before the child is executed. +@@ -228,118 +437,6 @@ + Added context manager support. + + +-.. data:: PIPE +- +- Special value that can be used as the *stdin*, *stdout* or *stderr* argument +- to :class:`Popen` and indicates that a pipe to the standard stream should be +- opened. +- +- +-.. data:: STDOUT +- +- Special value that can be used as the *stderr* argument to :class:`Popen` and +- indicates that standard error should go into the same handle as standard +- output. +- +- +-Convenience Functions +-^^^^^^^^^^^^^^^^^^^^^ +- +-This module also defines the following shortcut functions: +- +- +-.. function:: call(*popenargs, **kwargs) +- +- Run command with arguments. Wait for command to complete, then return the +- :attr:`returncode` attribute. +- +- The arguments are the same as for the :class:`Popen` constructor. Example:: +- +- >>> retcode = subprocess.call(["ls", "-l"]) +- +- .. warning:: +- +- Like :meth:`Popen.wait`, this will deadlock when using +- ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process +- generates enough output to a pipe such that it blocks waiting +- for the OS pipe buffer to accept more data. +- +- +-.. function:: check_call(*popenargs, **kwargs) +- +- Run command with arguments. Wait for command to complete. If the exit code was +- zero then return, otherwise raise :exc:`CalledProcessError`. The +- :exc:`CalledProcessError` object will have the return code in the +- :attr:`returncode` attribute. +- +- The arguments are the same as for the :class:`Popen` constructor. Example:: +- +- >>> subprocess.check_call(["ls", "-l"]) +- 0 +- +- .. warning:: +- +- See the warning for :func:`call`. +- +- +-.. function:: check_output(*popenargs, **kwargs) +- +- Run command with arguments and return its output as a byte string. +- +- If the exit code was non-zero it raises a :exc:`CalledProcessError`. The +- :exc:`CalledProcessError` object will have the return code in the +- :attr:`returncode` +- attribute and output in the :attr:`output` attribute. +- +- The arguments are the same as for the :class:`Popen` constructor. Example:: +- +- >>> subprocess.check_output(["ls", "-l", "/dev/null"]) +- b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' +- +- The stdout argument is not allowed as it is used internally. +- To capture standard error in the result, use ``stderr=subprocess.STDOUT``:: +- +- >>> subprocess.check_output( +- ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"], +- ... stderr=subprocess.STDOUT) +- b'ls: non_existent_file: No such file or directory\n' +- +- .. versionadded:: 3.1 +- +- +-.. function:: getstatusoutput(cmd) +- +- Return ``(status, output)`` of executing *cmd* in a shell. +- +- Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple +- ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the +- returned output will contain output or error messages. A trailing newline is +- stripped from the output. The exit status for the command can be interpreted +- according to the rules for the C function :c:func:`wait`. Example:: +- +- >>> subprocess.getstatusoutput('ls /bin/ls') +- (0, '/bin/ls') +- >>> subprocess.getstatusoutput('cat /bin/junk') +- (256, 'cat: /bin/junk: No such file or directory') +- >>> subprocess.getstatusoutput('/bin/junk') +- (256, 'sh: /bin/junk: not found') +- +- Availability: UNIX. +- +- +-.. function:: getoutput(cmd) +- +- Return output (stdout and stderr) of executing *cmd* in a shell. +- +- Like :func:`getstatusoutput`, except the exit status is ignored and the return +- value is a string containing the command's output. Example:: +- +- >>> subprocess.getoutput('ls /bin/ls') +- '/bin/ls' +- +- Availability: UNIX. +- +- + Exceptions + ^^^^^^^^^^ + +@@ -355,16 +452,19 @@ + A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid + arguments. + +-check_call() will raise :exc:`CalledProcessError`, if the called process returns +-a non-zero return code. ++:func:`check_call` and :func:`check_output` will raise ++:exc:`CalledProcessError` if the called process returns a non-zero return ++code. + + + Security + ^^^^^^^^ + +-Unlike some other popen functions, this implementation will never call /bin/sh +-implicitly. This means that all characters, including shell metacharacters, can +-safely be passed to child processes. ++Unlike some other popen functions, this implementation will never call a ++system shell implicitly. This means that all characters, including shell ++metacharacters, can safely be passed to child processes. Obviously, if the ++shell is invoked explicitly, then it is the application's responsibility to ++ensure that all whitespace and metacharacters are quoted appropriately. + + + Popen Objects +@@ -592,15 +692,21 @@ + Replacing Older Functions with the subprocess Module + ---------------------------------------------------- + +-In this section, "a ==> b" means that b can be used as a replacement for a. ++In this section, "a becomes b" means that b can be used as a replacement for a. + + .. note:: + +- All functions in this section fail (more or less) silently if the executed +- program cannot be found; this module raises an :exc:`OSError` exception. ++ All "a" functions in this section fail (more or less) silently if the ++ executed program cannot be found; the "b" replacements raise :exc:`OSError` ++ instead. + +-In the following examples, we assume that the subprocess module is imported with +-"from subprocess import \*". ++ In addition, the replacements using :func:`check_output` will fail with a ++ :exc:`CalledProcessError` if the requested operation produces a non-zero ++ return code. The output is still available as the ``output`` attribute of ++ the raised exception. ++ ++In the following examples, we assume that the relevant functions have already ++been imported from the subprocess module. + + + Replacing /bin/sh shell backquote +@@ -609,8 +715,8 @@ + :: + + output=`mycmd myarg` +- ==> +- output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] ++ # becomes ++ output = check_output(["mycmd", "myarg"]) + + + Replacing shell pipeline +@@ -619,7 +725,7 @@ + :: + + output=`dmesg | grep hda` +- ==> ++ # becomes + p1 = Popen(["dmesg"], stdout=PIPE) + p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) + p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. +@@ -628,22 +734,27 @@ + The p1.stdout.close() call after starting the p2 is important in order for p1 + to receive a SIGPIPE if p2 exits before p1. + ++Alternatively, for trusted input, the shell's own pipeline support may still ++be used directly: ++ ++ output=`dmesg | grep hda` ++ # becomes ++ output=check_output("dmesg | grep hda", shell=True) ++ ++ + Replacing :func:`os.system` + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + :: + + sts = os.system("mycmd" + " myarg") +- ==> +- p = Popen("mycmd" + " myarg", shell=True) +- sts = os.waitpid(p.pid, 0)[1] ++ # becomes ++ sts = call("mycmd" + " myarg", shell=True) + + Notes: + + * Calling the program through the shell is usually not required. + +-* It's easier to look at the :attr:`returncode` attribute than the exit status. +- + A more realistic example would look like this:: + + try: +@@ -768,6 +879,48 @@ + ``close_fds=True`` with :class:`Popen` to guarantee this behavior on + all platforms or past Python versions. + ++ ++Legacy Shell Invocation Functions ++--------------------------------- ++ ++This module also provides the following legacy functions from the 2.x ++``commands`` module. These operations implicitly invoke the system shell and ++none of the guarantees described above regarding security and exception ++handling consistency are valid for these functions. ++ ++.. function:: getstatusoutput(cmd) ++ ++ Return ``(status, output)`` of executing *cmd* in a shell. ++ ++ Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple ++ ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the ++ returned output will contain output or error messages. A trailing newline is ++ stripped from the output. The exit status for the command can be interpreted ++ according to the rules for the C function :c:func:`wait`. Example:: ++ ++ >>> subprocess.getstatusoutput('ls /bin/ls') ++ (0, '/bin/ls') ++ >>> subprocess.getstatusoutput('cat /bin/junk') ++ (256, 'cat: /bin/junk: No such file or directory') ++ >>> subprocess.getstatusoutput('/bin/junk') ++ (256, 'sh: /bin/junk: not found') ++ ++ Availability: UNIX. ++ ++ ++.. function:: getoutput(cmd) ++ ++ Return output (stdout and stderr) of executing *cmd* in a shell. ++ ++ Like :func:`getstatusoutput`, except the exit status is ignored and the return ++ value is a string containing the command's output. Example:: ++ ++ >>> subprocess.getoutput('ls /bin/ls') ++ '/bin/ls' ++ ++ Availability: UNIX. ++ ++ + Notes + ----- + +@@ -799,5 +952,3 @@ + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. +- +- +diff -r 137e45f15c0b Doc/library/sys.rst +--- a/Doc/library/sys.rst ++++ b/Doc/library/sys.rst +@@ -121,6 +121,15 @@ + Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`. + + ++.. data:: dont_write_bytecode ++ ++ If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the ++ import of source modules. This value is initially set to ``True`` or ++ ``False`` depending on the :option:`-B` command line option and the ++ :envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it ++ yourself to control bytecode file generation. ++ ++ + .. function:: excepthook(type, value, traceback) + + This function prints out a given traceback and exception to ``sys.stderr``. +@@ -185,10 +194,10 @@ + Python files are installed; by default, this is also ``'/usr/local'``. This can + be set at build time with the ``--exec-prefix`` argument to the + :program:`configure` script. Specifically, all configuration files (e.g. the +- :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix + +- '/lib/pythonversion/config'``, and shared library modules are installed in +- ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to +- ``version[:3]``. ++ :file:`pyconfig.h` header file) are installed in the directory ++ :file:`{exec_prefix}/lib/python{X.Y}/config', and shared library modules are ++ installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y* ++ is the version number of Python, for example ``3.2``. + + + .. data:: executable +@@ -287,8 +296,12 @@ + +---------------------+----------------+--------------------------------------------------+ + | :const:`radix` | FLT_RADIX | radix of exponent representation | + +---------------------+----------------+--------------------------------------------------+ +- | :const:`rounds` | FLT_ROUNDS | constant representing rounding mode | +- | | | used for arithmetic operations | ++ | :const:`rounds` | FLT_ROUNDS | integer constant representing the rounding mode | ++ | | | used for arithmetic operations. This reflects | ++ | | | the value of the system FLT_ROUNDS macro at | ++ | | | interpreter startup time. See section 5.2.4.2.2 | ++ | | | of the C99 standard for an explanation of the | ++ | | | possible values and their meanings. | + +---------------------+----------------+--------------------------------------------------+ + + The attribute :attr:`sys.float_info.dig` needs further explanation. If +@@ -743,10 +756,10 @@ + independent Python files are installed; by default, this is the string + ``'/usr/local'``. This can be set at build time with the ``--prefix`` + argument to the :program:`configure` script. The main collection of Python +- library modules is installed in the directory ``prefix + '/lib/pythonversion'`` ++ library modules is installed in the directory :file:`{prefix}/lib/python{X.Y}`` + while the platform independent header files (all except :file:`pyconfig.h`) are +- stored in ``prefix + '/include/pythonversion'``, where *version* is equal to +- ``version[:3]``. ++ stored in :file:`{prefix}/include/python{X.Y}``, where *X.Y* is the version ++ number of Python, for example ``3.2``. + + + .. data:: ps1 +@@ -764,15 +777,6 @@ + implement a dynamic prompt. + + +-.. data:: dont_write_bytecode +- +- If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the +- import of source modules. This value is initially set to ``True`` or ``False`` +- depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE`` +- environment variable, but you can set it yourself to control bytecode file +- generation. +- +- + .. function:: setcheckinterval(interval) + + Set the interpreter's "check interval". This integer value determines how often +@@ -930,31 +934,42 @@ + stdout + stderr + +- :term:`File objects ` corresponding to the interpreter's standard +- input, output and error streams. ``stdin`` is used for all interpreter input +- except for scripts but including calls to :func:`input`. ``stdout`` is used +- for the output of :func:`print` and :term:`expression` statements and for the +- prompts of :func:`input`. The interpreter's own prompts +- and (almost all of) its error messages go to ``stderr``. ``stdout`` and +- ``stderr`` needn't be built-in file objects: any object is acceptable as long +- as it has a :meth:`write` method that takes a string argument. (Changing these +- objects doesn't affect the standard I/O streams of processes executed by +- :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in +- the :mod:`os` module.) ++ :term:`File objects ` used by the interpreter for standard ++ input, output and errors: + +- The standard streams are in text mode by default. To write or read binary +- data to these, use the underlying binary buffer. For example, to write bytes +- to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``. Using +- :meth:`io.TextIOBase.detach` streams can be made binary by default. This ++ * ``stdin`` is used for all interactive input (including calls to ++ :func:`input`); ++ * ``stdout`` is used for the output of :func:`print` and :term:`expression` ++ statements and for the prompts of :func:`input`; ++ * The interpreter's own prompts and its error messages go to ``stderr``. ++ ++ By default, these streams are regular text streams as returned by the ++ :func:`open` function. Their parameters are chosen as follows: ++ ++ * The character encoding is platform-dependent. Under Windows, if the stream ++ is interactive (that is, if its :meth:`isatty` method returns True), the ++ console codepage is used, otherwise the ANSI code page. Under other ++ platforms, the locale encoding is used (see :meth:`locale.getpreferredencoding`). ++ ++ Under all platforms though, you can override this value by setting the ++ :envvar:`PYTHONIOENCODING` environment variable. ++ ++ * When interactive, standard streams are line-buffered. Otherwise, they ++ are block-buffered like regular text files. You can override this ++ value with the :option:`-u` command-line option. ++ ++ To write or read binary data from/to the standard streams, use the ++ underlying binary :data:`~io.TextIOBase.buffer`. For example, to write ++ bytes to :data:`stdout`, use ``sys.stdout.buffer.write(b'abc')``. Using ++ :meth:`io.TextIOBase.detach`, streams can be made binary by default. This + function sets :data:`stdin` and :data:`stdout` to binary:: + + def make_streams_binary(): + sys.stdin = sys.stdin.detach() + sys.stdout = sys.stdout.detach() + +- Note that the streams can be replaced with objects (like +- :class:`io.StringIO`) that do not support the +- :attr:`~io.BufferedIOBase.buffer` attribute or the ++ Note that the streams may be replaced with objects (like :class:`io.StringIO`) ++ that do not support the :attr:`~io.BufferedIOBase.buffer` attribute or the + :meth:`~io.BufferedIOBase.detach` method and can raise :exc:`AttributeError` + or :exc:`io.UnsupportedOperation`. + +diff -r 137e45f15c0b Doc/library/sysconfig.rst +--- a/Doc/library/sysconfig.rst ++++ b/Doc/library/sysconfig.rst +@@ -3,15 +3,16 @@ + + .. module:: sysconfig + :synopsis: Python's configuration information +-.. moduleauthor:: Tarek Ziade +-.. sectionauthor:: Tarek Ziade ++.. moduleauthor:: Tarek Ziadé ++.. sectionauthor:: Tarek Ziadé ++ + .. index:: + single: configuration information + ++.. versionadded:: 3.2 ++ + **Source code:** :source:`Lib/sysconfig.py` + +-.. versionadded:: 3.2 +- + -------------- + + The :mod:`sysconfig` module provides access to Python's configuration +@@ -129,7 +130,7 @@ + one may call this function and get the default value. + + If *scheme* is provided, it must be a value from the list returned by +- :func:`get_path_names`. Otherwise, the default scheme for the current ++ :func:`get_scheme_names`. Otherwise, the default scheme for the current + platform is used. + + If *vars* is provided, it must be a dictionary of variables that will update +diff -r 137e45f15c0b Doc/library/tarfile.rst +--- a/Doc/library/tarfile.rst ++++ b/Doc/library/tarfile.rst +@@ -101,10 +101,10 @@ + +-------------+--------------------------------------------+ + | ``'w|'`` | Open an uncompressed *stream* for writing. | + +-------------+--------------------------------------------+ +- | ``'w|gz'`` | Open an gzip compressed *stream* for | ++ | ``'w|gz'`` | Open a gzip compressed *stream* for | + | | writing. | + +-------------+--------------------------------------------+ +- | ``'w|bz2'`` | Open an bzip2 compressed *stream* for | ++ | ``'w|bz2'`` | Open a bzip2 compressed *stream* for | + | | writing. | + +-------------+--------------------------------------------+ + +diff -r 137e45f15c0b Doc/library/threading.rst +--- a/Doc/library/threading.rst ++++ b/Doc/library/threading.rst +@@ -634,20 +634,21 @@ + + .. versionadded:: 3.2 + +- .. method:: notify() ++ .. method:: notify(n=1) + +- Wake up a thread waiting on this condition, if any. If the calling thread +- has not acquired the lock when this method is called, a ++ By default, wake up one thread waiting on this condition, if any. If the ++ calling thread has not acquired the lock when this method is called, a + :exc:`RuntimeError` is raised. + +- This method wakes up one of the threads waiting for the condition +- variable, if any are waiting; it is a no-op if no threads are waiting. ++ This method wakes up at most *n* of the threads waiting for the condition ++ variable; it is a no-op if no threads are waiting. + +- The current implementation wakes up exactly one thread, if any are +- waiting. However, it's not safe to rely on this behavior. A future, +- optimized implementation may occasionally wake up more than one thread. ++ The current implementation wakes up exactly *n* threads, if at least *n* ++ threads are waiting. However, it's not safe to rely on this behavior. ++ A future, optimized implementation may occasionally wake up more than ++ *n* threads. + +- Note: the awakened thread does not actually return from its :meth:`wait` ++ Note: an awakened thread does not actually return from its :meth:`wait` + call until it can reacquire the lock. Since :meth:`notify` does not + release the lock, its caller should. + +@@ -864,7 +865,7 @@ + + Pass the barrier. When all the threads party to the barrier have called + this function, they are all released simultaneously. If a *timeout* is +- provided, is is used in preference to any that was supplied to the class ++ provided, it is used in preference to any that was supplied to the class + constructor. + + The return value is an integer in the range 0 to *parties* -- 1, different +diff -r 137e45f15c0b Doc/library/tkinter.ttk.rst +--- a/Doc/library/tkinter.ttk.rst ++++ b/Doc/library/tkinter.ttk.rst +@@ -1240,7 +1240,7 @@ + *layoutspec*, if specified, is expected to be a list or some other + sequence type (excluding strings), where each item should be a tuple and + the first item is the layout name and the second item should have the +- format described described in `Layouts`_. ++ format described in `Layouts`_. + + To understand the format, see the following example (it is not + intended to do anything useful):: +diff -r 137e45f15c0b Doc/library/turtle.rst +--- a/Doc/library/turtle.rst ++++ b/Doc/library/turtle.rst +@@ -204,7 +204,7 @@ + | :func:`onkeypress` + | :func:`onclick` | :func:`onscreenclick` + | :func:`ontimer` +- | :func:`mainloop` ++ | :func:`mainloop` | :func:`done` + + Settings and special methods + | :func:`mode` +@@ -1773,6 +1773,7 @@ + + + .. function:: mainloop() ++ done() + + Starts event loop - calling Tkinter's mainloop function. + Must be the last statement in a turtle graphics program. +diff -r 137e45f15c0b Doc/library/unittest.rst +--- a/Doc/library/unittest.rst ++++ b/Doc/library/unittest.rst +@@ -293,7 +293,7 @@ + + As a shortcut, ``python -m unittest`` is the equivalent of + ``python -m unittest discover``. If you want to pass arguments to test +- discovery the `discover` sub-command must be used explicitly. ++ discovery the ``discover`` sub-command must be used explicitly. + + The ``discover`` sub-command has the following options: + +@@ -305,11 +305,11 @@ + + .. cmdoption:: -s directory + +- Directory to start discovery ('.' default) ++ Directory to start discovery (``.`` default) + + .. cmdoption:: -p pattern + +- Pattern to match test files ('test*.py' default) ++ Pattern to match test files (``test*.py`` default) + + .. cmdoption:: -t directory + +@@ -725,7 +725,7 @@ + + .. versionchanged:: 3.2 + :class:`TestCase` can be instantiated successfully without providing a method +- name. This makes it easier to experiment with `TestCase` from the ++ name. This makes it easier to experiment with :class:`TestCase` from the + interactive interpreter. + + *methodName* defaults to :meth:`runTest`. +@@ -929,6 +929,8 @@ + + Test that *obj* is (or is not) an instance of *cls* (which can be a + class or a tuple of classes, as supported by :func:`isinstance`). ++ To check for a specific type (without including superclasses) use ++ :func:`assertIs(type(obj), cls) `. + + .. versionadded:: 3.2 + +@@ -940,17 +942,17 @@ + +---------------------------------------------------------+--------------------------------------+------------+ + | Method | Checks that | New in | + +=========================================================+======================================+============+ +- | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | | ++ | :meth:`assertRaises(exc, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | | + | ` | | | + +---------------------------------------------------------+--------------------------------------+------------+ +- | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 3.1 | +- | ` | and the message matches `re` | | ++ | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 3.1 | ++ | ` | and the message matches *re* | | + +---------------------------------------------------------+--------------------------------------+------------+ +- | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 | ++ | :meth:`assertWarns(warn, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | + | ` | | | + +---------------------------------------------------------+--------------------------------------+------------+ +- | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `warn` | 3.2 | +- | ` | and the message matches `re` | | ++ | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *warn* | 3.2 | ++ | ` | and the message matches *re* | | + +---------------------------------------------------------+--------------------------------------+------------+ + + .. method:: assertRaises(exception, callable, *args, **kwds) +@@ -1092,7 +1094,7 @@ + | :meth:`assertNotRegex(s, re) | ``not regex.search(s)`` | 3.2 | + | ` | | | + +---------------------------------------+--------------------------------+--------------+ +- | :meth:`assertCountEqual(a, b) | `a` and `b` have the same | 3.2 | ++ | :meth:`assertCountEqual(a, b) | *a* and *b* have the same | 3.2 | + | ` | elements in the same number, | | + | | regardless of their order | | + +---------------------------------------+--------------------------------+--------------+ +@@ -1887,7 +1889,7 @@ + .. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None) + + A basic test runner implementation that outputs results to a stream. If *stream* +- is `None`, the default, `sys.stderr` is used as the output stream. This class ++ is ``None``, the default, :data:`sys.stderr` is used as the output stream. This class + has a few configurable parameters, but is essentially very simple. Graphical + applications which run test suites should provide alternate implementations. + +@@ -1904,7 +1906,7 @@ + Added the ``warnings`` argument. + + .. versionchanged:: 3.2 +- The default stream is set to `sys.stderr` at instantiation time rather ++ The default stream is set to :data:`sys.stderr` at instantiation time rather + than import time. + + .. method:: _makeResult() +diff -r 137e45f15c0b Doc/library/urllib.parse.rst +--- a/Doc/library/urllib.parse.rst ++++ b/Doc/library/urllib.parse.rst +@@ -12,6 +12,10 @@ + pair: URL; parsing + pair: relative; URL + ++**Source code:** :source:`Lib/urllib/parse.py` ++ ++-------------- ++ + This module defines a standard interface to break Uniform Resource Locator (URL) + strings up in components (addressing scheme, network location, path etc.), to + combine the components back into a URL string, and to convert a "relative URL" +diff -r 137e45f15c0b Doc/library/urllib.request.rst +--- a/Doc/library/urllib.request.rst ++++ b/Doc/library/urllib.request.rst +@@ -1257,11 +1257,11 @@ + pair: HTTP; protocol + pair: FTP; protocol + +-* Currently, only the following protocols are supported: HTTP, (versions 0.9 and +- 1.0), FTP, and local files. ++* Currently, only the following protocols are supported: HTTP (versions 0.9 and ++ 1.0), FTP, and local files. + +-* The caching feature of :func:`urlretrieve` has been disabled until I find the +- time to hack proper processing of Expiration time headers. ++* The caching feature of :func:`urlretrieve` has been disabled until someone ++ finds the time to hack proper processing of Expiration time headers. + + * There should be a function to query whether a particular URL is in the cache. + +diff -r 137e45f15c0b Doc/library/uuid.rst +--- a/Doc/library/uuid.rst ++++ b/Doc/library/uuid.rst +@@ -222,34 +222,34 @@ + + >>> import uuid + +- # make a UUID based on the host ID and current time ++ >>> # make a UUID based on the host ID and current time + >>> uuid.uuid1() + UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') + +- # make a UUID using an MD5 hash of a namespace UUID and a name ++ >>> # make a UUID using an MD5 hash of a namespace UUID and a name + >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') + UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') + +- # make a random UUID ++ >>> # make a random UUID + >>> uuid.uuid4() + UUID('16fd2706-8baf-433b-82eb-8c7fada847da') + +- # make a UUID using a SHA-1 hash of a namespace UUID and a name ++ >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name + >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') + UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') + +- # make a UUID from a string of hex digits (braces and hyphens ignored) ++ >>> # make a UUID from a string of hex digits (braces and hyphens ignored) + >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') + +- # convert a UUID to a string of hex digits in standard form ++ >>> # convert a UUID to a string of hex digits in standard form + >>> str(x) + '00010203-0405-0607-0809-0a0b0c0d0e0f' + +- # get the raw 16 bytes of the UUID ++ >>> # get the raw 16 bytes of the UUID + >>> x.bytes + b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' + +- # make a UUID from a 16-byte string ++ >>> # make a UUID from a 16-byte string + >>> uuid.UUID(bytes=x.bytes) + UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') + +diff -r 137e45f15c0b Doc/library/xml.etree.elementtree.rst +--- a/Doc/library/xml.etree.elementtree.rst ++++ b/Doc/library/xml.etree.elementtree.rst +@@ -335,6 +335,8 @@ + elements whose tag equals *tag* are returned from the iterator. If the + tree structure is modified during iteration, the result is undefined. + ++ .. versionadded:: 3.2 ++ + + .. method:: iterfind(match) + +diff -r 137e45f15c0b Doc/library/xmlrpc.client.rst +--- a/Doc/library/xmlrpc.client.rst ++++ b/Doc/library/xmlrpc.client.rst +@@ -402,8 +402,8 @@ + MultiCall Objects + ----------------- + +-In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to +-encapsulate multiple calls to a remote server into a single request. ++The :class:`MultiCall` object provides a way to encapsulate multiple calls to a ++remote server into a single request [#]_. + + + .. class:: MultiCall(server) +@@ -534,3 +534,10 @@ + See :ref:`simplexmlrpcserver-example`. + + ++.. rubric:: Footnotes ++ ++.. [#] This approach has been first presented in `a discussion on xmlrpc.com ++ `_. ++.. the link now points to webarchive since the one at ++.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin ++.. doesn't reply) +diff -r 137e45f15c0b Doc/library/zipfile.rst +--- a/Doc/library/zipfile.rst ++++ b/Doc/library/zipfile.rst +@@ -30,15 +30,16 @@ + + .. exception:: BadZipFile + +- The error raised for bad ZIP files (old name: ``zipfile.error``). ++ The error raised for bad ZIP files. + + .. versionadded:: 3.2 + + + .. exception:: BadZipfile + +- This is an alias for :exc:`BadZipFile` that exists for compatibility with +- Python versions prior to 3.2. Usage is deprecated. ++ Alias of :exc:`BadZipFile`, for compatibility with older Python versions. ++ ++ .. deprecated:: 3.2 + + + .. exception:: LargeZipFile +@@ -397,7 +398,7 @@ + +-------+--------------------------+ + | Index | Value | + +=======+==========================+ +- | ``0`` | Year | ++ | ``0`` | Year (>= 1980) | + +-------+--------------------------+ + | ``1`` | Month (one-based) | + +-------+--------------------------+ +@@ -410,6 +411,10 @@ + | ``5`` | Seconds (zero-based) | + +-------+--------------------------+ + ++ .. note:: ++ ++ The ZIP file format does not support timestamps before 1980. ++ + + .. attribute:: ZipInfo.compress_type + +diff -r 137e45f15c0b Doc/reference/compound_stmts.rst +--- a/Doc/reference/compound_stmts.rst ++++ b/Doc/reference/compound_stmts.rst +@@ -478,7 +478,7 @@ + + **Default parameter values are evaluated when the function definition is + executed.** This means that the expression is evaluated once, when the function +-is defined, and that that same "pre-computed" value is used for each call. This ++is defined, and that the same "pre-computed" value is used for each call. This + is especially important to understand when a default parameter is a mutable + object, such as a list or a dictionary: if the function modifies the object + (e.g. by appending an item to a list), the default value is in effect modified. +diff -r 137e45f15c0b Doc/reference/datamodel.rst +--- a/Doc/reference/datamodel.rst ++++ b/Doc/reference/datamodel.rst +@@ -1157,6 +1157,14 @@ + .. XXX what about subclasses of string? + + ++.. method:: object.__bytes__(self) ++ ++ .. index:: builtin: bytes ++ ++ Called by :func:`bytes` to compute a byte-string representation of an ++ object. This should return a ``bytes`` object. ++ ++ + .. method:: object.__format__(self, format_spec) + + .. index:: +diff -r 137e45f15c0b Doc/reference/toplevel_components.rst +--- a/Doc/reference/toplevel_components.rst ++++ b/Doc/reference/toplevel_components.rst +@@ -111,6 +111,6 @@ + single: input; raw + single: readline() (file method) + +-Note: to read 'raw' input line without interpretation, you can use the the ++Note: to read 'raw' input line without interpretation, you can use the + :meth:`readline` method of file objects, including ``sys.stdin``. + +diff -r 137e45f15c0b Doc/tools/sphinxext/layout.html +--- a/Doc/tools/sphinxext/layout.html ++++ b/Doc/tools/sphinxext/layout.html +@@ -6,6 +6,7 @@ + {% endblock %} + {% block extrahead %} + ++ + {{ super() }} + {% endblock %} + {% block footer %} +diff -r 137e45f15c0b Doc/tools/sphinxext/static/copybutton.js +--- /dev/null ++++ b/Doc/tools/sphinxext/static/copybutton.js +@@ -0,0 +1,56 @@ ++$(document).ready(function() { ++ /* Add a [>>>] button on the top-right corner of code samples to hide ++ * the >>> and ... prompts and the output and thus make the code ++ * copyable. */ ++ var div = $('.highlight-python .highlight,' + ++ '.highlight-python3 .highlight') ++ var pre = div.find('pre'); ++ ++ // get the styles from the current theme ++ pre.parent().parent().css('position', 'relative'); ++ var hide_text = 'Hide the prompts and output'; ++ var show_text = 'Show the prompts and output'; ++ var border_width = pre.css('border-top-width'); ++ var border_style = pre.css('border-top-style'); ++ var border_color = pre.css('border-top-color'); ++ var button_styles = { ++ 'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0', ++ 'border-color': border_color, 'border-style': border_style, ++ 'border-width': border_width, 'color': border_color, 'text-size': '75%', ++ 'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em' ++ } ++ ++ // create and add the button to all the code blocks that contain >>> ++ div.each(function(index) { ++ var jthis = $(this); ++ if (jthis.find('.gp').length > 0) { ++ var button = $('>>>'); ++ button.css(button_styles) ++ button.attr('title', hide_text); ++ jthis.prepend(button); ++ } ++ // tracebacks (.gt) contain bare text elements that need to be ++ // wrapped in a span to work with .nextUntil() (see later) ++ jthis.find('pre:has(.gt)').contents().filter(function() { ++ return ((this.nodeType == 3) && (this.data.trim().length > 0)); ++ }).wrap(''); ++ }); ++ ++ // define the behavior of the button when it's clicked ++ $('.copybutton').toggle( ++ function() { ++ var button = $(this); ++ 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.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); ++ }); ++}); ++ +diff -r 137e45f15c0b Doc/tutorial/controlflow.rst +--- a/Doc/tutorial/controlflow.rst ++++ b/Doc/tutorial/controlflow.rst +@@ -412,8 +412,8 @@ + Keyword Arguments + ----------------- + +-Functions can also be called using keyword arguments of the form ``keyword = +-value``. For instance, the following function:: ++Functions can also be called using :term:`keyword arguments ` ++of the form ``kwarg=value``. For instance, the following function:: + + def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): + print("-- This parrot wouldn't", action, end=' ') +@@ -421,26 +421,31 @@ + print("-- Lovely plumage, the", type) + print("-- It's", state, "!") + +-could be called in any of the following ways:: ++accepts one required argument (``voltage``) and three optional arguments ++(``state``, ``action``, and ``type``). This function can be called in any ++of the following ways:: + +- parrot(1000) +- parrot(action = 'VOOOOOM', voltage = 1000000) +- parrot('a thousand', state = 'pushing up the daisies') +- parrot('a million', 'bereft of life', 'jump') ++ parrot(1000) # 1 positional argument ++ parrot(voltage=1000) # 1 keyword argument ++ parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments ++ parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments ++ parrot('a million', 'bereft of life', 'jump') # 3 positional arguments ++ parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword + +-but the following calls would all be invalid:: ++but all the following calls would be invalid:: + + parrot() # required argument missing +- parrot(voltage=5.0, 'dead') # non-keyword argument following keyword +- parrot(110, voltage=220) # duplicate value for argument +- parrot(actor='John Cleese') # unknown keyword ++ parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument ++ parrot(110, voltage=220) # duplicate value for the same argument ++ parrot(actor='John Cleese') # unknown keyword argument + +-In general, an argument list must have any positional arguments followed by any +-keyword arguments, where the keywords must be chosen from the formal parameter +-names. It's not important whether a formal parameter has a default value or +-not. No argument may receive a value more than once --- formal parameter names +-corresponding to positional arguments cannot be used as keywords in the same +-calls. Here's an example that fails due to this restriction:: ++In a function call, keyword arguments must follow positional arguments. ++All the keyword arguments passed must match one of the arguments ++accepted by the function (e.g. ``actor`` is not a valid argument for the ++``parrot`` function), and their order is not important. This also includes ++non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). ++No argument may receive a value more than once. ++Here's an example that fails due to this restriction:: + + >>> def function(a): + ... pass +diff -r 137e45f15c0b Doc/tutorial/datastructures.rst +--- a/Doc/tutorial/datastructures.rst ++++ b/Doc/tutorial/datastructures.rst +@@ -163,107 +163,137 @@ + List Comprehensions + ------------------- + +-List comprehensions provide a concise way to create lists from sequences. +-Common applications are to make lists where each element is the result of +-some operations applied to each member of the sequence, or to create a +-subsequence of those elements that satisfy a certain condition. ++List comprehensions provide a concise way to create lists. ++Common applications are to make new lists where each element is the result of ++some operations applied to each member of another sequence or iterable, or to ++create a subsequence of those elements that satisfy a certain condition. ++ ++For example, assume we want to create a list of squares, like:: ++ ++ >>> squares = [] ++ >>> for x in range(10): ++ ... squares.append(x**2) ++ ... ++ >>> squares ++ [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ++ ++We can obtain the same result with:: ++ ++ squares = [x**2 for x in range(10)] ++ ++This is also equivalent to ``squares = map(lambda x: x**2, range(10))``, ++but it's more concise and readable. + + A list comprehension consists of brackets containing an expression followed + by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if` +-clauses. The result will be a list resulting from evaluating the expression in +-the context of the :keyword:`for` and :keyword:`if` clauses which follow it. If +-the expression would evaluate to a tuple, it must be parenthesized. ++clauses. The result will be a new list resulting from evaluating the expression ++in the context of the :keyword:`for` and :keyword:`if` clauses which follow it. ++For example, this listcomp combines the elements of two lists if they are not ++equal:: + +-Here we take a list of numbers and return a list of three times each number:: ++ >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] ++ [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] + +- >>> vec = [2, 4, 6] +- >>> [3*x for x in vec] +- [6, 12, 18] ++and it's equivalent to:: + +-Now we get a little fancier:: ++ >>> combs = [] ++ >>> for x in [1,2,3]: ++ ... for y in [3,1,4]: ++ ... if x != y: ++ ... combs.append((x, y)) ++ ... ++ >>> combs ++ [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] + +- >>> [[x, x**2] for x in vec] +- [[2, 4], [4, 16], [6, 36]] ++Note how the order of the :keyword:`for` and :keyword:`if` statements is the ++same in both these snippets. + +-Here we apply a method call to each item in a sequence:: ++If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), ++it must be parenthesized. :: + ++ >>> vec = [-4, -2, 0, 2, 4] ++ >>> # create a new list with the values doubled ++ >>> [x*2 for x in vec] ++ [-8, -4, 0, 4, 8] ++ >>> # filter the list to exclude negative numbers ++ >>> [x for x in vec if x >= 0] ++ [0, 2, 4] ++ >>> # apply a function to all the elements ++ >>> [abs(x) for x in vec] ++ [4, 2, 0, 2, 4] ++ >>> # call a method on each element + >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] + >>> [weapon.strip() for weapon in freshfruit] + ['banana', 'loganberry', 'passion fruit'] +- +-Using the :keyword:`if` clause we can filter the stream:: +- +- >>> [3*x for x in vec if x > 3] +- [12, 18] +- >>> [3*x for x in vec if x < 2] +- [] +- +-Tuples can often be created without their parentheses, but not here:: +- +- >>> [x, x**2 for x in vec] # error - parens required for tuples ++ >>> # create a list of 2-tuples like (number, square) ++ >>> [(x, x**2) for x in range(6)] ++ [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] ++ >>> # the tuple must be parenthesized, otherwise an error is raised ++ >>> [x, x**2 for x in range(6)] + File "", line 1, in ? +- [x, x**2 for x in vec] ++ [x, x**2 for x in range(6)] + ^ + SyntaxError: invalid syntax +- >>> [(x, x**2) for x in vec] +- [(2, 4), (4, 16), (6, 36)] ++ >>> # flatten a list using a listcomp with two 'for' ++ >>> vec = [[1,2,3], [4,5,6], [7,8,9]] ++ >>> [num for elem in vec for num in elem] ++ [1, 2, 3, 4, 5, 6, 7, 8, 9] + +-Here are some nested for loops and other fancy behavior:: ++List comprehensions can contain complex expressions and nested functions:: + +- >>> vec1 = [2, 4, 6] +- >>> vec2 = [4, 3, -9] +- >>> [x*y for x in vec1 for y in vec2] +- [8, 6, -18, 16, 12, -36, 24, 18, -54] +- >>> [x+y for x in vec1 for y in vec2] +- [6, 5, -7, 8, 7, -5, 10, 9, -3] +- >>> [vec1[i]*vec2[i] for i in range(len(vec1))] +- [8, 12, -54] +- +-List comprehensions can be applied to complex expressions and nested functions:: +- +- >>> [str(round(355/113, i)) for i in range(1, 6)] ++ >>> from math import pi ++ >>> [str(round(pi, i)) for i in range(1, 6)] + ['3.1', '3.14', '3.142', '3.1416', '3.14159'] + +- + Nested List Comprehensions + -------------------------- + +-If you've got the stomach for it, list comprehensions can be nested. They are a +-powerful tool but -- like all powerful tools -- they need to be used carefully, +-if at all. ++The initial expression in a list comprehension can be any arbitrary expression, ++including another list comprehension. + +-Consider the following example of a 3x3 matrix held as a list containing three +-lists, one list per row:: ++Consider the following example of a 3x4 matrix implemented as a list of ++3 lists of length 4:: + +- >>> mat = [ +- ... [1, 2, 3], +- ... [4, 5, 6], +- ... [7, 8, 9], +- ... ] ++ >>> matrix = [ ++ ... [1, 2, 3, 4], ++ ... [5, 6, 7, 8], ++ ... [9, 10, 11, 12], ++ ... ] + +-Now, if you wanted to swap rows and columns, you could use a list +-comprehension:: ++The following list comprehension will transpose rows and columns:: + +- >>> print([[row[i] for row in mat] for i in [0, 1, 2]]) +- [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ++ >>> [[row[i] for row in matrix] for i in range(4)] ++ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +-Special care has to be taken for the *nested* list comprehension: ++As we saw in the previous section, the nested listcomp is evaluated in ++the context of the :keyword:`for` that follows it, so this example is ++equivalent to:: + +- To avoid apprehension when nesting list comprehensions, read from right to +- left. ++ >>> transposed = [] ++ >>> for i in range(4): ++ ... transposed.append([row[i] for row in matrix]) ++ ... ++ >>> transposed ++ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +-A more verbose version of this snippet shows the flow explicitly:: ++which, in turn, is the same as:: + +- for i in [0, 1, 2]: +- for row in mat: +- print(row[i], end="") +- print() ++ >>> transposed = [] ++ >>> for i in range(4): ++ ... # the following 3 lines implement the nested listcomp ++ ... transposed_row = [] ++ ... for row in matrix: ++ ... transposed_row.append(row[i]) ++ ... transposed.append(transposed_row) ++ ... ++ >>> transposed ++ [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] + +-In real world, you should prefer built-in functions to complex flow statements. ++In the real world, you should prefer built-in functions to complex flow statements. + The :func:`zip` function would do a great job for this use case:: + +- >>> list(zip(*mat)) +- [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ++ >>> zip(*matrix) ++ [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] + + See :ref:`tut-unpacking-arguments` for details on the asterisk in this line. + +diff -r 137e45f15c0b Doc/tutorial/floatingpoint.rst +--- a/Doc/tutorial/floatingpoint.rst ++++ b/Doc/tutorial/floatingpoint.rst +@@ -92,7 +92,7 @@ + (although some languages may not *display* the difference by default, or in all + output modes). + +-For more pleasant output, you may may wish to use string formatting to produce a limited number of significant digits:: ++For more pleasant output, you may wish to use string formatting to produce a limited number of significant digits:: + + >>> format(math.pi, '.12g') # give 12 significant digits + '3.14159265359' +diff -r 137e45f15c0b Doc/tutorial/interpreter.rst +--- a/Doc/tutorial/interpreter.rst ++++ b/Doc/tutorial/interpreter.rst +@@ -60,8 +60,7 @@ + + When a script file is used, it is sometimes useful to be able to run the script + and enter interactive mode afterwards. This can be done by passing :option:`-i` +-before the script. (This does not work if the script is read from standard +-input, for the same reason as explained in the previous paragraph.) ++before the script. + + + .. _tut-argpassing: +diff -r 137e45f15c0b Doc/using/cmdline.rst +--- a/Doc/using/cmdline.rst ++++ b/Doc/using/cmdline.rst +@@ -453,7 +453,8 @@ + .. envvar:: PYTHONDONTWRITEBYTECODE + + If this is set, Python won't try to write ``.pyc`` or ``.pyo`` files on the +- import of source modules. ++ import of source modules. This is equivalent to specifying the :option:`-B` ++ option. + + + .. envvar:: PYTHONIOENCODING +diff -r 137e45f15c0b Doc/using/unix.rst +--- a/Doc/using/unix.rst ++++ b/Doc/using/unix.rst +@@ -1,4 +1,4 @@ +-.. highlightlang:: none ++.. highlightlang:: sh + + .. _using-on-unix: + +@@ -55,8 +55,8 @@ + On OpenSolaris + -------------- + +-To install the newest Python versions on OpenSolaris, install blastwave +-(http://www.blastwave.org/howto.html) and type "pkg_get -i python" at the ++To install the newest Python versions on OpenSolaris, install `blastwave ++`_ and type ``pkg_get -i python`` at the + prompt. + + +@@ -65,22 +65,23 @@ + + If you want to compile CPython yourself, first thing you should do is get the + `source `_. You can download either the +-latest release's source or just grab a fresh `checkout +-`_. ++latest release's source or just grab a fresh `clone ++`_. (If you want ++to contribute patches, you will need a clone.) + +-The build process consists the usual :: ++The build process consists in the usual :: + + ./configure + make + make install + + invocations. Configuration options and caveats for specific Unix platforms are +-extensively documented in the :file:`README` file in the root of the Python ++extensively documented in the :source:`README` file in the root of the Python + source tree. + + .. warning:: + +- ``make install`` can overwrite or masquerade the :file:`python` binary. ++ ``make install`` can overwrite or masquerade the :file:`python3` binary. + ``make altinstall`` is therefore recommended instead of ``make install`` + since it only installs :file:`{exec_prefix}/bin/python{version}`. + +@@ -98,7 +99,7 @@ + +-----------------------------------------------+------------------------------------------+ + | File/directory | Meaning | + +===============================================+==========================================+ +-| :file:`{exec_prefix}/bin/python` | Recommended location of the interpreter. | ++| :file:`{exec_prefix}/bin/python3` | Recommended location of the interpreter. | + +-----------------------------------------------+------------------------------------------+ + | :file:`{prefix}/lib/python{version}`, | Recommended locations of the directories | + | :file:`{exec_prefix}/lib/python{version}` | containing the standard modules. | +@@ -108,10 +109,6 @@ + | | developing Python extensions and | + | | embedding the interpreter. | + +-----------------------------------------------+------------------------------------------+ +-| :file:`~/.pythonrc.py` | User-specific initialization file loaded | +-| | by the user module; not used by default | +-| | or by most applications. | +-+-----------------------------------------------+------------------------------------------+ + + + Miscellaneous +@@ -125,11 +122,11 @@ + and put an appropriate Shebang line at the top of the script. A good choice is + usually :: + +- #!/usr/bin/env python ++ #!/usr/bin/env python3 + + which searches for the Python interpreter in the whole :envvar:`PATH`. However, + some Unices may not have the :program:`env` command, so you may need to hardcode +-``/usr/bin/python`` as the interpreter path. ++``/usr/bin/python3`` as the interpreter path. + + To use shell commands in your Python scripts, look at the :mod:`subprocess` module. + +diff -r 137e45f15c0b Doc/using/windows.rst +--- a/Doc/using/windows.rst ++++ b/Doc/using/windows.rst +@@ -45,9 +45,9 @@ + "7 Minutes to "Hello World!"" + by Richard Dooling, 2006 + +- `Installing on Windows `_ ++ `Installing on Windows `_ + in "`Dive into Python: Python from novice to pro +- `_" ++ `_" + by Mark Pilgrim, 2004, + ISBN 1-59059-356-1 + +@@ -290,7 +290,7 @@ + If you want to compile CPython yourself, first thing you should do is get the + `source `_. You can download either the + latest release's source or just grab a fresh `checkout +-`_. ++`_. + + For Microsoft Visual C++, which is the compiler with which official Python + releases are built, the source tree contains solutions/project files. View the +diff -r 137e45f15c0b Doc/whatsnew/2.4.rst +--- a/Doc/whatsnew/2.4.rst ++++ b/Doc/whatsnew/2.4.rst +@@ -947,7 +947,7 @@ + :meth:`__len__` method. (Contributed by Raymond Hettinger.) + + * The methods :meth:`list.__getitem__`, :meth:`dict.__getitem__`, and +- :meth:`dict.__contains__` are are now implemented as :class:`method_descriptor` ++ :meth:`dict.__contains__` are now implemented as :class:`method_descriptor` + objects rather than :class:`wrapper_descriptor` objects. This form of access + doubles their performance and makes them more suitable for use as arguments to + functionals: ``map(mydict.__getitem__, keylist)``. (Contributed by Raymond +diff -r 137e45f15c0b Doc/whatsnew/2.7.rst +--- a/Doc/whatsnew/2.7.rst ++++ b/Doc/whatsnew/2.7.rst +@@ -1952,7 +1952,7 @@ + version 1.3. Some of the new features are: + + * The various parsing functions now take a *parser* keyword argument +- giving an :class:`XMLParser` instance that will ++ giving an :class:`~xml.etree.ElementTree.XMLParser` instance that will + be used. This makes it possible to override the file's internal encoding:: + + p = ET.XMLParser(encoding='utf-8') +@@ -1964,8 +1964,8 @@ + + * ElementTree's code for converting trees to a string has been + significantly reworked, making it roughly twice as fast in many +- cases. The :class:`ElementTree` :meth:`write` and :class:`Element` +- :meth:`write` methods now have a *method* parameter that can be ++ cases. The :meth:`ElementTree.write() ` ++ and :meth:`Element.write` methods now have a *method* parameter that can be + "xml" (the default), "html", or "text". HTML mode will output empty + elements as ```` instead of ````, and text + mode will skip over elements and only output the text chunks. If +@@ -1978,11 +1978,12 @@ + declarations are now output on the root element, not scattered throughout + the resulting XML. You can set the default namespace for a tree + by setting the :attr:`default_namespace` attribute and can +- register new prefixes with :meth:`register_namespace`. In XML mode, ++ register new prefixes with :meth:`~xml.etree.ElementTree.register_namespace`. In XML mode, + you can use the true/false *xml_declaration* parameter to suppress the + XML declaration. + +-* New :class:`Element` method: :meth:`extend` appends the items from a ++* New :class:`~xml.etree.ElementTree.Element` method: ++ :meth:`~xml.etree.ElementTree.Element.extend` appends the items from a + sequence to the element's children. Elements themselves behave like + sequences, so it's easy to move children from one element to + another:: +@@ -1998,13 +1999,15 @@ + # Outputs 1... + print ET.tostring(new) + +-* New :class:`Element` method: :meth:`iter` yields the children of the ++* New :class:`Element` method: ++ :meth:`~xml.etree.ElementTree.Element.iter` yields the children of the + element as a generator. It's also possible to write ``for child in + elem:`` to loop over an element's children. The existing method + :meth:`getiterator` is now deprecated, as is :meth:`getchildren` + which constructs and returns a list of children. + +-* New :class:`Element` method: :meth:`itertext` yields all chunks of ++* New :class:`Element` method: ++ :meth:`~xml.etree.ElementTree.Element.itertext` yields all chunks of + text that are descendants of the element. For example:: + + t = ET.XML(""" +diff -r 137e45f15c0b Doc/whatsnew/3.0.rst +--- a/Doc/whatsnew/3.0.rst ++++ b/Doc/whatsnew/3.0.rst +@@ -154,7 +154,9 @@ + :meth:`dict.itervalues` methods are no longer supported. + + * :func:`map` and :func:`filter` return iterators. If you really need +- a list, a quick fix is e.g. ``list(map(...))``, but a better fix is ++ a list and the input sequences are all of equal length, a quick ++ fix is to wrap :func:`map` in :func:`list`, e.g. ``list(map(...))``, ++ but a better fix is + often to use a list comprehension (especially when the original code + uses :keyword:`lambda`), or rewriting the code so it doesn't need a + list at all. Particularly tricky is :func:`map` invoked for the +@@ -162,6 +164,12 @@ + regular :keyword:`for` loop (since creating a list would just be + wasteful). + ++ If the input sequences are not of equal length, :func:`map` will ++ stop at the termination of the shortest of the sequences. For full ++ compatibility with `map` from Python 2.x, also wrap the sequences in ++ :func:`itertools.zip_longest`, e.g. ``map(func, *sequences)`` becomes ++ ``list(map(func, itertools.zip_longest(*sequences)))``. ++ + * :func:`range` now behaves like :func:`xrange` used to behave, except + it works with values of arbitrary size. The latter no longer + exists. +diff -r 137e45f15c0b Doc/whatsnew/3.2.rst +--- a/Doc/whatsnew/3.2.rst ++++ b/Doc/whatsnew/3.2.rst +@@ -234,8 +234,8 @@ + namespace, *concurrent*. Its first member is a *futures* package which provides + a uniform high-level interface for managing threads and processes. + +-The design for :mod:`concurrent.futures` was inspired by +-*java.util.concurrent.package*. In that model, a running call and its result ++The design for :mod:`concurrent.futures` was inspired by the ++*java.util.concurrent* package. In that model, a running call and its result + are represented by a :class:`~concurrent.futures.Future` object that abstracts + features common to threads, processes, and remote procedure calls. That object + supports status checks (running or done), timeouts, cancellations, adding +@@ -2362,7 +2362,7 @@ + (Patch by Florent Xicluna in :issue:`7622` and :issue:`7462`.) + + +-* String to integer conversions now work two "digits" at a time, reducing the ++* Integer to string conversions now work two "digits" at a time, reducing the + number of division and modulo operations. + + (:issue:`6713` by Gawain Bolton, Mark Dickinson, and Victor Stinner.) +diff -r 137e45f15c0b Grammar/Grammar +--- a/Grammar/Grammar ++++ b/Grammar/Grammar +@@ -88,6 +88,8 @@ + and_test: not_test ('and' not_test)* + not_test: 'not' not_test | comparison + comparison: expr (comp_op expr)* ++# <> isn't actually a valid comparison operator in Python. It's here for the ++# sake of a __future__ import described in PEP 401 + comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' + star_expr: '*' expr + expr: xor_expr ('|' xor_expr)* +diff -r 137e45f15c0b Include/Python.h +--- a/Include/Python.h ++++ b/Include/Python.h +@@ -100,7 +100,7 @@ + #include "warnings.h" + #include "weakrefobject.h" + #include "structseq.h" +- ++#include "accu.h" + + #include "codecs.h" + #include "pyerrors.h" +@@ -141,7 +141,7 @@ + #endif + + /* Argument must be a char or an int in [-128, 127] or [0, 255]. */ +-#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff)) ++#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff)) + + #include "pyfpe.h" + +diff -r 137e45f15c0b Include/accu.h +--- /dev/null ++++ b/Include/accu.h +@@ -0,0 +1,35 @@ ++#ifndef Py_LIMITED_API ++#ifndef Py_ACCU_H ++#define Py_ACCU_H ++ ++/*** This is a private API for use by the interpreter and the stdlib. ++ *** Its definition may be changed or removed at any moment. ++ ***/ ++ ++/* ++ * A two-level accumulator of unicode objects that avoids both the overhead ++ * of keeping a huge number of small separate objects, and the quadratic ++ * behaviour of using a naive repeated concatenation scheme. ++ */ ++ ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++typedef struct { ++ PyObject *large; /* A list of previously accumulated large strings */ ++ PyObject *small; /* Pending small strings */ ++} _PyAccu; ++ ++PyAPI_FUNC(int) _PyAccu_Init(_PyAccu *acc); ++PyAPI_FUNC(int) _PyAccu_Accumulate(_PyAccu *acc, PyObject *unicode); ++PyAPI_FUNC(PyObject *) _PyAccu_FinishAsList(_PyAccu *acc); ++PyAPI_FUNC(PyObject *) _PyAccu_Finish(_PyAccu *acc); ++PyAPI_FUNC(void) _PyAccu_Destroy(_PyAccu *acc); ++ ++#ifdef __cplusplus ++} ++#endif ++ ++#endif /* Py_ACCU_H */ ++#endif /* Py_LIMITED_API */ +diff -r 137e45f15c0b Include/descrobject.h +--- a/Include/descrobject.h ++++ b/Include/descrobject.h +@@ -77,6 +77,7 @@ + PyAPI_DATA(PyTypeObject) PyMethodDescr_Type; + PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type; + PyAPI_DATA(PyTypeObject) PyDictProxy_Type; ++PyAPI_DATA(PyTypeObject) _PyMethodWrapper_Type; + + PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); + PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); +diff -r 137e45f15c0b Include/dynamic_annotations.h +--- a/Include/dynamic_annotations.h ++++ b/Include/dynamic_annotations.h +@@ -103,26 +103,26 @@ + + /* Report that wait on the condition variable at address "cv" has succeeded + and the lock at address "lock" is held. */ +- #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \ ++#define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \ + AnnotateCondVarWait(__FILE__, __LINE__, cv, lock) + + /* Report that wait on the condition variable at "cv" has succeeded. Variant + w/o lock. */ +- #define _Py_ANNOTATE_CONDVAR_WAIT(cv) \ ++#define _Py_ANNOTATE_CONDVAR_WAIT(cv) \ + AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL) + + /* Report that we are about to signal on the condition variable at address + "cv". */ +- #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \ ++#define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \ + AnnotateCondVarSignal(__FILE__, __LINE__, cv) + + /* Report that we are about to signal_all on the condition variable at "cv". */ +- #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \ ++#define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \ + AnnotateCondVarSignalAll(__FILE__, __LINE__, cv) + + /* Annotations for user-defined synchronization mechanisms. */ +- #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj) +- #define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj) ++#define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj) ++#define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj) + + /* Report that the bytes in the range [pointer, pointer+size) are about + to be published safely. The race checker will create a happens-before +@@ -131,7 +131,7 @@ + Note: this annotation may not work properly if the race detector uses + sampling, i.e. does not observe all memory accesses. + */ +- #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \ ++#define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \ + AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size) + + /* Instruct the tool to create a happens-before arc between mu->Unlock() and +@@ -141,7 +141,7 @@ + This annotation makes sense only for hybrid race detectors. For pure + happens-before detectors this is a no-op. For more details see + http://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */ +- #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \ ++#define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \ + AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu) + + /* ------------------------------------------------------------- +@@ -152,7 +152,7 @@ + This might be used when the memory has been retrieved from a free list and + is about to be reused, or when a the locking discipline for a variable + changes. */ +- #define _Py_ANNOTATE_NEW_MEMORY(address, size) \ ++#define _Py_ANNOTATE_NEW_MEMORY(address, size) \ + AnnotateNewMemory(__FILE__, __LINE__, address, size) + + /* ------------------------------------------------------------- +@@ -164,20 +164,20 @@ + be used only for FIFO queues. For non-FIFO queues use + _Py_ANNOTATE_HAPPENS_BEFORE (for put) and _Py_ANNOTATE_HAPPENS_AFTER (for + get). */ +- #define _Py_ANNOTATE_PCQ_CREATE(pcq) \ ++#define _Py_ANNOTATE_PCQ_CREATE(pcq) \ + AnnotatePCQCreate(__FILE__, __LINE__, pcq) + + /* Report that the queue at address "pcq" is about to be destroyed. */ +- #define _Py_ANNOTATE_PCQ_DESTROY(pcq) \ ++#define _Py_ANNOTATE_PCQ_DESTROY(pcq) \ + AnnotatePCQDestroy(__FILE__, __LINE__, pcq) + + /* Report that we are about to put an element into a FIFO queue at address + "pcq". */ +- #define _Py_ANNOTATE_PCQ_PUT(pcq) \ ++#define _Py_ANNOTATE_PCQ_PUT(pcq) \ + AnnotatePCQPut(__FILE__, __LINE__, pcq) + + /* Report that we've just got an element from a FIFO queue at address "pcq". */ +- #define _Py_ANNOTATE_PCQ_GET(pcq) \ ++#define _Py_ANNOTATE_PCQ_GET(pcq) \ + AnnotatePCQGet(__FILE__, __LINE__, pcq) + + /* ------------------------------------------------------------- +@@ -189,13 +189,13 @@ + "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the + point where "pointer" has been allocated, preferably close to the point + where the race happens. See also _Py_ANNOTATE_BENIGN_RACE_STATIC. */ +- #define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \ ++#define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \ + AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \ + sizeof(*(pointer)), description) + + /* Same as _Py_ANNOTATE_BENIGN_RACE(address, description), but applies to + the memory range [address, address+size). */ +- #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ ++#define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ + AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description) + + /* Request the analysis tool to ignore all reads in the current thread +@@ -203,30 +203,30 @@ + Useful to ignore intentional racey reads, while still checking + other reads and all writes. + See also _Py_ANNOTATE_UNPROTECTED_READ. */ +- #define _Py_ANNOTATE_IGNORE_READS_BEGIN() \ ++#define _Py_ANNOTATE_IGNORE_READS_BEGIN() \ + AnnotateIgnoreReadsBegin(__FILE__, __LINE__) + + /* Stop ignoring reads. */ +- #define _Py_ANNOTATE_IGNORE_READS_END() \ ++#define _Py_ANNOTATE_IGNORE_READS_END() \ + AnnotateIgnoreReadsEnd(__FILE__, __LINE__) + + /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */ +- #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \ ++#define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \ + AnnotateIgnoreWritesBegin(__FILE__, __LINE__) + + /* Stop ignoring writes. */ +- #define _Py_ANNOTATE_IGNORE_WRITES_END() \ ++#define _Py_ANNOTATE_IGNORE_WRITES_END() \ + AnnotateIgnoreWritesEnd(__FILE__, __LINE__) + + /* Start ignoring all memory accesses (reads and writes). */ +- #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ ++#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ + do {\ + _Py_ANNOTATE_IGNORE_READS_BEGIN();\ + _Py_ANNOTATE_IGNORE_WRITES_BEGIN();\ + }while(0)\ + + /* Stop ignoring all memory accesses. */ +- #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \ ++#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \ + do {\ + _Py_ANNOTATE_IGNORE_WRITES_END();\ + _Py_ANNOTATE_IGNORE_READS_END();\ +@@ -234,29 +234,29 @@ + + /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events: + RWLOCK* and CONDVAR*. */ +- #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \ ++#define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \ + AnnotateIgnoreSyncBegin(__FILE__, __LINE__) + + /* Stop ignoring sync events. */ +- #define _Py_ANNOTATE_IGNORE_SYNC_END() \ ++#define _Py_ANNOTATE_IGNORE_SYNC_END() \ + AnnotateIgnoreSyncEnd(__FILE__, __LINE__) + + + /* Enable (enable!=0) or disable (enable==0) race detection for all threads. + This annotation could be useful if you want to skip expensive race analysis + during some period of program execution, e.g. during initialization. */ +- #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \ ++#define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \ + AnnotateEnableRaceDetection(__FILE__, __LINE__, enable) + + /* ------------------------------------------------------------- + Annotations useful for debugging. */ + + /* Request to trace every access to "address". */ +- #define _Py_ANNOTATE_TRACE_MEMORY(address) \ ++#define _Py_ANNOTATE_TRACE_MEMORY(address) \ + AnnotateTraceMemory(__FILE__, __LINE__, address) + + /* Report the current thread name to a race detector. */ +- #define _Py_ANNOTATE_THREAD_NAME(name) \ ++#define _Py_ANNOTATE_THREAD_NAME(name) \ + AnnotateThreadName(__FILE__, __LINE__, name) + + /* ------------------------------------------------------------- +@@ -265,20 +265,20 @@ + The "lock" argument is a pointer to the lock object. */ + + /* Report that a lock has been created at address "lock". */ +- #define _Py_ANNOTATE_RWLOCK_CREATE(lock) \ ++#define _Py_ANNOTATE_RWLOCK_CREATE(lock) \ + AnnotateRWLockCreate(__FILE__, __LINE__, lock) + + /* Report that the lock at address "lock" is about to be destroyed. */ +- #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \ ++#define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \ + AnnotateRWLockDestroy(__FILE__, __LINE__, lock) + + /* Report that the lock at address "lock" has been acquired. + is_w=1 for writer lock, is_w=0 for reader lock. */ +- #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ ++#define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ + AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) + + /* Report that the lock at address "lock" is about to be released. */ +- #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ ++#define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ + AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) + + /* ------------------------------------------------------------- +@@ -289,20 +289,20 @@ + /* Report that the "barrier" has been initialized with initial "count". + If 'reinitialization_allowed' is true, initialization is allowed to happen + multiple times w/o calling barrier_destroy() */ +- #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \ ++#define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \ + AnnotateBarrierInit(__FILE__, __LINE__, barrier, count, \ + reinitialization_allowed) + + /* Report that we are about to enter barrier_wait("barrier"). */ +- #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \ ++#define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \ + AnnotateBarrierWaitBefore(__FILE__, __LINE__, barrier) + + /* Report that we just exited barrier_wait("barrier"). */ +- #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \ ++#define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \ + AnnotateBarrierWaitAfter(__FILE__, __LINE__, barrier) + + /* Report that the "barrier" has been destroyed. */ +- #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \ ++#define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \ + AnnotateBarrierDestroy(__FILE__, __LINE__, barrier) + + /* ------------------------------------------------------------- +@@ -310,61 +310,61 @@ + + /* Report that we expect a race on the variable at "address". + Use only in unit tests for a race detector. */ +- #define _Py_ANNOTATE_EXPECT_RACE(address, description) \ ++#define _Py_ANNOTATE_EXPECT_RACE(address, description) \ + AnnotateExpectRace(__FILE__, __LINE__, address, description) + + /* A no-op. Insert where you like to test the interceptors. */ +- #define _Py_ANNOTATE_NO_OP(arg) \ ++#define _Py_ANNOTATE_NO_OP(arg) \ + AnnotateNoOp(__FILE__, __LINE__, arg) + + /* Force the race detector to flush its state. The actual effect depends on + * the implementation of the detector. */ +- #define _Py_ANNOTATE_FLUSH_STATE() \ ++#define _Py_ANNOTATE_FLUSH_STATE() \ + AnnotateFlushState(__FILE__, __LINE__) + + + #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ + +- #define _Py_ANNOTATE_RWLOCK_CREATE(lock) /* empty */ +- #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) /* empty */ +- #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */ +- #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */ +- #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */ +- #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */ +- #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */ +- #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) /* empty */ +- #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */ +- #define _Py_ANNOTATE_CONDVAR_WAIT(cv) /* empty */ +- #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */ +- #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */ +- #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) /* empty */ +- #define _Py_ANNOTATE_HAPPENS_AFTER(obj) /* empty */ +- #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */ +- #define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */ +- #define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */ +- #define _Py_ANNOTATE_PCQ_CREATE(pcq) /* empty */ +- #define _Py_ANNOTATE_PCQ_DESTROY(pcq) /* empty */ +- #define _Py_ANNOTATE_PCQ_PUT(pcq) /* empty */ +- #define _Py_ANNOTATE_PCQ_GET(pcq) /* empty */ +- #define _Py_ANNOTATE_NEW_MEMORY(address, size) /* empty */ +- #define _Py_ANNOTATE_EXPECT_RACE(address, description) /* empty */ +- #define _Py_ANNOTATE_BENIGN_RACE(address, description) /* empty */ +- #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */ +- #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */ +- #define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */ +- #define _Py_ANNOTATE_TRACE_MEMORY(arg) /* empty */ +- #define _Py_ANNOTATE_THREAD_NAME(name) /* empty */ +- #define _Py_ANNOTATE_IGNORE_READS_BEGIN() /* empty */ +- #define _Py_ANNOTATE_IGNORE_READS_END() /* empty */ +- #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */ +- #define _Py_ANNOTATE_IGNORE_WRITES_END() /* empty */ +- #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */ +- #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */ +- #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */ +- #define _Py_ANNOTATE_IGNORE_SYNC_END() /* empty */ +- #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */ +- #define _Py_ANNOTATE_NO_OP(arg) /* empty */ +- #define _Py_ANNOTATE_FLUSH_STATE() /* empty */ ++#define _Py_ANNOTATE_RWLOCK_CREATE(lock) /* empty */ ++#define _Py_ANNOTATE_RWLOCK_DESTROY(lock) /* empty */ ++#define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */ ++#define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */ ++#define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */ ++#define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */ ++#define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */ ++#define _Py_ANNOTATE_BARRIER_DESTROY(barrier) /* empty */ ++#define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */ ++#define _Py_ANNOTATE_CONDVAR_WAIT(cv) /* empty */ ++#define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */ ++#define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */ ++#define _Py_ANNOTATE_HAPPENS_BEFORE(obj) /* empty */ ++#define _Py_ANNOTATE_HAPPENS_AFTER(obj) /* empty */ ++#define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */ ++#define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */ ++#define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */ ++#define _Py_ANNOTATE_PCQ_CREATE(pcq) /* empty */ ++#define _Py_ANNOTATE_PCQ_DESTROY(pcq) /* empty */ ++#define _Py_ANNOTATE_PCQ_PUT(pcq) /* empty */ ++#define _Py_ANNOTATE_PCQ_GET(pcq) /* empty */ ++#define _Py_ANNOTATE_NEW_MEMORY(address, size) /* empty */ ++#define _Py_ANNOTATE_EXPECT_RACE(address, description) /* empty */ ++#define _Py_ANNOTATE_BENIGN_RACE(address, description) /* empty */ ++#define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */ ++#define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */ ++#define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */ ++#define _Py_ANNOTATE_TRACE_MEMORY(arg) /* empty */ ++#define _Py_ANNOTATE_THREAD_NAME(name) /* empty */ ++#define _Py_ANNOTATE_IGNORE_READS_BEGIN() /* empty */ ++#define _Py_ANNOTATE_IGNORE_READS_END() /* empty */ ++#define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */ ++#define _Py_ANNOTATE_IGNORE_WRITES_END() /* empty */ ++#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */ ++#define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */ ++#define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */ ++#define _Py_ANNOTATE_IGNORE_SYNC_END() /* empty */ ++#define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */ ++#define _Py_ANNOTATE_NO_OP(arg) /* empty */ ++#define _Py_ANNOTATE_FLUSH_STATE() /* empty */ + + #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ + +@@ -477,7 +477,7 @@ + return res; + } + /* Apply _Py_ANNOTATE_BENIGN_RACE_SIZED to a static variable. */ +- #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ ++#define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ + namespace { \ + class static_var ## _annotator { \ + public: \ +@@ -491,8 +491,8 @@ + } + #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ + +- #define _Py_ANNOTATE_UNPROTECTED_READ(x) (x) +- #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */ ++#define _Py_ANNOTATE_UNPROTECTED_READ(x) (x) ++#define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */ + + #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ + +diff -r 137e45f15c0b Include/fileobject.h +--- a/Include/fileobject.h ++++ b/Include/fileobject.h +@@ -44,6 +44,13 @@ + #endif + #endif /* Py_LIMITED_API */ + ++/* A routine to check if a file descriptor can be select()-ed. */ ++#ifdef HAVE_SELECT ++ #define _PyIsSelectable_fd(FD) (((FD) >= 0) && ((FD) < FD_SETSIZE)) ++#else ++ #define _PyIsSelectable_fd(FD) (1) ++#endif /* HAVE_SELECT */ ++ + #ifdef __cplusplus + } + #endif +diff -r 137e45f15c0b Include/object.h +--- a/Include/object.h ++++ b/Include/object.h +@@ -449,6 +449,7 @@ + #ifndef Py_LIMITED_API + PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *); + PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **); ++PyAPI_FUNC(PyTypeObject *) _PyType_CalculateMetaclass(PyTypeObject *, PyObject *); + #endif + PyAPI_FUNC(unsigned int) PyType_ClearCache(void); + PyAPI_FUNC(void) PyType_Modified(PyTypeObject *); +diff -r 137e45f15c0b Include/patchlevel.h +--- a/Include/patchlevel.h ++++ b/Include/patchlevel.h +@@ -23,7 +23,7 @@ + #define PY_RELEASE_SERIAL 0 + + /* Version as a string */ +-#define PY_VERSION "3.2.2" ++#define PY_VERSION "3.2.2+" + /*--end constants--*/ + + /* Subversion Revision number of this file (not of the repository). Empty +diff -r 137e45f15c0b Include/pyatomic.h +--- a/Include/pyatomic.h ++++ b/Include/pyatomic.h +@@ -58,13 +58,15 @@ + static __inline__ void + _Py_ANNOTATE_MEMORY_ORDER(const volatile void *address, _Py_memory_order order) + { ++ (void)address; /* shut up -Wunused-parameter */ + switch(order) { + case _Py_memory_order_release: + case _Py_memory_order_acq_rel: + case _Py_memory_order_seq_cst: + _Py_ANNOTATE_HAPPENS_BEFORE(address); + break; +- default: ++ case _Py_memory_order_relaxed: ++ case _Py_memory_order_acquire: + break; + } + switch(order) { +@@ -73,7 +75,8 @@ + case _Py_memory_order_seq_cst: + _Py_ANNOTATE_HAPPENS_AFTER(address); + break; +- default: ++ case _Py_memory_order_relaxed: ++ case _Py_memory_order_release: + break; + } + } +diff -r 137e45f15c0b Include/pyctype.h +--- a/Include/pyctype.h ++++ b/Include/pyctype.h +@@ -10,7 +10,7 @@ + #define PY_CTF_SPACE 0x08 + #define PY_CTF_XDIGIT 0x10 + +-extern const unsigned int _Py_ctype_table[256]; ++PyAPI_DATA(const unsigned int) _Py_ctype_table[256]; + + /* Unlike their C counterparts, the following macros are not meant to + * handle an int with any of the values [EOF, 0-UCHAR_MAX]. The argument +@@ -23,8 +23,8 @@ + #define Py_ISALNUM(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALNUM) + #define Py_ISSPACE(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_SPACE) + +-extern const unsigned char _Py_ctype_tolower[256]; +-extern const unsigned char _Py_ctype_toupper[256]; ++PyAPI_DATA(const unsigned char) _Py_ctype_tolower[256]; ++PyAPI_DATA(const unsigned char) _Py_ctype_toupper[256]; + + #define Py_TOLOWER(c) (_Py_ctype_tolower[Py_CHARMASK(c)]) + #define Py_TOUPPER(c) (_Py_ctype_toupper[Py_CHARMASK(c)]) +diff -r 137e45f15c0b Include/unicodeobject.h +--- a/Include/unicodeobject.h ++++ b/Include/unicodeobject.h +@@ -595,7 +595,7 @@ + + /* Convert the Unicode object to a wide character string. The output string + always ends with a nul character. If size is not NULL, write the number of +- wide characters (including the nul character) into *size. ++ wide characters (excluding the null character) into *size. + + Returns a buffer allocated by PyMem_Alloc() (use PyMem_Free() to free it) + on success. On error, returns NULL, *size is undefined and raises a +diff -r 137e45f15c0b Lib/_pyio.py +--- a/Lib/_pyio.py ++++ b/Lib/_pyio.py +@@ -6,6 +6,7 @@ + import abc + import codecs + import warnings ++import errno + # Import _thread instead of threading to reduce startup cost + try: + from _thread import allocate_lock as Lock +@@ -720,8 +721,11 @@ + + def close(self): + if self.raw is not None and not self.closed: +- self.flush() +- self.raw.close() ++ try: ++ # may raise BlockingIOError or BrokenPipeError etc ++ self.flush() ++ finally: ++ self.raw.close() + + def detach(self): + if self.raw is None: +@@ -1080,13 +1084,9 @@ + # XXX we can implement some more tricks to try and avoid + # partial writes + if len(self._write_buf) > self.buffer_size: +- # We're full, so let's pre-flush the buffer +- try: +- self._flush_unlocked() +- except BlockingIOError as e: +- # We can't accept anything else. +- # XXX Why not just let the exception pass through? +- raise BlockingIOError(e.errno, e.strerror, 0) ++ # We're full, so let's pre-flush the buffer. (This may ++ # raise BlockingIOError with characters_written == 0.) ++ self._flush_unlocked() + before = len(self._write_buf) + self._write_buf.extend(b) + written = len(self._write_buf) - before +@@ -1117,24 +1117,23 @@ + def _flush_unlocked(self): + if self.closed: + raise ValueError("flush of closed file") +- written = 0 +- try: +- while self._write_buf: +- try: +- n = self.raw.write(self._write_buf) +- except IOError as e: +- if e.errno != EINTR: +- raise +- continue +- if n > len(self._write_buf) or n < 0: +- raise IOError("write() returned incorrect number of bytes") +- del self._write_buf[:n] +- written += n +- except BlockingIOError as e: +- n = e.characters_written ++ while self._write_buf: ++ try: ++ n = self.raw.write(self._write_buf) ++ except BlockingIOError: ++ raise RuntimeError("self.raw should implement RawIOBase: it " ++ "should not raise BlockingIOError") ++ except IOError as e: ++ if e.errno != EINTR: ++ raise ++ continue ++ if n is None: ++ raise BlockingIOError( ++ errno.EAGAIN, ++ "write could not complete without blocking", 0) ++ if n > len(self._write_buf) or n < 0: ++ raise IOError("write() returned incorrect number of bytes") + del self._write_buf[:n] +- written += n +- raise BlockingIOError(e.errno, e.strerror, written) + + def tell(self): + return _BufferedIOMixin.tell(self) + len(self._write_buf) +@@ -1460,7 +1459,7 @@ + enabled. With this enabled, on input, the lines endings '\n', '\r', + or '\r\n' are translated to '\n' before being returned to the + caller. Conversely, on output, '\n' is translated to the system +- default line seperator, os.linesep. If newline is any other of its ++ default line separator, os.linesep. If newline is any other of its + legal values, that newline becomes the newline when the file is read + and it is returned untranslated. On output, '\n' is converted to the + newline. +diff -r 137e45f15c0b Lib/argparse.py +--- a/Lib/argparse.py ++++ b/Lib/argparse.py +@@ -92,10 +92,6 @@ + from gettext import gettext as _, ngettext + + +-def _callable(obj): +- return hasattr(obj, '__call__') or hasattr(obj, '__bases__') +- +- + SUPPRESS = '==SUPPRESS==' + + OPTIONAL = '?' +@@ -1286,13 +1282,13 @@ + + # create the action object, and add it to the parser + action_class = self._pop_action_class(kwargs) +- if not _callable(action_class): ++ if not callable(action_class): + raise ValueError('unknown action "%s"' % (action_class,)) + action = action_class(**kwargs) + + # raise an error if the action type is not callable + type_func = self._registry_get('type', action.type, action.type) +- if not _callable(type_func): ++ if not callable(type_func): + raise ValueError('%r is not callable' % (type_func,)) + + # raise an error if the metavar does not match the type +@@ -2240,7 +2236,7 @@ + + def _get_value(self, action, arg_string): + type_func = self._registry_get('type', action.type, action.type) +- if not _callable(type_func): ++ if not callable(type_func): + msg = _('%r is not callable') + raise ArgumentError(action, msg % type_func) + +diff -r 137e45f15c0b Lib/cgi.py +--- a/Lib/cgi.py ++++ b/Lib/cgi.py +@@ -291,7 +291,7 @@ + while s[:1] == ';': + s = s[1:] + end = s.find(';') +- while end > 0 and s.count('"', 0, end) % 2: ++ while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: + end = s.find(';', end + 1) + if end < 0: + end = len(s) +diff -r 137e45f15c0b Lib/cmd.py +--- a/Lib/cmd.py ++++ b/Lib/cmd.py +@@ -205,6 +205,8 @@ + if cmd is None: + return self.default(line) + self.lastcmd = line ++ if line == 'EOF' : ++ self.lastcmd = '' + if cmd == '': + return self.default(line) + else: +diff -r 137e45f15c0b Lib/collections.py +--- a/Lib/collections.py ++++ b/Lib/collections.py +@@ -583,8 +583,12 @@ + def __repr__(self): + if not self: + return '%s()' % self.__class__.__name__ +- items = ', '.join(map('%r: %r'.__mod__, self.most_common())) +- return '%s({%s})' % (self.__class__.__name__, items) ++ try: ++ items = ', '.join(map('%r: %r'.__mod__, self.most_common())) ++ return '%s({%s})' % (self.__class__.__name__, items) ++ except TypeError: ++ # handle case where values are not orderable ++ return '{0}({1!r})'.format(self.__class__.__name__, dict(self)) + + # Multiset-style mathematical operations discussed in: + # Knuth TAOCP Volume II section 4.6.3 exercise 19 +diff -r 137e45f15c0b Lib/compileall.py +--- a/Lib/compileall.py ++++ b/Lib/compileall.py +@@ -142,7 +142,7 @@ + + Arguments (all optional): + +- skip_curdir: if true, skip current directory (default true) ++ skip_curdir: if true, skip current directory (default True) + maxlevels: max recursion level (default 0) + force: as for compile_dir() (default False) + quiet: as for compile_dir() (default False) +@@ -177,17 +177,17 @@ + help='use legacy (pre-PEP3147) compiled file locations') + parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None, + help=('directory to prepend to file paths for use in ' +- 'compile time tracebacks and in runtime ' ++ 'compile-time tracebacks and in runtime ' + 'tracebacks in cases where the source file is ' + 'unavailable')) + parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None, +- help=('skip files matching the regular expression. ' +- 'The regexp is searched for in the full path ' +- 'to each file considered for compilation.')) ++ help=('skip files matching the regular expression; ' ++ 'the regexp is searched for in the full path ' ++ 'of each file considered for compilation')) + parser.add_argument('-i', metavar='FILE', dest='flist', + help=('add all the files and directories listed in ' +- 'FILE to the list considered for compilation. ' +- 'If "-", names are read from stdin.')) ++ 'FILE to the list considered for compilation; ' ++ 'if "-", names are read from stdin')) + parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*', + help=('zero or more file and directory names ' + 'to compile; if no arguments given, defaults ' +diff -r 137e45f15c0b Lib/configparser.py +--- a/Lib/configparser.py ++++ b/Lib/configparser.py +@@ -381,7 +381,7 @@ + + would resolve the "%(dir)s" to the value of dir. All reference + expansions are done late, on demand. If a user needs to use a bare % in +- a configuration file, she can escape it by writing %%. Other other % usage ++ a configuration file, she can escape it by writing %%. Other % usage + is considered a user error and raises `InterpolationSyntaxError'.""" + + _KEYCRE = re.compile(r"%\(([^)]+)\)s") +diff -r 137e45f15c0b Lib/copyreg.py +--- a/Lib/copyreg.py ++++ b/Lib/copyreg.py +@@ -10,7 +10,7 @@ + dispatch_table = {} + + def pickle(ob_type, pickle_function, constructor_ob=None): +- if not hasattr(pickle_function, '__call__'): ++ if not callable(pickle_function): + raise TypeError("reduction functions must be callable") + dispatch_table[ob_type] = pickle_function + +@@ -20,7 +20,7 @@ + constructor(constructor_ob) + + def constructor(object): +- if not hasattr(object, '__call__'): ++ if not callable(object): + raise TypeError("constructors must be callable") + + # Example: provide pickling support for complex numbers. +diff -r 137e45f15c0b Lib/ctypes/__init__.py +--- a/Lib/ctypes/__init__.py ++++ b/Lib/ctypes/__init__.py +@@ -265,7 +265,21 @@ + class c_wchar(_SimpleCData): + _type_ = "u" + +-POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param ++def _reset_cache(): ++ _pointer_type_cache.clear() ++ _c_functype_cache.clear() ++ if _os.name in ("nt", "ce"): ++ _win_functype_cache.clear() ++ # _SimpleCData.c_wchar_p_from_param ++ POINTER(c_wchar).from_param = c_wchar_p.from_param ++ # _SimpleCData.c_char_p_from_param ++ POINTER(c_char).from_param = c_char_p.from_param ++ _pointer_type_cache[None] = c_void_p ++ # XXX for whatever reasons, creating the first instance of a callback ++ # function is needed for the unittests on Win64 to succeed. This MAY ++ # be a compiler bug, since the problem occurs only when _ctypes is ++ # compiled with the MS SDK compiler. Or an uninitialized variable? ++ CFUNCTYPE(c_int)(lambda: None) + + def create_unicode_buffer(init, size=None): + """create_unicode_buffer(aString) -> character array +@@ -285,7 +299,6 @@ + return buf + raise TypeError(init) + +-POINTER(c_char).from_param = c_char_p.from_param #_SimpleCData.c_char_p_from_param + + # XXX Deprecated + def SetPointerType(pointer, cls): +@@ -445,8 +458,6 @@ + descr = FormatError(code).strip() + return WindowsError(code, descr) + +-_pointer_type_cache[None] = c_void_p +- + if sizeof(c_uint) == sizeof(c_void_p): + c_size_t = c_uint + c_ssize_t = c_int +@@ -529,8 +540,4 @@ + elif sizeof(kind) == 8: c_uint64 = kind + del(kind) + +-# XXX for whatever reasons, creating the first instance of a callback +-# function is needed for the unittests on Win64 to succeed. This MAY +-# be a compiler bug, since the problem occurs only when _ctypes is +-# compiled with the MS SDK compiler. Or an uninitialized variable? +-CFUNCTYPE(c_int)(lambda: None) ++_reset_cache() +diff -r 137e45f15c0b Lib/ctypes/test/test_arrays.py +--- a/Lib/ctypes/test/test_arrays.py ++++ b/Lib/ctypes/test/test_arrays.py +@@ -127,5 +127,57 @@ + t2 = my_int * 1 + self.assertTrue(t1 is t2) + ++ def test_subclass(self): ++ class T(Array): ++ _type_ = c_int ++ _length_ = 13 ++ class U(T): ++ pass ++ class V(U): ++ pass ++ class W(V): ++ pass ++ class X(T): ++ _type_ = c_short ++ class Y(T): ++ _length_ = 187 ++ ++ for c in [T, U, V, W]: ++ self.assertEqual(c._type_, c_int) ++ self.assertEqual(c._length_, 13) ++ self.assertEqual(c()._type_, c_int) ++ self.assertEqual(c()._length_, 13) ++ ++ self.assertEqual(X._type_, c_short) ++ self.assertEqual(X._length_, 13) ++ self.assertEqual(X()._type_, c_short) ++ self.assertEqual(X()._length_, 13) ++ ++ self.assertEqual(Y._type_, c_int) ++ self.assertEqual(Y._length_, 187) ++ self.assertEqual(Y()._type_, c_int) ++ self.assertEqual(Y()._length_, 187) ++ ++ def test_bad_subclass(self): ++ import sys ++ ++ with self.assertRaises(AttributeError): ++ class T(Array): ++ pass ++ with self.assertRaises(AttributeError): ++ class T(Array): ++ _type_ = c_int ++ with self.assertRaises(AttributeError): ++ class T(Array): ++ _length_ = 13 ++ with self.assertRaises(OverflowError): ++ class T(Array): ++ _type_ = c_int ++ _length_ = sys.maxsize * 2 ++ with self.assertRaises(AttributeError): ++ class T(Array): ++ _type_ = c_int ++ _length_ = 1.87 ++ + if __name__ == '__main__': + unittest.main() +diff -r 137e45f15c0b Lib/ctypes/test/test_as_parameter.py +--- a/Lib/ctypes/test/test_as_parameter.py ++++ b/Lib/ctypes/test/test_as_parameter.py +@@ -74,6 +74,7 @@ + def test_callbacks(self): + f = dll._testfunc_callback_i_if + f.restype = c_int ++ f.argtypes = None + + MyCallback = CFUNCTYPE(c_int, c_int) + +diff -r 137e45f15c0b Lib/ctypes/test/test_callbacks.py +--- a/Lib/ctypes/test/test_callbacks.py ++++ b/Lib/ctypes/test/test_callbacks.py +@@ -134,6 +134,14 @@ + if isinstance(x, X)] + self.assertEqual(len(live), 0) + ++ def test_issue12483(self): ++ import gc ++ class Nasty: ++ def __del__(self): ++ gc.collect() ++ CFUNCTYPE(None)(lambda x=Nasty(): None) ++ ++ + try: + WINFUNCTYPE + except NameError: +diff -r 137e45f15c0b Lib/ctypes/test/test_functions.py +--- a/Lib/ctypes/test/test_functions.py ++++ b/Lib/ctypes/test/test_functions.py +@@ -250,6 +250,7 @@ + def test_callbacks(self): + f = dll._testfunc_callback_i_if + f.restype = c_int ++ f.argtypes = None + + MyCallback = CFUNCTYPE(c_int, c_int) + +diff -r 137e45f15c0b Lib/ctypes/test/test_structures.py +--- a/Lib/ctypes/test/test_structures.py ++++ b/Lib/ctypes/test/test_structures.py +@@ -239,6 +239,14 @@ + pass + self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)]) + ++ def test_invalid_name(self): ++ # field name must be string ++ def declare_with_name(name): ++ class S(Structure): ++ _fields_ = [(name, c_int)] ++ ++ self.assertRaises(TypeError, declare_with_name, b"x") ++ + def test_intarray_fields(self): + class SomeInts(Structure): + _fields_ = [("a", c_int * 4)] +@@ -318,6 +326,18 @@ + else: + self.assertEqual(msg, "(Phone) TypeError: too many initializers") + ++ def test_huge_field_name(self): ++ # issue12881: segfault with large structure field names ++ def create_class(length): ++ class S(Structure): ++ _fields_ = [('x' * length, c_int)] ++ ++ for length in [10 ** i for i in range(0, 8)]: ++ try: ++ create_class(length) ++ except MemoryError: ++ # MemoryErrors are OK, we just don't want to segfault ++ pass + + def get_except(self, func, *args): + try: +diff -r 137e45f15c0b Lib/curses/__init__.py +--- a/Lib/curses/__init__.py ++++ b/Lib/curses/__init__.py +@@ -54,4 +54,4 @@ + try: + has_key + except NameError: +- from has_key import has_key ++ from .has_key import has_key +diff -r 137e45f15c0b Lib/datetime.py +--- a/Lib/datetime.py ++++ b/Lib/datetime.py +@@ -2057,7 +2057,7 @@ + + Because we know z.d said z was in daylight time (else [5] would have held and + we would have stopped then), and we know z.d != z'.d (else [8] would have held +-and we we have stopped then), and there are only 2 possible values dst() can ++and we have stopped then), and there are only 2 possible values dst() can + return in Eastern, it follows that z'.d must be 0 (which it is in the example, + but the reasoning doesn't depend on the example -- it depends on there being + two possible dst() outcomes, one zero and the other non-zero). Therefore +diff -r 137e45f15c0b Lib/dbm/__init__.py +--- a/Lib/dbm/__init__.py ++++ b/Lib/dbm/__init__.py +@@ -166,7 +166,7 @@ + return "" + + # Check for GNU dbm +- if magic == 0x13579ace: ++ if magic in (0x13579ace, 0x13579acd, 0x13579acf): + return "dbm.gnu" + + # Later versions of Berkeley db hash file have a 12-byte pad in +diff -r 137e45f15c0b Lib/distutils/command/build_py.py +--- a/Lib/distutils/command/build_py.py ++++ b/Lib/distutils/command/build_py.py +@@ -2,7 +2,8 @@ + + Implements the Distutils 'build_py' command.""" + +-import sys, os ++import os ++import imp + import sys + from glob import glob + +@@ -311,9 +312,11 @@ + outputs.append(filename) + if include_bytecode: + if self.compile: +- outputs.append(filename + "c") ++ outputs.append(imp.cache_from_source(filename, ++ debug_override=True)) + if self.optimize > 0: +- outputs.append(filename + "o") ++ outputs.append(imp.cache_from_source(filename, ++ debug_override=False)) + + outputs += [ + os.path.join(build_dir, filename) +diff -r 137e45f15c0b Lib/distutils/command/install_egg_info.py +--- a/Lib/distutils/command/install_egg_info.py ++++ b/Lib/distutils/command/install_egg_info.py +@@ -40,9 +40,8 @@ + "Creating "+self.install_dir) + log.info("Writing %s", target) + if not self.dry_run: +- f = open(target, 'w') +- self.distribution.metadata.write_pkg_file(f) +- f.close() ++ with open(target, 'w', encoding='UTF-8') as f: ++ self.distribution.metadata.write_pkg_file(f) + + def get_outputs(self): + return self.outputs +diff -r 137e45f15c0b Lib/distutils/command/install_lib.py +--- a/Lib/distutils/command/install_lib.py ++++ b/Lib/distutils/command/install_lib.py +@@ -4,6 +4,7 @@ + (install all Python modules).""" + + import os ++import imp + import sys + + from distutils.core import Command +@@ -164,9 +165,11 @@ + if ext != PYTHON_SOURCE_EXTENSION: + continue + if self.compile: +- bytecode_files.append(py_file + "c") ++ bytecode_files.append(imp.cache_from_source( ++ py_file, debug_override=True)) + if self.optimize > 0: +- bytecode_files.append(py_file + "o") ++ bytecode_files.append(imp.cache_from_source( ++ py_file, debug_override=False)) + + return bytecode_files + +diff -r 137e45f15c0b Lib/distutils/command/sdist.py +--- a/Lib/distutils/command/sdist.py ++++ b/Lib/distutils/command/sdist.py +@@ -306,7 +306,10 @@ + + try: + self.filelist.process_template_line(line) +- except DistutilsTemplateError as msg: ++ # the call above can raise a DistutilsTemplateError for ++ # malformed lines, or a ValueError from the lower-level ++ # convert_path function ++ except (DistutilsTemplateError, ValueError) as msg: + self.warn("%s, line %d: %s" % (template.filename, + template.current_line, + msg)) +diff -r 137e45f15c0b Lib/distutils/dist.py +--- a/Lib/distutils/dist.py ++++ b/Lib/distutils/dist.py +@@ -537,7 +537,7 @@ + for (help_option, short, desc, func) in cmd_class.help_options: + if hasattr(opts, parser.get_attr_name(help_option)): + help_option_found=1 +- if hasattr(func, '__call__'): ++ if callable(func): + func() + else: + raise DistutilsClassError( +@@ -1010,17 +1010,16 @@ + def write_pkg_info(self, base_dir): + """Write the PKG-INFO file into the release tree. + """ +- pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w') +- try: ++ with open(os.path.join(base_dir, 'PKG-INFO'), 'w', ++ encoding='UTF-8') as pkg_info: + self.write_pkg_file(pkg_info) +- finally: +- pkg_info.close() + + def write_pkg_file(self, file): + """Write the PKG-INFO format data to a file object. + """ + version = '1.0' +- if self.provides or self.requires or self.obsoletes: ++ if (self.provides or self.requires or self.obsoletes or ++ self.classifiers or self.download_url): + version = '1.1' + + file.write('Metadata-Version: %s\n' % version) +diff -r 137e45f15c0b Lib/distutils/filelist.py +--- a/Lib/distutils/filelist.py ++++ b/Lib/distutils/filelist.py +@@ -313,7 +313,10 @@ + # ditch end of pattern character + empty_pattern = glob_to_re('') + prefix_re = (glob_to_re(prefix))[:-len(empty_pattern)] +- pattern_re = "^" + os.path.join(prefix_re, ".*" + pattern_re) ++ # match both path separators, as in Postel's principle ++ sep_pat = "[" + re.escape(os.path.sep + os.path.altsep ++ if os.path.altsep else os.path.sep) + "]" ++ pattern_re = "^" + sep_pat.join([prefix_re, ".*" + pattern_re]) + else: # no prefix -- respect anchor flag + if anchor: + pattern_re = "^" + pattern_re +diff -r 137e45f15c0b Lib/distutils/msvc9compiler.py +--- a/Lib/distutils/msvc9compiler.py ++++ b/Lib/distutils/msvc9compiler.py +@@ -627,15 +627,7 @@ + self.library_filename(dll_name)) + ld_args.append ('/IMPLIB:' + implib_file) + +- # Embedded manifests are recommended - see MSDN article titled +- # "How to: Embed a Manifest Inside a C/C++ Application" +- # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx) +- # Ask the linker to generate the manifest in the temp dir, so +- # we can embed it later. +- temp_manifest = os.path.join( +- build_temp, +- os.path.basename(output_filename) + ".manifest") +- ld_args.append('/MANIFESTFILE:' + temp_manifest) ++ self.manifest_setup_ldargs(output_filename, build_temp, ld_args) + + if extra_preargs: + ld_args[:0] = extra_preargs +@@ -653,21 +645,54 @@ + # will still consider the DLL up-to-date, but it will not have a + # manifest. Maybe we should link to a temp file? OTOH, that + # implies a build environment error that shouldn't go undetected. +- if target_desc == CCompiler.EXECUTABLE: +- mfid = 1 +- else: +- mfid = 2 +- # Remove references to the Visual C runtime +- self._remove_visual_c_ref(temp_manifest) +- out_arg = '-outputresource:%s;%s' % (output_filename, mfid) +- try: +- self.spawn(['mt.exe', '-nologo', '-manifest', +- temp_manifest, out_arg]) +- except DistutilsExecError as msg: +- raise LinkError(msg) ++ mfinfo = self.manifest_get_embed_info(target_desc, ld_args) ++ if mfinfo is not None: ++ mffilename, mfid = mfinfo ++ out_arg = '-outputresource:%s;%s' % (output_filename, mfid) ++ try: ++ self.spawn(['mt.exe', '-nologo', '-manifest', ++ mffilename, out_arg]) ++ except DistutilsExecError as msg: ++ raise LinkError(msg) + else: + log.debug("skipping %s (up-to-date)", output_filename) + ++ def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): ++ # If we need a manifest at all, an embedded manifest is recommended. ++ # See MSDN article titled ++ # "How to: Embed a Manifest Inside a C/C++ Application" ++ # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx) ++ # Ask the linker to generate the manifest in the temp dir, so ++ # we can check it, and possibly embed it, later. ++ temp_manifest = os.path.join( ++ build_temp, ++ os.path.basename(output_filename) + ".manifest") ++ ld_args.append('/MANIFESTFILE:' + temp_manifest) ++ ++ def manifest_get_embed_info(self, target_desc, ld_args): ++ # If a manifest should be embedded, return a tuple of ++ # (manifest_filename, resource_id). Returns None if no manifest ++ # should be embedded. See http://bugs.python.org/issue7833 for why ++ # we want to avoid any manifest for extension modules if we can) ++ for arg in ld_args: ++ if arg.startswith("/MANIFESTFILE:"): ++ temp_manifest = arg.split(":", 1)[1] ++ break ++ else: ++ # no /MANIFESTFILE so nothing to do. ++ return None ++ if target_desc == CCompiler.EXECUTABLE: ++ # by default, executables always get the manifest with the ++ # CRT referenced. ++ mfid = 1 ++ else: ++ # Extension modules try and avoid any manifest if possible. ++ mfid = 2 ++ temp_manifest = self._remove_visual_c_ref(temp_manifest) ++ if temp_manifest is None: ++ return None ++ return temp_manifest, mfid ++ + def _remove_visual_c_ref(self, manifest_file): + try: + # Remove references to the Visual C runtime, so they will +@@ -676,6 +701,8 @@ + # runtimes are not in WinSxS folder, but in Python's own + # folder), the runtimes do not need to be in every folder + # with .pyd's. ++ # Returns either the filename of the modified manifest or ++ # None if no manifest should be embedded. + manifest_f = open(manifest_file) + try: + manifest_buf = manifest_f.read() +@@ -688,9 +715,18 @@ + manifest_buf = re.sub(pattern, "", manifest_buf) + pattern = "\s*" + manifest_buf = re.sub(pattern, "", manifest_buf) ++ # Now see if any other assemblies are referenced - if not, we ++ # don't want a manifest embedded. ++ pattern = re.compile( ++ r"""|)""", re.DOTALL) ++ if re.search(pattern, manifest_buf) is None: ++ return None ++ + manifest_f = open(manifest_file, 'w') + try: + manifest_f.write(manifest_buf) ++ return manifest_file + finally: + manifest_f.close() + except IOError: +diff -r 137e45f15c0b Lib/distutils/sysconfig.py +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -218,7 +218,7 @@ + """Return full pathname of installed Makefile from the Python build.""" + if python_build: + return os.path.join(os.path.dirname(sys.executable), "Makefile") +- lib_dir = get_python_lib(plat_specific=1, standard_lib=1) ++ lib_dir = get_python_lib(plat_specific=0, standard_lib=1) + config_file = 'config-{}{}'.format(get_python_version(), build_flags) + return os.path.join(lib_dir, config_file, 'Makefile') + +diff -r 137e45f15c0b Lib/distutils/tests/support.py +--- a/Lib/distutils/tests/support.py ++++ b/Lib/distutils/tests/support.py +@@ -141,9 +141,9 @@ + + Example use: + +- def test_compile(self): +- copy_xxmodule_c(self.tmpdir) +- self.assertIn('xxmodule.c', os.listdir(self.tmpdir) ++ def test_compile(self): ++ copy_xxmodule_c(self.tmpdir) ++ self.assertIn('xxmodule.c', os.listdir(self.tmpdir)) + + If the source file can be found, it will be copied to *directory*. If not, + the test will be skipped. Errors during copy are not caught. +@@ -175,10 +175,9 @@ + def fixup_build_ext(cmd): + """Function needed to make build_ext tests pass. + +- When Python was build with --enable-shared on Unix, -L. is not good +- enough to find the libpython.so. This is because regrtest runs +- it under a tempdir, not in the top level where the .so lives. By the +- time we've gotten here, Python's already been chdir'd to the tempdir. ++ When Python was built with --enable-shared on Unix, -L. is not enough to ++ find libpython.so, because regrtest runs in a tempdir, not in the ++ source directory where the .so lives. + + When Python was built with in debug mode on Windows, build_ext commands + need their debug attribute set, and it is not done automatically for +diff -r 137e45f15c0b Lib/distutils/tests/test_bdist_dumb.py +--- a/Lib/distutils/tests/test_bdist_dumb.py ++++ b/Lib/distutils/tests/test_bdist_dumb.py +@@ -1,8 +1,10 @@ + """Tests for distutils.command.bdist_dumb.""" + ++import os ++import imp ++import sys ++import zipfile + import unittest +-import sys +-import os + from test.support import run_unittest + + from distutils.core import Distribution +@@ -72,15 +74,24 @@ + + # see what we have + dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) +- base = "%s.%s" % (dist.get_fullname(), cmd.plat_name) ++ base = "%s.%s.zip" % (dist.get_fullname(), cmd.plat_name) + if os.name == 'os2': + base = base.replace(':', '-') + +- wanted = ['%s.zip' % base] +- self.assertEqual(dist_created, wanted) ++ self.assertEqual(dist_created, [base]) + + # now let's check what we have in the zip file +- # XXX to be done ++ fp = zipfile.ZipFile(os.path.join('dist', base)) ++ try: ++ contents = fp.namelist() ++ finally: ++ 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.%s.pyc' % imp.get_tag(), ++ 'foo.py'] ++ self.assertEqual(contents, sorted(wanted)) + + def test_suite(): + return unittest.makeSuite(BuildDumbTestCase) +diff -r 137e45f15c0b Lib/distutils/tests/test_build_py.py +--- a/Lib/distutils/tests/test_build_py.py ++++ b/Lib/distutils/tests/test_build_py.py +@@ -2,7 +2,7 @@ + + import os + import sys +-import io ++import imp + import unittest + + from distutils.command.build_py import build_py +@@ -53,23 +53,20 @@ + # This makes sure the list of outputs includes byte-compiled + # files for Python modules but not for package data files + # (there shouldn't *be* byte-code files for those!). +- # + self.assertEqual(len(cmd.get_outputs()), 3) + pkgdest = os.path.join(destination, "pkg") + files = os.listdir(pkgdest) ++ pycache_dir = os.path.join(pkgdest, "__pycache__") + self.assertIn("__init__.py", files) + self.assertIn("README.txt", files) +- # XXX even with -O, distutils writes pyc, not pyo; bug? + if sys.dont_write_bytecode: +- self.assertNotIn("__init__.pyc", files) ++ self.assertFalse(os.path.exists(pycache_dir)) + else: +- self.assertIn("__init__.pyc", files) ++ pyc_files = os.listdir(pycache_dir) ++ self.assertIn("__init__.%s.pyc" % imp.get_tag(), pyc_files) + + def test_empty_package_dir(self): +- # See SF 1668596/1720897. +- cwd = os.getcwd() +- +- # create the distribution files. ++ # See bugs #1668596/#1720897 + sources = self.mkdtemp() + open(os.path.join(sources, "__init__.py"), "w").close() + +@@ -78,30 +75,55 @@ + open(os.path.join(testdir, "testfile"), "w").close() + + os.chdir(sources) +- old_stdout = sys.stdout +- sys.stdout = io.StringIO() ++ dist = Distribution({"packages": ["pkg"], ++ "package_dir": {"pkg": ""}, ++ "package_data": {"pkg": ["doc/*"]}}) ++ # script_name need not exist, it just need to be initialized ++ dist.script_name = os.path.join(sources, "setup.py") ++ dist.script_args = ["build"] ++ dist.parse_command_line() + + try: +- dist = Distribution({"packages": ["pkg"], +- "package_dir": {"pkg": ""}, +- "package_data": {"pkg": ["doc/*"]}}) +- # script_name need not exist, it just need to be initialized +- dist.script_name = os.path.join(sources, "setup.py") +- dist.script_args = ["build"] +- dist.parse_command_line() ++ dist.run_commands() ++ except DistutilsFileError: ++ self.fail("failed package_data test when package_dir is ''") + +- try: +- dist.run_commands() +- except DistutilsFileError: +- self.fail("failed package_data test when package_dir is ''") +- finally: +- # Restore state. +- os.chdir(cwd) +- sys.stdout = old_stdout ++ @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') ++ def test_byte_compile(self): ++ project_dir, dist = self.create_dist(py_modules=['boiledeggs']) ++ os.chdir(project_dir) ++ self.write_file('boiledeggs.py', 'import antigravity') ++ cmd = build_py(dist) ++ cmd.compile = 1 ++ cmd.build_lib = 'here' ++ cmd.finalize_options() ++ cmd.run() ++ ++ found = os.listdir(cmd.build_lib) ++ self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) ++ found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) ++ self.assertEqual(found, ['boiledeggs.%s.pyc' % imp.get_tag()]) ++ ++ @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') ++ def test_byte_compile_optimized(self): ++ project_dir, dist = self.create_dist(py_modules=['boiledeggs']) ++ os.chdir(project_dir) ++ self.write_file('boiledeggs.py', 'import antigravity') ++ cmd = build_py(dist) ++ cmd.compile = 0 ++ cmd.optimize = 1 ++ cmd.build_lib = 'here' ++ cmd.finalize_options() ++ cmd.run() ++ ++ found = os.listdir(cmd.build_lib) ++ self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) ++ found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) ++ self.assertEqual(sorted(found), ['boiledeggs.%s.pyo' % imp.get_tag()]) + + def test_dont_write_bytecode(self): + # makes sure byte_compile is not used +- pkg_dir, dist = self.create_dist() ++ dist = self.create_dist()[1] + cmd = build_py(dist) + cmd.compile = 1 + cmd.optimize = 1 +@@ -115,6 +137,7 @@ + + self.assertIn('byte-compiling is disabled', self.logs[0][1]) + ++ + def test_suite(): + return unittest.makeSuite(BuildPyTestCase) + +diff -r 137e45f15c0b Lib/distutils/tests/test_check.py +--- a/Lib/distutils/tests/test_check.py ++++ b/Lib/distutils/tests/test_check.py +@@ -46,6 +46,15 @@ + cmd = self._run(metadata, strict=1) + self.assertEqual(cmd._warnings, 0) + ++ # now a test with non-ASCII characters ++ metadata = {'url': 'xxx', 'author': '\u00c9ric', ++ 'author_email': 'xxx', 'name': 'xxx', ++ 'version': 'xxx', ++ 'description': 'Something about esszet \u00df', ++ 'long_description': 'More things about esszet \u00df'} ++ cmd = self._run(metadata) ++ self.assertEqual(cmd._warnings, 0) ++ + def test_check_document(self): + if not HAS_DOCUTILS: # won't test without docutils + return +@@ -80,8 +89,8 @@ + self.assertRaises(DistutilsSetupError, self._run, metadata, + **{'strict': 1, 'restructuredtext': 1}) + +- # and non-broken rest +- metadata['long_description'] = 'title\n=====\n\ntest' ++ # and non-broken rest, including a non-ASCII character to test #12114 ++ metadata['long_description'] = 'title\n=====\n\ntest \u00df' + cmd = self._run(metadata, strict=1, restructuredtext=1) + self.assertEqual(cmd._warnings, 0) + +diff -r 137e45f15c0b Lib/distutils/tests/test_config_cmd.py +--- a/Lib/distutils/tests/test_config_cmd.py ++++ b/Lib/distutils/tests/test_config_cmd.py +@@ -44,10 +44,10 @@ + cmd = config(dist) + + # simple pattern searches +- match = cmd.search_cpp(pattern='xxx', body='// xxx') ++ match = cmd.search_cpp(pattern='xxx', body='/* xxx */') + self.assertEqual(match, 0) + +- match = cmd.search_cpp(pattern='_configtest', body='// xxx') ++ match = cmd.search_cpp(pattern='_configtest', body='/* xxx */') + self.assertEqual(match, 1) + + def test_finalize_options(self): +diff -r 137e45f15c0b Lib/distutils/tests/test_dist.py +--- a/Lib/distutils/tests/test_dist.py ++++ b/Lib/distutils/tests/test_dist.py +@@ -74,7 +74,7 @@ + self.assertEqual(d.get_command_packages(), + ["distutils.command", "foo.bar", "distutils.tests"]) + cmd = d.get_command_obj("test_dist") +- self.assertTrue(isinstance(cmd, test_dist)) ++ self.assertIsInstance(cmd, test_dist) + self.assertEqual(cmd.sample_option, "sometext") + + def test_command_packages_configfile(self): +@@ -106,28 +106,23 @@ + def test_empty_options(self): + # an empty options dictionary should not stay in the + # list of attributes +- klass = Distribution + + # catching warnings + warns = [] ++ + def _warn(msg): + warns.append(msg) + +- old_warn = warnings.warn ++ self.addCleanup(setattr, warnings, 'warn', warnings.warn) + warnings.warn = _warn +- try: +- dist = klass(attrs={'author': 'xxx', +- 'name': 'xxx', +- 'version': 'xxx', +- 'url': 'xxxx', +- 'options': {}}) +- finally: +- warnings.warn = old_warn ++ dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx', ++ 'version': 'xxx', 'url': 'xxxx', ++ 'options': {}}) + + self.assertEqual(len(warns), 0) ++ self.assertNotIn('options', dir(dist)) + + def test_finalize_options(self): +- + attrs = {'keywords': 'one,two', + 'platforms': 'one,two'} + +@@ -150,7 +145,6 @@ + cmds = dist.get_command_packages() + self.assertEqual(cmds, ['distutils.command', 'one', 'two']) + +- + def test_announce(self): + # make sure the level is known + dist = Distribution() +@@ -158,6 +152,7 @@ + kwargs = {'level': 'ok2'} + self.assertRaises(ValueError, dist.announce, args, kwargs) + ++ + class MetadataTestCase(support.TempdirManager, support.EnvironGuard, + unittest.TestCase): + +@@ -170,15 +165,20 @@ + sys.argv[:] = self.argv[1] + super(MetadataTestCase, self).tearDown() + ++ def format_metadata(self, dist): ++ sio = io.StringIO() ++ dist.metadata.write_pkg_file(sio) ++ return sio.getvalue() ++ + def test_simple_metadata(self): + attrs = {"name": "package", + "version": "1.0"} + dist = Distribution(attrs) + meta = self.format_metadata(dist) +- self.assertTrue("Metadata-Version: 1.0" in meta) +- self.assertTrue("provides:" not in meta.lower()) +- self.assertTrue("requires:" not in meta.lower()) +- self.assertTrue("obsoletes:" not in meta.lower()) ++ self.assertIn("Metadata-Version: 1.0", meta) ++ self.assertNotIn("provides:", meta.lower()) ++ self.assertNotIn("requires:", meta.lower()) ++ self.assertNotIn("obsoletes:", meta.lower()) + + def test_provides(self): + attrs = {"name": "package", +@@ -190,9 +190,9 @@ + self.assertEqual(dist.get_provides(), + ["package", "package.sub"]) + meta = self.format_metadata(dist) +- self.assertTrue("Metadata-Version: 1.1" in meta) +- self.assertTrue("requires:" not in meta.lower()) +- self.assertTrue("obsoletes:" not in meta.lower()) ++ self.assertIn("Metadata-Version: 1.1", meta) ++ self.assertNotIn("requires:", meta.lower()) ++ self.assertNotIn("obsoletes:", meta.lower()) + + def test_provides_illegal(self): + self.assertRaises(ValueError, Distribution, +@@ -210,11 +210,11 @@ + self.assertEqual(dist.get_requires(), + ["other", "another (==1.0)"]) + meta = self.format_metadata(dist) +- self.assertTrue("Metadata-Version: 1.1" in meta) +- self.assertTrue("provides:" not in meta.lower()) +- self.assertTrue("Requires: other" in meta) +- self.assertTrue("Requires: another (==1.0)" in meta) +- self.assertTrue("obsoletes:" not in meta.lower()) ++ self.assertIn("Metadata-Version: 1.1", meta) ++ self.assertNotIn("provides:", meta.lower()) ++ self.assertIn("Requires: other", meta) ++ self.assertIn("Requires: another (==1.0)", meta) ++ self.assertNotIn("obsoletes:", meta.lower()) + + def test_requires_illegal(self): + self.assertRaises(ValueError, Distribution, +@@ -232,11 +232,11 @@ + self.assertEqual(dist.get_obsoletes(), + ["other", "another (<1.0)"]) + meta = self.format_metadata(dist) +- self.assertTrue("Metadata-Version: 1.1" in meta) +- self.assertTrue("provides:" not in meta.lower()) +- self.assertTrue("requires:" not in meta.lower()) +- self.assertTrue("Obsoletes: other" in meta) +- self.assertTrue("Obsoletes: another (<1.0)" in meta) ++ self.assertIn("Metadata-Version: 1.1", meta) ++ self.assertNotIn("provides:", meta.lower()) ++ self.assertNotIn("requires:", meta.lower()) ++ self.assertIn("Obsoletes: other", meta) ++ self.assertIn("Obsoletes: another (<1.0)", meta) + + def test_obsoletes_illegal(self): + self.assertRaises(ValueError, Distribution, +@@ -244,10 +244,34 @@ + "version": "1.0", + "obsoletes": ["my.pkg (splat)"]}) + +- def format_metadata(self, dist): +- sio = io.StringIO() +- dist.metadata.write_pkg_file(sio) +- return sio.getvalue() ++ def test_classifier(self): ++ attrs = {'name': 'Boa', 'version': '3.0', ++ 'classifiers': ['Programming Language :: Python :: 3']} ++ dist = Distribution(attrs) ++ meta = self.format_metadata(dist) ++ self.assertIn('Metadata-Version: 1.1', meta) ++ ++ def test_download_url(self): ++ attrs = {'name': 'Boa', 'version': '3.0', ++ 'download_url': 'http://example.org/boa'} ++ dist = Distribution(attrs) ++ meta = self.format_metadata(dist) ++ self.assertIn('Metadata-Version: 1.1', meta) ++ ++ def test_long_description(self): ++ long_desc = textwrap.dedent("""\ ++ example:: ++ We start here ++ and continue here ++ and end here.""") ++ attrs = {"name": "package", ++ "version": "1.0", ++ "long_description": long_desc} ++ ++ dist = Distribution(attrs) ++ meta = self.format_metadata(dist) ++ meta = meta.replace('\n' + 8 * ' ', '\n') ++ self.assertIn(long_desc, meta) + + def test_custom_pydistutils(self): + # fixes #2166 +@@ -272,14 +296,14 @@ + if sys.platform in ('linux', 'darwin'): + os.environ['HOME'] = temp_dir + files = dist.find_config_files() +- self.assertTrue(user_filename in files) ++ self.assertIn(user_filename, files) + + # win32-style + if sys.platform == 'win32': + # home drive should be found + os.environ['HOME'] = temp_dir + files = dist.find_config_files() +- self.assertTrue(user_filename in files, ++ self.assertIn(user_filename, files, + '%r not found in %r' % (user_filename, files)) + finally: + os.remove(user_filename) +@@ -301,22 +325,8 @@ + + output = [line for line in s.getvalue().split('\n') + if line.strip() != ''] +- self.assertTrue(len(output) > 0) ++ self.assertTrue(output) + +- def test_long_description(self): +- long_desc = textwrap.dedent("""\ +- example:: +- We start here +- and continue here +- and end here.""") +- attrs = {"name": "package", +- "version": "1.0", +- "long_description": long_desc} +- +- dist = Distribution(attrs) +- meta = self.format_metadata(dist) +- meta = meta.replace('\n' + 8 * ' ', '\n') +- self.assertTrue(long_desc in meta) + + def test_suite(): + suite = unittest.TestSuite() +diff -r 137e45f15c0b Lib/distutils/tests/test_filelist.py +--- a/Lib/distutils/tests/test_filelist.py ++++ b/Lib/distutils/tests/test_filelist.py +@@ -1,11 +1,25 @@ + """Tests for distutils.filelist.""" ++import re + import unittest ++from distutils import debug ++from distutils.log import WARN ++from distutils.errors import DistutilsTemplateError ++from distutils.filelist import glob_to_re, translate_pattern, FileList + +-from distutils.filelist import glob_to_re, FileList + from test.support import captured_stdout, run_unittest +-from distutils import debug ++from distutils.tests import support + +-class FileListTestCase(unittest.TestCase): ++ ++class FileListTestCase(support.LoggingSilencer, ++ unittest.TestCase): ++ ++ def assertNoWarnings(self): ++ self.assertEqual(self.get_logs(WARN), []) ++ self.clear_logs() ++ ++ def assertWarnings(self): ++ self.assertGreater(len(self.get_logs(WARN)), 0) ++ self.clear_logs() + + def test_glob_to_re(self): + # simple cases +@@ -23,18 +37,191 @@ + file_list = FileList() + with captured_stdout() as stdout: + file_list.debug_print('xxx') +- stdout.seek(0) +- self.assertEqual(stdout.read(), '') ++ self.assertEqual(stdout.getvalue(), '') + + debug.DEBUG = True + try: + with captured_stdout() as stdout: + file_list.debug_print('xxx') +- stdout.seek(0) +- self.assertEqual(stdout.read(), 'xxx\n') ++ self.assertEqual(stdout.getvalue(), 'xxx\n') + finally: + debug.DEBUG = False + ++ def test_set_allfiles(self): ++ file_list = FileList() ++ files = ['a', 'b', 'c'] ++ file_list.set_allfiles(files) ++ self.assertEqual(file_list.allfiles, files) ++ ++ def test_remove_duplicates(self): ++ file_list = FileList() ++ file_list.files = ['a', 'b', 'a', 'g', 'c', 'g'] ++ # files must be sorted beforehand (sdist does it) ++ file_list.sort() ++ file_list.remove_duplicates() ++ self.assertEqual(file_list.files, ['a', 'b', 'c', 'g']) ++ ++ def test_translate_pattern(self): ++ # not regex ++ self.assertTrue(hasattr( ++ translate_pattern('a', anchor=True, is_regex=False), ++ 'search')) ++ ++ # is a regex ++ regex = re.compile('a') ++ self.assertEqual( ++ translate_pattern(regex, anchor=True, is_regex=True), ++ regex) ++ ++ # plain string flagged as regex ++ self.assertTrue(hasattr( ++ translate_pattern('a', anchor=True, is_regex=True), ++ 'search')) ++ ++ # glob support ++ self.assertTrue(translate_pattern( ++ '*.py', anchor=True, is_regex=False).search('filelist.py')) ++ ++ def test_exclude_pattern(self): ++ # return False if no match ++ file_list = FileList() ++ self.assertFalse(file_list.exclude_pattern('*.py')) ++ ++ # return True if files match ++ file_list = FileList() ++ file_list.files = ['a.py', 'b.py'] ++ self.assertTrue(file_list.exclude_pattern('*.py')) ++ ++ # test excludes ++ file_list = FileList() ++ file_list.files = ['a.py', 'a.txt'] ++ file_list.exclude_pattern('*.py') ++ self.assertEqual(file_list.files, ['a.txt']) ++ ++ def test_include_pattern(self): ++ # return False if no match ++ file_list = FileList() ++ file_list.set_allfiles([]) ++ self.assertFalse(file_list.include_pattern('*.py')) ++ ++ # return True if files match ++ file_list = FileList() ++ file_list.set_allfiles(['a.py', 'b.txt']) ++ self.assertTrue(file_list.include_pattern('*.py')) ++ ++ # test * matches all files ++ file_list = FileList() ++ self.assertIsNone(file_list.allfiles) ++ file_list.set_allfiles(['a.py', 'b.txt']) ++ file_list.include_pattern('*') ++ self.assertEqual(file_list.allfiles, ['a.py', 'b.txt']) ++ ++ def test_process_template(self): ++ # invalid lines ++ file_list = FileList() ++ for action in ('include', 'exclude', 'global-include', ++ 'global-exclude', 'recursive-include', ++ 'recursive-exclude', 'graft', 'prune', 'blarg'): ++ self.assertRaises(DistutilsTemplateError, ++ file_list.process_template_line, action) ++ ++ # include ++ file_list = FileList() ++ file_list.set_allfiles(['a.py', 'b.txt', 'd/c.py']) ++ ++ file_list.process_template_line('include *.py') ++ self.assertEqual(file_list.files, ['a.py']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('include *.rb') ++ self.assertEqual(file_list.files, ['a.py']) ++ self.assertWarnings() ++ ++ # exclude ++ file_list = FileList() ++ file_list.files = ['a.py', 'b.txt', 'd/c.py'] ++ ++ file_list.process_template_line('exclude *.py') ++ self.assertEqual(file_list.files, ['b.txt', 'd/c.py']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('exclude *.rb') ++ self.assertEqual(file_list.files, ['b.txt', 'd/c.py']) ++ self.assertWarnings() ++ ++ # global-include ++ file_list = FileList() ++ file_list.set_allfiles(['a.py', 'b.txt', 'd/c.py']) ++ ++ file_list.process_template_line('global-include *.py') ++ self.assertEqual(file_list.files, ['a.py', 'd/c.py']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('global-include *.rb') ++ self.assertEqual(file_list.files, ['a.py', 'd/c.py']) ++ self.assertWarnings() ++ ++ # global-exclude ++ file_list = FileList() ++ file_list.files = ['a.py', 'b.txt', 'd/c.py'] ++ ++ file_list.process_template_line('global-exclude *.py') ++ self.assertEqual(file_list.files, ['b.txt']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('global-exclude *.rb') ++ self.assertEqual(file_list.files, ['b.txt']) ++ self.assertWarnings() ++ ++ # recursive-include ++ file_list = FileList() ++ file_list.set_allfiles(['a.py', 'd/b.py', 'd/c.txt', 'd/d/e.py']) ++ ++ file_list.process_template_line('recursive-include d *.py') ++ self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('recursive-include e *.py') ++ self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py']) ++ self.assertWarnings() ++ ++ # recursive-exclude ++ file_list = FileList() ++ file_list.files = ['a.py', 'd/b.py', 'd/c.txt', 'd/d/e.py'] ++ ++ file_list.process_template_line('recursive-exclude d *.py') ++ self.assertEqual(file_list.files, ['a.py', 'd/c.txt']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('recursive-exclude e *.py') ++ self.assertEqual(file_list.files, ['a.py', 'd/c.txt']) ++ self.assertWarnings() ++ ++ # graft ++ file_list = FileList() ++ file_list.set_allfiles(['a.py', 'd/b.py', 'd/d/e.py', 'f/f.py']) ++ ++ file_list.process_template_line('graft d') ++ self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('graft e') ++ self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py']) ++ self.assertWarnings() ++ ++ # prune ++ file_list = FileList() ++ file_list.files = ['a.py', 'd/b.py', 'd/d/e.py', 'f/f.py'] ++ ++ file_list.process_template_line('prune d') ++ self.assertEqual(file_list.files, ['a.py', 'f/f.py']) ++ self.assertNoWarnings() ++ ++ file_list.process_template_line('prune e') ++ self.assertEqual(file_list.files, ['a.py', 'f/f.py']) ++ self.assertWarnings() ++ ++ + def test_suite(): + return unittest.makeSuite(FileListTestCase) + +diff -r 137e45f15c0b Lib/distutils/tests/test_install.py +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -1,6 +1,7 @@ + """Tests for distutils.command.install.""" + + import os ++import imp + import sys + import unittest + import site +@@ -20,9 +21,8 @@ + + + def _make_ext_name(modname): +- if os.name == 'nt': +- if sys.executable.endswith('_d.exe'): +- modname += '_d' ++ if os.name == 'nt' and sys.executable.endswith('_d.exe'): ++ modname += '_d' + return modname + sysconfig.get_config_var('SO') + + +@@ -68,10 +68,7 @@ + check_path(cmd.install_data, destination) + + def test_user_site(self): +- # site.USER_SITE was introduced in 2.6 +- if sys.version < '2.6': +- return +- ++ # test install with --user + # preparing the environment for the test + self.old_user_base = site.USER_BASE + self.old_user_site = site.USER_SITE +@@ -88,19 +85,17 @@ + self.old_expand = os.path.expanduser + os.path.expanduser = _expanduser + +- try: +- # this is the actual test +- self._test_user_site() +- finally: ++ def cleanup(): + site.USER_BASE = self.old_user_base + site.USER_SITE = self.old_user_site + install_module.USER_BASE = self.old_user_base + install_module.USER_SITE = self.old_user_site + os.path.expanduser = self.old_expand + +- def _test_user_site(self): ++ self.addCleanup(cleanup) ++ + for key in ('nt_user', 'unix_user', 'os2_home'): +- self.assertTrue(key in INSTALL_SCHEMES) ++ self.assertIn(key, INSTALL_SCHEMES) + + dist = Distribution({'name': 'xx'}) + cmd = install(dist) +@@ -108,14 +103,14 @@ + # making sure the user option is there + options = [name for name, short, lable in + cmd.user_options] +- self.assertTrue('user' in options) ++ self.assertIn('user', options) + + # setting a value + cmd.user = 1 + + # user base and site shouldn't be created yet +- self.assertTrue(not os.path.exists(self.user_base)) +- self.assertTrue(not os.path.exists(self.user_site)) ++ self.assertFalse(os.path.exists(self.user_base)) ++ self.assertFalse(os.path.exists(self.user_site)) + + # let's run finalize + cmd.ensure_finalized() +@@ -124,8 +119,8 @@ + self.assertTrue(os.path.exists(self.user_base)) + self.assertTrue(os.path.exists(self.user_site)) + +- self.assertTrue('userbase' in cmd.config_vars) +- self.assertTrue('usersite' in cmd.config_vars) ++ self.assertIn('userbase', cmd.config_vars) ++ self.assertIn('usersite', cmd.config_vars) + + def test_handle_extra_path(self): + dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) +@@ -178,15 +173,16 @@ + + def test_record(self): + install_dir = self.mkdtemp() +- project_dir, dist = self.create_dist(scripts=['hello']) +- self.addCleanup(os.chdir, os.getcwd()) ++ project_dir, dist = self.create_dist(py_modules=['hello'], ++ scripts=['sayhi']) + os.chdir(project_dir) +- self.write_file('hello', "print('o hai')") ++ self.write_file('hello.py', "def main(): print('o hai')") ++ self.write_file('sayhi', 'from hello import main; main()') + + cmd = install(dist) + dist.command_obj['install'] = cmd + cmd.root = install_dir +- cmd.record = os.path.join(project_dir, 'RECORD') ++ cmd.record = os.path.join(project_dir, 'filelist') + cmd.ensure_finalized() + cmd.run() + +@@ -197,7 +193,7 @@ + f.close() + + found = [os.path.basename(line) for line in content.splitlines()] +- expected = ['hello', ++ expected = ['hello.py', 'hello.%s.pyc' % imp.get_tag(), 'sayhi', + 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] + self.assertEqual(found, expected) + +@@ -205,7 +201,6 @@ + install_dir = self.mkdtemp() + project_dir, dist = self.create_dist(ext_modules=[ + Extension('xx', ['xxmodule.c'])]) +- self.addCleanup(os.chdir, os.getcwd()) + os.chdir(project_dir) + support.copy_xxmodule_c(project_dir) + +@@ -217,7 +212,7 @@ + dist.command_obj['install'] = cmd + dist.command_obj['build_ext'] = buildextcmd + cmd.root = install_dir +- cmd.record = os.path.join(project_dir, 'RECORD') ++ cmd.record = os.path.join(project_dir, 'filelist') + cmd.ensure_finalized() + cmd.run() + +@@ -243,6 +238,7 @@ + install_module.DEBUG = False + self.assertTrue(len(self.logs) > old_logs_len) + ++ + def test_suite(): + return unittest.makeSuite(InstallTestCase) + +diff -r 137e45f15c0b Lib/distutils/tests/test_install_lib.py +--- a/Lib/distutils/tests/test_install_lib.py ++++ b/Lib/distutils/tests/test_install_lib.py +@@ -1,6 +1,7 @@ + """Tests for distutils.command.install_data.""" + import sys + import os ++import imp + import unittest + + from distutils.command.install_lib import install_lib +@@ -9,13 +10,14 @@ + from distutils.errors import DistutilsOptionError + from test.support import run_unittest + ++ + class InstallLibTestCase(support.TempdirManager, + support.LoggingSilencer, + support.EnvironGuard, + unittest.TestCase): + + def test_finalize_options(self): +- pkg_dir, dist = self.create_dist() ++ dist = self.create_dist()[1] + cmd = install_lib(dist) + + cmd.finalize_options() +@@ -32,56 +34,64 @@ + cmd.finalize_options() + self.assertEqual(cmd.optimize, 2) + +- @unittest.skipUnless(not sys.dont_write_bytecode, +- 'byte-compile not supported') ++ @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') + def test_byte_compile(self): +- pkg_dir, dist = self.create_dist() ++ project_dir, dist = self.create_dist() ++ os.chdir(project_dir) + cmd = install_lib(dist) + cmd.compile = cmd.optimize = 1 + +- f = os.path.join(pkg_dir, 'foo.py') ++ f = os.path.join(project_dir, 'foo.py') + self.write_file(f, '# python file') + cmd.byte_compile([f]) +- self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc'))) +- self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo'))) ++ pyc_file = imp.cache_from_source('foo.py', debug_override=True) ++ pyo_file = imp.cache_from_source('foo.py', debug_override=False) ++ self.assertTrue(os.path.exists(pyc_file)) ++ self.assertTrue(os.path.exists(pyo_file)) + + def test_get_outputs(self): +- pkg_dir, dist = self.create_dist() ++ project_dir, dist = self.create_dist() ++ os.chdir(project_dir) ++ os.mkdir('spam') + cmd = install_lib(dist) + + # setting up a dist environment + cmd.compile = cmd.optimize = 1 +- cmd.install_dir = pkg_dir +- f = os.path.join(pkg_dir, 'foo.py') +- self.write_file(f, '# python file') +- cmd.distribution.py_modules = [pkg_dir] ++ cmd.install_dir = self.mkdtemp() ++ f = os.path.join(project_dir, 'spam', '__init__.py') ++ self.write_file(f, '# python package') + cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] +- cmd.distribution.packages = [pkg_dir] ++ cmd.distribution.packages = ['spam'] + cmd.distribution.script_name = 'setup.py' + +- # get_output should return 4 elements +- self.assertTrue(len(cmd.get_outputs()) >= 2) ++ # get_outputs should return 4 elements: spam/__init__.py, .pyc and ++ # .pyo, foo.import-tag-abiflags.so / foo.pyd ++ outputs = cmd.get_outputs() ++ self.assertEqual(len(outputs), 4, outputs) + + def test_get_inputs(self): +- pkg_dir, dist = self.create_dist() ++ project_dir, dist = self.create_dist() ++ os.chdir(project_dir) ++ os.mkdir('spam') + cmd = install_lib(dist) + + # setting up a dist environment + cmd.compile = cmd.optimize = 1 +- cmd.install_dir = pkg_dir +- f = os.path.join(pkg_dir, 'foo.py') +- self.write_file(f, '# python file') +- cmd.distribution.py_modules = [pkg_dir] ++ cmd.install_dir = self.mkdtemp() ++ f = os.path.join(project_dir, 'spam', '__init__.py') ++ self.write_file(f, '# python package') + cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] +- cmd.distribution.packages = [pkg_dir] ++ cmd.distribution.packages = ['spam'] + cmd.distribution.script_name = 'setup.py' + +- # get_input should return 2 elements +- self.assertEqual(len(cmd.get_inputs()), 2) ++ # get_inputs should return 2 elements: spam/__init__.py and ++ # foo.import-tag-abiflags.so / foo.pyd ++ inputs = cmd.get_inputs() ++ self.assertEqual(len(inputs), 2, inputs) + + def test_dont_write_bytecode(self): + # makes sure byte_compile is not used +- pkg_dir, dist = self.create_dist() ++ dist = self.create_dist()[1] + cmd = install_lib(dist) + cmd.compile = 1 + cmd.optimize = 1 +@@ -95,6 +105,7 @@ + + self.assertTrue('byte-compiling is disabled' in self.logs[0][1]) + ++ + def test_suite(): + return unittest.makeSuite(InstallLibTestCase) + +diff -r 137e45f15c0b Lib/distutils/tests/test_msvc9compiler.py +--- a/Lib/distutils/tests/test_msvc9compiler.py ++++ b/Lib/distutils/tests/test_msvc9compiler.py +@@ -7,7 +7,36 @@ + from distutils.tests import support + from test.support import run_unittest + +-_MANIFEST = """\ ++# A manifest with the only assembly reference being the msvcrt assembly, so ++# should have the assembly completely stripped. Note that although the ++# assembly has a reference the assembly is removed - that is ++# currently a "feature", not a bug :) ++_MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++""" ++ ++# A manifest with references to assemblies other than msvcrt. When processed, ++# this assembly should be returned with just the msvcrt part removed. ++_MANIFEST_WITH_MULTIPLE_REFERENCES = """\ + + +@@ -115,7 +144,7 @@ + manifest = os.path.join(tempdir, 'manifest') + f = open(manifest, 'w') + try: +- f.write(_MANIFEST) ++ f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES) + finally: + f.close() + +@@ -133,6 +162,20 @@ + # makes sure the manifest was properly cleaned + self.assertEqual(content, _CLEANED_MANIFEST) + ++ def test_remove_entire_manifest(self): ++ from distutils.msvc9compiler import MSVCCompiler ++ tempdir = self.mkdtemp() ++ manifest = os.path.join(tempdir, 'manifest') ++ f = open(manifest, 'w') ++ try: ++ f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE) ++ finally: ++ f.close() ++ ++ compiler = MSVCCompiler() ++ got = compiler._remove_visual_c_ref(manifest) ++ self.assertIs(got, None) ++ + + def test_suite(): + return unittest.makeSuite(msvc9compilerTestCase) +diff -r 137e45f15c0b Lib/distutils/tests/test_register.py +--- a/Lib/distutils/tests/test_register.py ++++ b/Lib/distutils/tests/test_register.py +@@ -214,7 +214,7 @@ + + # metadata are OK but long_description is broken + metadata = {'url': 'xxx', 'author': 'xxx', +- 'author_email': 'xxx', ++ 'author_email': 'éxéxé', + 'name': 'xxx', 'version': 'xxx', + 'long_description': 'title\n==\n\ntext'} + +@@ -247,6 +247,24 @@ + finally: + del register_module.input + ++ # and finally a Unicode test (bug #12114) ++ metadata = {'url': 'xxx', 'author': '\u00c9ric', ++ 'author_email': 'xxx', 'name': 'xxx', ++ 'version': 'xxx', ++ 'description': 'Something about esszet \u00df', ++ 'long_description': 'More things about esszet \u00df'} ++ ++ cmd = self._get_cmd(metadata) ++ cmd.ensure_finalized() ++ cmd.strict = 1 ++ inputs = Inputs('1', 'tarek', 'y') ++ register_module.input = inputs.__call__ ++ # let's run the command ++ try: ++ cmd.run() ++ finally: ++ del register_module.input ++ + def test_check_metadata_deprecated(self): + # makes sure make_metadata is deprecated + cmd = self._get_cmd() +diff -r 137e45f15c0b Lib/distutils/tests/test_sdist.py +--- a/Lib/distutils/tests/test_sdist.py ++++ b/Lib/distutils/tests/test_sdist.py +@@ -15,6 +15,7 @@ + from distutils.errors import DistutilsOptionError + from distutils.spawn import find_executable + from distutils.log import WARN ++from distutils.filelist import FileList + from distutils.archive_util import ARCHIVE_FORMATS + + SETUP_PY = """ +@@ -78,9 +79,6 @@ + dist.include_package_data = True + cmd = sdist(dist) + cmd.dist_dir = 'dist' +- def _warn(*args): +- pass +- cmd.warn = _warn + return dist, cmd + + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') +@@ -235,7 +233,8 @@ + # with the `check` subcommand + cmd.ensure_finalized() + cmd.run() +- warnings = self.get_logs(WARN) ++ warnings = [msg for msg in self.get_logs(WARN) if ++ msg.startswith('warning: check:')] + self.assertEqual(len(warnings), 2) + + # trying with a complete set of metadata +@@ -244,7 +243,8 @@ + cmd.ensure_finalized() + cmd.metadata_check = 0 + cmd.run() +- warnings = self.get_logs(WARN) ++ warnings = [msg for msg in self.get_logs(WARN) if ++ msg.startswith('warning: check:')] + self.assertEqual(len(warnings), 0) + + def test_check_metadata_deprecated(self): +@@ -266,7 +266,6 @@ + self.assertEqual(len(output), num_formats) + + def test_finalize_options(self): +- + dist, cmd = self.get_cmd() + cmd.finalize_options() + +@@ -286,6 +285,32 @@ + cmd.formats = 'supazipa' + self.assertRaises(DistutilsOptionError, cmd.finalize_options) + ++ # the following tests make sure there is a nice error message instead ++ # of a traceback when parsing an invalid manifest template ++ ++ def _check_template(self, content): ++ dist, cmd = self.get_cmd() ++ os.chdir(self.tmp_dir) ++ self.write_file('MANIFEST.in', content) ++ cmd.ensure_finalized() ++ cmd.filelist = FileList() ++ cmd.read_template() ++ warnings = self.get_logs(WARN) ++ self.assertEqual(len(warnings), 1) ++ ++ def test_invalid_template_unknown_command(self): ++ self._check_template('taunt knights *') ++ ++ def test_invalid_template_wrong_arguments(self): ++ # this manifest command takes one argument ++ self._check_template('prune') ++ ++ @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only') ++ def test_invalid_template_wrong_path(self): ++ # on Windows, trailing slashes are not allowed ++ # this used to crash instead of raising a warning: #8286 ++ self._check_template('include examples/') ++ + @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') + def test_get_file_list(self): + # make sure MANIFEST is recalculated +diff -r 137e45f15c0b Lib/distutils/util.py +--- a/Lib/distutils/util.py ++++ b/Lib/distutils/util.py +@@ -4,7 +4,11 @@ + one of the other *util.py modules. + """ + +-import sys, os, string, re ++import os ++import re ++import imp ++import sys ++import string + from distutils.errors import DistutilsPlatformError + from distutils.dep_util import newer + from distutils.spawn import spawn +@@ -415,9 +419,9 @@ + verbose=1, dry_run=0, + direct=None): + """Byte-compile a collection of Python source files to either .pyc +- or .pyo files in the same directory. 'py_files' is a list of files +- to compile; any files that don't end in ".py" are silently skipped. +- 'optimize' must be one of the following: ++ or .pyo files in a __pycache__ subdirectory. 'py_files' is a list ++ of files to compile; any files that don't end in ".py" are silently ++ skipped. 'optimize' must be one of the following: + 0 - don't optimize (generate .pyc) + 1 - normal optimization (like "python -O") + 2 - extra optimization (like "python -OO") +@@ -529,7 +533,10 @@ + # Terminology from the py_compile module: + # cfile - byte-compiled file + # dfile - purported source filename (same as 'file' by default) +- cfile = file + (__debug__ and "c" or "o") ++ if optimize >= 0: ++ cfile = imp.cache_from_source(file, debug_override=not optimize) ++ else: ++ cfile = imp.cache_from_source(file) + dfile = file + if prefix: + if file[:len(prefix)] != prefix: +diff -r 137e45f15c0b Lib/doctest.py +--- a/Lib/doctest.py ++++ b/Lib/doctest.py +@@ -440,6 +440,25 @@ + self.options = options + self.exc_msg = exc_msg + ++ def __eq__(self, other): ++ if type(self) is not type(other): ++ return NotImplemented ++ ++ return self.source == other.source and \ ++ self.want == other.want and \ ++ self.lineno == other.lineno and \ ++ self.indent == other.indent and \ ++ self.options == other.options and \ ++ self.exc_msg == other.exc_msg ++ ++ def __ne__(self, other): ++ return not self == other ++ ++ def __hash__(self): ++ return hash((self.source, self.want, self.lineno, self.indent, ++ self.exc_msg)) ++ ++ + class DocTest: + """ + A collection of doctest examples that should be run in a single +@@ -488,6 +507,22 @@ + return ('' % + (self.name, self.filename, self.lineno, examples)) + ++ def __eq__(self, other): ++ if type(self) is not type(other): ++ return NotImplemented ++ ++ return self.examples == other.examples and \ ++ self.docstring == other.docstring and \ ++ self.globs == other.globs and \ ++ self.name == other.name and \ ++ self.filename == other.filename and \ ++ self.lineno == other.lineno ++ ++ def __ne__(self, other): ++ return not self == other ++ ++ def __hash__(self): ++ return hash((self.docstring, self.name, self.filename, self.lineno)) + + # This lets us sort tests by name: + def __lt__(self, other): +@@ -2204,6 +2239,23 @@ + def id(self): + return self._dt_test.name + ++ def __eq__(self, other): ++ if type(self) is not type(other): ++ return NotImplemented ++ ++ return self._dt_test == other._dt_test and \ ++ self._dt_optionflags == other._dt_optionflags and \ ++ self._dt_setUp == other._dt_setUp and \ ++ self._dt_tearDown == other._dt_tearDown and \ ++ self._dt_checker == other._dt_checker ++ ++ def __ne__(self, other): ++ return not self == other ++ ++ def __hash__(self): ++ return hash((self._dt_optionflags, self._dt_setUp, self._dt_tearDown, ++ self._dt_checker)) ++ + def __repr__(self): + name = self._dt_test.name.split('.') + return "%s (%s)" % (name[-1], '.'.join(name[:-1])) +diff -r 137e45f15c0b Lib/email/_parseaddr.py +--- a/Lib/email/_parseaddr.py ++++ b/Lib/email/_parseaddr.py +@@ -178,7 +178,7 @@ + front of you. + + Note: this class interface is deprecated and may be removed in the future. +- Use rfc822.AddressList instead. ++ Use email.utils.AddressList instead. + """ + + def __init__(self, field): +diff -r 137e45f15c0b Lib/encodings/__init__.py +--- a/Lib/encodings/__init__.py ++++ b/Lib/encodings/__init__.py +@@ -120,12 +120,11 @@ + if not 4 <= len(entry) <= 7: + raise CodecRegistryError('module "%s" (%s) failed to register' + % (mod.__name__, mod.__file__)) +- if not hasattr(entry[0], '__call__') or \ +- not hasattr(entry[1], '__call__') or \ +- (entry[2] is not None and not hasattr(entry[2], '__call__')) or \ +- (entry[3] is not None and not hasattr(entry[3], '__call__')) or \ +- (len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \ +- (len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')): ++ if not callable(entry[0]) or not callable(entry[1]) or \ ++ (entry[2] is not None and not callable(entry[2])) or \ ++ (entry[3] is not None and not callable(entry[3])) or \ ++ (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \ ++ (len(entry) > 5 and entry[5] is not None and not callable(entry[5])): + raise CodecRegistryError('incompatible codecs in module "%s" (%s)' + % (mod.__name__, mod.__file__)) + if len(entry)<7 or entry[6] is None: +diff -r 137e45f15c0b Lib/fileinput.py +--- a/Lib/fileinput.py ++++ b/Lib/fileinput.py +@@ -225,10 +225,11 @@ + raise ValueError("FileInput opening mode must be one of " + "'r', 'rU', 'U' and 'rb'") + self._mode = mode +- if inplace and openhook: +- raise ValueError("FileInput cannot use an opening hook in inplace mode") +- elif openhook and not hasattr(openhook, '__call__'): +- raise ValueError("FileInput openhook must be callable") ++ if openhook: ++ if inplace: ++ raise ValueError("FileInput cannot use an opening hook in inplace mode") ++ if not callable(openhook): ++ raise ValueError("FileInput openhook must be callable") + self._openhook = openhook + + def __del__(self): +diff -r 137e45f15c0b Lib/functools.py +--- a/Lib/functools.py ++++ b/Lib/functools.py +@@ -141,7 +141,7 @@ + + hits = misses = 0 + kwd_mark = (object(),) # separates positional and keyword args +- lock = Lock() # needed because ordereddicts aren't threadsafe ++ lock = Lock() # needed because OrderedDict isn't threadsafe + + if maxsize is None: + cache = dict() # simple cache without ordering or size limit +@@ -155,13 +155,15 @@ + try: + result = cache[key] + hits += 1 ++ return result + except KeyError: +- result = user_function(*args, **kwds) +- cache[key] = result +- misses += 1 ++ pass ++ result = user_function(*args, **kwds) ++ cache[key] = result ++ misses += 1 + return result + else: +- cache = OrderedDict() # ordered least recent to most recent ++ cache = OrderedDict() # ordered least recent to most recent + cache_popitem = cache.popitem + cache_renew = cache.move_to_end + +@@ -171,18 +173,20 @@ + key = args + if kwds: + key += kwd_mark + tuple(sorted(kwds.items())) +- try: +- with lock: ++ with lock: ++ try: + result = cache[key] +- cache_renew(key) # record recent use of this key ++ cache_renew(key) # record recent use of this key + hits += 1 +- except KeyError: +- result = user_function(*args, **kwds) +- with lock: +- cache[key] = result # record recent use of this key +- misses += 1 +- if len(cache) > maxsize: +- cache_popitem(0) # purge least recently used cache entry ++ return result ++ except KeyError: ++ pass ++ result = user_function(*args, **kwds) ++ with lock: ++ cache[key] = result # record recent use of this key ++ misses += 1 ++ if len(cache) > maxsize: ++ cache_popitem(0) # purge least recently used cache entry + return result + + def cache_info(): +diff -r 137e45f15c0b Lib/heapq.py +--- a/Lib/heapq.py ++++ b/Lib/heapq.py +@@ -185,6 +185,8 @@ + + Equivalent to: sorted(iterable, reverse=True)[:n] + """ ++ if n < 0: ++ return [] + it = iter(iterable) + result = list(islice(it, n)) + if not result: +@@ -201,6 +203,8 @@ + + Equivalent to: sorted(iterable)[:n] + """ ++ if n < 0: ++ return [] + if hasattr(iterable, '__len__') and n * 10 <= len(iterable): + # For smaller values of n, the bisect method is faster than a minheap. + # It is also memory efficient, consuming only n elements of space. +diff -r 137e45f15c0b Lib/hmac.py +--- a/Lib/hmac.py ++++ b/Lib/hmac.py +@@ -39,7 +39,7 @@ + import hashlib + digestmod = hashlib.md5 + +- if hasattr(digestmod, '__call__'): ++ if callable(digestmod): + self.digest_cons = digestmod + else: + self.digest_cons = lambda d=b'': digestmod.new(d) +diff -r 137e45f15c0b Lib/html/__init__.py +--- a/Lib/html/__init__.py ++++ b/Lib/html/__init__.py +@@ -13,7 +13,8 @@ + """ + Replace special characters "&", "<" and ">" to HTML-safe sequences. + If the optional flag quote is true (the default), the quotation mark +- character (") is also translated. ++ characters, both double quote (") and single quote (') characters are also ++ translated. + """ + if quote: + return s.translate(_escape_map_full) +diff -r 137e45f15c0b Lib/html/parser.py +--- a/Lib/html/parser.py ++++ b/Lib/html/parser.py +@@ -14,7 +14,6 @@ + # Regular expressions used for parsing + + interesting_normal = re.compile('[&<]') +-interesting_cdata = re.compile(r'<(/|\Z)') + incomplete = re.compile('&[a-zA-Z#]') + + entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]') +@@ -30,8 +29,8 @@ + r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*' + r'(\'[^\']*\'|"[^"]*"|[^\s"\'=<>`]*))?') + attrfind_tolerant = re.compile( +- r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*' +- r'(\'[^\']*\'|"[^"]*"|[^>\s]*))?') ++ r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*' ++ r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?') + locatestarttagend = re.compile(r""" + <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name + (?:\s+ # whitespace before attribute name +@@ -49,19 +48,21 @@ + locatestarttagend_tolerant = re.compile(r""" + <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name + (?:\s* # optional whitespace before attribute name +- (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name +- (?:\s*=\s* # value indicator ++ (?:(?<=['"\s])[^\s/>][^\s/=>]* # attribute name ++ (?:\s*=+\s* # value indicator + (?:'[^']*' # LITA-enclosed value +- |\"[^\"]*\" # LIT-enclosed value +- |[^'\">\s]+ # bare value ++ |"[^"]*" # LIT-enclosed value ++ |(?!['"])[^>\s]* # bare value + ) + (?:\s*,)* # possibly followed by a comma +- )? +- ) +- )* ++ )?\s* ++ )* ++ )? + \s* # trailing whitespace + """, re.VERBOSE) + endendtag = re.compile('>') ++# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between ++# ') + + +@@ -121,6 +122,7 @@ + self.rawdata = '' + self.lasttag = '???' + self.interesting = interesting_normal ++ self.cdata_elem = None + _markupbase.ParserBase.reset(self) + + def feed(self, data): +@@ -145,11 +147,13 @@ + """Return full source of start tag: '<...>'.""" + return self.__starttag_text + +- def set_cdata_mode(self): +- self.interesting = interesting_cdata ++ def set_cdata_mode(self, elem): ++ self.cdata_elem = elem.lower() ++ self.interesting = re.compile(r'' % self.cdata_elem, re.I) + + def clear_cdata_mode(self): + self.interesting = interesting_normal ++ self.cdata_elem = None + + # Internal -- handle data as far as reasonable. May leave state + # and data to be processed by a subsequent call. If 'end' is +@@ -163,6 +167,8 @@ + if match: + j = match.start() + else: ++ if self.cdata_elem: ++ break + j = n + if i < j: self.handle_data(rawdata[i:j]) + i = self.updatepos(i, j) +@@ -245,7 +251,7 @@ + else: + assert 0, "interesting.search() lied" + # end while +- if end and i < n: ++ if end and i < n and not self.cdata_elem: + self.handle_data(rawdata[i:n]) + i = self.updatepos(i, n) + self.rawdata = rawdata[i:] +@@ -277,12 +283,11 @@ + assert match, 'unexpected call to parse_starttag()' + k = match.end() + self.lasttag = tag = rawdata[i+1:k].lower() +- + while k < endpos: + if self.strict: + m = attrfind.match(rawdata, k) + else: +- m = attrfind_tolerant.search(rawdata, k) ++ m = attrfind_tolerant.match(rawdata, k) + if not m: + break + attrname, rest, attrvalue = m.group(1, 2, 3) +@@ -291,6 +296,7 @@ + elif attrvalue[:1] == '\'' == attrvalue[-1:] or \ + attrvalue[:1] == '"' == attrvalue[-1:]: + attrvalue = attrvalue[1:-1] ++ if attrvalue: + attrvalue = self.unescape(attrvalue) + attrs.append((attrname.lower(), attrvalue)) + k = m.end() +@@ -315,7 +321,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 +@@ -372,6 +378,9 @@ + j = match.end() + match = endtagfind.match(rawdata, i) # + if not match: ++ if self.cdata_elem is not None: ++ self.handle_data(rawdata[i:j]) ++ return j + if self.strict: + self.error("bad end tag: %r" % (rawdata[i:j],)) + k = rawdata.find('<', i + 1, j) +@@ -381,8 +390,14 @@ + j = i + 1 + self.handle_data(rawdata[i:j]) + return j +- tag = match.group(1) +- self.handle_endtag(tag.lower()) ++ ++ elem = match.group(1).lower() # script or style ++ if self.cdata_elem is not None: ++ if elem != self.cdata_elem: ++ self.handle_data(rawdata[i:j]) ++ return j ++ ++ self.handle_endtag(elem.lower()) + self.clear_cdata_mode() + return j + +@@ -458,4 +473,4 @@ + return '&'+s+';' + + return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", +- replaceEntities, s, re.ASCII) ++ replaceEntities, s, flags=re.ASCII) +diff -r 137e45f15c0b Lib/http/client.py +--- a/Lib/http/client.py ++++ b/Lib/http/client.py +@@ -678,7 +678,10 @@ + try: + port = int(host[i+1:]) + except ValueError: +- raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) ++ if host[i+1:] == "": # http://foo.com:/ == http://foo.com/ ++ port = self.default_port ++ else: ++ raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) + host = host[:i] + else: + port = self.default_port +@@ -947,11 +950,11 @@ + def endheaders(self, message_body=None): + """Indicate that the last header line has been sent to the server. + +- This method sends the request to the server. The optional +- message_body argument can be used to pass message body +- associated with the request. The message body will be sent in +- the same packet as the message headers if possible. The +- message_body should be a string. ++ This method sends the request to the server. The optional message_body ++ argument can be used to pass a message body associated with the ++ request. The message body will be sent in the same packet as the ++ message headers if it is a string, otherwise it is sent as a separate ++ packet. + """ + if self.__state == _CS_REQ_STARTED: + self.__state = _CS_REQ_SENT +diff -r 137e45f15c0b Lib/http/cookiejar.py +--- a/Lib/http/cookiejar.py ++++ b/Lib/http/cookiejar.py +@@ -1,4 +1,4 @@ +-"""HTTP cookie handling for web clients. ++r"""HTTP cookie handling for web clients. + + This module has (now fairly distant) origins in Gisle Aas' Perl module + HTTP::Cookies, from the libwww-perl library. +@@ -1020,7 +1020,7 @@ + (not erhn.startswith(".") and + not ("."+erhn).endswith(domain))): + _debug(" effective request-host %s (even with added " +- "initial dot) does not end end with %s", ++ "initial dot) does not end with %s", + erhn, domain) + return False + if (cookie.version > 0 or +diff -r 137e45f15c0b Lib/idlelib/ColorDelegator.py +--- a/Lib/idlelib/ColorDelegator.py ++++ b/Lib/idlelib/ColorDelegator.py +@@ -20,10 +20,10 @@ + # 1st 'file' colorized normal, 2nd as builtin, 3rd as string + builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" + comment = any("COMMENT", [r"#[^\n]*"]) +- sqstring = r"(\b[rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" +- dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?' +- sq3string = r"(\b[rRuU])?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" +- dq3string = r'(\b[rRuU])?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' ++ sqstring = r"(\b[rRbB])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" ++ dqstring = r'(\b[rRbB])?"[^"\\\n]*(\\.[^"\\\n]*)*"?' ++ sq3string = r"(\b[rRbB])?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" ++ dq3string = r'(\b[rRbB])?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' + string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) + return kw + "|" + builtin + "|" + comment + "|" + string +\ + "|" + any("SYNC", [r"\n"]) +diff -r 137e45f15c0b Lib/idlelib/EditorWindow.py +--- a/Lib/idlelib/EditorWindow.py ++++ b/Lib/idlelib/EditorWindow.py +@@ -799,12 +799,17 @@ + rf_list = [path for path in rf_list if path not in bad_paths] + ulchars = "1234567890ABCDEFGHIJK" + rf_list = rf_list[0:len(ulchars)] +- rf_file = open(self.recent_files_path, 'w', +- encoding='utf_8', errors='replace') + try: +- rf_file.writelines(rf_list) +- finally: +- rf_file.close() ++ with open(self.recent_files_path, 'w', ++ encoding='utf_8', errors='replace') as rf_file: ++ rf_file.writelines(rf_list) ++ except IOError as err: ++ if not getattr(self.root, "recentfilelist_error_displayed", False): ++ self.root.recentfilelist_error_displayed = True ++ tkMessageBox.showerror(title='IDLE Error', ++ message='Unable to update Recent Files list:\n%s' ++ % str(err), ++ parent=self.text) + # for each edit window instance, construct the recent files menu + for instance in self.top.instance_dict: + menu = instance.recent_files_menu +diff -r 137e45f15c0b Lib/idlelib/PyShell.py +--- a/Lib/idlelib/PyShell.py ++++ b/Lib/idlelib/PyShell.py +@@ -1,16 +1,17 @@ + #! /usr/bin/env python3 + ++import getopt + import os + import os.path +-import sys +-import getopt + import re + import socket ++import subprocess ++import sys ++import threading + import time +-import threading ++import tokenize + import traceback + import types +-import subprocess + + import linecache + from code import InteractiveInterpreter +@@ -201,18 +202,26 @@ + breaks = self.breakpoints + filename = self.io.filename + try: +- lines = open(self.breakpointPath,"r").readlines() ++ with open(self.breakpointPath, "r") as fp: ++ lines = fp.readlines() + except IOError: + lines = [] +- new_file = open(self.breakpointPath,"w") +- for line in lines: +- if not line.startswith(filename + '='): +- new_file.write(line) +- self.update_breakpoints() +- breaks = self.breakpoints +- if breaks: +- new_file.write(filename + '=' + str(breaks) + '\n') +- new_file.close() ++ try: ++ with open(self.breakpointPath, "w") as new_file: ++ for line in lines: ++ if not line.startswith(filename + '='): ++ new_file.write(line) ++ self.update_breakpoints() ++ breaks = self.breakpoints ++ if breaks: ++ new_file.write(filename + '=' + str(breaks) + '\n') ++ except IOError as err: ++ if not getattr(self.root, "breakpoint_error_displayed", False): ++ self.root.breakpoint_error_displayed = True ++ tkMessageBox.showerror(title='IDLE Error', ++ message='Unable to update breakpoint list:\n%s' ++ % str(err), ++ parent=self.text) + + def restore_file_breaks(self): + self.text.update() # this enables setting "BREAK" tags to be visible +@@ -220,7 +229,8 @@ + if filename is None: + return + if os.path.isfile(self.breakpointPath): +- lines = open(self.breakpointPath,"r").readlines() ++ with open(self.breakpointPath, "r") as fp: ++ lines = fp.readlines() + for line in lines: + if line.startswith(filename + '='): + breakpoint_linenumbers = eval(line[len(filename)+1:]) +@@ -338,6 +348,7 @@ + self.restarting = False + self.subprocess_arglist = None + self.port = PORT ++ self.original_compiler_flags = self.compile.compiler.flags + + rpcclt = None + rpcsubproc = None +@@ -445,6 +456,7 @@ + gui = RemoteDebugger.restart_subprocess_debugger(self.rpcclt) + # reload remote debugger breakpoints for all PyShellEditWindows + debug.load_breakpoints() ++ self.compile.compiler.flags = self.original_compiler_flags + self.restarting = False + return self.rpcclt + +@@ -571,7 +583,8 @@ + def execfile(self, filename, source=None): + "Execute an existing file" + if source is None: +- source = open(filename, "r").read() ++ with tokenize.open(filename) as fp: ++ source = fp.read() + try: + code = compile(source, filename, "exec") + except (OverflowError, SyntaxError): +@@ -640,9 +653,9 @@ + text = tkconsole.text + text.tag_remove("ERROR", "1.0", "end") + type, value, tb = sys.exc_info() +- msg = value.msg or "" +- lineno = value.lineno or 1 +- offset = value.offset or 0 ++ msg = getattr(value, 'msg', '') or value or "" ++ lineno = getattr(value, 'lineno', '') or 1 ++ offset = getattr(value, 'offset', '') or 0 + if offset == 0: + lineno += 1 #mark end of offending line + if lineno == 1: +diff -r 137e45f15c0b Lib/idlelib/ScriptBinding.py +--- a/Lib/idlelib/ScriptBinding.py ++++ b/Lib/idlelib/ScriptBinding.py +@@ -67,25 +67,20 @@ + + def tabnanny(self, filename): + # XXX: tabnanny should work on binary files as well +- with open(filename, 'r', encoding='iso-8859-1') as f: +- two_lines = f.readline() + f.readline() +- encoding = IOBinding.coding_spec(two_lines) +- if not encoding: +- encoding = 'utf-8' +- f = open(filename, 'r', encoding=encoding) +- try: +- tabnanny.process_tokens(tokenize.generate_tokens(f.readline)) +- except tokenize.TokenError as msg: +- msgtxt, (lineno, start) = msg +- self.editwin.gotoline(lineno) +- self.errorbox("Tabnanny Tokenizing Error", +- "Token Error: %s" % msgtxt) +- return False +- except tabnanny.NannyNag as nag: +- # The error messages from tabnanny are too confusing... +- self.editwin.gotoline(nag.get_lineno()) +- self.errorbox("Tab/space error", indent_message) +- return False ++ with tokenize.open(filename) as f: ++ try: ++ tabnanny.process_tokens(tokenize.generate_tokens(f.readline)) ++ except tokenize.TokenError as msg: ++ msgtxt, (lineno, start) = msg ++ self.editwin.gotoline(lineno) ++ self.errorbox("Tabnanny Tokenizing Error", ++ "Token Error: %s" % msgtxt) ++ return False ++ except tabnanny.NannyNag as nag: ++ # The error messages from tabnanny are too confusing... ++ self.editwin.gotoline(nag.get_lineno()) ++ self.errorbox("Tab/space error", indent_message) ++ return False + return True + + def checksyntax(self, filename): +@@ -106,10 +101,10 @@ + try: + # If successful, return the compiled code + return compile(source, filename, "exec") +- except (SyntaxError, OverflowError) as value: +- msg = value.msg or "" +- lineno = value.lineno or 1 +- offset = value.offset or 0 ++ except (SyntaxError, OverflowError, ValueError) as value: ++ msg = getattr(value, 'msg', '') or value or "" ++ lineno = getattr(value, 'lineno', '') or 1 ++ offset = getattr(value, 'offset', '') or 0 + if offset == 0: + lineno += 1 #mark end of offending line + pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1) +diff -r 137e45f15c0b Lib/idlelib/rpc.py +--- a/Lib/idlelib/rpc.py ++++ b/Lib/idlelib/rpc.py +@@ -570,7 +570,7 @@ + # Adds names to dictionary argument 'methods' + for name in dir(obj): + attr = getattr(obj, name) +- if hasattr(attr, '__call__'): ++ if callable(attr): + methods[name] = 1 + if isinstance(obj, type): + for super in obj.__bases__: +@@ -579,7 +579,7 @@ + def _getattributes(obj, attributes): + for name in dir(obj): + attr = getattr(obj, name) +- if not hasattr(attr, '__call__'): ++ if not callable(attr): + attributes[name] = 1 + + class MethodProxy(object): +diff -r 137e45f15c0b Lib/imaplib.py +--- a/Lib/imaplib.py ++++ b/Lib/imaplib.py +@@ -1385,7 +1385,7 @@ + """Convert date_time to IMAP4 INTERNALDATE representation. + + Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The +- date_time argument can be a number (int or float) represening ++ date_time argument can be a number (int or float) representing + seconds since epoch (as returned by time.time()), a 9-tuple + representing local time (as returned by time.localtime()), or a + double-quoted string. In the last case, it is assumed to already +diff -r 137e45f15c0b Lib/importlib/_bootstrap.py +--- a/Lib/importlib/_bootstrap.py ++++ b/Lib/importlib/_bootstrap.py +@@ -816,7 +816,9 @@ + for finder in meta_path: + loader = finder.find_module(name, path) + if loader is not None: +- loader.load_module(name) ++ # The parent import may have already imported this module. ++ if name not in sys.modules: ++ loader.load_module(name) + break + else: + raise ImportError(_ERR_MSG.format(name)) +diff -r 137e45f15c0b Lib/importlib/test/test_api.py +--- a/Lib/importlib/test/test_api.py ++++ b/Lib/importlib/test/test_api.py +@@ -67,6 +67,23 @@ + importlib.import_module('.support') + + ++ def test_loaded_once(self): ++ # Issue #13591: Modules should only be loaded once when ++ # initializing the parent package attempts to import the ++ # module currently being imported. ++ b_load_count = 0 ++ def load_a(): ++ importlib.import_module('a.b') ++ def load_b(): ++ nonlocal b_load_count ++ b_load_count += 1 ++ code = {'a': load_a, 'a.b': load_b} ++ modules = ['a.__init__', 'a.b'] ++ with util.mock_modules(*modules, module_code=code) as mock: ++ with util.import_state(meta_path=[mock]): ++ importlib.import_module('a.b') ++ self.assertEqual(b_load_count, 1) ++ + def test_main(): + from test.support import run_unittest + run_unittest(ImportModuleTests) +diff -r 137e45f15c0b Lib/importlib/test/util.py +--- a/Lib/importlib/test/util.py ++++ b/Lib/importlib/test/util.py +@@ -84,8 +84,9 @@ + + """A mock importer/loader.""" + +- def __init__(self, *names): ++ def __init__(self, *names, module_code={}): + self.modules = {} ++ self.module_code = {} + for name in names: + if not name.endswith('.__init__'): + import_name = name +@@ -105,6 +106,8 @@ + if import_name != name: + module.__path__ = [''] + self.modules[import_name] = module ++ if import_name in module_code: ++ self.module_code[import_name] = module_code[import_name] + + def __getitem__(self, name): + return self.modules[name] +@@ -120,6 +123,8 @@ + raise ImportError + else: + sys.modules[fullname] = self.modules[fullname] ++ if fullname in self.module_code: ++ self.module_code[fullname]() + return self.modules[fullname] + + def __enter__(self): +diff -r 137e45f15c0b Lib/inspect.py +--- a/Lib/inspect.py ++++ b/Lib/inspect.py +@@ -483,7 +483,7 @@ + return sys.modules.get(modulesbyfile[file]) + # Update the filename to module name cache and check yet again + # Copy sys.modules in order to cope with changes while iterating +- for modname, module in sys.modules.items(): ++ for modname, module in list(sys.modules.items()): + if ismodule(module) and hasattr(module, '__file__'): + f = module.__file__ + if f == _filesbymodname.get(modname, None): +@@ -1084,7 +1084,7 @@ + + def _check_class(klass, attr): + for entry in _static_getmro(klass): +- if not _shadowed_dict(type(entry)): ++ if _shadowed_dict(type(entry)) is _sentinel: + try: + return entry.__dict__[attr] + except KeyError: +@@ -1109,8 +1109,8 @@ + if not (type(class_dict) is types.GetSetDescriptorType and + class_dict.__name__ == "__dict__" and + class_dict.__objclass__ is entry): +- return True +- return False ++ return class_dict ++ return _sentinel + + def getattr_static(obj, attr, default=_sentinel): + """Retrieve attributes without triggering dynamic lookup via the +@@ -1126,7 +1126,9 @@ + instance_result = _sentinel + if not _is_type(obj): + klass = type(obj) +- if not _shadowed_dict(klass): ++ dict_attr = _shadowed_dict(klass) ++ if (dict_attr is _sentinel or ++ type(dict_attr) is types.MemberDescriptorType): + instance_result = _check_instance(obj, attr) + else: + klass = obj +diff -r 137e45f15c0b Lib/keyword.py +--- a/Lib/keyword.py ++++ b/Lib/keyword.py +@@ -7,7 +7,7 @@ + To update the symbols in this file, 'cd' to the top directory of + the python source tree after building the interpreter and run: + +- python Lib/keyword.py ++ ./python Lib/keyword.py + """ + + __all__ = ["iskeyword", "kwlist"] +diff -r 137e45f15c0b Lib/lib2to3/patcomp.py +--- a/Lib/lib2to3/patcomp.py ++++ b/Lib/lib2to3/patcomp.py +@@ -11,6 +11,7 @@ + __author__ = "Guido van Rossum " + + # Python imports ++import io + import os + + # Fairly local imports +@@ -32,7 +33,7 @@ + def tokenize_wrapper(input): + """Tokenizes a string suppressing significant whitespace.""" + skip = set((token.NEWLINE, token.INDENT, token.DEDENT)) +- tokens = tokenize.generate_tokens(driver.generate_lines(input).__next__) ++ tokens = tokenize.generate_tokens(io.StringIO(input).readline) + for quintuple in tokens: + type, value, start, end, line_text = quintuple + if type not in skip: +diff -r 137e45f15c0b Lib/lib2to3/pgen2/driver.py +--- a/Lib/lib2to3/pgen2/driver.py ++++ b/Lib/lib2to3/pgen2/driver.py +@@ -17,6 +17,7 @@ + + # Python imports + import codecs ++import io + import os + import logging + import sys +@@ -101,18 +102,10 @@ + + def parse_string(self, text, debug=False): + """Parse a string and return the syntax tree.""" +- tokens = tokenize.generate_tokens(generate_lines(text).__next__) ++ tokens = tokenize.generate_tokens(io.StringIO(text).readline) + return self.parse_tokens(tokens, debug) + + +-def generate_lines(text): +- """Generator that behaves like readline without using StringIO.""" +- for line in text.splitlines(True): +- yield line +- while True: +- yield "" +- +- + def load_grammar(gt="Grammar.txt", gp=None, + save=True, force=False, logger=None): + """Load the grammar (maybe from a pickle).""" +diff -r 137e45f15c0b Lib/lib2to3/tests/test_parser.py +--- a/Lib/lib2to3/tests/test_parser.py ++++ b/Lib/lib2to3/tests/test_parser.py +@@ -14,10 +14,21 @@ + + # Python imports + import os ++import unittest + + # Local imports + from lib2to3.pgen2 import tokenize + from ..pgen2.parse import ParseError ++from lib2to3.pygram import python_symbols as syms ++ ++ ++class TestDriver(support.TestCase): ++ ++ def test_formfeed(self): ++ s = """print 1\n\x0Cprint 2\n""" ++ t = driver.parse_string(s) ++ self.assertEqual(t.children[0].children[0].type, syms.print_stmt) ++ self.assertEqual(t.children[1].children[0].type, syms.print_stmt) + + + class GrammarTest(support.TestCase): +@@ -147,19 +158,22 @@ + + """A cut-down version of pytree_idempotency.py.""" + ++ # Issue 13125 ++ @unittest.expectedFailure + def test_all_project_files(self): + for filepath in support.all_project_files(): + with open(filepath, "rb") as fp: + encoding = tokenize.detect_encoding(fp.readline)[0] + self.assertTrue(encoding is not None, + "can't detect encoding for %s" % filepath) +- with open(filepath, "r") as fp: ++ with open(filepath, "r", encoding=encoding) as fp: + source = fp.read() +- source = source.decode(encoding) +- tree = driver.parse_string(source) ++ try: ++ tree = driver.parse_string(source) ++ except ParseError as err: ++ print('ParseError on file', filepath, err) ++ continue + new = str(tree) +- if encoding: +- new = new.encode(encoding) + if diff(filepath, new): + self.fail("Idempotency failed: %s" % filepath) + +@@ -202,14 +216,14 @@ + self.validate(s) + + +-def diff(fn, result, encoding): +- f = open("@", "w") ++def diff(fn, result): + try: +- f.write(result.encode(encoding)) +- finally: +- f.close() +- try: ++ with open('@', 'w') as f: ++ f.write(str(result)) + fn = fn.replace('"', '\\"') + return os.system('diff -u "%s" @' % fn) + finally: +- os.remove("@") ++ try: ++ os.remove("@") ++ except OSError: ++ pass +diff -r 137e45f15c0b Lib/locale.py +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -142,8 +142,6 @@ + grouping = conv[monetary and 'mon_grouping' or 'grouping'] + if not grouping: + return (s, 0) +- result = "" +- seps = 0 + if s[-1] == ' ': + stripped = s.rstrip() + right_spaces = s[len(stripped):] +@@ -442,13 +440,17 @@ + No aliasing or normalizing takes place. + + """ +- language, encoding = localetuple +- if language is None: +- language = 'C' +- if encoding is None: +- return language +- else: +- return language + '.' + encoding ++ try: ++ language, encoding = localetuple ++ ++ if language is None: ++ language = 'C' ++ if encoding is None: ++ return language ++ else: ++ return language + '.' + encoding ++ except (TypeError, ValueError): ++ raise TypeError('Locale must be None, a string, or an iterable of two strings -- language code, encoding.') + + def getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')): + +@@ -524,9 +526,10 @@ + def setlocale(category, locale=None): + + """ Set the locale for the given category. The locale can be +- a string, a locale tuple (language code, encoding), or None. ++ a string, an iterable of two strings (language code and encoding), ++ or None. + +- Locale tuples are converted to strings the locale aliasing ++ Iterables are converted to strings using the locale aliasing + engine. Locale strings are passed directly to the C lib. + + category may be given as one of the LC_* values. +@@ -1595,8 +1598,7 @@ + # to include every locale up to Windows Vista. + # + # NOTE: this mapping is incomplete. If your language is missing, please +-# submit a bug report to Python bug manager, which you can find via: +-# http://www.python.org/dev/ ++# submit a bug report to the Python bug tracker at http://bugs.python.org/ + # Make sure you include the missing language identifier and the suggested + # locale code. + # +diff -r 137e45f15c0b Lib/logging/__init__.py +--- a/Lib/logging/__init__.py ++++ b/Lib/logging/__init__.py +@@ -61,8 +61,6 @@ + # + if hasattr(sys, 'frozen'): #support for py2exe + _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) +-elif __file__[-4:].lower() in ['.pyc', '.pyo']: +- _srcfile = __file__[:-4] + '.py' + else: + _srcfile = __file__ + _srcfile = os.path.normcase(_srcfile) +@@ -1096,6 +1094,8 @@ + placeholder to now point to the logger. + """ + rv = None ++ if not isinstance(name, str): ++ raise TypeError('A logger name must be a string') + _acquireLock() + try: + if name in self.loggerDict: +diff -r 137e45f15c0b Lib/logging/config.py +--- a/Lib/logging/config.py ++++ b/Lib/logging/config.py +@@ -471,7 +471,7 @@ + def configure_custom(self, config): + """Configure an object with a user-supplied factory.""" + c = config.pop('()') +- if not hasattr(c, '__call__'): ++ if not callable(c): + c = self.resolve(c) + props = config.pop('.', None) + # Check for valid identifiers +@@ -690,7 +690,7 @@ + filters = config.pop('filters', None) + if '()' in config: + c = config.pop('()') +- if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: ++ if not callable(c): + c = self.resolve(c) + factory = c + else: +diff -r 137e45f15c0b Lib/mailbox.py +--- a/Lib/mailbox.py ++++ b/Lib/mailbox.py +@@ -273,11 +273,9 @@ + else: + raise NoSuchMailboxError(self._path) + self._toc = {} +- self._toc_mtimes = {} +- for subdir in ('cur', 'new'): +- self._toc_mtimes[subdir] = os.path.getmtime(self._paths[subdir]) +- self._last_read = time.time() # Records last time we read cur/new +- self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing ++ self._toc_mtimes = {'cur': 0, 'new': 0} ++ self._last_read = 0 # Records last time we read cur/new ++ self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing + + def add(self, message): + """Add message and return assigned key.""" +diff -r 137e45f15c0b Lib/mimetypes.py +--- a/Lib/mimetypes.py ++++ b/Lib/mimetypes.py +@@ -199,7 +199,7 @@ + list of standard types, else to the list of non-standard + types. + """ +- with open(filename) as fp: ++ with open(filename, encoding='utf-8') as fp: + self.readfp(fp, strict) + + def readfp(self, fp, strict=True): +diff -r 137e45f15c0b Lib/msilib/schema.py +--- a/Lib/msilib/schema.py ++++ b/Lib/msilib/schema.py +@@ -958,7 +958,7 @@ + ('ServiceInstall','StartType','N',0,4,None, None, None, None, 'Type of the service',), + ('Shortcut','Name','N',None, None, None, None, 'Filename',None, 'The name of the shortcut to be created.',), + ('Shortcut','Description','Y',None, None, None, None, 'Text',None, 'The description for the shortcut.',), +-('Shortcut','Component_','N',None, None, 'Component',1,'Identifier',None, 'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.',), ++('Shortcut','Component_','N',None, None, 'Component',1,'Identifier',None, 'Foreign key into the Component table denoting the component whose selection gates the shortcut creation/deletion.',), + ('Shortcut','Icon_','Y',None, None, 'Icon',1,'Identifier',None, 'Foreign key into the File table denoting the external icon file for the shortcut.',), + ('Shortcut','IconIndex','Y',-32767,32767,None, None, None, None, 'The icon index for the shortcut.',), + ('Shortcut','Directory_','N',None, None, 'Directory',1,'Identifier',None, 'Foreign key into the Directory table denoting the directory where the shortcut file is created.',), +diff -r 137e45f15c0b Lib/multiprocessing/__init__.py +--- a/Lib/multiprocessing/__init__.py ++++ b/Lib/multiprocessing/__init__.py +@@ -9,7 +9,7 @@ + # wrapper for 'threading'. + # + # Try calling `multiprocessing.doc.main()` to read the html +-# documentation in in a webbrowser. ++# documentation in a webbrowser. + # + # + # Copyright (c) 2006-2008, R Oudkerk +diff -r 137e45f15c0b Lib/multiprocessing/managers.py +--- a/Lib/multiprocessing/managers.py ++++ b/Lib/multiprocessing/managers.py +@@ -134,7 +134,7 @@ + temp = [] + for name in dir(obj): + func = getattr(obj, name) +- if hasattr(func, '__call__'): ++ if callable(func): + temp.append(name) + return temp + +@@ -510,7 +510,7 @@ + ''' + assert self._state.value == State.INITIAL + +- if initializer is not None and not hasattr(initializer, '__call__'): ++ if initializer is not None and not callable(initializer): + raise TypeError('initializer must be a callable') + + # pipe over which we will retrieve address of server +diff -r 137e45f15c0b Lib/multiprocessing/pool.py +--- a/Lib/multiprocessing/pool.py ++++ b/Lib/multiprocessing/pool.py +@@ -151,7 +151,7 @@ + if processes < 1: + raise ValueError("Number of processes must be at least 1") + +- if initializer is not None and not hasattr(initializer, '__call__'): ++ if initializer is not None and not callable(initializer): + raise TypeError('initializer must be a callable') + + self._processes = processes +@@ -321,7 +321,11 @@ + + @staticmethod + def _handle_workers(pool): +- while pool._worker_handler._state == RUN and pool._state == RUN: ++ thread = threading.current_thread() ++ ++ # Keep maintaining workers until the cache gets drained, unless the pool ++ # is terminated. ++ while thread._state == RUN or (pool._cache and thread._state != TERMINATE): + pool._maintain_pool() + time.sleep(0.1) + # send sentinel to stop workers +diff -r 137e45f15c0b Lib/multiprocessing/queues.py +--- a/Lib/multiprocessing/queues.py ++++ b/Lib/multiprocessing/queues.py +@@ -126,7 +126,11 @@ + if not self._rlock.acquire(block, timeout): + raise Empty + try: +- if not self._poll(block and (deadline-time.time()) or 0.0): ++ if block: ++ timeout = deadline - time.time() ++ if timeout < 0 or not self._poll(timeout): ++ raise Empty ++ elif not self._poll(): + raise Empty + res = self._recv() + self._sem.release() +diff -r 137e45f15c0b Lib/numbers.py +--- a/Lib/numbers.py ++++ b/Lib/numbers.py +@@ -303,7 +303,7 @@ + raise NotImplementedError + + def __index__(self): +- """someobject[self]""" ++ """Called whenever an index is needed, such as in slicing""" + return int(self) + + @abstractmethod +diff -r 137e45f15c0b Lib/optparse.py +--- a/Lib/optparse.py ++++ b/Lib/optparse.py +@@ -705,7 +705,7 @@ + + def _check_callback(self): + if self.action == "callback": +- if not hasattr(self.callback, '__call__'): ++ if not callable(self.callback): + raise OptionError( + "callback not callable: %r" % self.callback, self) + if (self.callback_args is not None and +diff -r 137e45f15c0b Lib/pickle.py +--- a/Lib/pickle.py ++++ b/Lib/pickle.py +@@ -299,20 +299,20 @@ + f(self, obj) # Call unbound method with explicit self + return + +- # Check for a class with a custom metaclass; treat as regular class +- try: +- issc = issubclass(t, type) +- except TypeError: # t is not a class (old Boost; see SF #502085) +- issc = 0 +- if issc: +- self.save_global(obj) +- return +- + # Check copyreg.dispatch_table + reduce = dispatch_table.get(t) + if reduce: + rv = reduce(obj) + else: ++ # Check for a class with a custom metaclass; treat as regular class ++ try: ++ issc = issubclass(t, type) ++ except TypeError: # t is not a class (old Boost; see SF #502085) ++ issc = False ++ if issc: ++ self.save_global(obj) ++ return ++ + # Check for a __reduce_ex__ method, fall back to __reduce__ + reduce = getattr(obj, "__reduce_ex__", None) + if reduce: +@@ -364,7 +364,7 @@ + raise PicklingError("args from save_reduce() should be a tuple") + + # Assert that func is callable +- if not hasattr(func, '__call__'): ++ if not callable(func): + raise PicklingError("func from save_reduce() should be callable") + + save = self.save +@@ -487,7 +487,11 @@ + + def save_bytes(self, obj, pack=struct.pack): + if self.proto < 3: +- self.save_reduce(bytes, (list(obj),), obj=obj) ++ if len(obj) == 0: ++ self.save_reduce(bytes, (), obj=obj) ++ else: ++ self.save_reduce(codecs.encode, ++ (str(obj, 'latin1'), 'latin1'), obj=obj) + return + n = len(obj) + if n < 256: +@@ -1156,16 +1160,22 @@ + + def load_put(self): + i = int(self.readline()[:-1]) ++ if i < 0: ++ raise ValueError("negative PUT argument") + self.memo[i] = self.stack[-1] + dispatch[PUT[0]] = load_put + + def load_binput(self): + i = self.read(1)[0] ++ if i < 0: ++ raise ValueError("negative BINPUT argument") + self.memo[i] = self.stack[-1] + dispatch[BINPUT[0]] = load_binput + + def load_long_binput(self): + i = mloads(b'i' + self.read(4)) ++ if i < 0: ++ raise ValueError("negative LONG_BINPUT argument") + self.memo[i] = self.stack[-1] + dispatch[LONG_BINPUT[0]] = load_long_binput + +diff -r 137e45f15c0b Lib/pickletools.py +--- a/Lib/pickletools.py ++++ b/Lib/pickletools.py +@@ -2083,27 +2083,22 @@ + 29: ( MARK + 30: d DICT (MARK at 29) + 31: p PUT 2 +- 34: c GLOBAL '__builtin__ bytes' +- 53: p PUT 3 +- 56: ( MARK +- 57: ( MARK +- 58: l LIST (MARK at 57) ++ 34: c GLOBAL '_codecs encode' ++ 50: p PUT 3 ++ 53: ( MARK ++ 54: V UNICODE 'abc' + 59: p PUT 4 +- 62: L LONG 97 +- 67: a APPEND +- 68: L LONG 98 +- 73: a APPEND +- 74: L LONG 99 +- 79: a APPEND +- 80: t TUPLE (MARK at 56) +- 81: p PUT 5 +- 84: R REDUCE +- 85: p PUT 6 +- 88: V UNICODE 'def' +- 93: p PUT 7 +- 96: s SETITEM +- 97: a APPEND +- 98: . STOP ++ 62: V UNICODE 'latin1' ++ 70: p PUT 5 ++ 73: t TUPLE (MARK at 53) ++ 74: p PUT 6 ++ 77: R REDUCE ++ 78: p PUT 7 ++ 81: V UNICODE 'def' ++ 86: p PUT 8 ++ 89: s SETITEM ++ 90: a APPEND ++ 91: . STOP + highest protocol among opcodes = 0 + + Try again with a "binary" pickle. +@@ -2122,25 +2117,22 @@ + 14: q BINPUT 1 + 16: } EMPTY_DICT + 17: q BINPUT 2 +- 19: c GLOBAL '__builtin__ bytes' +- 38: q BINPUT 3 +- 40: ( MARK +- 41: ] EMPTY_LIST +- 42: q BINPUT 4 +- 44: ( MARK +- 45: K BININT1 97 +- 47: K BININT1 98 +- 49: K BININT1 99 +- 51: e APPENDS (MARK at 44) +- 52: t TUPLE (MARK at 40) +- 53: q BINPUT 5 +- 55: R REDUCE +- 56: q BINPUT 6 +- 58: X BINUNICODE 'def' +- 66: q BINPUT 7 +- 68: s SETITEM +- 69: e APPENDS (MARK at 3) +- 70: . STOP ++ 19: c GLOBAL '_codecs encode' ++ 35: q BINPUT 3 ++ 37: ( MARK ++ 38: X BINUNICODE 'abc' ++ 46: q BINPUT 4 ++ 48: X BINUNICODE 'latin1' ++ 59: q BINPUT 5 ++ 61: t TUPLE (MARK at 37) ++ 62: q BINPUT 6 ++ 64: R REDUCE ++ 65: q BINPUT 7 ++ 67: X BINUNICODE 'def' ++ 75: q BINPUT 8 ++ 77: s SETITEM ++ 78: e APPENDS (MARK at 3) ++ 79: . STOP + highest protocol among opcodes = 1 + + Exercise the INST/OBJ/BUILD family. +diff -r 137e45f15c0b Lib/pipes.py +--- a/Lib/pipes.py ++++ b/Lib/pipes.py +@@ -54,8 +54,6 @@ + + To create a new template object initialized to a given one: + t2 = t.clone() +- +-For an example, see the function test() at the end of the file. + """ # ' + + +diff -r 137e45f15c0b Lib/pkgutil.py +--- a/Lib/pkgutil.py ++++ b/Lib/pkgutil.py +@@ -191,8 +191,11 @@ + + yielded = {} + import inspect +- +- filenames = os.listdir(self.path) ++ try: ++ filenames = os.listdir(self.path) ++ except OSError: ++ # ignore unreadable directories like import does ++ filenames = [] + filenames.sort() # handle packages before same-named modules + + for fn in filenames: +@@ -205,7 +208,12 @@ + + if not modname and os.path.isdir(path) and '.' not in fn: + modname = fn +- for fn in os.listdir(path): ++ try: ++ dircontents = os.listdir(path) ++ except OSError: ++ # ignore unreadable directories like import does ++ dircontents = [] ++ for fn in dircontents: + subname = inspect.getmodulename(fn) + if subname=='__init__': + ispkg = True +diff -r 137e45f15c0b Lib/plat-linux3/CDROM.py +--- a/Lib/plat-linux3/CDROM.py ++++ /dev/null +@@ -1,207 +0,0 @@ +-# Generated by h2py from /usr/include/linux/cdrom.h +- +-CDROMPAUSE = 0x5301 +-CDROMRESUME = 0x5302 +-CDROMPLAYMSF = 0x5303 +-CDROMPLAYTRKIND = 0x5304 +-CDROMREADTOCHDR = 0x5305 +-CDROMREADTOCENTRY = 0x5306 +-CDROMSTOP = 0x5307 +-CDROMSTART = 0x5308 +-CDROMEJECT = 0x5309 +-CDROMVOLCTRL = 0x530a +-CDROMSUBCHNL = 0x530b +-CDROMREADMODE2 = 0x530c +-CDROMREADMODE1 = 0x530d +-CDROMREADAUDIO = 0x530e +-CDROMEJECT_SW = 0x530f +-CDROMMULTISESSION = 0x5310 +-CDROM_GET_MCN = 0x5311 +-CDROM_GET_UPC = CDROM_GET_MCN +-CDROMRESET = 0x5312 +-CDROMVOLREAD = 0x5313 +-CDROMREADRAW = 0x5314 +-CDROMREADCOOKED = 0x5315 +-CDROMSEEK = 0x5316 +-CDROMPLAYBLK = 0x5317 +-CDROMREADALL = 0x5318 +-CDROMGETSPINDOWN = 0x531d +-CDROMSETSPINDOWN = 0x531e +-CDROMCLOSETRAY = 0x5319 +-CDROM_SET_OPTIONS = 0x5320 +-CDROM_CLEAR_OPTIONS = 0x5321 +-CDROM_SELECT_SPEED = 0x5322 +-CDROM_SELECT_DISC = 0x5323 +-CDROM_MEDIA_CHANGED = 0x5325 +-CDROM_DRIVE_STATUS = 0x5326 +-CDROM_DISC_STATUS = 0x5327 +-CDROM_CHANGER_NSLOTS = 0x5328 +-CDROM_LOCKDOOR = 0x5329 +-CDROM_DEBUG = 0x5330 +-CDROM_GET_CAPABILITY = 0x5331 +-CDROMAUDIOBUFSIZ = 0x5382 +-DVD_READ_STRUCT = 0x5390 +-DVD_WRITE_STRUCT = 0x5391 +-DVD_AUTH = 0x5392 +-CDROM_SEND_PACKET = 0x5393 +-CDROM_NEXT_WRITABLE = 0x5394 +-CDROM_LAST_WRITTEN = 0x5395 +-CDROM_PACKET_SIZE = 12 +-CGC_DATA_UNKNOWN = 0 +-CGC_DATA_WRITE = 1 +-CGC_DATA_READ = 2 +-CGC_DATA_NONE = 3 +-CD_MINS = 74 +-CD_SECS = 60 +-CD_FRAMES = 75 +-CD_SYNC_SIZE = 12 +-CD_MSF_OFFSET = 150 +-CD_CHUNK_SIZE = 24 +-CD_NUM_OF_CHUNKS = 98 +-CD_FRAMESIZE_SUB = 96 +-CD_HEAD_SIZE = 4 +-CD_SUBHEAD_SIZE = 8 +-CD_EDC_SIZE = 4 +-CD_ZERO_SIZE = 8 +-CD_ECC_SIZE = 276 +-CD_FRAMESIZE = 2048 +-CD_FRAMESIZE_RAW = 2352 +-CD_FRAMESIZE_RAWER = 2646 +-CD_FRAMESIZE_RAW1 = (CD_FRAMESIZE_RAW-CD_SYNC_SIZE) +-CD_FRAMESIZE_RAW0 = (CD_FRAMESIZE_RAW-CD_SYNC_SIZE-CD_HEAD_SIZE) +-CD_XA_HEAD = (CD_HEAD_SIZE+CD_SUBHEAD_SIZE) +-CD_XA_TAIL = (CD_EDC_SIZE+CD_ECC_SIZE) +-CD_XA_SYNC_HEAD = (CD_SYNC_SIZE+CD_XA_HEAD) +-CDROM_LBA = 0x01 +-CDROM_MSF = 0x02 +-CDROM_DATA_TRACK = 0x04 +-CDROM_LEADOUT = 0xAA +-CDROM_AUDIO_INVALID = 0x00 +-CDROM_AUDIO_PLAY = 0x11 +-CDROM_AUDIO_PAUSED = 0x12 +-CDROM_AUDIO_COMPLETED = 0x13 +-CDROM_AUDIO_ERROR = 0x14 +-CDROM_AUDIO_NO_STATUS = 0x15 +-CDC_CLOSE_TRAY = 0x1 +-CDC_OPEN_TRAY = 0x2 +-CDC_LOCK = 0x4 +-CDC_SELECT_SPEED = 0x8 +-CDC_SELECT_DISC = 0x10 +-CDC_MULTI_SESSION = 0x20 +-CDC_MCN = 0x40 +-CDC_MEDIA_CHANGED = 0x80 +-CDC_PLAY_AUDIO = 0x100 +-CDC_RESET = 0x200 +-CDC_IOCTLS = 0x400 +-CDC_DRIVE_STATUS = 0x800 +-CDC_GENERIC_PACKET = 0x1000 +-CDC_CD_R = 0x2000 +-CDC_CD_RW = 0x4000 +-CDC_DVD = 0x8000 +-CDC_DVD_R = 0x10000 +-CDC_DVD_RAM = 0x20000 +-CDS_NO_INFO = 0 +-CDS_NO_DISC = 1 +-CDS_TRAY_OPEN = 2 +-CDS_DRIVE_NOT_READY = 3 +-CDS_DISC_OK = 4 +-CDS_AUDIO = 100 +-CDS_DATA_1 = 101 +-CDS_DATA_2 = 102 +-CDS_XA_2_1 = 103 +-CDS_XA_2_2 = 104 +-CDS_MIXED = 105 +-CDO_AUTO_CLOSE = 0x1 +-CDO_AUTO_EJECT = 0x2 +-CDO_USE_FFLAGS = 0x4 +-CDO_LOCK = 0x8 +-CDO_CHECK_TYPE = 0x10 +-CD_PART_MAX = 64 +-CD_PART_MASK = (CD_PART_MAX - 1) +-GPCMD_BLANK = 0xa1 +-GPCMD_CLOSE_TRACK = 0x5b +-GPCMD_FLUSH_CACHE = 0x35 +-GPCMD_FORMAT_UNIT = 0x04 +-GPCMD_GET_CONFIGURATION = 0x46 +-GPCMD_GET_EVENT_STATUS_NOTIFICATION = 0x4a +-GPCMD_GET_PERFORMANCE = 0xac +-GPCMD_INQUIRY = 0x12 +-GPCMD_LOAD_UNLOAD = 0xa6 +-GPCMD_MECHANISM_STATUS = 0xbd +-GPCMD_MODE_SELECT_10 = 0x55 +-GPCMD_MODE_SENSE_10 = 0x5a +-GPCMD_PAUSE_RESUME = 0x4b +-GPCMD_PLAY_AUDIO_10 = 0x45 +-GPCMD_PLAY_AUDIO_MSF = 0x47 +-GPCMD_PLAY_AUDIO_TI = 0x48 +-GPCMD_PLAY_CD = 0xbc +-GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1e +-GPCMD_READ_10 = 0x28 +-GPCMD_READ_12 = 0xa8 +-GPCMD_READ_CDVD_CAPACITY = 0x25 +-GPCMD_READ_CD = 0xbe +-GPCMD_READ_CD_MSF = 0xb9 +-GPCMD_READ_DISC_INFO = 0x51 +-GPCMD_READ_DVD_STRUCTURE = 0xad +-GPCMD_READ_FORMAT_CAPACITIES = 0x23 +-GPCMD_READ_HEADER = 0x44 +-GPCMD_READ_TRACK_RZONE_INFO = 0x52 +-GPCMD_READ_SUBCHANNEL = 0x42 +-GPCMD_READ_TOC_PMA_ATIP = 0x43 +-GPCMD_REPAIR_RZONE_TRACK = 0x58 +-GPCMD_REPORT_KEY = 0xa4 +-GPCMD_REQUEST_SENSE = 0x03 +-GPCMD_RESERVE_RZONE_TRACK = 0x53 +-GPCMD_SCAN = 0xba +-GPCMD_SEEK = 0x2b +-GPCMD_SEND_DVD_STRUCTURE = 0xad +-GPCMD_SEND_EVENT = 0xa2 +-GPCMD_SEND_KEY = 0xa3 +-GPCMD_SEND_OPC = 0x54 +-GPCMD_SET_READ_AHEAD = 0xa7 +-GPCMD_SET_STREAMING = 0xb6 +-GPCMD_START_STOP_UNIT = 0x1b +-GPCMD_STOP_PLAY_SCAN = 0x4e +-GPCMD_TEST_UNIT_READY = 0x00 +-GPCMD_VERIFY_10 = 0x2f +-GPCMD_WRITE_10 = 0x2a +-GPCMD_WRITE_AND_VERIFY_10 = 0x2e +-GPCMD_SET_SPEED = 0xbb +-GPCMD_PLAYAUDIO_TI = 0x48 +-GPCMD_GET_MEDIA_STATUS = 0xda +-GPMODE_R_W_ERROR_PAGE = 0x01 +-GPMODE_WRITE_PARMS_PAGE = 0x05 +-GPMODE_AUDIO_CTL_PAGE = 0x0e +-GPMODE_POWER_PAGE = 0x1a +-GPMODE_FAULT_FAIL_PAGE = 0x1c +-GPMODE_TO_PROTECT_PAGE = 0x1d +-GPMODE_CAPABILITIES_PAGE = 0x2a +-GPMODE_ALL_PAGES = 0x3f +-GPMODE_CDROM_PAGE = 0x0d +-DVD_STRUCT_PHYSICAL = 0x00 +-DVD_STRUCT_COPYRIGHT = 0x01 +-DVD_STRUCT_DISCKEY = 0x02 +-DVD_STRUCT_BCA = 0x03 +-DVD_STRUCT_MANUFACT = 0x04 +-DVD_LAYERS = 4 +-DVD_LU_SEND_AGID = 0 +-DVD_HOST_SEND_CHALLENGE = 1 +-DVD_LU_SEND_KEY1 = 2 +-DVD_LU_SEND_CHALLENGE = 3 +-DVD_HOST_SEND_KEY2 = 4 +-DVD_AUTH_ESTABLISHED = 5 +-DVD_AUTH_FAILURE = 6 +-DVD_LU_SEND_TITLE_KEY = 7 +-DVD_LU_SEND_ASF = 8 +-DVD_INVALIDATE_AGID = 9 +-DVD_LU_SEND_RPC_STATE = 10 +-DVD_HOST_SEND_RPC_STATE = 11 +-DVD_CPM_NO_COPYRIGHT = 0 +-DVD_CPM_COPYRIGHTED = 1 +-DVD_CP_SEC_NONE = 0 +-DVD_CP_SEC_EXIST = 1 +-DVD_CGMS_UNRESTRICTED = 0 +-DVD_CGMS_SINGLE = 2 +-DVD_CGMS_RESTRICTED = 3 +- +-CDROM_MAX_SLOTS = 256 +diff -r 137e45f15c0b Lib/plat-linux3/DLFCN.py +--- a/Lib/plat-linux3/DLFCN.py ++++ /dev/null +@@ -1,83 +0,0 @@ +-# 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 = 199506 +-_XOPEN_SOURCE = 600 +-_XOPEN_SOURCE_EXTENDED = 1 +-_LARGEFILE64_SOURCE = 1 +-_BSD_SOURCE = 1 +-_SVID_SOURCE = 1 +-_BSD_SOURCE = 1 +-_SVID_SOURCE = 1 +-__USE_ISOC99 = 1 +-_POSIX_SOURCE = 1 +-_POSIX_C_SOURCE = 2 +-_POSIX_C_SOURCE = 199506 +-__USE_POSIX = 1 +-__USE_POSIX2 = 1 +-__USE_POSIX199309 = 1 +-__USE_POSIX199506 = 1 +-__USE_XOPEN = 1 +-__USE_XOPEN_EXTENDED = 1 +-__USE_UNIX98 = 1 +-_LARGEFILE_SOURCE = 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_GNU = 1 +-__USE_REENTRANT = 1 +-__STDC_IEC_559__ = 1 +-__STDC_IEC_559_COMPLEX__ = 1 +-__STDC_ISO_10646__ = 200009 +-__GNU_LIBRARY__ = 6 +-__GLIBC__ = 2 +-__GLIBC_MINOR__ = 2 +- +-# Included from sys/cdefs.h +-_SYS_CDEFS_H = 1 +-def __PMT(args): return args +- +-def __P(args): return args +- +-def __PMT(args): return args +- +-def __STRING(x): return #x +- +-__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 +- +-__USE_LARGEFILE = 1 +-__USE_LARGEFILE64 = 1 +-__USE_EXTERN_INLINES = 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_GLOBAL = 0x00100 +-RTLD_LOCAL = 0 +-RTLD_NODELETE = 0x01000 +diff -r 137e45f15c0b Lib/plat-linux3/IN.py +--- a/Lib/plat-linux3/IN.py ++++ /dev/null +@@ -1,615 +0,0 @@ +-# 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 = 199506 +-_XOPEN_SOURCE = 600 +-_XOPEN_SOURCE_EXTENDED = 1 +-_LARGEFILE64_SOURCE = 1 +-_BSD_SOURCE = 1 +-_SVID_SOURCE = 1 +-_BSD_SOURCE = 1 +-_SVID_SOURCE = 1 +-__USE_ISOC99 = 1 +-_POSIX_SOURCE = 1 +-_POSIX_C_SOURCE = 2 +-_POSIX_C_SOURCE = 199506 +-__USE_POSIX = 1 +-__USE_POSIX2 = 1 +-__USE_POSIX199309 = 1 +-__USE_POSIX199506 = 1 +-__USE_XOPEN = 1 +-__USE_XOPEN_EXTENDED = 1 +-__USE_UNIX98 = 1 +-_LARGEFILE_SOURCE = 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_GNU = 1 +-__USE_REENTRANT = 1 +-__STDC_IEC_559__ = 1 +-__STDC_IEC_559_COMPLEX__ = 1 +-__STDC_ISO_10646__ = 200009 +-__GNU_LIBRARY__ = 6 +-__GLIBC__ = 2 +-__GLIBC_MINOR__ = 2 +- +-# Included from sys/cdefs.h +-_SYS_CDEFS_H = 1 +-def __PMT(args): return args +- +-def __P(args): return args +- +-def __PMT(args): return args +- +-def __STRING(x): return #x +- +-__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 +- +-__USE_LARGEFILE = 1 +-__USE_LARGEFILE64 = 1 +-__USE_EXTERN_INLINES = 1 +- +-# Included from gnu/stubs.h +- +-# Included from stdint.h +-_STDINT_H = 1 +- +-# Included from bits/wchar.h +-_BITS_WCHAR_H = 1 +-__WCHAR_MIN = (-2147483647 - 1) +-__WCHAR_MAX = (2147483647) +- +-# Included from bits/wordsize.h +-__WORDSIZE = 32 +-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 = (-9223372036854775807-1) +-INT_FAST32_MIN = (-9223372036854775807-1) +-INT_FAST16_MIN = (-2147483647-1) +-INT_FAST32_MIN = (-2147483647-1) +-INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) +-INT_FAST8_MAX = (127) +-INT_FAST16_MAX = (9223372036854775807) +-INT_FAST32_MAX = (9223372036854775807) +-INT_FAST16_MAX = (2147483647) +-INT_FAST32_MAX = (2147483647) +-INT_FAST64_MAX = (__INT64_C(9223372036854775807)) +-UINT_FAST8_MAX = (255) +-UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) +-INTPTR_MIN = (-9223372036854775807-1) +-INTPTR_MAX = (9223372036854775807) +-INTPTR_MIN = (-2147483647-1) +-INTPTR_MAX = (2147483647) +-INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) +-INTMAX_MAX = (__INT64_C(9223372036854775807)) +-UINTMAX_MAX = (__UINT64_C(18446744073709551615)) +-PTRDIFF_MIN = (-9223372036854775807-1) +-PTRDIFF_MAX = (9223372036854775807) +-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 ## U +- +-def UINT16_C(c): return c ## U +- +-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 bits/types.h +-_BITS_TYPES_H = 1 +-__FD_SETSIZE = 1024 +- +-# Included from bits/pthreadtypes.h +-_BITS_PTHREADTYPES_H = 1 +- +-# Included from bits/sched.h +-SCHED_OTHER = 0 +-SCHED_FIFO = 1 +-SCHED_RR = 2 +-CSIGNAL = 0x000000ff +-CLONE_VM = 0x00000100 +-CLONE_FS = 0x00000200 +-CLONE_FILES = 0x00000400 +-CLONE_SIGHAND = 0x00000800 +-CLONE_PID = 0x00001000 +-CLONE_PTRACE = 0x00002000 +-CLONE_VFORK = 0x00004000 +-__defined_schedparam = 1 +-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/socket.h +- +-# 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 = 9223372036854775807 +-LONG_MAX = 2147483647 +-LONG_MIN = (-LONG_MAX - 1) +- +-# 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 = 6 +-_POSIX_DELAYTIMER_MAX = 32 +-_POSIX_LINK_MAX = 8 +-_POSIX_MAX_CANON = 255 +-_POSIX_MAX_INPUT = 255 +-_POSIX_MQ_OPEN_MAX = 8 +-_POSIX_MQ_PRIO_MAX = 32 +-_POSIX_NGROUPS_MAX = 0 +-_POSIX_OPEN_MAX = 16 +-_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX +-_POSIX_NAME_MAX = 14 +-_POSIX_PATH_MAX = 256 +-_POSIX_PIPE_BUF = 512 +-_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_TZNAME_MAX = 6 +-_POSIX_QLIMIT = 1 +-_POSIX_HIWAT = _POSIX_PIPE_BUF +-_POSIX_UIO_MAXIOV = 16 +-_POSIX_TTY_NAME_MAX = 9 +-_POSIX_TIMER_MAX = 32 +-_POSIX_LOGIN_NAME_MAX = 9 +-_POSIX_CLOCKRES_MIN = 20000000 +- +-# Included from bits/local_lim.h +- +-# Included from linux/limits.h +-NR_OPEN = 1024 +-NGROUPS_MAX = 32 +-ARG_MAX = 131072 +-CHILD_MAX = 999 +-OPEN_MAX = 256 +-LINK_MAX = 127 +-MAX_CANON = 255 +-MAX_INPUT = 255 +-NAME_MAX = 255 +-PATH_MAX = 4096 +-PIPE_BUF = 4096 +-RTSIG_MAX = 32 +-_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 +-SSIZE_MAX = LONG_MAX +-NGROUPS_MAX = _POSIX_NGROUPS_MAX +- +-# 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 = 4096 +-L_ctermid = 9 +-L_cuserid = 9 +-FOPEN_MAX = 16 +-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 +-from TYPES import * +-PF_UNSPEC = 0 +-PF_LOCAL = 1 +-PF_UNIX = PF_LOCAL +-PF_FILE = PF_LOCAL +-PF_INET = 2 +-PF_AX25 = 3 +-PF_IPX = 4 +-PF_APPLETALK = 5 +-PF_NETROM = 6 +-PF_BRIDGE = 7 +-PF_ATMPVC = 8 +-PF_X25 = 9 +-PF_INET6 = 10 +-PF_ROSE = 11 +-PF_DECnet = 12 +-PF_NETBEUI = 13 +-PF_SECURITY = 14 +-PF_KEY = 15 +-PF_NETLINK = 16 +-PF_ROUTE = PF_NETLINK +-PF_PACKET = 17 +-PF_ASH = 18 +-PF_ECONET = 19 +-PF_ATMSVC = 20 +-PF_SNA = 22 +-PF_IRDA = 23 +-PF_PPPOX = 24 +-PF_WANPIPE = 25 +-PF_BLUETOOTH = 31 +-PF_MAX = 32 +-AF_UNSPEC = PF_UNSPEC +-AF_LOCAL = PF_LOCAL +-AF_UNIX = PF_UNIX +-AF_FILE = PF_FILE +-AF_INET = PF_INET +-AF_AX25 = PF_AX25 +-AF_IPX = PF_IPX +-AF_APPLETALK = PF_APPLETALK +-AF_NETROM = PF_NETROM +-AF_BRIDGE = PF_BRIDGE +-AF_ATMPVC = PF_ATMPVC +-AF_X25 = PF_X25 +-AF_INET6 = PF_INET6 +-AF_ROSE = PF_ROSE +-AF_DECnet = PF_DECnet +-AF_NETBEUI = PF_NETBEUI +-AF_SECURITY = PF_SECURITY +-AF_KEY = PF_KEY +-AF_NETLINK = PF_NETLINK +-AF_ROUTE = PF_ROUTE +-AF_PACKET = PF_PACKET +-AF_ASH = PF_ASH +-AF_ECONET = PF_ECONET +-AF_ATMSVC = PF_ATMSVC +-AF_SNA = PF_SNA +-AF_IRDA = PF_IRDA +-AF_PPPOX = PF_PPPOX +-AF_WANPIPE = PF_WANPIPE +-AF_BLUETOOTH = PF_BLUETOOTH +-AF_MAX = PF_MAX +-SOL_RAW = 255 +-SOL_DECNET = 261 +-SOL_X25 = 262 +-SOL_PACKET = 263 +-SOL_ATM = 264 +-SOL_AAL = 265 +-SOL_IRDA = 266 +-SOMAXCONN = 128 +- +-# Included from bits/sockaddr.h +-_BITS_SOCKADDR_H = 1 +-def __SOCKADDR_COMMON(sa_prefix): return \ +- +-_SS_SIZE = 128 +-def CMSG_FIRSTHDR(mhdr): return \ +- +- +-# Included from asm/socket.h +- +-# Included from asm/sockios.h +-FIOSETOWN = 0x8901 +-SIOCSPGRP = 0x8902 +-FIOGETOWN = 0x8903 +-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 +-SCM_TIMESTAMP = SO_TIMESTAMP +-SO_ACCEPTCONN = 30 +-SOCK_STREAM = 1 +-SOCK_DGRAM = 2 +-SOCK_RAW = 3 +-SOCK_RDM = 4 +-SOCK_SEQPACKET = 5 +-SOCK_PACKET = 10 +-SOCK_MAX = (SOCK_PACKET+1) +- +-# Included from bits/in.h +-IP_TOS = 1 +-IP_TTL = 2 +-IP_HDRINCL = 3 +-IP_OPTIONS = 4 +-IP_ROUTER_ALERT = 5 +-IP_RECVOPTS = 6 +-IP_RETOPTS = 7 +-IP_PKTINFO = 8 +-IP_PKTOPTIONS = 9 +-IP_PMTUDISC = 10 +-IP_MTU_DISCOVER = 10 +-IP_RECVERR = 11 +-IP_RECVTTL = 12 +-IP_RECVTOS = 13 +-IP_MULTICAST_IF = 32 +-IP_MULTICAST_TTL = 33 +-IP_MULTICAST_LOOP = 34 +-IP_ADD_MEMBERSHIP = 35 +-IP_DROP_MEMBERSHIP = 36 +-IP_RECVRETOPTS = IP_RETOPTS +-IP_PMTUDISC_DONT = 0 +-IP_PMTUDISC_WANT = 1 +-IP_PMTUDISC_DO = 2 +-SOL_IP = 0 +-IP_DEFAULT_MULTICAST_TTL = 1 +-IP_DEFAULT_MULTICAST_LOOP = 1 +-IP_MAX_MEMBERSHIPS = 20 +-IPV6_ADDRFORM = 1 +-IPV6_PKTINFO = 2 +-IPV6_HOPOPTS = 3 +-IPV6_DSTOPTS = 4 +-IPV6_RTHDR = 5 +-IPV6_PKTOPTIONS = 6 +-IPV6_CHECKSUM = 7 +-IPV6_HOPLIMIT = 8 +-IPV6_NEXTHOP = 9 +-IPV6_AUTHHDR = 10 +-IPV6_UNICAST_HOPS = 16 +-IPV6_MULTICAST_IF = 17 +-IPV6_MULTICAST_HOPS = 18 +-IPV6_MULTICAST_LOOP = 19 +-IPV6_JOIN_GROUP = 20 +-IPV6_LEAVE_GROUP = 21 +-IPV6_ROUTER_ALERT = 22 +-IPV6_MTU_DISCOVER = 23 +-IPV6_MTU = 24 +-IPV6_RECVERR = 25 +-IPV6_RXHOPOPTS = IPV6_HOPOPTS +-IPV6_RXDSTOPTS = IPV6_DSTOPTS +-IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP +-IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP +-IPV6_PMTUDISC_DONT = 0 +-IPV6_PMTUDISC_WANT = 1 +-IPV6_PMTUDISC_DO = 2 +-SOL_IPV6 = 41 +-SOL_ICMPV6 = 58 +-IPV6_RTHDR_LOOSE = 0 +-IPV6_RTHDR_STRICT = 1 +-IPV6_RTHDR_TYPE_0 = 0 +- +-# 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 __bswap_constant_16 (x) +- +-def __bswap_constant_32(x): return \ +- +-def __bswap_32(x): return \ +- +-def __bswap_32(x): return \ +- +-def __bswap_32(x): return __bswap_constant_32 (x) +- +-def __bswap_constant_64(x): return \ +- +-def __bswap_64(x): return \ +- +-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 +diff -r 137e45f15c0b Lib/plat-linux3/TYPES.py +--- a/Lib/plat-linux3/TYPES.py ++++ /dev/null +@@ -1,170 +0,0 @@ +-# 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 = 199506 +-_XOPEN_SOURCE = 600 +-_XOPEN_SOURCE_EXTENDED = 1 +-_LARGEFILE64_SOURCE = 1 +-_BSD_SOURCE = 1 +-_SVID_SOURCE = 1 +-_BSD_SOURCE = 1 +-_SVID_SOURCE = 1 +-__USE_ISOC99 = 1 +-_POSIX_SOURCE = 1 +-_POSIX_C_SOURCE = 2 +-_POSIX_C_SOURCE = 199506 +-__USE_POSIX = 1 +-__USE_POSIX2 = 1 +-__USE_POSIX199309 = 1 +-__USE_POSIX199506 = 1 +-__USE_XOPEN = 1 +-__USE_XOPEN_EXTENDED = 1 +-__USE_UNIX98 = 1 +-_LARGEFILE_SOURCE = 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_GNU = 1 +-__USE_REENTRANT = 1 +-__STDC_IEC_559__ = 1 +-__STDC_IEC_559_COMPLEX__ = 1 +-__STDC_ISO_10646__ = 200009 +-__GNU_LIBRARY__ = 6 +-__GLIBC__ = 2 +-__GLIBC_MINOR__ = 2 +- +-# Included from sys/cdefs.h +-_SYS_CDEFS_H = 1 +-def __PMT(args): return args +- +-def __P(args): return args +- +-def __PMT(args): return args +- +-def __STRING(x): return #x +- +-__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 +- +-__USE_LARGEFILE = 1 +-__USE_LARGEFILE64 = 1 +-__USE_EXTERN_INLINES = 1 +- +-# Included from gnu/stubs.h +- +-# Included from bits/types.h +-_BITS_TYPES_H = 1 +-__FD_SETSIZE = 1024 +- +-# Included from bits/pthreadtypes.h +-_BITS_PTHREADTYPES_H = 1 +- +-# Included from bits/sched.h +-SCHED_OTHER = 0 +-SCHED_FIFO = 1 +-SCHED_RR = 2 +-CSIGNAL = 0x000000ff +-CLONE_VM = 0x00000100 +-CLONE_FS = 0x00000200 +-CLONE_FILES = 0x00000400 +-CLONE_SIGHAND = 0x00000800 +-CLONE_PID = 0x00001000 +-CLONE_PTRACE = 0x00002000 +-CLONE_VFORK = 0x00004000 +-__defined_schedparam = 1 +- +-# Included from time.h +-_TIME_H = 1 +- +-# Included from bits/time.h +-_BITS_TIME_H = 1 +-CLOCKS_PER_SEC = 1000000 +-CLOCK_REALTIME = 0 +-CLOCK_PROCESS_CPUTIME_ID = 2 +-CLOCK_THREAD_CPUTIME_ID = 3 +-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 +-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 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 __sigmask(sig): return \ +- +-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 major(dev): return ((int)(((dev) >> 8) & 0xff)) +- +-def minor(dev): return ((int)((dev) & 0xff)) +- +-def major(dev): return (((dev).__val[1] >> 8) & 0xff) +- +-def minor(dev): return ((dev).__val[1] & 0xff) +- +-def major(dev): return (((dev).__val[0] >> 8) & 0xff) +- +-def minor(dev): return ((dev).__val[0] & 0xff) +diff -r 137e45f15c0b Lib/plat-linux3/regen +--- a/Lib/plat-linux3/regen ++++ /dev/null +@@ -1,8 +0,0 @@ +-#! /bin/sh +-case `uname` in +-Linux*) ;; +-*) echo Probably not on a Linux system 1>&2 +- exit 1;; +-esac +-set -v +-h2py -i '(u_long)' /usr/include/sys/types.h /usr/include/netinet/in.h /usr/include/dlfcn.h +diff -r 137e45f15c0b Lib/platform.py +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -181,7 +181,7 @@ + elif so: + if lib != 'glibc': + lib = 'libc' +- if soversion > version: ++ if soversion and soversion > version: + version = soversion + if threads and version[-len(threads):] != threads: + version = version + threads +diff -r 137e45f15c0b Lib/py_compile.py +--- a/Lib/py_compile.py ++++ b/Lib/py_compile.py +@@ -130,7 +130,9 @@ + else: + cfile = imp.cache_from_source(file) + try: +- os.makedirs(os.path.dirname(cfile)) ++ dirname = os.path.dirname(cfile) ++ if dirname: ++ os.makedirs(dirname) + except OSError as error: + if error.errno != errno.EEXIST: + raise +diff -r 137e45f15c0b Lib/pydoc.py +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -775,7 +775,7 @@ + push(msg) + for name, kind, homecls, value in ok: + base = self.docother(getattr(object, name), name, mod) +- if hasattr(value, '__call__') or inspect.isdatadescriptor(value): ++ if callable(value) or inspect.isdatadescriptor(value): + doc = getattr(value, "__doc__", None) + else: + doc = None +@@ -1044,10 +1044,11 @@ + if docloc is not None: + result = result + self.section('MODULE REFERENCE', docloc + """ + +-The following documentation is automatically generated from the Python source +-files. It may be incomplete, incorrect or include features that are considered +-implementation detail and may vary between Python implementations. When in +-doubt, consult the module reference at the location listed above. ++The following documentation is automatically generated from the Python ++source files. It may be incomplete, incorrect or include features that ++are considered implementation detail and may vary between Python ++implementations. When in doubt, consult the module reference at the ++location listed above. + """) + + if desc: +@@ -1198,7 +1199,7 @@ + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: +- if hasattr(value, '__call__') or inspect.isdatadescriptor(value): ++ if callable(value) or inspect.isdatadescriptor(value): + doc = getdoc(value) + else: + doc = None +diff -r 137e45f15c0b Lib/random.py +--- a/Lib/random.py ++++ b/Lib/random.py +@@ -36,7 +36,6 @@ + + """ + +-from __future__ import division + from warnings import warn as _warn + from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType + from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil +diff -r 137e45f15c0b Lib/re.py +--- a/Lib/re.py ++++ b/Lib/re.py +@@ -326,7 +326,7 @@ + if i == j: + break + action = self.lexicon[m.lastindex-1][1] +- if hasattr(action, "__call__"): ++ if callable(action): + self.match = m + action = action(self, m.group()) + if action is not None: +diff -r 137e45f15c0b Lib/rlcompleter.py +--- a/Lib/rlcompleter.py ++++ b/Lib/rlcompleter.py +@@ -87,7 +87,7 @@ + return None + + def _callable_postfix(self, val, word): +- if hasattr(val, '__call__'): ++ if callable(val): + word = word + "(" + return word + +diff -r 137e45f15c0b Lib/sched.py +--- a/Lib/sched.py ++++ b/Lib/sched.py +@@ -94,7 +94,7 @@ + restarted. + + It is legal for both the delay function and the action +- function to to modify the queue or to raise an exception; ++ function to modify the queue or to raise an exception; + exceptions are not caught but the scheduler's state remains + well-defined so run() may be called again. + +diff -r 137e45f15c0b Lib/shutil.py +--- a/Lib/shutil.py ++++ b/Lib/shutil.py +@@ -398,7 +398,7 @@ + + if not os.path.exists(archive_dir): + if logger is not None: +- logger.info("creating %s" % archive_dir) ++ logger.info("creating %s", archive_dir) + if not dry_run: + os.makedirs(archive_dir) + +@@ -523,7 +523,7 @@ + """ + if extra_args is None: + extra_args = [] +- if not isinstance(function, collections.Callable): ++ if not callable(function): + raise TypeError('The %s object is not callable' % function) + if not isinstance(extra_args, (tuple, list)): + raise TypeError('extra_args needs to be a sequence') +@@ -616,7 +616,7 @@ + raise RegistryError(msg % (extension, + existing_extensions[extension])) + +- if not isinstance(function, collections.Callable): ++ if not callable(function): + raise TypeError('The registered function must be a callable') + + +diff -r 137e45f15c0b Lib/smtpd.py +--- a/Lib/smtpd.py ++++ b/Lib/smtpd.py +@@ -678,6 +678,16 @@ + if __name__ == '__main__': + options = parseargs() + # Become nobody ++ classname = options.classname ++ if "." in classname: ++ lastdot = classname.rfind(".") ++ mod = __import__(classname[:lastdot], globals(), locals(), [""]) ++ classname = classname[lastdot+1:] ++ else: ++ import __main__ as mod ++ class_ = getattr(mod, classname) ++ proxy = class_((options.localhost, options.localport), ++ (options.remotehost, options.remoteport)) + if options.setuid: + try: + import pwd +@@ -691,16 +701,6 @@ + if e.errno != errno.EPERM: raise + print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr) + sys.exit(1) +- classname = options.classname +- if "." in classname: +- lastdot = classname.rfind(".") +- mod = __import__(classname[:lastdot], globals(), locals(), [""]) +- classname = classname[lastdot+1:] +- else: +- import __main__ as mod +- class_ = getattr(mod, classname) +- proxy = class_((options.localhost, options.localport), +- (options.remotehost, options.remoteport)) + try: + asyncore.loop() + except KeyboardInterrupt: +diff -r 137e45f15c0b Lib/smtplib.py +--- a/Lib/smtplib.py ++++ b/Lib/smtplib.py +@@ -364,8 +364,10 @@ + while 1: + try: + line = self.file.readline() +- except socket.error: +- line = '' ++ except socket.error as e: ++ self.close() ++ raise SMTPServerDisconnected("Connection unexpectedly closed: " ++ + str(e)) + if not line: + self.close() + raise SMTPServerDisconnected("Connection unexpectedly closed") +@@ -910,6 +912,7 @@ + + def prompt(prompt): + sys.stdout.write(prompt + ": ") ++ sys.stdout.flush() + return sys.stdin.readline().strip() + + fromaddr = prompt("From") +diff -r 137e45f15c0b Lib/socketserver.py +--- a/Lib/socketserver.py ++++ b/Lib/socketserver.py +@@ -82,7 +82,7 @@ + data is stored externally (e.g. in the file system), a synchronous + class will essentially render the service "deaf" while one request is + being handled -- which may be for a very long time if a client is slow +-to reqd all the data it has requested. Here a threading or forking ++to read all the data it has requested. Here a threading or forking + server is appropriate. + + In some cases, it may be appropriate to process part of a request +@@ -588,8 +588,7 @@ + """Start a new thread to process the request.""" + t = threading.Thread(target = self.process_request_thread, + args = (request, client_address)) +- if self.daemon_threads: +- t.daemon = True ++ t.daemon = self.daemon_threads + t.start() + + +diff -r 137e45f15c0b Lib/subprocess.py +--- a/Lib/subprocess.py ++++ b/Lib/subprocess.py +@@ -429,12 +429,16 @@ + except: + MAXFD = 256 + ++# This lists holds Popen instances for which the underlying process had not ++# exited at the time its __del__ method got called: those processes are wait()ed ++# for synchronously from _cleanup() when a new Popen object is created, to avoid ++# zombie processes. + _active = [] + + def _cleanup(): + for inst in _active[:]: + res = inst._internal_poll(_deadstate=sys.maxsize) +- if res is not None and res >= 0: ++ if res is not None: + try: + _active.remove(inst) + except ValueError: +@@ -1191,6 +1195,7 @@ + errread, errwrite, + errpipe_read, errpipe_write, + restore_signals, start_new_session, preexec_fn) ++ self._child_created = True + else: + # Pure Python implementation: It is not thread safe. + # This implementation may deadlock in the child if your +diff -r 137e45f15c0b Lib/symbol.py +--- a/Lib/symbol.py ++++ b/Lib/symbol.py +@@ -7,7 +7,7 @@ + # To update the symbols in this file, 'cd' to the top directory of + # the python source tree after building the interpreter and run: + # +-# python Lib/symbol.py ++# ./python Lib/symbol.py + + #--start constants-- + single_input = 256 +diff -r 137e45f15c0b Lib/tarfile.py +--- a/Lib/tarfile.py ++++ b/Lib/tarfile.py +@@ -196,16 +196,18 @@ + """ + # There are two possible encodings for a number field, see + # itn() below. +- if s[0] != chr(0o200): ++ if s[0] in (0o200, 0o377): ++ n = 0 ++ for i in range(len(s) - 1): ++ n <<= 8 ++ n += s[i + 1] ++ if s[0] == 0o377: ++ n = -(256 ** (len(s) - 1) - n) ++ else: + try: + n = int(nts(s, "ascii", "strict") or "0", 8) + except ValueError: + raise InvalidHeaderError("invalid header") +- else: +- n = 0 +- for i in range(len(s) - 1): +- n <<= 8 +- n += ord(s[i + 1]) + return n + + def itn(n, digits=8, format=DEFAULT_FORMAT): +@@ -214,25 +216,26 @@ + # POSIX 1003.1-1988 requires numbers to be encoded as a string of + # octal digits followed by a null-byte, this allows values up to + # (8**(digits-1))-1. GNU tar allows storing numbers greater than +- # that if necessary. A leading 0o200 byte indicates this particular +- # encoding, the following digits-1 bytes are a big-endian +- # representation. This allows values up to (256**(digits-1))-1. ++ # that if necessary. A leading 0o200 or 0o377 byte indicate this ++ # particular encoding, the following digits-1 bytes are a big-endian ++ # base-256 representation. This allows values up to (256**(digits-1))-1. ++ # A 0o200 byte indicates a positive number, a 0o377 byte a negative ++ # number. + if 0 <= n < 8 ** (digits - 1): + s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL ++ elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1): ++ if n >= 0: ++ s = bytearray([0o200]) ++ else: ++ s = bytearray([0o377]) ++ n = 256 ** digits + n ++ ++ for i in range(digits - 1): ++ s.insert(1, n & 0o377) ++ n >>= 8 + else: +- if format != GNU_FORMAT or n >= 256 ** (digits - 1): +- raise ValueError("overflow in number field") ++ raise ValueError("overflow in number field") + +- if n < 0: +- # XXX We mimic GNU tar's behaviour with negative numbers, +- # this could raise OverflowError. +- n = struct.unpack("L", struct.pack("l", n))[0] +- +- s = bytearray() +- for i in range(digits - 1): +- s.insert(0, n & 0o377) +- n >>= 8 +- s.insert(0, 0o200) + return s + + def calc_chksums(buf): +@@ -624,7 +627,7 @@ + def getcomptype(self): + if self.buf.startswith(b"\037\213\010"): + return "gz" +- if self.buf.startswith(b"BZh91"): ++ if self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY": + return "bz2" + return "tar" + +@@ -2368,17 +2371,11 @@ + try: + g = grp.getgrnam(tarinfo.gname)[2] + except KeyError: +- try: +- g = grp.getgrgid(tarinfo.gid)[2] +- except KeyError: +- g = os.getgid() ++ g = tarinfo.gid + try: + u = pwd.getpwnam(tarinfo.uname)[2] + except KeyError: +- try: +- u = pwd.getpwuid(tarinfo.uid)[2] +- except KeyError: +- u = os.getuid() ++ u = tarinfo.uid + try: + if tarinfo.issym() and hasattr(os, "lchown"): + os.lchown(targetpath, u, g) +diff -r 137e45f15c0b Lib/tempfile.py +--- a/Lib/tempfile.py ++++ b/Lib/tempfile.py +@@ -112,8 +112,13 @@ + + characters = "abcdefghijklmnopqrstuvwxyz0123456789_" + +- def __init__(self): +- self.rng = _Random() ++ @property ++ def rng(self): ++ cur_pid = _os.getpid() ++ if cur_pid != getattr(self, '_rng_pid', None): ++ self._rng = _Random() ++ self._rng_pid = cur_pid ++ return self._rng + + def __iter__(self): + return self +diff -r 137e45f15c0b Lib/test/mime.types +--- /dev/null ++++ b/Lib/test/mime.types +@@ -0,0 +1,1445 @@ ++# This is a comment. I love comments. -*- indent-tabs-mode: t -*- ++ ++# This file controls what Internet media types are sent to the client for ++# given file extension(s). Sending the correct media type to the client ++# is important so they know how to handle the content of the file. ++# Extra types can either be added here or by using an AddType directive ++# in your config files. For more information about Internet media types, ++# please read RFC 2045, 2046, 2047, 2048, and 2077. The Internet media type ++# registry is at . ++ ++# IANA types ++ ++# MIME type Extensions ++application/1d-interleaved-parityfec ++application/3gpp-ims+xml ++application/activemessage ++application/andrew-inset ez ++application/applefile ++application/atom+xml atom ++application/atomcat+xml atomcat ++application/atomicmail ++application/atomsvc+xml atomsvc ++application/auth-policy+xml apxml ++application/batch-SMTP ++application/beep+xml ++application/cals-1840 ++application/ccxml+xml ccxml ++application/cdmi-capability cdmia ++application/cdmi-container cdmic ++application/cdmi-domain cdmid ++application/cdmi-object cdmio ++application/cdmi-queue cdmiq ++application/cea-2018+xml ++application/cellml+xml cellml cml ++application/cfw ++application/cnrp+xml ++application/commonground ++application/conference-info+xml ++application/cpl+xml cpl ++application/csta+xml ++application/CSTAdata+xml ++application/cybercash ++application/davmount+xml davmount ++application/dca-rft ++application/dec-dx ++application/dialog-info+xml ++application/dicom dcm ++application/dns ++application/dskpp+xml xmls ++application/dssc+der dssc ++application/dssc+xml xdssc ++application/dvcs dvc ++application/ecmascript ++application/EDI-Consent ++application/EDI-X12 ++application/EDIFACT ++application/emma+xml emma ++application/epp+xml ++application/eshop ++application/exi exi ++application/fastinfoset finf ++application/fastsoap ++# fits, fit, fts: image/fits ++application/fits ++application/font-tdpfr pfr ++application/framework-attributes+xml ++application/H224 ++application/hal+xml hal ++application/held+xml ++application/http ++application/hyperstudio stk ++application/ibe-key-request+xml ++application/ibe-pkg-reply+xml ++application/ibe-pp-data ++application/iges ++application/im-iscomposing+xml ++application/index ++application/index.cmd ++application/index.obj ++application/index.response ++application/index.vnd ++application/iotp ++application/ipfix ipfix ++application/ipp ++application/isup ++application/javascript js ++application/json json ++application/kpml-request+xml ++application/kpml-response+xml ++application/lost+xml lostxml ++application/mac-binhex40 hqx ++application/macwriteii ++application/mads+xml mads ++application/marc mrc ++application/marcxml+xml mrcx ++application/mathematica nb ma mb ++application/mathml-content+xml ++application/mathml-presentation+xml ++application/mathml+xml mml ++application/mbms-associated-procedure-description+xml ++application/mbms-deregister+xml ++application/mbms-envelope+xml ++application/mbms-msk-response+xml ++application/mbms-msk+xml ++application/mbms-protection-description+xml ++application/mbms-reception-report+xml ++application/mbms-register-response+xml ++application/mbms-register+xml ++application/mbms-user-service-description+xml ++application/mbox mbox ++application/media_control+xml ++application/mediaservercontrol+xml ++application/metalink4+xml meta4 ++application/mets+xml mets ++application/mikey ++application/mods+xml mods ++application/moss-keys ++application/moss-signature ++application/mosskey-data ++application/mosskey-request ++application/mp21 m21 mp21 ++# mp4, mpg4: video/mp4, see RFC 4337 ++application/mp4 ++application/mpeg4-generic ++application/mpeg4-iod ++application/mpeg4-iod-xmt ++application/msc-ivr+xml ++application/msc-mixer+xml ++application/msword doc ++application/mxf mxf ++application/nasdata ++application/news-checkgroups ++application/news-groupinfo ++application/news-transmission ++application/nss ++application/ocsp-request orq ++application/ocsp-response ors ++application/octet-stream bin lha lzh exe class so dll img iso ++application/oda oda ++application/oebps-package+xml opf ++application/ogg ogx ++application/parityfec ++# xer: application/xcap-error+xml ++application/patch-ops-error+xml ++application/pdf pdf ++application/pgp-encrypted ++application/pgp-keys ++application/pgp-signature sig ++application/pidf-diff+xml ++application/pidf+xml ++application/pkcs10 p10 ++application/pkcs7-mime p7m p7c ++application/pkcs7-signature p7s ++application/pkcs8 p8 ++# ac: application/vnd.nokia.n-gage.ac+xml ++application/pkix-attr-cert ++application/pkix-cert cer ++application/pkix-crl crl ++application/pkix-pkipath pkipath ++application/pkixcmp ++application/pls+xml pls ++application/poc-settings+xml ++application/postscript ps eps ai ++application/prs.alvestrand.titrax-sheet ++application/prs.cww cw cww ++application/prs.nprend rnd rct ++application/prs.plucker ++application/prs.rdf-xml-crypt rdf-crypt ++application/prs.xsf+xml xsf ++application/pskc+xml pskcxml ++application/qsig ++application/rdf+xml rdf ++application/reginfo+xml rif ++application/relax-ng-compact-syntax rnc ++application/remote-printing ++application/resource-lists-diff+xml rld ++application/resource-lists+xml rl ++application/riscos ++application/rlmi+xml ++application/rls-services+xml rs ++application/rtf rtf ++application/rtx ++application/samlassertion+xml ++application/samlmetadata+xml ++application/sbml+xml ++application/scvp-cv-request scq ++application/scvp-cv-response scs ++application/scvp-vp-request spq ++application/scvp-vp-response spp ++application/sdp sdp ++application/set-payment ++application/set-payment-initiation ++application/set-registration ++application/set-registration-initiation ++application/sgml ++application/sgml-open-catalog soc ++application/shf+xml shf ++application/sieve siv sieve ++application/simple-filter+xml cl ++application/simple-message-summary ++application/simpleSymbolContainer ++application/slate ++# obsoleted by application/smil+xml ++application/smil smil smi sml ++# smil, smi: application/smil for now ++application/smil+xml ++application/soap+fastinfoset ++application/soap+xml ++application/sparql-query rq ++application/sparql-results+xml srx ++application/spirits-event+xml ++application/srgs gram ++application/srgs+xml grxml ++application/sru+xml sru ++application/ssml+xml ssml ++application/tamp-apex-update tau ++application/tamp-apex-update-confirm auc ++application/tamp-community-update tcu ++application/tamp-community-update-confirm cuc ++application/tamp-error ter ++application/tamp-sequence-adjust tsa ++application/tamp-sequence-adjust-confirm sac ++# tsq: application/timestamp-query ++application/tamp-status-query ++# tsr: application/timestamp-reply ++application/tamp-status-response ++application/tamp-update tur ++application/tamp-update-confirm tuc ++application/tei+xml tei teiCorpus odd ++application/thraud+xml tfi ++application/timestamp-query tsq ++application/timestamp-reply tsr ++application/timestamped-data tsd ++application/tve-trigger ++application/ulpfec ++application/vemmi ++application/vnd.3gpp.bsf+xml ++application/vnd.3gpp.pic-bw-large plb ++application/vnd.3gpp.pic-bw-small psb ++application/vnd.3gpp.pic-bw-var pvb ++# sms: application/vnd.3gpp2.sms ++application/vnd.3gpp.sms ++application/vnd.3gpp2.bcmcsinfo+xml ++application/vnd.3gpp2.sms sms ++application/vnd.3gpp2.tcap tcap ++application/vnd.3M.Post-it-Notes pwn ++application/vnd.accpac.simply.aso aso ++application/vnd.accpac.simply.imp imp ++application/vnd.acucobol acu ++application/vnd.acucorp atc acutc ++application/vnd.adobe.fxp fxp fxpl ++application/vnd.adobe.partial-upload ++application/vnd.adobe.xdp+xml xdp ++application/vnd.adobe.xfdf xfdf ++application/vnd.aether.imp ++application/vnd.ah-barcode ++application/vnd.ahead.space ahead ++application/vnd.airzip.filesecure.azf azf ++application/vnd.airzip.filesecure.azs azs ++application/vnd.americandynamics.acc acc ++application/vnd.amiga.ami ami ++application/vnd.amundsen.maze+xml ++application/vnd.anser-web-certificate-issue-initiation cii ++# Not in IANA listing, but is on FTP site? ++application/vnd.anser-web-funds-transfer-initiation fti ++# atx: audio/ATRAC-X ++application/vnd.antix.game-component ++application/vnd.apple.installer+xml dist distz pkg mpkg ++# m3u: application/x-mpegurl for now ++application/vnd.apple.mpegurl m3u8 ++application/vnd.aristanetworks.swi swi ++application/vnd.audiograph aep ++application/vnd.autopackage package ++application/vnd.avistar+xml ++application/vnd.blueice.multipass mpm ++application/vnd.bluetooth.ep.oob ep ++application/vnd.bmi bmi ++application/vnd.businessobjects rep ++application/vnd.cab-jscript ++application/vnd.canon-cpdl ++application/vnd.canon-lips ++application/vnd.cendio.thinlinc.clientconf tlclient ++application/vnd.chemdraw+xml cdxml ++application/vnd.chipnuts.karaoke-mmd mmd ++application/vnd.cinderella cdy ++application/vnd.cirpack.isdn-ext ++application/vnd.claymore cla ++application/vnd.cloanto.rp9 rp9 ++application/vnd.clonk.c4group c4g c4d c4f c4p c4u ++application/vnd.cluetrust.cartomobile-config c11amc ++application/vnd.cluetrust.cartomobile-config-pkg c11amz ++# icc: application/vnd.iccprofile ++application/vnd.commerce-battelle ica icf icd ic0 ic1 ic2 ic3 ic4 ic5 ic6 ic7 ic8 ++application/vnd.commonspace csp cst ++application/vnd.contact.cmsg cdbcmsg ++application/vnd.cosmocaller cmc ++application/vnd.crick.clicker clkx ++application/vnd.crick.clicker.keyboard clkk ++application/vnd.crick.clicker.palette clkp ++application/vnd.crick.clicker.template clkt ++application/vnd.crick.clicker.wordbank clkw ++application/vnd.criticaltools.wbs+xml wbs ++application/vnd.ctc-posml pml ++application/vnd.ctct.ws+xml ++application/vnd.cups-pdf ++application/vnd.cups-postscript ++application/vnd.cups-ppd ppd ++application/vnd.cups-raster ++application/vnd.cups-raw ++application/vnd.curl curl ++application/vnd.cybank ++application/vnd.data-vision.rdz rdz ++application/vnd.dece.data uvf uvvf uvd uvvd ++application/vnd.dece.ttml+xml uvt uvvt ++application/vnd.dece.unspecified uvx uvvx ++application/vnd.denovo.fcselayout-link fe_launch ++application/vnd.dir-bi.plate-dl-nosuffix ++application/vnd.dna dna ++application/vnd.dolby.mobile.1 ++application/vnd.dolby.mobile.2 ++application/vnd.dpgraph dpg mwc dpgraph ++application/vnd.dreamfactory dfac ++application/vnd.dvb.ait ait ++# class: application/octet-stream ++application/vnd.dvb.dvbj ++application/vnd.dvb.esgcontainer ++application/vnd.dvb.ipdcdftnotifaccess ++application/vnd.dvb.ipdcesgaccess ++application/vnd.dvb.ipdcesgaccess2 ++application/vnd.dvb.ipdcesgpdd ++application/vnd.dvb.ipdcroaming ++application/vnd.dvb.iptv.alfec-base ++application/vnd.dvb.iptv.alfec-enhancement ++application/vnd.dvb.notif-aggregate-root+xml ++application/vnd.dvb.notif-container+xml ++application/vnd.dvb.notif-generic+xml ++application/vnd.dvb.notif-ia-msglist+xml ++application/vnd.dvb.notif-ia-registration-request+xml ++application/vnd.dvb.notif-ia-registration-response+xml ++application/vnd.dvb.notif-init+xml ++# pfr: application/font-tdpfr ++application/vnd.dvb.pfr ++application/vnd.dvb.service svc ++# dxr: application/x-director ++application/vnd.dxr ++application/vnd.dynageo geo ++application/vnd.easykaraoke.cdgdownload ++application/vnd.ecdis-update ++application/vnd.ecowin.chart mag ++application/vnd.ecowin.filerequest ++application/vnd.ecowin.fileupdate ++application/vnd.ecowin.series ++application/vnd.ecowin.seriesrequest ++application/vnd.ecowin.seriesupdate ++application/vnd.enliven nml ++application/vnd.epson.esf esf ++application/vnd.epson.msf msf ++application/vnd.epson.quickanime qam ++application/vnd.epson.salt slt ++application/vnd.epson.ssf ssf ++application/vnd.ericsson.quickcall qcall qca ++application/vnd.eszigno3+xml es3 et3 ++application/vnd.etsi.aoc+xml ++application/vnd.etsi.cug+xml ++application/vnd.etsi.iptvcommand+xml ++application/vnd.etsi.iptvdiscovery+xml ++application/vnd.etsi.iptvprofile+xml ++application/vnd.etsi.iptvsad-bc+xml ++application/vnd.etsi.iptvsad-cod+xml ++application/vnd.etsi.iptvsad-npvr+xml ++application/vnd.etsi.iptvservice+xml ++application/vnd.etsi.iptvsync+xml ++application/vnd.etsi.iptvueprofile+xml ++application/vnd.etsi.mcid+xml ++application/vnd.etsi.overload-control-policy-dataset+xml ++application/vnd.etsi.sci+xml ++application/vnd.etsi.simservs+xml ++application/vnd.etsi.tsl.der ++application/vnd.etsi.tsl+xml ++application/vnd.eudora.data ++application/vnd.ezpix-album ez2 ++application/vnd.ezpix-package ez3 ++application/vnd.f-secure.mobile ++application/vnd.fdf fdf ++application/vnd.fdsn.mseed msd mseed ++application/vnd.fdsn.seed seed dataless ++application/vnd.ffsns ++# all extensions: application/vnd.hbci ++application/vnd.fints ++application/vnd.FloGraphIt gph ++application/vnd.fluxtime.clip ftc ++application/vnd.font-fontforge-sfd sfd ++application/vnd.framemaker fm ++application/vnd.frogans.fnc fnc ++application/vnd.frogans.ltf ltf ++application/vnd.fsc.weblaunch fsc ++application/vnd.fujitsu.oasys oas ++application/vnd.fujitsu.oasys2 oa2 ++application/vnd.fujitsu.oasys3 oa3 ++application/vnd.fujitsu.oasysgp fg5 ++application/vnd.fujitsu.oasysprs bh2 ++application/vnd.fujixerox.ART-EX ++application/vnd.fujixerox.ART4 ++application/vnd.fujixerox.ddd ddd ++application/vnd.fujixerox.docuworks xdw ++application/vnd.fujixerox.docuworks.binder xbd ++application/vnd.fujixerox.HBPL ++application/vnd.fut-misnet ++application/vnd.fuzzysheet fzs ++application/vnd.genomatix.tuxedo txd ++application/vnd.geocube+xml g3 g³ ++application/vnd.geogebra.file ggb ++application/vnd.geogebra.tool ggt ++application/vnd.geometry-explorer gex gre ++application/vnd.geonext gxt ++application/vnd.geoplan g2w ++application/vnd.geospace g3w ++application/vnd.globalplatform.card-content-mgt ++application/vnd.globalplatform.card-content-mgt-response ++# application/vnd.gmx deprecated 2009-03-04 ++application/vnd.google-earth.kml+xml kml ++application/vnd.google-earth.kmz kmz ++application/vnd.grafeq gqf gqs ++application/vnd.gridmp ++application/vnd.groove-account gac ++application/vnd.groove-help ghf ++application/vnd.groove-identity-message gim ++application/vnd.groove-injector grv ++application/vnd.groove-tool-message gtm ++application/vnd.groove-tool-template tpl ++application/vnd.groove-vcard vcg ++application/vnd.HandHeld-Entertainment+xml zmm ++application/vnd.hbci hbci hbc kom upa pkd bpd ++# rep: application/vnd.businessobjects ++application/vnd.hcl-bireports ++application/vnd.hhe.lesson-player les ++application/vnd.hp-HPGL hpgl ++application/vnd.hp-hpid hpi hpid ++application/vnd.hp-hps hps ++application/vnd.hp-jlyt jlt ++application/vnd.hp-PCL pcl ++application/vnd.hp-PCLXL ++application/vnd.httphone ++application/vnd.hydrostatix.sof-data sfd-hdstx ++application/vnd.hzn-3d-crossword x3d ++application/vnd.ibm.afplinedata ++application/vnd.ibm.electronic-media emm ++application/vnd.ibm.MiniPay mpy ++application/vnd.ibm.modcap list3820 listafp afp pseg3820 ++application/vnd.ibm.rights-management irm ++application/vnd.ibm.secure-container sc ++application/vnd.iccprofile icc icm ++application/vnd.igloader igl ++application/vnd.immervision-ivp ivp ++application/vnd.immervision-ivu ivu ++application/vnd.informedcontrol.rms+xml ++# application/vnd.informix-visionary obsoleted by application/vnd.visionary ++application/vnd.infotech.project ++application/vnd.infotech.project+xml ++application/vnd.insors.igm igm ++application/vnd.intercon.formnet xpw xpx ++application/vnd.intergeo i2g ++application/vnd.intertrust.digibox ++application/vnd.intertrust.nncp ++application/vnd.intu.qbo qbo ++application/vnd.intu.qfx qfx ++application/vnd.iptc.g2.conceptitem+xml ++application/vnd.iptc.g2.knowledgeitem+xml ++application/vnd.iptc.g2.newsitem+xml ++application/vnd.iptc.g2.packageitem+xml ++application/vnd.ipunplugged.rcprofile rcprofile ++application/vnd.irepository.package+xml irp ++application/vnd.is-xpr xpr ++application/vnd.isac.fcs fcs ++application/vnd.jam jam ++application/vnd.japannet-directory-service ++application/vnd.japannet-jpnstore-wakeup ++application/vnd.japannet-payment-wakeup ++application/vnd.japannet-registration ++application/vnd.japannet-registration-wakeup ++application/vnd.japannet-setstore-wakeup ++application/vnd.japannet-verification ++application/vnd.japannet-verification-wakeup ++application/vnd.jcp.javame.midlet-rms rms ++application/vnd.jisp jisp ++application/vnd.joost.joda-archive joda ++application/vnd.kahootz ktz ktr ++application/vnd.kde.karbon karbon ++application/vnd.kde.kchart chrt ++application/vnd.kde.kformula kfo ++application/vnd.kde.kivio flw ++application/vnd.kde.kontour kon ++application/vnd.kde.kpresenter kpr kpt ++application/vnd.kde.kspread ksp ++application/vnd.kde.kword kwd kwt ++application/vnd.kenameaapp htke ++application/vnd.kidspiration kia ++application/vnd.Kinar kne knp sdf ++application/vnd.koan skp skd skm skt ++application/vnd.kodak-descriptor sse ++application/vnd.las.las+xml lasxml ++application/vnd.liberty-request+xml ++application/vnd.llamagraphics.life-balance.desktop lbd ++application/vnd.llamagraphics.life-balance.exchange+xml lbe ++application/vnd.lotus-1-2-3 123 wk4 wk3 wk1 ++application/vnd.lotus-approach apr vew ++application/vnd.lotus-freelance prz pre ++application/vnd.lotus-notes nsf ntf ndl ns4 ns3 ns2 nsh nsg ++application/vnd.lotus-organizer or3 or2 org ++application/vnd.lotus-screencam scm ++application/vnd.lotus-wordpro lwp sam ++application/vnd.macports.portpkg portpkg ++application/vnd.marlin.drm.actiontoken+xml ++application/vnd.marlin.drm.conftoken+xml ++application/vnd.marlin.drm.license+xml ++application/vnd.marlin.drm.mdcf mdc ++application/vnd.mcd mcd ++application/vnd.medcalcdata mc1 ++application/vnd.mediastation.cdkey cdkey ++application/vnd.meridian-slingshot ++application/vnd.MFER mwf ++application/vnd.mfmp mfm ++application/vnd.micrografx.flo flo ++application/vnd.micrografx.igx igx ++application/vnd.mif mif ++application/vnd.minisoft-hp3000-save ++application/vnd.mitsubishi.misty-guard.trustweb ++application/vnd.Mobius.DAF daf ++application/vnd.Mobius.DIS dis ++application/vnd.Mobius.MBK mbk ++application/vnd.Mobius.MQY mqy ++application/vnd.Mobius.MSL msl ++application/vnd.Mobius.PLC plc ++application/vnd.Mobius.TXF txf ++application/vnd.mophun.application mpn ++application/vnd.mophun.certificate mpc ++application/vnd.motorola.flexsuite ++application/vnd.motorola.flexsuite.adsi ++application/vnd.motorola.flexsuite.fis ++application/vnd.motorola.flexsuite.gotap ++application/vnd.motorola.flexsuite.kmr ++application/vnd.motorola.flexsuite.ttc ++application/vnd.motorola.flexsuite.wem ++application/vnd.motorola.iprm ++application/vnd.mozilla.xul+xml xul ++application/vnd.ms-artgalry cil ++application/vnd.ms-asf asf ++application/vnd.ms-cab-compressed cab ++application/vnd.ms-excel xls ++application/vnd.ms-excel.template.macroEnabled.12 xltm ++application/vnd.ms-excel.addin.macroEnabled.12 xlam ++application/vnd.ms-excel.sheet.binary.macroEnabled.12 xlsb ++application/vnd.ms-excel.sheet.macroEnabled.12 xlsm ++application/vnd.ms-fontobject eot ++application/vnd.ms-htmlhelp chm ++application/vnd.ms-ims ims ++application/vnd.ms-lrm lrm ++application/vnd.ms-office.activeX+xml ++application/vnd.ms-officetheme thmx ++application/vnd.ms-playready.initiator+xml ++application/vnd.ms-powerpoint ppt ++application/vnd.ms-powerpoint.addin.macroEnabled.12 ppam ++application/vnd.ms-powerpoint.presentation.macroEnabled.12 pptm ++application/vnd.ms-powerpoint.slide.macroEnabled.12 sldm ++application/vnd.ms-powerpoint.slideshow.macroEnabled.12 ppsm ++application/vnd.ms-powerpoint.template.macroEnabled.12 potm ++application/vnd.ms-project mpp ++application/vnd.ms-tnef tnef tnf ++application/vnd.ms-wmdrm.lic-chlg-req ++application/vnd.ms-wmdrm.lic-resp ++application/vnd.ms-wmdrm.meter-chlg-req ++application/vnd.ms-wmdrm.meter-resp ++application/vnd.ms-word.document.macroEnabled.12 docm ++application/vnd.ms-word.template.macroEnabled.12 dotm ++application/vnd.ms-works wcm wdb wks wps ++application/vnd.ms-wpl wpl ++application/vnd.ms-xpsdocument xps ++application/vnd.mseq mseq ++application/vnd.msign ++application/vnd.multiad.creator crtr ++application/vnd.multiad.creator.cif cif ++application/vnd.music-niff ++application/vnd.musician mus ++application/vnd.muvee.style msty ++application/vnd.ncd.control ++application/vnd.ncd.reference ++application/vnd.nervana entity request bkm kcm ++application/vnd.netfpx ++application/vnd.neurolanguage.nlu nlu ++application/vnd.noblenet-directory nnd ++application/vnd.noblenet-sealer nns ++application/vnd.noblenet-web nnw ++application/vnd.nokia.catalogs ++application/vnd.nokia.conml+wbxml ++application/vnd.nokia.conml+xml ++application/vnd.nokia.iptv.config+xml ++application/vnd.nokia.iSDS-radio-presets ++application/vnd.nokia.landmark+wbxml ++application/vnd.nokia.landmark+xml ++application/vnd.nokia.landmarkcollection+xml ++application/vnd.nokia.n-gage.ac+xml ac ++application/vnd.nokia.n-gage.data ngdat ++application/vnd.nokia.n-gage.symbian.install n-gage ++application/vnd.nokia.ncd ++application/vnd.nokia.pcd+wbxml ++application/vnd.nokia.pcd+xml ++application/vnd.nokia.radio-preset rpst ++application/vnd.nokia.radio-presets rpss ++application/vnd.novadigm.EDM edm ++application/vnd.novadigm.EDX edx ++application/vnd.novadigm.EXT ext ++application/vnd.ntt-local.file-transfer ++application/vnd.ntt-local.sip-ta_remote ++application/vnd.ntt-local.sip-ta_tcp_stream ++application/vnd.oasis.opendocument.chart odc ++application/vnd.oasis.opendocument.chart-template otc ++application/vnd.oasis.opendocument.database odb ++application/vnd.oasis.opendocument.formula odf ++application/vnd.oasis.opendocument.formula-template otf ++application/vnd.oasis.opendocument.graphics odg ++application/vnd.oasis.opendocument.graphics-template otg ++application/vnd.oasis.opendocument.image odi ++application/vnd.oasis.opendocument.image-template oti ++application/vnd.oasis.opendocument.presentation odp ++application/vnd.oasis.opendocument.presentation-template otp ++application/vnd.oasis.opendocument.spreadsheet ods ++application/vnd.oasis.opendocument.spreadsheet-template ots ++application/vnd.oasis.opendocument.text odt ++application/vnd.oasis.opendocument.text-master odm ++application/vnd.oasis.opendocument.text-template ott ++application/vnd.oasis.opendocument.text-web oth ++application/vnd.obn ++application/vnd.oipf.contentaccessdownload+xml ++application/vnd.oipf.contentaccessstreaming+xml ++application/vnd.oipf.cspg-hexbinary ++application/vnd.oipf.dae.svg+xml ++application/vnd.oipf.dae.xhtml+xml ++application/vnd.oipf.mippvcontrolmessage+xml ++application/vnd.oipf.pae.gem ++application/vnd.oipf.spdiscovery+xml ++application/vnd.oipf.spdlist+xml ++application/vnd.oipf.ueprofile+xml ++application/vnd.olpc-sugar xo ++application/vnd.oma.bcast.associated-procedure-parameter+xml ++application/vnd.oma.bcast.drm-trigger+xml ++application/vnd.oma.bcast.imd+xml ++application/vnd.oma.bcast.ltkm ++application/vnd.oma.bcast.notification+xml ++application/vnd.oma.bcast.provisioningtrigger ++application/vnd.oma.bcast.sgboot ++application/vnd.oma.bcast.sgdd+xml ++application/vnd.oma.bcast.sgdu ++application/vnd.oma.bcast.simple-symbol-container ++application/vnd.oma.bcast.smartcard-trigger+xml ++application/vnd.oma.bcast.sprov+xml ++application/vnd.oma.bcast.stkm ++application/vnd.oma.cab-address-book+xml ++application/vnd.oma.cab-feature-handler+xml ++application/vnd.oma.cab-pcc+xml ++application/vnd.oma.cab-user-prefs+xml ++application/vnd.oma.dcd ++application/vnd.oma.dcdc ++application/vnd.oma.dd2+xml dd2 ++application/vnd.oma.drm.risd+xml ++application/vnd.oma.group-usage-list+xml ++application/vnd.oma.poc.detailed-progress-report+xml ++application/vnd.oma.poc.final-report+xml ++application/vnd.oma.poc.groups+xml ++application/vnd.oma.poc.invocation-descriptor+xml ++application/vnd.oma.poc.optimized-progress-report+xml ++application/vnd.oma.push ++application/vnd.oma.scidm.messages+xml ++application/vnd.oma.xcap-directory+xml ++application/vnd.oma-scws-config ++application/vnd.oma-scws-http-request ++application/vnd.oma-scws-http-response ++application/vnd.omads-email+xml ++application/vnd.omads-file+xml ++application/vnd.omads-folder+xml ++application/vnd.omaloc-supl-init ++application/vnd.openofficeorg.extension oxt ++application/vnd.openxmlformats-officedocument.custom-properties+xml ++application/vnd.openxmlformats-officedocument.customXmlProperties+xml ++application/vnd.openxmlformats-officedocument.drawing+xml ++application/vnd.openxmlformats-officedocument.drawingml.chart+xml ++application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml ++application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml ++application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml ++application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml ++application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml ++application/vnd.openxmlformats-officedocument.extended-properties+xml ++application/vnd.openxmlformats-officedocument.presentationml.commentAuthors+xml ++application/vnd.openxmlformats-officedocument.presentationml.comments+xml ++application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml ++application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml ++application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml ++application/vnd.openxmlformats-officedocument.presentationml.presProps+xml ++application/vnd.openxmlformats-officedocument.presentationml.presentation pptx ++application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml ++application/vnd.openxmlformats-officedocument.presentationml.slide sldx ++application/vnd.openxmlformats-officedocument.presentationml.slide+xml ++application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml ++application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml ++application/vnd.openxmlformats-officedocument.presentationml.slideUpdateInfo+xml ++application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx ++application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml ++application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml ++application/vnd.openxmlformats-officedocument.presentationml.tags+xml ++application/vnd.openxmlformats-officedocument.presentationml.template potx ++application/vnd.openxmlformats-officedocument.presentationml.template.main+xml ++application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx ++application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx ++application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml ++application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml ++application/vnd.openxmlformats-officedocument.theme+xml ++application/vnd.openxmlformats-officedocument.themeOverride+xml ++application/vnd.openxmlformats-officedocument.vmlDrawing ++application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.document docx ++application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx ++application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml ++application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml ++application/vnd.openxmlformats-package.core-properties+xml ++application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml ++application/vnd.openxmlformats-package.relationships+xml ++application/vnd.osa.netdeploy ndc ++application/vnd.osgeo.mapguide.package mgp ++# jar: application/x-java-archive ++application/vnd.osgi.bundle ++application/vnd.osgi.dp dp ++application/vnd.otps.ct-kip+xml ++application/vnd.palm prc pdb pqa oprc ++application/vnd.paos+xml ++application/vnd.pawaafile paw ++application/vnd.pg.format str ++application/vnd.pg.osasli ei6 ++application/vnd.piaccess.application-license pil ++application/vnd.picsel efif ++application/vnd.pmi.widget wg ++application/vnd.poc.group-advertisement+xml ++application/vnd.pocketlearn plf ++application/vnd.powerbuilder6 pbd ++application/vnd.powerbuilder6-s ++application/vnd.powerbuilder7 ++application/vnd.powerbuilder7-s ++application/vnd.powerbuilder75 ++application/vnd.powerbuilder75-s ++application/vnd.preminet preminet ++application/vnd.previewsystems.box box vbox ++application/vnd.proteus.magazine mgz ++application/vnd.publishare-delta-tree qps ++# pti: image/prs.pti ++application/vnd.pvi.ptid1 ptid ++application/vnd.pwg-multiplexed ++application/vnd.pwg-xhtml-print+xml ++application/vnd.qualcomm.brew-app-res bar ++application/vnd.Quark.QuarkXPress qxd qxt qwd qwt qxl qxb ++application/vnd.quobject-quoxdocument quox quiz ++application/vnd.radisys.moml+xml ++application/vnd.radisys.msml-audit-conf+xml ++application/vnd.radisys.msml-audit-conn+xml ++application/vnd.radisys.msml-audit-dialog+xml ++application/vnd.radisys.msml-audit-stream+xml ++application/vnd.radisys.msml-audit+xml ++application/vnd.radisys.msml-conf+xml ++application/vnd.radisys.msml-dialog-base+xml ++application/vnd.radisys.msml-dialog-fax-detect+xml ++application/vnd.radisys.msml-dialog-fax-sendrecv+xml ++application/vnd.radisys.msml-dialog-group+xml ++application/vnd.radisys.msml-dialog-speech+xml ++application/vnd.radisys.msml-dialog-transform+xml ++application/vnd.radisys.msml-dialog+xml ++application/vnd.radisys.msml+xml ++application/vnd.rainstor.data tree ++application/vnd.rapid ++application/vnd.realvnc.bed bed ++application/vnd.recordare.musicxml mxl ++application/vnd.recordare.musicxml+xml ++application/vnd.RenLearn.rlprint ++application/vnd.rig.cryptonote cryptonote ++application/vnd.route66.link66+xml link66 ++application/vnd.ruckus.download ++application/vnd.s3sms ++application/vnd.sailingtracker.track st ++application/vnd.sbm.cid ++application/vnd.sbm.mid2 ++application/vnd.scribus scd sla slaz ++application/vnd.sealed.3df s3df ++application/vnd.sealed.csf scsf ++application/vnd.sealed.doc sdoc sdo s1w ++application/vnd.sealed.eml seml sem ++application/vnd.sealed.mht smht smh ++application/vnd.sealed.net ++# spp: application/scvp-vp-response ++application/vnd.sealed.ppt sppt s1p ++application/vnd.sealed.tiff stif ++application/vnd.sealed.xls sxls sxl s1e ++# stm: audio/x-stm ++application/vnd.sealedmedia.softseal.html stml s1h ++application/vnd.sealedmedia.softseal.pdf spdf spd s1a ++application/vnd.seemail see ++application/vnd.sema sema ++application/vnd.semd semd ++application/vnd.semf semf ++application/vnd.shana.informed.formdata ifm ++application/vnd.shana.informed.formtemplate itp ++application/vnd.shana.informed.interchange iif ++application/vnd.shana.informed.package ipk ++application/vnd.SimTech-MindMapper twd twds ++application/vnd.smaf mmf ++application/vnd.smart.notebook notebook ++application/vnd.smart.teacher teacher ++application/vnd.software602.filler.form+xml fo ++application/vnd.software602.filler.form-xml-zip zfo ++application/vnd.solent.sdkm+xml sdkm sdkd ++application/vnd.spotfire.dxp dxp ++application/vnd.spotfire.sfs sfs ++application/vnd.sss-cod ++application/vnd.sss-dtf ++application/vnd.sss-ntf ++application/vnd.stepmania.stepchart sm ++application/vnd.street-stream ++application/vnd.sun.wadl+xml wadl ++application/vnd.sus-calendar sus susp ++application/vnd.svd ++application/vnd.swiftview-ics ++application/vnd.syncml.dm.notification ++application/vnd.syncml.ds.notification ++application/vnd.syncml.dm+wbxml bdm ++application/vnd.syncml.dm+xml xdm ++application/vnd.syncml+xml xsm ++application/vnd.tao.intent-module-archive tao ++application/vnd.tmobile-livetv tmo ++application/vnd.trid.tpt tpt ++application/vnd.triscape.mxs mxs ++application/vnd.trueapp tra ++application/vnd.truedoc ++# cab: application/vnd.ms-cab-compressed ++application/vnd.ubisoft.webplayer ++application/vnd.ufdl ufdl ufd frm ++application/vnd.uiq.theme utz ++application/vnd.umajin umj ++application/vnd.unity unityweb ++application/vnd.uoml+xml uoml uo ++application/vnd.uplanet.alert ++application/vnd.uplanet.alert-wbxml ++application/vnd.uplanet.bearer-choice ++application/vnd.uplanet.bearer-choice-wbxml ++application/vnd.uplanet.cacheop ++application/vnd.uplanet.cacheop-wbxml ++application/vnd.uplanet.channel ++application/vnd.uplanet.channel-wbxml ++application/vnd.uplanet.list ++application/vnd.uplanet.list-wbxml ++application/vnd.uplanet.listcmd ++application/vnd.uplanet.listcmd-wbxml ++application/vnd.uplanet.signal ++application/vnd.vcx vcx ++# sxi: application/vnd.sun.xml.impress ++application/vnd.vd-study mxi study-inter model-inter ++# mcd: application/vnd.mcd ++application/vnd.vectorworks vwx ++application/vnd.verimatrix.vcas ++application/vnd.vidsoft.vidconference vsc ++application/vnd.visio vsd vst vsw vss ++application/vnd.visionary vis ++# vsc: application/vnd.vidsoft.vidconference ++application/vnd.vividence.scriptfile ++application/vnd.vsf vsf ++application/vnd.wap.sic sic ++application/vnd.wap.slc slc ++application/vnd.wap.wbxml wbxml ++application/vnd.wap.wmlc wmlc ++application/vnd.wap.wmlscriptc wmlsc ++application/vnd.webturbo wtb ++application/vnd.wfa.wsc wsc ++application/vnd.wmc wmc ++application/vnd.wmf.bootstrap ++# nb: application/mathematica for now ++application/vnd.wolfram.mathematica ++application/vnd.wolfram.mathematica.package m ++application/vnd.wolfram.player nbp ++application/vnd.wordperfect wpd ++application/vnd.wqd wqd ++application/vnd.wrq-hp3000-labelled ++application/vnd.wt.stf stf ++application/vnd.wv.csp+xml ++application/vnd.wv.csp+wbxml wv ++application/vnd.wv.ssp+xml ++application/vnd.xara xar ++application/vnd.xfdl xfdl xfd ++application/vnd.xfdl.webform ++application/vnd.xmi+xml ++application/vnd.xmpie.cpkg cpkg ++application/vnd.xmpie.dpkg dpkg ++# dpkg: application/vnd.xmpie.dpkg ++application/vnd.xmpie.plan ++application/vnd.xmpie.ppkg ppkg ++application/vnd.xmpie.xlim xlim ++application/vnd.yamaha.hv-dic hvd ++application/vnd.yamaha.hv-script hvs ++application/vnd.yamaha.hv-voice hvp ++application/vnd.yamaha.openscoreformat osf ++application/vnd.yamaha.openscoreformat.osfpvg+xml ++application/vnd.yamaha.remote-setup ++application/vnd.yamaha.smaf-audio saf ++application/vnd.yamaha.smaf-phrase spf ++application/vnd.yamaha.tunnel-udpencap ++application/vnd.yellowriver-custom-menu cmp ++application/vnd.zul zir zirz ++application/vnd.zzazz.deck+xml zaz ++application/voicexml+xml vxml ++application/vq-rtcp-xr ++application/watcherinfo+xml wif ++application/whoispp-query ++application/whoispp-response ++application/widget wgt ++application/wita ++application/wordperfect5.1 ++application/wsdl+xml wsdl ++application/wspolicy+xml wspolicy ++application/x400-bp ++application/xcap-att+xml xav ++application/xcap-caps+xml xca ++application/xcap-diff+xml xdf ++application/xcap-el+xml xel ++application/xcap-error+xml xer ++application/xcap-ns+xml xns ++application/xcon-conference-info-diff+xml ++application/xcon-conference-info+xml ++application/xenc+xml ++application/xhtml+xml xhtml xhtm xht ++# application/xhtml-voice+xml obsoleted by application/xv+xml ++# xml, xsd, rng: text/xml ++application/xml ++# mod: audio/x-mod ++application/xml-dtd dtd ++# ent: text/xml-external-parsed-entity ++application/xml-external-parsed-entity ++application/xmpp+xml ++application/xop+xml xop ++application/xslt+xml xsl xslt ++application/xv+xml mxml xhvml xvml xvm ++application/yang yang ++application/yin+xml yin ++application/zip zip ++audio/1d-interleaved-parityfec ++audio/32kadpcm 726 ++# 3gp, 3gpp: video/3gpp ++audio/3gpp ++# 3g2, 3gpp2: video/3gpp2 ++audio/3gpp2 ++audio/ac3 ac3 ++audio/AMR amr ++audio/AMR-WB awb ++audio/amr-wb+ ++audio/asc acn ++# aa3, omg: audio/ATRAC3 ++audio/ATRAC-ADVANCED-LOSSLESS aal ++# aa3, omg: audio/ATRAC3 ++audio/ATRAC-X atx ++audio/ATRAC3 at3 aa3 omg ++audio/basic au snd ++audio/BV16 ++audio/BV32 ++audio/clearmode ++audio/CN ++audio/DAT12 ++audio/dls dls ++audio/dsr-es201108 ++audio/dsr-es202050 ++audio/dsr-es202211 ++audio/dsr-es202212 ++audio/DVI4 ++audio/eac3 ++audio/EVRC evc ++# qcp: audio/qcelp ++audio/EVRC-QCP ++audio/EVRC0 ++audio/EVRC1 ++audio/EVRCB evb ++audio/EVRCB0 ++audio/EVRCWB evw ++audio/EVRCWB0 ++audio/EVRCWB1 ++audio/G719 ++audio/G722 ++audio/G7221 ++audio/G723 ++audio/G726-16 ++audio/G726-24 ++audio/G726-32 ++audio/G726-40 ++audio/G728 ++audio/G729 ++audio/G7291 ++audio/G729D ++audio/G729E ++audio/GSM ++audio/GSM-EFR ++audio/GSM-HR-08 ++audio/iLBC lbc ++audio/ip-mr_v2.5 ++# wav: audio/wav ++audio/L16 l16 ++audio/L20 ++audio/L24 ++audio/L8 ++audio/LPC ++audio/mobile-xmf mxmf ++# mp4, mpg4: video/mp4, see RFC 4337 ++audio/mp4 ++audio/MP4A-LATM ++audio/MPA ++audio/mpa-robust ++audio/mpeg mp3 mpga mp1 mp2 ++audio/mpeg4-generic ++audio/ogg oga ogg spx ++audio/parityfec ++audio/PCMA ++audio/PCMA-WB ++audio/PCMU ++audio/PCMU-WB ++audio/prs.sid sid psid ++audio/qcelp qcp ++audio/RED ++audio/rtp-enc-aescm128 ++audio/rtp-midi ++audio/rtx ++audio/SMV smv ++# qcp: audio/qcelp, see RFC 3625 ++audio/SMV-QCP ++audio/SMV0 ++# mid: audio/midi ++audio/sp-midi ++audio/speex ++audio/t140c ++audio/t38 ++audio/telephone-event ++audio/tone ++audio/UEMCLIP ++audio/ulpfec ++audio/VDVI ++audio/VMR-WB ++audio/vnd.3gpp.iufp ++audio/vnd.4SB ++audio/vnd.audikoz koz ++audio/vnd.CELP ++audio/vnd.cisco.nse ++audio/vnd.cmles.radio-events ++audio/vnd.cns.anp1 ++audio/vnd.cns.inf1 ++audio/vnd.dece.audio uva uvva ++audio/vnd.digital-winds eol ++audio/vnd.dlna.adts ++audio/vnd.dolby.heaac.1 ++audio/vnd.dolby.heaac.2 ++audio/vnd.dolby.mlp mlp ++audio/vnd.dolby.mps ++audio/vnd.dolby.pl2 ++audio/vnd.dolby.pl2x ++audio/vnd.dolby.pl2z ++audio/vnd.dolby.pulse.1 ++audio/vnd.dra ++# wav: audio/wav, cpt: application/mac-compactpro ++audio/vnd.dts dts ++audio/vnd.dts.hd dtshd ++audio/vnd.dvb.file dvb ++audio/vnd.everad.plj plj ++# rm: audio/x-pn-realaudio ++audio/vnd.hns.audio ++audio/vnd.lucent.voice lvp ++audio/vnd.ms-playready.media.pya pya ++# mxmf: audio/mobile-xmf ++audio/vnd.nokia.mobile-xmf ++audio/vnd.nortel.vbk vbk ++audio/vnd.nuera.ecelp4800 ecelp4800 ++audio/vnd.nuera.ecelp7470 ecelp7470 ++audio/vnd.nuera.ecelp9600 ecelp9600 ++audio/vnd.octel.sbc ++# audio/vnd.qcelp deprecated in favour of audio/qcelp ++audio/vnd.rhetorex.32kadpcm ++audio/vnd.rip rip ++audio/vnd.sealedmedia.softseal.mpeg smp3 smp s1m ++audio/vnd.vmx.cvsd ++audio/vorbis ++audio/vorbis-config ++image/cgm ++image/fits fits fit fts ++image/g3fax ++image/gif gif ++image/ief ief ++image/jp2 jp2 jpg2 ++image/jpeg jpg jpeg jpe jfif ++image/jpm jpm jpgm ++image/jpx jpx jpf ++image/ktx ktx ++image/naplps ++image/png png ++image/prs.btif btif btf ++image/prs.pti pti ++image/svg+xml svg svgz ++image/t38 t38 ++image/tiff tiff tif ++image/tiff-fx tfx ++image/vnd.adobe.photoshop psd ++image/vnd.cns.inf2 ++image/vnd.dece.graphic uvi uvvi uvg uvvg ++image/vnd.djvu djvu djv ++image/vnd.dvb.subtitle sub ++image/vnd.dwg ++image/vnd.dxf dxf ++image/vnd.fastbidsheet fbs ++image/vnd.fpx fpx ++image/vnd.fst fst ++image/vnd.fujixerox.edmics-mmr mmr ++image/vnd.fujixerox.edmics-rlc rlc ++image/vnd.globalgraphics.pgb pgb ++image/vnd.microsoft.icon ico ++image/vnd.mix ++image/vnd.ms-modi mdi ++image/vnd.net-fpx ++image/vnd.radiance hdr rgbe xyze ++image/vnd.sealed.png spng spn s1n ++image/vnd.sealedmedia.softseal.gif sgif sgi s1g ++image/vnd.sealedmedia.softseal.jpg sjpg sjp s1j ++image/vnd.svf ++image/vnd.wap.wbmp wbmp ++image/vnd.xiff xif ++message/CPIM ++message/delivery-status ++message/disposition-notification ++message/external-body ++message/feedback-report ++message/global u8msg ++message/global-delivery-status u8dsn ++message/global-disposition-notification u8mdn ++message/global-headers u8hdr ++message/http ++# cl: application/simple-filter+xml ++message/imdn+xml ++# message/news obsoleted by message/rfc822 ++message/partial ++message/rfc822 eml mail art ++message/s-http ++message/sip ++message/sipfrag ++message/tracking-status ++message/vnd.si.simp ++model/iges igs iges ++model/mesh msh mesh silo ++model/vnd.collada+xml dae ++model/vnd.dwf dwf ++# 3dml, 3dm: text/vnd.in3d.3dml ++model/vnd.flatland.3dml ++model/vnd.gdl gdl gsm win dor lmp rsm msm ism ++model/vnd.gs-gdl ++model/vnd.gtw gtw ++model/vnd.moml+xml moml ++model/vnd.mts mts ++model/vnd.parasolid.transmit.binary x_b xmt_bin ++model/vnd.parasolid.transmit.text x_t xmt_txt ++model/vnd.vtu vtu ++model/vrml wrl vrml ++multipart/alternative ++multipart/appledouble ++multipart/byteranges ++multipart/digest ++multipart/encrypted ++multipart/form-data ++multipart/header-set ++multipart/mixed ++multipart/parallel ++multipart/related ++multipart/report ++multipart/signed ++multipart/voice-message vpm ++text/1d-interleaved-parityfec ++text/calendar ics ifb ++text/css css ++text/csv csv ++text/directory ++text/dns soa zone ++# text/ecmascript obsoleted by application/ecmascript ++text/enriched ++text/html html htm ++# text/javascript obsoleted by application/javascript ++text/n3 n3 ++text/parityfec ++text/plain txt asc text pm el c h cc hh cxx hxx f90 ++text/prs.fallenstein.rst rst ++text/prs.lines.tag tag dsc ++text/RED ++text/rfc822-headers ++text/richtext rtx ++# rtf: application/rtf ++text/rtf ++text/rtp-enc-aescm128 ++text/rtx ++text/sgml sgml sgm ++text/t140 ++text/tab-separated-values tsv ++text/troff ++text/turtle ttl ++text/ulpfec ++text/uri-list uris uri ++text/vnd.abc abc ++# curl: application/vnd.curl ++text/vnd.curl ++text/vnd.DMClientScript dms ++text/vnd.esmertec.theme-descriptor jtd ++text/vnd.fly fly ++text/vnd.fmi.flexstor flx ++text/vnd.graphviz gv dot ++text/vnd.in3d.3dml 3dml 3dm ++text/vnd.in3d.spot spot spo ++text/vnd.IPTC.NewsML ++text/vnd.IPTC.NITF ++text/vnd.latex-z ++text/vnd.motorola.reflex ++text/vnd.ms-mediapackage mpf ++text/vnd.net2phone.commcenter.command ccc ++text/vnd.radisys.msml-basic-layout ++text/vnd.si.uricatalogue uric ++text/vnd.sun.j2me.app-descriptor jad ++text/vnd.trolltech.linguist ts ++text/vnd.wap.si si ++text/vnd.wap.sl sl ++text/vnd.wap.wml wml ++text/vnd.wap.wmlscript wmls ++text/xml xml xsd rng ++text/xml-external-parsed-entity ent ++video/1d-interleaved-parityfec ++video/3gpp 3gp 3gpp ++video/3gpp2 3g2 3gpp2 ++video/3gpp-tt ++video/BMPEG ++video/BT656 ++video/CelB ++video/DV ++video/H261 ++video/H263 ++video/H263-1998 ++video/H263-2000 ++video/H264 ++video/H264-RCDO ++video/H264-SVC ++video/JPEG ++video/jpeg2000 ++video/mj2 mj2 mjp2 ++video/MP1S ++video/MP2P ++video/MP2T ++video/mp4 mp4 mpg4 ++video/MP4V-ES ++video/mpeg mpeg mpg mpe ++video/mpeg4-generic ++video/MPV ++video/nv ++video/ogg ogv ++video/parityfec ++video/pointer ++video/quicktime mov qt ++video/raw ++video/rtp-enc-aescm128 ++video/rtx ++video/SMPTE292M ++video/ulpfec ++video/vc1 ++video/vnd.CCTV ++video/vnd.dece.hd uvh uvvh ++video/vnd.dece.mobile uvm uvvm ++video/vnd.dece.mp4 uvu uvvu ++video/vnd.dece.pd uvp uvvp ++video/vnd.dece.sd uvs uvvs ++video/vnd.dece.video uvv uvvv ++video/vnd.directv.mpeg ++video/vnd.directv.mpeg-tts ++video/vnd.dlna.mpeg-tts ++video/vnd.fvt fvt ++# rm: audio/x-pn-realaudio ++video/vnd.hns.video ++video/vnd.iptvforum.1dparityfec-1010 ++video/vnd.iptvforum.1dparityfec-2005 ++video/vnd.iptvforum.2dparityfec-1010 ++video/vnd.iptvforum.2dparityfec-2005 ++video/vnd.iptvforum.ttsavc ++video/vnd.iptvforum.ttsmpeg2 ++video/vnd.motorola.video ++video/vnd.motorola.videop ++video/vnd.mpegurl mxu m4u ++video/vnd.ms-playready.media.pyv pyv ++video/vnd.nokia.interleaved-multimedia nim ++video/vnd.nokia.videovoip ++# mp4: video/mp4 ++video/vnd.objectvideo ++video/vnd.sealed.mpeg1 smpg s11 ++# smpg: video/vnd.sealed.mpeg1 ++video/vnd.sealed.mpeg4 s14 ++video/vnd.sealed.swf sswf ssw ++video/vnd.sealedmedia.softseal.mov smov smo s1q ++# uvu, uvvu: video/vnd.dece.mp4 ++video/vnd.uvvu.mp4 ++video/vnd.vivo ++ ++# Non-IANA types ++ ++application/epub+zip epub ++application/mac-compactpro cpt ++application/metalink+xml metalink ++application/rss+xml rss ++application/vnd.android.package-archive apk ++application/vnd.oma.dd+xml dd ++application/vnd.oma.drm.content dcf ++# odf: application/vnd.oasis.opendocument.formula ++application/vnd.oma.drm.dcf o4a o4v ++application/vnd.oma.drm.message dm ++application/vnd.oma.drm.rights+wbxml drc ++application/vnd.oma.drm.rights+xml dr ++application/vnd.sun.xml.calc sxc ++application/vnd.sun.xml.calc.template stc ++application/vnd.sun.xml.draw sxd ++application/vnd.sun.xml.draw.template std ++application/vnd.sun.xml.impress sxi ++application/vnd.sun.xml.impress.template sti ++application/vnd.sun.xml.math sxm ++application/vnd.sun.xml.writer sxw ++application/vnd.sun.xml.writer.global sxg ++application/vnd.sun.xml.writer.template stw ++application/vnd.symbian.install sis ++application/vnd.wap.mms-message mms ++application/x-annodex anx ++application/x-bcpio bcpio ++application/x-bittorrent torrent ++application/x-bzip2 bz2 ++application/x-cdlink vcd ++application/x-chess-pgn pgn ++application/x-cpio cpio ++application/x-csh csh ++application/x-director dcr dir dxr ++application/x-dvi dvi ++application/x-futuresplash spl ++application/x-gtar gtar ++application/x-gzip gz tgz ++application/x-hdf hdf ++application/x-java-archive jar ++application/x-java-jnlp-file jnlp ++application/x-java-pack200 pack ++application/x-killustrator kil ++application/x-latex latex ++application/x-netcdf nc cdf ++application/x-perl pl ++application/x-rpm rpm ++application/x-sh sh ++application/x-shar shar ++application/x-shockwave-flash swf ++application/x-stuffit sit ++application/x-sv4cpio sv4cpio ++application/x-sv4crc sv4crc ++application/x-tar tar ++application/x-tcl tcl ++application/x-tex tex ++application/x-texinfo texinfo texi ++application/x-troff t tr roff ++application/x-troff-man man 1 2 3 4 5 6 7 8 ++application/x-troff-me me ++application/x-troff-ms ms ++application/x-ustar ustar ++application/x-wais-source src ++application/x-xpinstall xpi ++application/x-xspf+xml xspf ++application/x-xz xz ++audio/midi mid midi kar ++audio/x-aiff aif aiff aifc ++audio/x-annodex axa ++audio/x-flac flac ++audio/x-mod mod ult uni m15 mtm 669 med ++audio/x-mpegurl m3u ++audio/x-ms-wax wax ++audio/x-ms-wma wma ++audio/x-pn-realaudio ram rm ++audio/x-realaudio ra ++audio/x-s3m s3m ++audio/x-stm stm ++audio/x-wav wav ++chemical/x-xyz xyz ++image/bmp bmp ++image/x-cmu-raster ras ++image/x-portable-anymap pnm ++image/x-portable-bitmap pbm ++image/x-portable-graymap pgm ++image/x-portable-pixmap ppm ++image/x-rgb rgb ++image/x-targa tga ++image/x-xbitmap xbm ++image/x-xpixmap xpm ++image/x-xwindowdump xwd ++text/cache-manifest manifest ++text/html-sandboxed sandboxed ++text/x-pod pod ++text/x-setext etx ++text/x-vcard vcf ++video/webm webm ++video/x-annodex axv ++video/x-flv flv ++video/x-javafx fxm ++video/x-ms-asf asx ++video/x-ms-wm wm ++video/x-ms-wmv wmv ++video/x-ms-wmx wmx ++video/x-ms-wvx wvx ++video/x-msvideo avi ++video/x-sgi-movie movie ++x-conference/x-cooltalk ice ++x-epoc/x-sisx-app sisx +diff -r 137e45f15c0b Lib/test/nokia.pem +--- /dev/null ++++ b/Lib/test/nokia.pem +@@ -0,0 +1,31 @@ ++# Certificate for projects.developer.nokia.com:443 (see issue 13034) ++-----BEGIN CERTIFICATE----- ++MIIFLDCCBBSgAwIBAgIQLubqdkCgdc7lAF9NfHlUmjANBgkqhkiG9w0BAQUFADCB ++vDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL ++ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2Ug ++YXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykxMDE2MDQGA1UEAxMt ++VmVyaVNpZ24gQ2xhc3MgMyBJbnRlcm5hdGlvbmFsIFNlcnZlciBDQSAtIEczMB4X ++DTExMDkyMTAwMDAwMFoXDTEyMDkyMDIzNTk1OVowcTELMAkGA1UEBhMCRkkxDjAM ++BgNVBAgTBUVzcG9vMQ4wDAYDVQQHFAVFc3BvbzEOMAwGA1UEChQFTm9raWExCzAJ ++BgNVBAsUAkJJMSUwIwYDVQQDFBxwcm9qZWN0cy5kZXZlbG9wZXIubm9raWEuY29t ++MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCr92w1bpHYSYxUEx8N/8Iddda2 ++lYi+aXNtQfV/l2Fw9Ykv3Ipw4nLeGTj18FFlAZgMdPRlgrzF/NNXGw/9l3/qKdow ++CypkQf8lLaxb9Ze1E/KKmkRJa48QTOqvo6GqKuTI6HCeGlG1RxDb8YSKcQWLiytn ++yj3Wp4MgRQO266xmMQIDAQABo4IB9jCCAfIwQQYDVR0RBDowOIIccHJvamVjdHMu ++ZGV2ZWxvcGVyLm5va2lhLmNvbYIYcHJvamVjdHMuZm9ydW0ubm9raWEuY29tMAkG ++A1UdEwQCMAAwCwYDVR0PBAQDAgWgMEEGA1UdHwQ6MDgwNqA0oDKGMGh0dHA6Ly9T ++VlJJbnRsLUczLWNybC52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNybDBEBgNVHSAE ++PTA7MDkGC2CGSAGG+EUBBxcDMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZl ++cmlzaWduLmNvbS9ycGEwKAYDVR0lBCEwHwYJYIZIAYb4QgQBBggrBgEFBQcDAQYI ++KwYBBQUHAwIwcgYIKwYBBQUHAQEEZjBkMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz ++cC52ZXJpc2lnbi5jb20wPAYIKwYBBQUHMAKGMGh0dHA6Ly9TVlJJbnRsLUczLWFp ++YS52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNlcjBuBggrBgEFBQcBDARiMGChXqBc ++MFowWDBWFglpbWFnZS9naWYwITAfMAcGBSsOAwIaBBRLa7kolgYMu9BSOJsprEsH ++iyEFGDAmFiRodHRwOi8vbG9nby52ZXJpc2lnbi5jb20vdnNsb2dvMS5naWYwDQYJ ++KoZIhvcNAQEFBQADggEBACQuPyIJqXwUyFRWw9x5yDXgMW4zYFopQYOw/ItRY522 ++O5BsySTh56BWS6mQB07XVfxmYUGAvRQDA5QHpmY8jIlNwSmN3s8RKo+fAtiNRlcL ++x/mWSfuMs3D/S6ev3D6+dpEMZtjrhOdctsarMKp8n/hPbwhAbg5hVjpkW5n8vz2y ++0KxvvkA1AxpLwpVv7OlK17ttzIHw8bp9HTlHBU5s8bKz4a565V/a5HI0CSEv/+0y ++ko4/ghTnZc1CkmUngKKeFMSah/mT/xAh8XnE2l1AazFa8UKuYki1e+ArHaGZc4ix ++UYOtiRphwfuYQhRZ7qX9q2MMkCMI65XNK/SaFrAbbG0= ++-----END CERTIFICATE----- +diff -r 137e45f15c0b Lib/test/pickletester.py +--- a/Lib/test/pickletester.py ++++ b/Lib/test/pickletester.py +@@ -2,10 +2,14 @@ + import unittest + import pickle + import pickletools ++import sys + import copyreg + from http.cookies import SimpleCookie + +-from test.support import TestFailed, TESTFN, run_with_locale ++from test.support import ( ++ TestFailed, TESTFN, run_with_locale, ++ _2G, _4G, bigmemtest, ++ ) + + from pickle import bytes_types + +@@ -14,6 +18,8 @@ + # kind of outer loop. + protocols = range(pickle.HIGHEST_PROTOCOL + 1) + ++character_size = 4 if sys.maxunicode > 0xFFFF else 2 ++ + + # Return True if opcode code appears in the pickle, else False. + def opcode_in_pickle(code, pickle): +@@ -115,6 +121,19 @@ + class use_metaclass(object, metaclass=metaclass): + pass + ++class pickling_metaclass(type): ++ def __eq__(self, other): ++ return (type(self) == type(other) and ++ self.reduce_args == other.reduce_args) ++ ++ def __reduce__(self): ++ return (create_dynamic_class, self.reduce_args) ++ ++def create_dynamic_class(name, bases): ++ result = pickling_metaclass(name, bases, dict()) ++ result.reduce_args = (name, bases) ++ return result ++ + # DATA0 .. DATA2 are the pickles we expect under the various protocols, for + # the object returned by create_data(). + +@@ -617,9 +636,15 @@ + + def test_bytes(self): + for proto in protocols: +- for u in b'', b'xyz', b'xyz'*100: +- p = self.dumps(u) +- self.assertEqual(self.loads(p), u) ++ for s in b'', b'xyz', b'xyz'*100: ++ p = self.dumps(s) ++ self.assertEqual(self.loads(p), s) ++ for s in [bytes([i]) for i in range(256)]: ++ p = self.dumps(s) ++ self.assertEqual(self.loads(p), s) ++ for s in [bytes([i, i]) for i in range(256)]: ++ p = self.dumps(s) ++ self.assertEqual(self.loads(p), s) + + def test_ints(self): + import sys +@@ -689,6 +714,14 @@ + b = self.loads(s) + self.assertEqual(a.__class__, b.__class__) + ++ def test_dynamic_class(self): ++ a = create_dynamic_class("my_dynamic_class", (object,)) ++ copyreg.pickle(pickling_metaclass, pickling_metaclass.__reduce__) ++ for proto in protocols: ++ s = self.dumps(a, proto) ++ b = self.loads(s) ++ self.assertEqual(a, b) ++ + def test_structseq(self): + import time + import os +@@ -1098,6 +1131,117 @@ + empty = self.loads(b'\x80\x03U\x00q\x00.', encoding='koi8-r') + self.assertEqual(empty, '') + ++ def check_negative_32b_binXXX(self, dumped): ++ if sys.maxsize > 2**32: ++ self.skipTest("test is only meaningful on 32-bit builds") ++ # XXX Pure Python pickle reads lengths as signed and passes ++ # them directly to read() (hence the EOFError) ++ with self.assertRaises((pickle.UnpicklingError, EOFError, ++ ValueError, OverflowError)): ++ self.loads(dumped) ++ ++ def test_negative_32b_binbytes(self): ++ # On 32-bit builds, a BINBYTES of 2**31 or more is refused ++ self.check_negative_32b_binXXX(b'\x80\x03B\xff\xff\xff\xffxyzq\x00.') ++ ++ def test_negative_32b_binunicode(self): ++ # On 32-bit builds, a BINUNICODE of 2**31 or more is refused ++ self.check_negative_32b_binXXX(b'\x80\x03X\xff\xff\xff\xffxyzq\x00.') ++ ++ def test_negative_put(self): ++ # Issue #12847 ++ dumped = b'Va\np-1\n.' ++ self.assertRaises(ValueError, self.loads, dumped) ++ ++ def test_negative_32b_binput(self): ++ # Issue #12847 ++ if sys.maxsize > 2**32: ++ self.skipTest("test is only meaningful on 32-bit builds") ++ dumped = b'\x80\x03X\x01\x00\x00\x00ar\xff\xff\xff\xff.' ++ self.assertRaises(ValueError, self.loads, dumped) ++ ++ ++class BigmemPickleTests(unittest.TestCase): ++ ++ # Binary protocols can serialize longs of up to 2GB-1 ++ ++ @bigmemtest(size=_2G, memuse=1 + 1, dry_run=False) ++ def test_huge_long_32b(self, size): ++ data = 1 << (8 * size) ++ try: ++ for proto in protocols: ++ if proto < 2: ++ continue ++ with self.assertRaises((ValueError, OverflowError)): ++ self.dumps(data, protocol=proto) ++ finally: ++ data = None ++ ++ # Protocol 3 can serialize up to 4GB-1 as a bytes object ++ # (older protocols don't have a dedicated opcode for bytes and are ++ # too inefficient) ++ ++ @bigmemtest(size=_2G, memuse=1 + 1, dry_run=False) ++ def test_huge_bytes_32b(self, size): ++ data = b"abcd" * (size // 4) ++ try: ++ for proto in protocols: ++ if proto < 3: ++ continue ++ try: ++ pickled = self.dumps(data, protocol=proto) ++ self.assertTrue(b"abcd" in pickled[:15]) ++ self.assertTrue(b"abcd" in pickled[-15:]) ++ finally: ++ pickled = None ++ finally: ++ data = None ++ ++ @bigmemtest(size=_4G, memuse=1 + 1, dry_run=False) ++ def test_huge_bytes_64b(self, size): ++ data = b"a" * size ++ try: ++ for proto in protocols: ++ if proto < 3: ++ continue ++ with self.assertRaises((ValueError, OverflowError)): ++ self.dumps(data, protocol=proto) ++ finally: ++ data = None ++ ++ # All protocols use 1-byte per printable ASCII character; we add another ++ # byte because the encoded form has to be copied into the internal buffer. ++ ++ @bigmemtest(size=_2G, memuse=2 + character_size, dry_run=False) ++ def test_huge_str_32b(self, size): ++ data = "abcd" * (size // 4) ++ try: ++ for proto in protocols: ++ try: ++ pickled = self.dumps(data, protocol=proto) ++ self.assertTrue(b"abcd" in pickled[:15]) ++ self.assertTrue(b"abcd" in pickled[-15:]) ++ finally: ++ pickled = None ++ finally: ++ data = None ++ ++ # BINUNICODE (protocols 1, 2 and 3) cannot carry more than ++ # 2**32 - 1 bytes of utf-8 encoded unicode. ++ ++ @bigmemtest(size=_4G, memuse=1 + character_size, dry_run=False) ++ def test_huge_str_64b(self, size): ++ data = "a" * size ++ try: ++ for proto in protocols: ++ if proto == 0: ++ continue ++ with self.assertRaises((ValueError, OverflowError)): ++ self.dumps(data, protocol=proto) ++ finally: ++ data = None ++ ++ + # Test classes for reduce_ex + + class REX_one(object): +diff -r 137e45f15c0b Lib/test/regrtest.py +--- a/Lib/test/regrtest.py ++++ b/Lib/test/regrtest.py +@@ -165,6 +165,7 @@ + import platform + import random + import re ++import shutil + import sys + import sysconfig + import tempfile +@@ -887,6 +888,7 @@ + 'os.environ', 'sys.path', 'sys.path_hooks', '__import__', + 'warnings.filters', 'asyncore.socket_map', + 'logging._handlers', 'logging._handlerList', ++ 'shutil.archive_formats', 'shutil.unpack_formats', + 'sys.warnoptions', 'threading._dangling', + 'multiprocessing.process._dangling') + +@@ -956,6 +958,23 @@ + asyncore.close_all(ignore_all=True) + asyncore.socket_map.update(saved_map) + ++ def get_shutil_archive_formats(self): ++ # we could call get_archives_formats() but that only returns the ++ # registry keys; we want to check the values too (the functions that ++ # are registered) ++ return shutil._ARCHIVE_FORMATS, shutil._ARCHIVE_FORMATS.copy() ++ def restore_shutil_archive_formats(self, saved): ++ shutil._ARCHIVE_FORMATS = saved[0] ++ shutil._ARCHIVE_FORMATS.clear() ++ shutil._ARCHIVE_FORMATS.update(saved[1]) ++ ++ def get_shutil_unpack_formats(self): ++ return shutil._UNPACK_FORMATS, shutil._UNPACK_FORMATS.copy() ++ def restore_shutil_unpack_formats(self, saved): ++ shutil._UNPACK_FORMATS = saved[0] ++ shutil._UNPACK_FORMATS.clear() ++ shutil._UNPACK_FORMATS.update(saved[1]) ++ + def get_logging__handlers(self): + # _handlers is a WeakValueDictionary + return id(logging._handlers), logging._handlers, logging._handlers.copy() +@@ -1255,6 +1274,13 @@ + filecmp._cache.clear() + struct._clearcache() + doctest.master = None ++ try: ++ import ctypes ++ except ImportError: ++ # Don't worry about resetting the cache if ctypes is not supported ++ pass ++ else: ++ ctypes._reset_cache() + + # Collect cyclic trash. + gc.collect() +diff -r 137e45f15c0b Lib/test/string_tests.py +--- a/Lib/test/string_tests.py ++++ b/Lib/test/string_tests.py +@@ -641,6 +641,23 @@ + self.checkequal('Aaaa', 'aaaa', 'capitalize') + self.checkequal('Aaaa', 'AaAa', 'capitalize') + ++ # check that titlecased chars are lowered correctly ++ # \u1ffc is the titlecased char ++ self.checkequal('\u1ffc\u1ff3\u1ff3\u1ff3', ++ '\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize') ++ # check with cased non-letter chars ++ self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd', ++ '\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize') ++ self.checkequal('\u24c5\u24e8\u24e3\u24d7\u24de\u24dd', ++ '\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize') ++ self.checkequal('\u2160\u2171\u2172', ++ '\u2160\u2161\u2162', 'capitalize') ++ self.checkequal('\u2160\u2171\u2172', ++ '\u2170\u2171\u2172', 'capitalize') ++ # check with Ll chars with no upper - nothing changes here ++ self.checkequal('\u019b\u1d00\u1d86\u0221\u1fb7', ++ '\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize') ++ + self.checkraises(TypeError, 'hello', 'capitalize', 42) + + def test_lower(self): +diff -r 137e45f15c0b Lib/test/support.py +--- a/Lib/test/support.py ++++ b/Lib/test/support.py +@@ -877,6 +877,7 @@ + ] + default_gai_errnos = [ + ('EAI_AGAIN', -3), ++ ('EAI_FAIL', -4), + ('EAI_NONAME', -2), + ('EAI_NODATA', -5), + # Encountered when trying to resolve IPv6-only hostnames +@@ -1053,45 +1054,54 @@ + raise ValueError('Memory limit %r too low to be useful' % (limit,)) + max_memuse = memlimit + +-def bigmemtest(minsize, memuse): ++def _memory_watchdog(start_evt, finish_evt, period=10.0): ++ """A function which periodically watches the process' memory consumption ++ and prints it out. ++ """ ++ # XXX: because of the GIL, and because the very long operations tested ++ # in most bigmem tests are uninterruptible, the loop below gets woken up ++ # much less often than expected. ++ # The polling code should be rewritten in raw C, without holding the GIL, ++ # and push results onto an anonymous pipe. ++ try: ++ page_size = os.sysconf('SC_PAGESIZE') ++ except (ValueError, AttributeError): ++ try: ++ page_size = os.sysconf('SC_PAGE_SIZE') ++ except (ValueError, AttributeError): ++ page_size = 4096 ++ procfile = '/proc/{pid}/statm'.format(pid=os.getpid()) ++ try: ++ f = open(procfile, 'rb') ++ except IOError as e: ++ warnings.warn('/proc not available for stats: {}'.format(e), ++ RuntimeWarning) ++ sys.stderr.flush() ++ return ++ with f: ++ start_evt.set() ++ old_data = -1 ++ while not finish_evt.wait(period): ++ f.seek(0) ++ statm = f.read().decode('ascii') ++ data = int(statm.split()[5]) ++ if data != old_data: ++ old_data = data ++ print(" ... process data size: {data:.1f}G" ++ .format(data=data * page_size / (1024 ** 3))) ++ ++def bigmemtest(size, memuse, dry_run=True): + """Decorator for bigmem tests. + + 'minsize' is the minimum useful size for the test (in arbitrary, + test-interpreted units.) 'memuse' is the number of 'bytes per size' for + the test, or a good estimate of it. + +- The decorator tries to guess a good value for 'size' and passes it to +- the decorated test function. If minsize * memuse is more than the +- allowed memory use (as defined by max_memuse), the test is skipped. +- Otherwise, minsize is adjusted upward to use up to max_memuse. ++ if 'dry_run' is False, it means the test doesn't support dummy runs ++ when -M is not specified. + """ + def decorator(f): + def wrapper(self): +- # Retrieve values in case someone decided to adjust them +- minsize = wrapper.minsize +- memuse = wrapper.memuse +- if not max_memuse: +- # If max_memuse is 0 (the default), +- # we still want to run the tests with size set to a few kb, +- # to make sure they work. We still want to avoid using +- # too much memory, though, but we do that noisily. +- maxsize = 5147 +- self.assertFalse(maxsize * memuse > 20 * _1M) +- else: +- maxsize = int(max_memuse / memuse) +- if maxsize < minsize: +- raise unittest.SkipTest( +- "not enough memory: %.1fG minimum needed" +- % (minsize * memuse / (1024 ** 3))) +- return f(self, maxsize) +- wrapper.minsize = minsize +- wrapper.memuse = memuse +- return wrapper +- return decorator +- +-def precisionbigmemtest(size, memuse): +- def decorator(f): +- def wrapper(self): + size = wrapper.size + memuse = wrapper.memuse + if not real_max_memuse: +@@ -1099,12 +1109,34 @@ + else: + maxsize = size + +- if real_max_memuse and real_max_memuse < maxsize * memuse: +- raise unittest.SkipTest( +- "not enough memory: %.1fG minimum needed" +- % (size * memuse / (1024 ** 3))) ++ if ((real_max_memuse or not dry_run) ++ and real_max_memuse < maxsize * memuse): ++ raise unittest.SkipTest( ++ "not enough memory: %.1fG minimum needed" ++ % (size * memuse / (1024 ** 3))) + +- return f(self, maxsize) ++ if real_max_memuse and verbose and threading: ++ print() ++ print(" ... expected peak memory use: {peak:.1f}G" ++ .format(peak=size * memuse / (1024 ** 3))) ++ sys.stdout.flush() ++ start_evt = threading.Event() ++ finish_evt = threading.Event() ++ t = threading.Thread(target=_memory_watchdog, ++ args=(start_evt, finish_evt, 0.5)) ++ t.daemon = True ++ t.start() ++ start_evt.set() ++ else: ++ t = None ++ ++ try: ++ return f(self, maxsize) ++ finally: ++ if t: ++ finish_evt.set() ++ t.join() ++ + wrapper.size = size + wrapper.memuse = memuse + return wrapper +diff -r 137e45f15c0b Lib/test/test_argparse.py +--- a/Lib/test/test_argparse.py ++++ b/Lib/test/test_argparse.py +@@ -1502,6 +1502,8 @@ + return self.name == other.name + + ++@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, ++ "non-root user required") + class TestFileTypeW(TempDirMixin, ParserTestCase): + """Test the FileType option/argument type for writing files""" + +diff -r 137e45f15c0b Lib/test/test_ast.py +--- a/Lib/test/test_ast.py ++++ b/Lib/test/test_ast.py +@@ -290,7 +290,7 @@ + self.assertEqual(x.body, body) + + def test_nodeclasses(self): +- # Zero arguments constructor explicitely allowed ++ # Zero arguments constructor explicitly allowed + x = ast.BinOp() + self.assertEqual(x._fields, ('left', 'op', 'right')) + +@@ -486,6 +486,17 @@ + self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j) + self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j) + ++ def test_bad_integer(self): ++ # issue13436: Bad error message with invalid numeric values ++ body = [ast.ImportFrom(module='time', ++ names=[ast.alias(name='sleep')], ++ level=None, ++ lineno=None, col_offset=None)] ++ mod = ast.Module(body) ++ with self.assertRaises(ValueError) as cm: ++ compile(mod, 'test', 'exec') ++ self.assertIn("invalid integer value: None", str(cm.exception)) ++ + + def test_main(): + support.run_unittest(AST_Tests, ASTHelpers_Test) +diff -r 137e45f15c0b Lib/test/test_bigmem.py +--- a/Lib/test/test_bigmem.py ++++ b/Lib/test/test_bigmem.py +@@ -1,5 +1,5 @@ + from test import support +-from test.support import bigmemtest, _1G, _2G, _4G, precisionbigmemtest ++from test.support import bigmemtest, _1G, _2G, _4G + + import unittest + import operator +@@ -25,10 +25,10 @@ + # a large object, make the subobject of a length that is not a power of + # 2. That way, int-wrapping problems are more easily detected. + # +-# - While the bigmemtest decorator speaks of 'minsize', all tests will +-# actually be called with a much smaller number too, in the normal +-# test run (5Kb currently.) This is so the tests themselves get frequent +-# testing. Consequently, always make all large allocations based on the ++# - Despite the bigmemtest decorator, all tests will actually be called ++# with a much smaller number too, in the normal test run (5Kb currently.) ++# This is so the tests themselves get frequent testing. ++# Consequently, always make all large allocations based on the + # passed-in 'size', and don't rely on the size being very large. Also, + # memuse-per-size should remain sane (less than a few thousand); if your + # test uses more, adjust 'size' upward, instead. +@@ -42,7 +42,7 @@ + + class BaseStrTest: + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_capitalize(self, size): + _ = self.from_latin1 + SUBSTR = self.from_latin1(' abc def ghi') +@@ -52,7 +52,7 @@ + SUBSTR.capitalize()) + self.assertEqual(caps.lstrip(_('-')), SUBSTR) + +- @bigmemtest(minsize=_2G + 10, memuse=1) ++ @bigmemtest(size=_2G + 10, memuse=1) + def test_center(self, size): + SUBSTR = self.from_latin1(' abc def ghi') + s = SUBSTR.center(size) +@@ -63,7 +63,7 @@ + self.assertEqual(s[lpadsize:-rpadsize], SUBSTR) + self.assertEqual(s.strip(), SUBSTR.strip()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_count(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -75,7 +75,7 @@ + self.assertEqual(s.count(_('i')), 1) + self.assertEqual(s.count(_('j')), 0) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_endswith(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -87,7 +87,7 @@ + self.assertFalse(s.endswith(_('a') + SUBSTR)) + self.assertFalse(SUBSTR.endswith(s)) + +- @bigmemtest(minsize=_2G + 10, memuse=2) ++ @bigmemtest(size=_2G + 10, memuse=2) + def test_expandtabs(self, size): + _ = self.from_latin1 + s = _('-') * size +@@ -100,7 +100,7 @@ + self.assertEqual(len(s), size - remainder) + self.assertEqual(len(s.strip(_(' '))), 0) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_find(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -117,7 +117,7 @@ + sublen + size + SUBSTR.find(_('i'))) + self.assertEqual(s.find(_('j')), -1) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_index(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -134,7 +134,7 @@ + sublen + size + SUBSTR.index(_('i'))) + self.assertRaises(ValueError, s.index, _('j')) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_isalnum(self, size): + _ = self.from_latin1 + SUBSTR = _('123456') +@@ -143,7 +143,7 @@ + s += _('.') + self.assertFalse(s.isalnum()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_isalpha(self, size): + _ = self.from_latin1 + SUBSTR = _('zzzzzzz') +@@ -152,7 +152,7 @@ + s += _('.') + self.assertFalse(s.isalpha()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_isdigit(self, size): + _ = self.from_latin1 + SUBSTR = _('123456') +@@ -161,7 +161,7 @@ + s += _('z') + self.assertFalse(s.isdigit()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_islower(self, size): + _ = self.from_latin1 + chars = _(''.join( +@@ -172,7 +172,7 @@ + s += _('A') + self.assertFalse(s.islower()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_isspace(self, size): + _ = self.from_latin1 + whitespace = _(' \f\n\r\t\v') +@@ -182,7 +182,7 @@ + s += _('j') + self.assertFalse(s.isspace()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_istitle(self, size): + _ = self.from_latin1 + SUBSTR = _('123456') +@@ -193,7 +193,7 @@ + s += _('aA') + self.assertFalse(s.istitle()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_isupper(self, size): + _ = self.from_latin1 + chars = _(''.join( +@@ -204,7 +204,7 @@ + s += _('a') + self.assertFalse(s.isupper()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_join(self, size): + _ = self.from_latin1 + s = _('A') * size +@@ -214,7 +214,7 @@ + self.assertTrue(x.startswith(_('aaaaaA'))) + self.assertTrue(x.endswith(_('Abbbbb'))) + +- @bigmemtest(minsize=_2G + 10, memuse=1) ++ @bigmemtest(size=_2G + 10, memuse=1) + def test_ljust(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -223,7 +223,7 @@ + self.assertEqual(len(s), size) + self.assertEqual(s.strip(), SUBSTR.strip()) + +- @bigmemtest(minsize=_2G + 10, memuse=2) ++ @bigmemtest(size=_2G + 10, memuse=2) + def test_lower(self, size): + _ = self.from_latin1 + s = _('A') * size +@@ -231,7 +231,7 @@ + self.assertEqual(len(s), size) + self.assertEqual(s.count(_('a')), size) + +- @bigmemtest(minsize=_2G + 10, memuse=1) ++ @bigmemtest(size=_2G + 10, memuse=1) + def test_lstrip(self, size): + _ = self.from_latin1 + SUBSTR = _('abc def ghi') +@@ -246,7 +246,7 @@ + stripped = s.lstrip() + self.assertTrue(stripped is s) + +- @bigmemtest(minsize=_2G + 10, memuse=2) ++ @bigmemtest(size=_2G + 10, memuse=2) + def test_replace(self, size): + _ = self.from_latin1 + replacement = _('a') +@@ -259,7 +259,7 @@ + self.assertEqual(s.count(replacement), 4) + self.assertEqual(s[-10:], _(' aaaa')) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_rfind(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -275,7 +275,7 @@ + SUBSTR.rfind(_('i'))) + self.assertEqual(s.rfind(_('j')), -1) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_rindex(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -294,7 +294,7 @@ + SUBSTR.rindex(_('i'))) + self.assertRaises(ValueError, s.rindex, _('j')) + +- @bigmemtest(minsize=_2G + 10, memuse=1) ++ @bigmemtest(size=_2G + 10, memuse=1) + def test_rjust(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -303,7 +303,7 @@ + self.assertEqual(len(s), size) + self.assertEqual(s.strip(), SUBSTR.strip()) + +- @bigmemtest(minsize=_2G + 10, memuse=1) ++ @bigmemtest(size=_2G + 10, memuse=1) + def test_rstrip(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -321,7 +321,7 @@ + # The test takes about size bytes to build a string, and then about + # sqrt(size) substrings of sqrt(size) in size and a list to + # hold sqrt(size) items. It's close but just over 2x size. +- @bigmemtest(minsize=_2G, memuse=2.1) ++ @bigmemtest(size=_2G, memuse=2.1) + def test_split_small(self, size): + _ = self.from_latin1 + # Crudely calculate an estimate so that the result of s.split won't +@@ -347,7 +347,7 @@ + # suffer for the list size. (Otherwise, it'd cost another 48 times + # size in bytes!) Nevertheless, a list of size takes + # 8*size bytes. +- @bigmemtest(minsize=_2G + 5, memuse=10) ++ @bigmemtest(size=_2G + 5, memuse=10) + def test_split_large(self, size): + _ = self.from_latin1 + s = _(' a') * size + _(' ') +@@ -359,7 +359,7 @@ + self.assertEqual(len(l), size + 1) + self.assertEqual(set(l), set([_(' ')])) + +- @bigmemtest(minsize=_2G, memuse=2.1) ++ @bigmemtest(size=_2G, memuse=2.1) + def test_splitlines(self, size): + _ = self.from_latin1 + # Crudely calculate an estimate so that the result of s.split won't +@@ -373,7 +373,7 @@ + for item in l: + self.assertEqual(item, expected) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_startswith(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi') +@@ -382,7 +382,7 @@ + self.assertTrue(s.startswith(_('-') * size)) + self.assertFalse(s.startswith(SUBSTR)) + +- @bigmemtest(minsize=_2G, memuse=1) ++ @bigmemtest(size=_2G, memuse=1) + def test_strip(self, size): + _ = self.from_latin1 + SUBSTR = _(' abc def ghi ') +@@ -394,7 +394,7 @@ + self.assertEqual(len(s), size) + self.assertEqual(s.strip(), SUBSTR.strip()) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_swapcase(self, size): + _ = self.from_latin1 + SUBSTR = _("aBcDeFG12.'\xa9\x00") +@@ -406,7 +406,7 @@ + self.assertEqual(s[:sublen * 3], SUBSTR.swapcase() * 3) + self.assertEqual(s[-sublen * 3:], SUBSTR.swapcase() * 3) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_title(self, size): + _ = self.from_latin1 + SUBSTR = _('SpaaHAaaAaham') +@@ -415,7 +415,7 @@ + self.assertTrue(s.startswith((SUBSTR * 3).title())) + self.assertTrue(s.endswith(SUBSTR.lower() * 3)) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_translate(self, size): + _ = self.from_latin1 + SUBSTR = _('aZz.z.Aaz.') +@@ -438,7 +438,7 @@ + self.assertEqual(s.count(_('!')), repeats * 2) + self.assertEqual(s.count(_('z')), repeats * 3) + +- @bigmemtest(minsize=_2G + 5, memuse=2) ++ @bigmemtest(size=_2G + 5, memuse=2) + def test_upper(self, size): + _ = self.from_latin1 + s = _('a') * size +@@ -446,7 +446,7 @@ + self.assertEqual(len(s), size) + self.assertEqual(s.count(_('A')), size) + +- @bigmemtest(minsize=_2G + 20, memuse=1) ++ @bigmemtest(size=_2G + 20, memuse=1) + def test_zfill(self, size): + _ = self.from_latin1 + SUBSTR = _('-568324723598234') +@@ -458,7 +458,7 @@ + + # This test is meaningful even with size < 2G, as long as the + # doubled string is > 2G (but it tests more if both are > 2G :) +- @bigmemtest(minsize=_1G + 2, memuse=3) ++ @bigmemtest(size=_1G + 2, memuse=3) + def test_concat(self, size): + _ = self.from_latin1 + s = _('.') * size +@@ -469,7 +469,7 @@ + + # This test is meaningful even with size < 2G, as long as the + # repeated string is > 2G (but it tests more if both are > 2G :) +- @bigmemtest(minsize=_1G + 2, memuse=3) ++ @bigmemtest(size=_1G + 2, memuse=3) + def test_repeat(self, size): + _ = self.from_latin1 + s = _('.') * size +@@ -478,7 +478,7 @@ + self.assertEqual(len(s), size * 2) + self.assertEqual(s.count(_('.')), size * 2) + +- @bigmemtest(minsize=_2G + 20, memuse=2) ++ @bigmemtest(size=_2G + 20, memuse=2) + def test_slice_and_getitem(self, size): + _ = self.from_latin1 + SUBSTR = _('0123456789') +@@ -512,7 +512,7 @@ + self.assertRaises(IndexError, operator.getitem, s, len(s) + 1) + self.assertRaises(IndexError, operator.getitem, s, len(s) + 1<<31) + +- @bigmemtest(minsize=_2G, memuse=2) ++ @bigmemtest(size=_2G, memuse=2) + def test_contains(self, size): + _ = self.from_latin1 + SUBSTR = _('0123456789') +@@ -526,7 +526,7 @@ + s += _('a') + self.assertIn(_('a'), s) + +- @bigmemtest(minsize=_2G + 10, memuse=2) ++ @bigmemtest(size=_2G + 10, memuse=2) + def test_compare(self, size): + _ = self.from_latin1 + s1 = _('-') * size +@@ -539,7 +539,7 @@ + s2 = _('.') * size + self.assertFalse(s1 == s2) + +- @bigmemtest(minsize=_2G + 10, memuse=1) ++ @bigmemtest(size=_2G + 10, memuse=1) + def test_hash(self, size): + # Not sure if we can do any meaningful tests here... Even if we + # start relying on the exact algorithm used, the result will be +@@ -590,46 +590,36 @@ + getattr(type(self), name).memuse = memuse + + # the utf8 encoder preallocates big time (4x the number of characters) +- @bigmemtest(minsize=_2G + 2, memuse=character_size + 4) ++ @bigmemtest(size=_2G + 2, memuse=character_size + 4) + def test_encode(self, size): + return self.basic_encode_test(size, 'utf-8') + +- @precisionbigmemtest(size=_4G // 6 + 2, memuse=character_size + 1) ++ @bigmemtest(size=_4G // 6 + 2, memuse=character_size + 1) + def test_encode_raw_unicode_escape(self, size): + try: + return self.basic_encode_test(size, 'raw_unicode_escape') + except MemoryError: + pass # acceptable on 32-bit + +- @precisionbigmemtest(size=_4G // 5 + 70, memuse=character_size + 1) ++ @bigmemtest(size=_4G // 5 + 70, memuse=character_size + 1) + def test_encode_utf7(self, size): + try: + return self.basic_encode_test(size, 'utf7') + except MemoryError: + pass # acceptable on 32-bit + +- @precisionbigmemtest(size=_4G // 4 + 5, memuse=character_size + 4) ++ @bigmemtest(size=_4G // 4 + 5, memuse=character_size + 4) + def test_encode_utf32(self, size): + try: + return self.basic_encode_test(size, 'utf32', expectedsize=4*size+4) + except MemoryError: + pass # acceptable on 32-bit + +- @precisionbigmemtest(size=_2G - 1, memuse=character_size + 1) ++ @bigmemtest(size=_2G - 1, memuse=character_size + 1) + def test_encode_ascii(self, size): + return self.basic_encode_test(size, 'ascii', c='A') + +- @precisionbigmemtest(size=_4G // 5, memuse=character_size * (6 + 1)) +- def test_unicode_repr_overflow(self, size): +- try: +- s = "\uDCBA"*size +- r = repr(s) +- except MemoryError: +- pass # acceptable on 32-bit +- else: +- self.assertTrue(s == eval(r)) +- +- @bigmemtest(minsize=_2G + 10, memuse=character_size * 2) ++ @bigmemtest(size=_2G + 10, memuse=character_size * 2) + def test_format(self, size): + s = '-' * size + sf = '%s' % (s,) +@@ -650,7 +640,7 @@ + self.assertEqual(s.count('.'), 3) + self.assertEqual(s.count('-'), size * 2) + +- @bigmemtest(minsize=_2G + 10, memuse=character_size * 2) ++ @bigmemtest(size=_2G + 10, memuse=character_size * 2) + def test_repr_small(self, size): + s = '-' * size + s = repr(s) +@@ -671,7 +661,7 @@ + self.assertEqual(s.count('\\'), size) + self.assertEqual(s.count('0'), size * 2) + +- @bigmemtest(minsize=_2G + 10, memuse=character_size * 5) ++ @bigmemtest(size=_2G + 10, memuse=character_size * 5) + def test_repr_large(self, size): + s = '\x00' * size + s = repr(s) +@@ -681,27 +671,46 @@ + self.assertEqual(s.count('\\'), size) + self.assertEqual(s.count('0'), size * 2) + +- @bigmemtest(minsize=2**32 / 5, memuse=character_size * 7) ++ @bigmemtest(size=_2G // 5 + 1, memuse=character_size * 7) + def test_unicode_repr(self, size): + # Use an assigned, but not printable code point. + # It is in the range of the low surrogates \uDC00-\uDFFF. +- s = "\uDCBA" * size +- for f in (repr, ascii): +- r = f(s) +- self.assertTrue(len(r) > size) +- self.assertTrue(r.endswith(r"\udcba'"), r[-10:]) +- del r ++ char = "\uDCBA" ++ s = char * size ++ try: ++ for f in (repr, ascii): ++ r = f(s) ++ self.assertEqual(len(r), 2 + (len(f(char)) - 2) * size) ++ self.assertTrue(r.endswith(r"\udcba'"), r[-10:]) ++ r = None ++ finally: ++ r = s = None + + # The character takes 4 bytes even in UCS-2 builds because it will + # be decomposed into surrogates. +- @bigmemtest(minsize=2**32 / 5, memuse=4 + character_size * 9) ++ @bigmemtest(size=_2G // 5 + 1, memuse=4 + character_size * 9) + def test_unicode_repr_wide(self, size): +- s = "\U0001DCBA" * size +- for f in (repr, ascii): +- r = f(s) +- self.assertTrue(len(r) > size) +- self.assertTrue(r.endswith(r"\U0001dcba'"), r[-12:]) +- del r ++ char = "\U0001DCBA" ++ s = char * size ++ try: ++ for f in (repr, ascii): ++ r = f(s) ++ self.assertEqual(len(r), 2 + (len(f(char)) - 2) * size) ++ self.assertTrue(r.endswith(r"\U0001dcba'"), r[-12:]) ++ r = None ++ finally: ++ r = s = None ++ ++ @bigmemtest(size=_4G // 5, memuse=character_size * (6 + 1)) ++ def _test_unicode_repr_overflow(self, size): ++ # XXX not sure what this test is about ++ char = "\uDCBA" ++ s = char * size ++ try: ++ r = repr(s) ++ self.assertTrue(s == eval(r)) ++ finally: ++ r = s = None + + + class BytesTest(unittest.TestCase, BaseStrTest): +@@ -709,7 +718,7 @@ + def from_latin1(self, s): + return s.encode("latin1") + +- @bigmemtest(minsize=_2G + 2, memuse=1 + character_size) ++ @bigmemtest(size=_2G + 2, memuse=1 + character_size) + def test_decode(self, size): + s = self.from_latin1('.') * size + self.assertEqual(len(s.decode('utf-8')), size) +@@ -720,7 +729,7 @@ + def from_latin1(self, s): + return bytearray(s.encode("latin1")) + +- @bigmemtest(minsize=_2G + 2, memuse=1 + character_size) ++ @bigmemtest(size=_2G + 2, memuse=1 + character_size) + def test_decode(self, size): + s = self.from_latin1('.') * size + self.assertEqual(len(s.decode('utf-8')), size) +@@ -739,7 +748,7 @@ + # having more than 2<<31 references to any given object. Hence the + # use of different types of objects as contents in different tests. + +- @bigmemtest(minsize=_2G + 2, memuse=16) ++ @bigmemtest(size=_2G + 2, memuse=16) + def test_compare(self, size): + t1 = ('',) * size + t2 = ('',) * size +@@ -762,15 +771,15 @@ + t = t + t + self.assertEqual(len(t), size * 2) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=24) ++ @bigmemtest(size=_2G // 2 + 2, memuse=24) + def test_concat_small(self, size): + return self.basic_concat_test(size) + +- @bigmemtest(minsize=_2G + 2, memuse=24) ++ @bigmemtest(size=_2G + 2, memuse=24) + def test_concat_large(self, size): + return self.basic_concat_test(size) + +- @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 10, memuse=8 * 5) + def test_contains(self, size): + t = (1, 2, 3, 4, 5) * size + self.assertEqual(len(t), size * 5) +@@ -778,7 +787,7 @@ + self.assertNotIn((1, 2, 3, 4, 5), t) + self.assertNotIn(0, t) + +- @bigmemtest(minsize=_2G + 10, memuse=8) ++ @bigmemtest(size=_2G + 10, memuse=8) + def test_hash(self, size): + t1 = (0,) * size + h1 = hash(t1) +@@ -786,7 +795,7 @@ + t2 = (0,) * (size + 1) + self.assertFalse(h1 == hash(t2)) + +- @bigmemtest(minsize=_2G + 10, memuse=8) ++ @bigmemtest(size=_2G + 10, memuse=8) + def test_index_and_slice(self, size): + t = (None,) * size + self.assertEqual(len(t), size) +@@ -811,19 +820,19 @@ + t = t * 2 + self.assertEqual(len(t), size * 2) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=24) ++ @bigmemtest(size=_2G // 2 + 2, memuse=24) + def test_repeat_small(self, size): + return self.basic_test_repeat(size) + +- @bigmemtest(minsize=_2G + 2, memuse=24) ++ @bigmemtest(size=_2G + 2, memuse=24) + def test_repeat_large(self, size): + return self.basic_test_repeat(size) + +- @bigmemtest(minsize=_1G - 1, memuse=12) ++ @bigmemtest(size=_1G - 1, memuse=12) + def test_repeat_large_2(self, size): + return self.basic_test_repeat(size) + +- @precisionbigmemtest(size=_1G - 1, memuse=9) ++ @bigmemtest(size=_1G - 1, memuse=9) + def test_from_2G_generator(self, size): + self.skipTest("test needs much more memory than advertised, see issue5438") + try: +@@ -837,7 +846,7 @@ + count += 1 + self.assertEqual(count, size) + +- @precisionbigmemtest(size=_1G - 25, memuse=9) ++ @bigmemtest(size=_1G - 25, memuse=9) + def test_from_almost_2G_generator(self, size): + self.skipTest("test needs much more memory than advertised, see issue5438") + try: +@@ -860,11 +869,11 @@ + self.assertEqual(s[-5:], '0, 0)') + self.assertEqual(s.count('0'), size) + +- @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size) ++ @bigmemtest(size=_2G // 3 + 2, memuse=8 + 3 * character_size) + def test_repr_small(self, size): + return self.basic_test_repr(size) + +- @bigmemtest(minsize=_2G + 2, memuse=8 + 3 * character_size) ++ @bigmemtest(size=_2G + 2, memuse=8 + 3 * character_size) + def test_repr_large(self, size): + return self.basic_test_repr(size) + +@@ -875,7 +884,7 @@ + # lists hold references to various objects to test their refcount + # limits. + +- @bigmemtest(minsize=_2G + 2, memuse=16) ++ @bigmemtest(size=_2G + 2, memuse=16) + def test_compare(self, size): + l1 = [''] * size + l2 = [''] * size +@@ -898,11 +907,11 @@ + l = l + l + self.assertEqual(len(l), size * 2) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=24) ++ @bigmemtest(size=_2G // 2 + 2, memuse=24) + def test_concat_small(self, size): + return self.basic_test_concat(size) + +- @bigmemtest(minsize=_2G + 2, memuse=24) ++ @bigmemtest(size=_2G + 2, memuse=24) + def test_concat_large(self, size): + return self.basic_test_concat(size) + +@@ -913,15 +922,15 @@ + self.assertTrue(l[0] is l[-1]) + self.assertTrue(l[size - 1] is l[size + 1]) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=24) ++ @bigmemtest(size=_2G // 2 + 2, memuse=24) + def test_inplace_concat_small(self, size): + return self.basic_test_inplace_concat(size) + +- @bigmemtest(minsize=_2G + 2, memuse=24) ++ @bigmemtest(size=_2G + 2, memuse=24) + def test_inplace_concat_large(self, size): + return self.basic_test_inplace_concat(size) + +- @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 10, memuse=8 * 5) + def test_contains(self, size): + l = [1, 2, 3, 4, 5] * size + self.assertEqual(len(l), size * 5) +@@ -929,12 +938,12 @@ + self.assertNotIn([1, 2, 3, 4, 5], l) + self.assertNotIn(0, l) + +- @bigmemtest(minsize=_2G + 10, memuse=8) ++ @bigmemtest(size=_2G + 10, memuse=8) + def test_hash(self, size): + l = [0] * size + self.assertRaises(TypeError, hash, l) + +- @bigmemtest(minsize=_2G + 10, memuse=8) ++ @bigmemtest(size=_2G + 10, memuse=8) + def test_index_and_slice(self, size): + l = [None] * size + self.assertEqual(len(l), size) +@@ -998,11 +1007,11 @@ + l = l * 2 + self.assertEqual(len(l), size * 2) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=24) ++ @bigmemtest(size=_2G // 2 + 2, memuse=24) + def test_repeat_small(self, size): + return self.basic_test_repeat(size) + +- @bigmemtest(minsize=_2G + 2, memuse=24) ++ @bigmemtest(size=_2G + 2, memuse=24) + def test_repeat_large(self, size): + return self.basic_test_repeat(size) + +@@ -1018,11 +1027,11 @@ + self.assertEqual(len(l), size * 2) + self.assertTrue(l[size - 1] is l[-1]) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=16) ++ @bigmemtest(size=_2G // 2 + 2, memuse=16) + def test_inplace_repeat_small(self, size): + return self.basic_test_inplace_repeat(size) + +- @bigmemtest(minsize=_2G + 2, memuse=16) ++ @bigmemtest(size=_2G + 2, memuse=16) + def test_inplace_repeat_large(self, size): + return self.basic_test_inplace_repeat(size) + +@@ -1035,17 +1044,17 @@ + self.assertEqual(s[-5:], '0, 0]') + self.assertEqual(s.count('0'), size) + +- @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size) ++ @bigmemtest(size=_2G // 3 + 2, memuse=8 + 3 * character_size) + def test_repr_small(self, size): + return self.basic_test_repr(size) + +- @bigmemtest(minsize=_2G + 2, memuse=8 + 3 * character_size) ++ @bigmemtest(size=_2G + 2, memuse=8 + 3 * character_size) + def test_repr_large(self, size): + return self.basic_test_repr(size) + + # list overallocates ~1/8th of the total size (on first expansion) so + # the single list.append call puts memuse at 9 bytes per size. +- @bigmemtest(minsize=_2G, memuse=9) ++ @bigmemtest(size=_2G, memuse=9) + def test_append(self, size): + l = [object()] * size + l.append(object()) +@@ -1053,7 +1062,7 @@ + self.assertTrue(l[-3] is l[-2]) + self.assertFalse(l[-2] is l[-1]) + +- @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 2, memuse=8 * 5) + def test_count(self, size): + l = [1, 2, 3, 4, 5] * size + self.assertEqual(l.count(1), size) +@@ -1066,15 +1075,15 @@ + self.assertTrue(l[0] is l[-1]) + self.assertTrue(l[size - 1] is l[size + 1]) + +- @bigmemtest(minsize=_2G // 2 + 2, memuse=16) ++ @bigmemtest(size=_2G // 2 + 2, memuse=16) + def test_extend_small(self, size): + return self.basic_test_extend(size) + +- @bigmemtest(minsize=_2G + 2, memuse=16) ++ @bigmemtest(size=_2G + 2, memuse=16) + def test_extend_large(self, size): + return self.basic_test_extend(size) + +- @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 2, memuse=8 * 5) + def test_index(self, size): + l = [1, 2, 3, 4, 5] * size + size *= 5 +@@ -1085,7 +1094,7 @@ + self.assertRaises(ValueError, l.index, 6) + + # This tests suffers from overallocation, just like test_append. +- @bigmemtest(minsize=_2G + 10, memuse=9) ++ @bigmemtest(size=_2G + 10, memuse=9) + def test_insert(self, size): + l = [1.0] * size + l.insert(size - 1, "A") +@@ -1104,7 +1113,7 @@ + self.assertEqual(l[:3], [1.0, "C", 1.0]) + self.assertEqual(l[size - 3:], ["A", 1.0, "B"]) + +- @bigmemtest(minsize=_2G // 5 + 4, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 4, memuse=8 * 5) + def test_pop(self, size): + l = ["a", "b", "c", "d", "e"] * size + size *= 5 +@@ -1128,7 +1137,7 @@ + self.assertEqual(item, "c") + self.assertEqual(l[-2:], ["b", "d"]) + +- @bigmemtest(minsize=_2G + 10, memuse=8) ++ @bigmemtest(size=_2G + 10, memuse=8) + def test_remove(self, size): + l = [10] * size + self.assertEqual(len(l), size) +@@ -1148,7 +1157,7 @@ + self.assertEqual(len(l), size) + self.assertEqual(l[-2:], [10, 10]) + +- @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 2, memuse=8 * 5) + def test_reverse(self, size): + l = [1, 2, 3, 4, 5] * size + l.reverse() +@@ -1156,7 +1165,7 @@ + self.assertEqual(l[-5:], [5, 4, 3, 2, 1]) + self.assertEqual(l[:5], [5, 4, 3, 2, 1]) + +- @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) ++ @bigmemtest(size=_2G // 5 + 2, memuse=8 * 5) + def test_sort(self, size): + l = [1, 2, 3, 4, 5] * size + l.sort() +diff -r 137e45f15c0b Lib/test/test_builtin.py +--- a/Lib/test/test_builtin.py ++++ b/Lib/test/test_builtin.py +@@ -6,12 +6,18 @@ + import warnings + import collections + import io ++import os + import ast + import types + import builtins + import random ++import traceback + from test.support import fcmp, TESTFN, unlink, run_unittest, check_warnings + from operator import neg ++try: ++ import pty, signal ++except ImportError: ++ pty = signal = None + + + class Squares: +@@ -988,6 +994,82 @@ + fp.close() + unlink(TESTFN) + ++ @unittest.skipUnless(pty, "the pty and signal modules must be available") ++ def check_input_tty(self, prompt, terminal_input, stdio_encoding=None): ++ if not sys.stdin.isatty() or not sys.stdout.isatty(): ++ self.skipTest("stdin and stdout must be ttys") ++ r, w = os.pipe() ++ try: ++ pid, fd = pty.fork() ++ except (OSError, AttributeError) as e: ++ os.close(r) ++ os.close(w) ++ self.skipTest("pty.fork() raised {}".format(e)) ++ if pid == 0: ++ # Child ++ try: ++ # Make sure we don't get stuck if there's a problem ++ signal.alarm(2) ++ os.close(r) ++ # Check the error handlers are accounted for ++ if stdio_encoding: ++ sys.stdin = io.TextIOWrapper(sys.stdin.detach(), ++ encoding=stdio_encoding, ++ errors='surrogateescape') ++ sys.stdout = io.TextIOWrapper(sys.stdout.detach(), ++ encoding=stdio_encoding, ++ errors='replace') ++ with open(w, "w") as wpipe: ++ print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe) ++ print(ascii(input(prompt)), file=wpipe) ++ except: ++ traceback.print_exc() ++ finally: ++ # We don't want to return to unittest... ++ os._exit(0) ++ # Parent ++ os.close(w) ++ os.write(fd, terminal_input + b"\r\n") ++ # Get results from the pipe ++ with open(r, "r") as rpipe: ++ lines = [] ++ while True: ++ line = rpipe.readline().strip() ++ if line == "": ++ # The other end was closed => the child exited ++ break ++ lines.append(line) ++ # Check the result was got and corresponds to the user's terminal input ++ if len(lines) != 2: ++ # Something went wrong, try to get at stderr ++ with open(fd, "r", encoding="ascii", errors="ignore") as child_output: ++ self.fail("got %d lines in pipe but expected 2, child output was:\n%s" ++ % (len(lines), child_output.read())) ++ os.close(fd) ++ # Check we did exercise the GNU readline path ++ self.assertIn(lines[0], {'tty = True', 'tty = False'}) ++ if lines[0] != 'tty = True': ++ self.skipTest("standard IO in should have been a tty") ++ input_result = eval(lines[1]) # ascii() -> eval() roundtrip ++ if stdio_encoding: ++ expected = terminal_input.decode(stdio_encoding, 'surrogateescape') ++ else: ++ expected = terminal_input.decode(sys.stdin.encoding) # what else? ++ self.assertEqual(input_result, expected) ++ ++ def test_input_tty(self): ++ # Test input() functionality when wired to a tty (the code path ++ # is different and invokes GNU readline if available). ++ self.check_input_tty("prompt", b"quux") ++ ++ def test_input_tty_non_ascii(self): ++ # Check stdin/stdout encoding is used when invoking GNU readline ++ self.check_input_tty("prompté", b"quux\xe9", "utf-8") ++ ++ def test_input_tty_non_ascii_unicode_errors(self): ++ # Check stdin/stdout error handler is used when invoking GNU readline ++ self.check_input_tty("prompté", b"quux\xe9", "ascii") ++ + def test_repr(self): + self.assertEqual(repr(''), '\'\'') + self.assertEqual(repr(0), '0') +diff -r 137e45f15c0b Lib/test/test_cgi.py +--- a/Lib/test/test_cgi.py ++++ b/Lib/test/test_cgi.py +@@ -348,6 +348,10 @@ + self.assertEqual( + cgi.parse_header('attachment; filename="strange;name";size=123;'), + ("attachment", {"filename": "strange;name", "size": "123"})) ++ self.assertEqual( ++ cgi.parse_header('form-data; name="files"; filename="fo\\"o;bar"'), ++ ("form-data", {"name": "files", "filename": 'fo"o;bar'})) ++ + + BOUNDARY = "---------------------------721837373350705526688164684" + +diff -r 137e45f15c0b Lib/test/test_cmd_line.py +--- a/Lib/test/test_cmd_line.py ++++ b/Lib/test/test_cmd_line.py +@@ -272,6 +272,64 @@ + self.assertRegex(err.decode('ascii', 'ignore'), 'SyntaxError') + self.assertEqual(b'', out) + ++ def test_stdout_flush_at_shutdown(self): ++ # Issue #5319: if stdout.flush() fails at shutdown, an error should ++ # be printed out. ++ code = """if 1: ++ import os, sys ++ sys.stdout.write('x') ++ os.close(sys.stdout.fileno())""" ++ rc, out, err = assert_python_ok('-c', code) ++ self.assertEqual(b'', out) ++ self.assertRegex(err.decode('ascii', 'ignore'), ++ 'Exception IOError: .* ignored') ++ ++ def test_closed_stdout(self): ++ # Issue #13444: if stdout has been explicitly closed, we should ++ # not attempt to flush it at shutdown. ++ code = "import sys; sys.stdout.close()" ++ rc, out, err = assert_python_ok('-c', code) ++ self.assertEqual(b'', err) ++ ++ # Issue #7111: Python should work without standard streams ++ ++ @unittest.skipIf(os.name != 'posix', "test needs POSIX semantics") ++ def _test_no_stdio(self, streams): ++ code = """if 1: ++ import os, sys ++ for i, s in enumerate({streams}): ++ if getattr(sys, s) is not None: ++ os._exit(i + 1) ++ os._exit(42)""".format(streams=streams) ++ def preexec(): ++ if 'stdin' in streams: ++ os.close(0) ++ if 'stdout' in streams: ++ os.close(1) ++ if 'stderr' in streams: ++ os.close(2) ++ p = subprocess.Popen( ++ [sys.executable, "-E", "-c", code], ++ stdin=subprocess.PIPE, ++ stdout=subprocess.PIPE, ++ stderr=subprocess.PIPE, ++ preexec_fn=preexec) ++ out, err = p.communicate() ++ self.assertEqual(test.support.strip_python_stderr(err), b'') ++ self.assertEqual(p.returncode, 42) ++ ++ def test_no_stdin(self): ++ self._test_no_stdio(['stdin']) ++ ++ def test_no_stdout(self): ++ self._test_no_stdio(['stdout']) ++ ++ def test_no_stderr(self): ++ self._test_no_stdio(['stderr']) ++ ++ def test_no_std_streams(self): ++ self._test_no_stdio(['stdin', 'stdout', 'stderr']) ++ + + def test_main(): + test.support.run_unittest(CmdLineTest) +diff -r 137e45f15c0b Lib/test/test_collections.py +--- a/Lib/test/test_collections.py ++++ b/Lib/test/test_collections.py +@@ -893,6 +893,12 @@ + c.subtract('aaaabbcce') + self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1)) + ++ def test_repr_nonsortable(self): ++ c = Counter(a=2, b=None) ++ r = repr(c) ++ self.assertIn("'a': 2", r) ++ self.assertIn("'b': None", r) ++ + def test_helper_function(self): + # two paths, one for real dicts and one for other mappings + elems = list('abracadabra') +diff -r 137e45f15c0b Lib/test/test_curses.py +--- a/Lib/test/test_curses.py ++++ b/Lib/test/test_curses.py +@@ -183,14 +183,14 @@ + win = curses.newwin(5,5) + win = curses.newwin(5,5, 1,1) + curses.nl() ; curses.nl(1) +- curses.putp('abc') ++ curses.putp(b'abc') + curses.qiflush() + curses.raw() ; curses.raw(1) + curses.setsyx(5,5) + curses.tigetflag('hc') + curses.tigetnum('co') + curses.tigetstr('cr') +- curses.tparm('cr') ++ curses.tparm(b'cr') + curses.typeahead(sys.__stdin__.fileno()) + curses.unctrl('a') + curses.ungetch('a') +@@ -264,6 +264,11 @@ + curses.ungetch(1025) + stdscr.getkey() + ++def test_issue10570(): ++ b = curses.tparm(curses.tigetstr("cup"), 5, 3) ++ assert type(b) is bytes ++ curses.putp(b) ++ + def main(stdscr): + curses.savetty() + try: +@@ -272,6 +277,7 @@ + test_userptr_without_set(stdscr) + test_resize_term(stdscr) + test_issue6243(stdscr) ++ test_issue10570() + finally: + curses.resetty() + +diff -r 137e45f15c0b Lib/test/test_defaultdict.py +--- a/Lib/test/test_defaultdict.py ++++ b/Lib/test/test_defaultdict.py +@@ -172,6 +172,9 @@ + finally: + os.remove(tfn) + ++ def test_callable_arg(self): ++ self.assertRaises(TypeError, defaultdict, {}) ++ + def test_pickleing(self): + d = defaultdict(int) + d[1] +diff -r 137e45f15c0b Lib/test/test_descr.py +--- a/Lib/test/test_descr.py ++++ b/Lib/test/test_descr.py +@@ -625,6 +625,174 @@ + # The most derived metaclass of D is A rather than type. + class D(B, C): + pass ++ self.assertIs(A, type(D)) ++ ++ # issue1294232: correct metaclass calculation ++ new_calls = [] # to check the order of __new__ calls ++ class AMeta(type): ++ @staticmethod ++ def __new__(mcls, name, bases, ns): ++ new_calls.append('AMeta') ++ return super().__new__(mcls, name, bases, ns) ++ @classmethod ++ def __prepare__(mcls, name, bases): ++ return {} ++ ++ class BMeta(AMeta): ++ @staticmethod ++ def __new__(mcls, name, bases, ns): ++ new_calls.append('BMeta') ++ return super().__new__(mcls, name, bases, ns) ++ @classmethod ++ def __prepare__(mcls, name, bases): ++ ns = super().__prepare__(name, bases) ++ ns['BMeta_was_here'] = True ++ return ns ++ ++ class A(metaclass=AMeta): ++ pass ++ self.assertEqual(['AMeta'], new_calls) ++ new_calls[:] = [] ++ ++ class B(metaclass=BMeta): ++ pass ++ # BMeta.__new__ calls AMeta.__new__ with super: ++ self.assertEqual(['BMeta', 'AMeta'], new_calls) ++ new_calls[:] = [] ++ ++ class C(A, B): ++ pass ++ # The most derived metaclass is BMeta: ++ self.assertEqual(['BMeta', 'AMeta'], new_calls) ++ new_calls[:] = [] ++ # BMeta.__prepare__ should've been called: ++ self.assertIn('BMeta_was_here', C.__dict__) ++ ++ # The order of the bases shouldn't matter: ++ class C2(B, A): ++ pass ++ self.assertEqual(['BMeta', 'AMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertIn('BMeta_was_here', C2.__dict__) ++ ++ # Check correct metaclass calculation when a metaclass is declared: ++ class D(C, metaclass=type): ++ pass ++ self.assertEqual(['BMeta', 'AMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertIn('BMeta_was_here', D.__dict__) ++ ++ class E(C, metaclass=AMeta): ++ pass ++ self.assertEqual(['BMeta', 'AMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertIn('BMeta_was_here', E.__dict__) ++ ++ # Special case: the given metaclass isn't a class, ++ # so there is no metaclass calculation. ++ marker = object() ++ def func(*args, **kwargs): ++ return marker ++ class X(metaclass=func): ++ pass ++ class Y(object, metaclass=func): ++ pass ++ class Z(D, metaclass=func): ++ pass ++ self.assertIs(marker, X) ++ self.assertIs(marker, Y) ++ self.assertIs(marker, Z) ++ ++ # The given metaclass is a class, ++ # but not a descendant of type. ++ prepare_calls = [] # to track __prepare__ calls ++ class ANotMeta: ++ def __new__(mcls, *args, **kwargs): ++ new_calls.append('ANotMeta') ++ return super().__new__(mcls) ++ @classmethod ++ def __prepare__(mcls, name, bases): ++ prepare_calls.append('ANotMeta') ++ return {} ++ class BNotMeta(ANotMeta): ++ def __new__(mcls, *args, **kwargs): ++ new_calls.append('BNotMeta') ++ return super().__new__(mcls) ++ @classmethod ++ def __prepare__(mcls, name, bases): ++ prepare_calls.append('BNotMeta') ++ return super().__prepare__(name, bases) ++ ++ class A(metaclass=ANotMeta): ++ pass ++ self.assertIs(ANotMeta, type(A)) ++ self.assertEqual(['ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ self.assertEqual(['ANotMeta'], new_calls) ++ new_calls[:] = [] ++ ++ class B(metaclass=BNotMeta): ++ pass ++ self.assertIs(BNotMeta, type(B)) ++ self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) ++ new_calls[:] = [] ++ ++ class C(A, B): ++ pass ++ self.assertIs(BNotMeta, type(C)) ++ self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ ++ class C2(B, A): ++ pass ++ self.assertIs(BNotMeta, type(C2)) ++ self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ ++ # This is a TypeError, because of a metaclass conflict: ++ # BNotMeta is neither a subclass, nor a superclass of type ++ with self.assertRaises(TypeError): ++ class D(C, metaclass=type): ++ pass ++ ++ class E(C, metaclass=ANotMeta): ++ pass ++ self.assertIs(BNotMeta, type(E)) ++ self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ ++ class F(object(), C): ++ pass ++ self.assertIs(BNotMeta, type(F)) ++ self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ ++ class F2(C, object()): ++ pass ++ self.assertIs(BNotMeta, type(F2)) ++ self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls) ++ new_calls[:] = [] ++ self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls) ++ prepare_calls[:] = [] ++ ++ # TypeError: BNotMeta is neither a ++ # subclass, nor a superclass of int ++ with self.assertRaises(TypeError): ++ class X(C, int()): ++ pass ++ with self.assertRaises(TypeError): ++ class X(int(), C): ++ pass + + def test_module_subclasses(self): + # Testing Python subclass of module... +diff -r 137e45f15c0b Lib/test/test_doctest.py +--- a/Lib/test/test_doctest.py ++++ b/Lib/test/test_doctest.py +@@ -258,6 +258,21 @@ + >>> e = doctest.Example('raise X()', '', exc_msg) + >>> e.exc_msg + '\n' ++ ++Compare `Example`: ++ >>> example = doctest.Example('print 1', '1\n') ++ >>> same_example = doctest.Example('print 1', '1\n') ++ >>> other_example = doctest.Example('print 42', '42\n') ++ >>> example == same_example ++ True ++ >>> example != same_example ++ False ++ >>> hash(example) == hash(same_example) ++ True ++ >>> example == other_example ++ False ++ >>> example != other_example ++ True + """ + + def test_DocTest(): r""" +@@ -347,6 +362,50 @@ + Traceback (most recent call last): + ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)' + ++Compare `DocTest`: ++ ++ >>> docstring = ''' ++ ... >>> print 12 ++ ... 12 ++ ... ''' ++ >>> test = parser.get_doctest(docstring, globs, 'some_test', ++ ... 'some_test', 20) ++ >>> same_test = parser.get_doctest(docstring, globs, 'some_test', ++ ... 'some_test', 20) ++ >>> test == same_test ++ True ++ >>> test != same_test ++ False ++ >>> hash(test) == hash(same_test) ++ True ++ >>> docstring = ''' ++ ... >>> print 42 ++ ... 42 ++ ... ''' ++ >>> other_test = parser.get_doctest(docstring, globs, 'other_test', ++ ... 'other_file', 10) ++ >>> test == other_test ++ False ++ >>> test != other_test ++ True ++ ++Compare `DocTestCase`: ++ ++ >>> DocTestCase = doctest.DocTestCase ++ >>> test_case = DocTestCase(test) ++ >>> same_test_case = DocTestCase(same_test) ++ >>> other_test_case = DocTestCase(other_test) ++ >>> test_case == same_test_case ++ True ++ >>> test_case != same_test_case ++ False ++ >>> hash(test_case) == hash(same_test_case) ++ True ++ >>> test == other_test_case ++ False ++ >>> test != other_test_case ++ True ++ + """ + + def test_DocTestFinder(): r""" +diff -r 137e45f15c0b Lib/test/test_exceptions.py +--- a/Lib/test/test_exceptions.py ++++ b/Lib/test/test_exceptions.py +@@ -5,6 +5,7 @@ + import unittest + import pickle + import weakref ++import errno + + from test.support import (TESTFN, unlink, run_unittest, captured_output, + gc_collect, cpython_only) +@@ -607,6 +608,68 @@ + gc_collect() + self.assertEqual(sys.exc_info(), (None, None, None)) + ++ def _check_generator_cleanup_exc_state(self, testfunc): ++ # Issue #12791: exception state is cleaned up as soon as a generator ++ # is closed (reference cycles are broken). ++ class MyException(Exception): ++ def __init__(self, obj): ++ self.obj = obj ++ class MyObj: ++ pass ++ ++ def raising_gen(): ++ try: ++ raise MyException(obj) ++ except MyException: ++ yield ++ ++ obj = MyObj() ++ wr = weakref.ref(obj) ++ g = raising_gen() ++ next(g) ++ testfunc(g) ++ g = obj = None ++ obj = wr() ++ self.assertIs(obj, None) ++ ++ def test_generator_throw_cleanup_exc_state(self): ++ def do_throw(g): ++ try: ++ g.throw(RuntimeError()) ++ except RuntimeError: ++ pass ++ self._check_generator_cleanup_exc_state(do_throw) ++ ++ def test_generator_close_cleanup_exc_state(self): ++ def do_close(g): ++ g.close() ++ self._check_generator_cleanup_exc_state(do_close) ++ ++ def test_generator_del_cleanup_exc_state(self): ++ def do_del(g): ++ g = None ++ self._check_generator_cleanup_exc_state(do_del) ++ ++ def test_generator_next_cleanup_exc_state(self): ++ def do_next(g): ++ try: ++ next(g) ++ except StopIteration: ++ pass ++ else: ++ self.fail("should have raised StopIteration") ++ self._check_generator_cleanup_exc_state(do_next) ++ ++ def test_generator_send_cleanup_exc_state(self): ++ def do_send(g): ++ try: ++ g.send(None) ++ except StopIteration: ++ pass ++ else: ++ self.fail("should have raised StopIteration") ++ self._check_generator_cleanup_exc_state(do_send) ++ + def test_3114(self): + # Bug #3114: in its destructor, MyObject retrieves a pointer to + # obsolete and/or deallocated objects. +@@ -787,6 +850,13 @@ + self.fail("RuntimeError not raised") + self.assertEqual(wr(), None) + ++ def test_errno_ENOTDIR(self): ++ # Issue #12802: "not a directory" errors are ENOTDIR even on Windows ++ with self.assertRaises(OSError) as cm: ++ os.listdir(__file__) ++ self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) ++ ++ + def test_main(): + run_unittest(ExceptionTests) + +diff -r 137e45f15c0b Lib/test/test_fcntl.py +--- a/Lib/test/test_fcntl.py ++++ b/Lib/test/test_fcntl.py +@@ -23,12 +23,8 @@ + else: + start_len = "qq" + +- if sys.platform in ('netbsd1', 'netbsd2', 'netbsd3', +- 'Darwin1.2', 'darwin', +- 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5', +- 'freebsd6', 'freebsd7', 'freebsd8', +- 'bsdos2', 'bsdos3', 'bsdos4', +- 'openbsd', 'openbsd2', 'openbsd3', 'openbsd4'): ++ if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd', 'bsdos')) ++ or sys.platform == 'darwin'): + if struct.calcsize('l') == 8: + off_t = 'l' + pid_t = 'i' +diff -r 137e45f15c0b Lib/test/test_float.py +--- a/Lib/test/test_float.py ++++ b/Lib/test/test_float.py +@@ -128,6 +128,12 @@ + self.assertRaises(TypeError, float, Foo4(42)) + self.assertAlmostEqual(float(FooStr('8')), 9.) + ++ def test_is_integer(self): ++ self.assertFalse((1.1).is_integer()) ++ self.assertTrue((1.).is_integer()) ++ self.assertFalse(float("nan").is_integer()) ++ self.assertFalse(float("inf").is_integer()) ++ + def test_floatasratio(self): + for f, ratio in [ + (0.875, (7, 8)), +diff -r 137e45f15c0b Lib/test/test_functools.py +--- a/Lib/test/test_functools.py ++++ b/Lib/test/test_functools.py +@@ -655,6 +655,22 @@ + self.assertEqual(fib.cache_info(), + functools._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)) + ++ def test_lru_with_exceptions(self): ++ # Verify that user_function exceptions get passed through without ++ # creating a hard-to-read chained exception. ++ # http://bugs.python.org/issue13177 ++ for maxsize in (None, 100): ++ @functools.lru_cache(maxsize) ++ def func(i): ++ return 'abc'[i] ++ self.assertEqual(func(0), 'a') ++ with self.assertRaises(IndexError) as cm: ++ func(15) ++ self.assertIsNone(cm.exception.__context__) ++ # Verify that the previous exception did not result in a cached entry ++ with self.assertRaises(IndexError): ++ func(15) ++ + def test_main(verbose=None): + test_classes = ( + TestPartial, +diff -r 137e45f15c0b Lib/test/test_generators.py +--- a/Lib/test/test_generators.py ++++ b/Lib/test/test_generators.py +@@ -1673,6 +1673,32 @@ + ... + ValueError: 7 + ++Plain "raise" inside a generator should preserve the traceback (#13188). ++The traceback should have 3 levels: ++- g.throw() ++- f() ++- 1/0 ++ ++>>> def f(): ++... try: ++... yield ++... except: ++... raise ++>>> g = f() ++>>> try: ++... 1/0 ++... except ZeroDivisionError as v: ++... try: ++... g.throw(v) ++... except Exception as w: ++... tb = w.__traceback__ ++>>> levels = 0 ++>>> while tb: ++... levels += 1 ++... tb = tb.tb_next ++>>> levels ++3 ++ + Now let's try closing a generator: + + >>> def f(): +diff -r 137e45f15c0b Lib/test/test_grammar.py +--- a/Lib/test/test_grammar.py ++++ b/Lib/test/test_grammar.py +@@ -493,13 +493,35 @@ + assert 1, 1 + assert lambda x:x + assert 1, lambda x:x+1 ++ ++ try: ++ assert True ++ except AssertionError as e: ++ self.fail("'assert True' should not have raised an AssertionError") ++ ++ try: ++ assert True, 'this should always pass' ++ except AssertionError as e: ++ self.fail("'assert True, msg' should not have " ++ "raised an AssertionError") ++ ++ # these tests fail if python is run with -O, so check __debug__ ++ @unittest.skipUnless(__debug__, "Won't work if __debug__ is False") ++ def testAssert2(self): + try: + assert 0, "msg" + except AssertionError as e: + self.assertEqual(e.args[0], "msg") + else: +- if __debug__: +- self.fail("AssertionError not raised by assert 0") ++ self.fail("AssertionError not raised by assert 0") ++ ++ try: ++ assert False ++ except AssertionError as e: ++ self.assertEqual(len(e.args), 0) ++ else: ++ self.fail("AssertionError not raised by 'assert False'") ++ + + ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef + # Tested below +diff -r 137e45f15c0b Lib/test/test_hashlib.py +--- a/Lib/test/test_hashlib.py ++++ b/Lib/test/test_hashlib.py +@@ -17,7 +17,7 @@ + import unittest + import warnings + from test import support +-from test.support import _4G, precisionbigmemtest ++from test.support import _4G, bigmemtest + + # Were we compiled --with-pydebug or with #define Py_DEBUG? + COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount') +@@ -196,7 +196,7 @@ + b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', + 'd174ab98d277d9f5a5611c2c9f419d9f') + +- @precisionbigmemtest(size=_4G + 5, memuse=1) ++ @bigmemtest(size=_4G + 5, memuse=1) + def test_case_md5_huge(self, size): + if size == _4G + 5: + try: +@@ -204,7 +204,7 @@ + except OverflowError: + pass # 32-bit arch + +- @precisionbigmemtest(size=_4G - 1, memuse=1) ++ @bigmemtest(size=_4G - 1, memuse=1) + def test_case_md5_uintmax(self, size): + if size == _4G - 1: + try: +diff -r 137e45f15c0b Lib/test/test_htmlparser.py +--- a/Lib/test/test_htmlparser.py ++++ b/Lib/test/test_htmlparser.py +@@ -72,9 +72,12 @@ + + class TestCaseBase(unittest.TestCase): + ++ def get_collector(self): ++ raise NotImplementedError ++ + def _run_check(self, source, expected_events, collector=None): + if collector is None: +- collector = EventCollector() ++ collector = self.get_collector() + parser = collector + for s in source: + parser.feed(s) +@@ -96,7 +99,10 @@ + self.assertRaises(html.parser.HTMLParseError, parse) + + +-class HTMLParserTestCase(TestCaseBase): ++class HTMLParserStrictTestCase(TestCaseBase): ++ ++ def get_collector(self): ++ return EventCollector(strict=True) + + def test_processing_instruction_only(self): + self._run_check("", [ +@@ -190,60 +196,6 @@ + ("data", "this < text > contains < bare>pointy< brackets"), + ]) + +- def test_attr_syntax(self): +- output = [ +- ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)]) +- ] +- self._run_check("""
""", output) +- self._run_check("""""", output) +- self._run_check("""""", output) +- self._run_check("""""", output) +- +- def test_attr_values(self): +- self._run_check("""""", +- [("starttag", "a", [("b", "xxx\n\txxx"), +- ("c", "yyy\t\nyyy"), +- ("d", "\txyz\n")]) +- ]) +- self._run_check("""""", [ +- ("starttag", "a", [("b", ""), ("c", "")]), +- ]) +- # Regression test for SF patch #669683. +- self._run_check("", [ +- ("starttag", "e", [("a", "rgb(1,2,3)")]), +- ]) +- # Regression test for SF bug #921657. +- self._run_check("", [ +- ("starttag", "a", [("href", "mailto:xyz@example.com")]), +- ]) +- +- def test_attr_nonascii(self): +- # see issue 7311 +- self._run_check("\u4e2d\u6587", [ +- ("starttag", "img", [("src", "/foo/bar.png"), +- ("alt", "\u4e2d\u6587")]), +- ]) +- self._run_check("", [ +- ("starttag", "a", [("title", "\u30c6\u30b9\u30c8"), +- ("href", "\u30c6\u30b9\u30c8.html")]), +- ]) +- self._run_check('', [ +- ("starttag", "a", [("title", "\u30c6\u30b9\u30c8"), +- ("href", "\u30c6\u30b9\u30c8.html")]), +- ]) +- +- def test_attr_entity_replacement(self): +- self._run_check("""""", [ +- ("starttag", "a", [("b", "&><\"'")]), +- ]) +- +- def test_attr_funky_names(self): +- self._run_check("""""", [ +- ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]), +- ]) +- + def test_illegal_declarations(self): + self._parse_error('') + +@@ -289,13 +241,11 @@ + self._parse_error("") + self._parse_error("") + self._parse_error("") + self._parse_error("'") + self._parse_error(" """ +- self._run_check(s, [ +- ("starttag", "script", []), +- ("data", " "), +- ("endtag", "script"), +- ]) ++ contents = [ ++ ' ¬-an-entity-ref;', ++ "", ++ '

', ++ 'foo = "";', ++ 'foo = "";', ++ 'foo = <\n/script> ', ++ '', ++ ('\n//<\\/s\'+\'cript>\');\n//]]>'), ++ '\n\n', ++ 'foo = "";', ++ '', ++ # these two should be invalid according to the HTML 5 spec, ++ # section 8.1.2.2 ++ #'foo = ', ++ #'foo = ', ++ ] ++ elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style'] ++ for content in contents: ++ for element in elements: ++ element_lower = element.lower() ++ s = '<{element}>{content}'.format(element=element, ++ content=content) ++ self._run_check(s, [("starttag", element_lower, []), ++ ("data", content), ++ ("endtag", element_lower)]) + +- def test_entityrefs_in_attributes(self): +- self._run_check("", [ +- ("starttag", "html", [("foo", "\u20AC&aa&unsupported;")]) +- ]) ++ def test_cdata_with_closing_tags(self): ++ # see issue #13358 ++ # make sure that HTMLParser calls handle_data only once for each CDATA. ++ # The normal event collector normalizes the events in get_events, ++ # so we override it to return the original list of events. ++ class Collector(EventCollector): ++ def get_events(self): ++ return self.events + ++ content = """ ¬-an-entity-ref; ++

++ ''""" ++ for element in [' script', 'script ', ' script ', ++ '\nscript', 'script\n', '\nscript\n']: ++ element_lower = element.lower().strip() ++ s = '`` and ````. ++ ++- Issue #10817: Fix urlretrieve function to raise ContentTooShortError even ++ when reporthook is None. Patch by Jyrki Pulliainen. ++ ++- Issue #13296: Fix IDLE to clear compile __future__ flags on shell restart. ++ (Patch by Roger Serwy) ++ ++- Issue #13293: Better error message when trying to marshal bytes using ++ xmlrpc.client. ++ ++- Issue #13291: NameError in xmlrpc package. ++ ++- Issue #13258: Use callable() built-in in the standard library. ++ ++- Issue #13273: fix a bug that prevented HTMLParser to properly detect some ++ tags when strict=False. ++ ++- Issue #10332: multiprocessing: fix a race condition when a Pool is closed ++ before all tasks have completed. ++ ++- Issue #13255: wrong docstrings in array module. ++ ++- Issue #9168: now smtpd is able to bind privileged port. ++ ++- Issue #12529: fix cgi.parse_header issue on strings with double-quotes and ++ semicolons together. Patch by Ben Darnell and Petri Lehtinen. ++ ++- Issue #12448: smtplib now flushes stdout while running ``python -m smtplib`` ++ in order to display the prompt correctly. ++ ++- Issue #6090: zipfile raises a ValueError when a document with a timestamp ++ earlier than 1980 is provided. Patch contributed by Petri Lehtinen. ++ ++- Issue #13194: zlib.compressobj().copy() and zlib.decompressobj().copy() are ++ now available on Windows. ++ ++- Issue #13158: Fix decoding and encoding of GNU tar specific base-256 number ++ fields in tarfile. ++ ++- Issue #13177: Functools lru_cache() no longer calls the original function ++ inside an exception handler. This makes tracebacks easier to read because ++ chained exceptions are avoided. ++ ++- Issue #13025: mimetypes is now reading MIME types using the UTF-8 encoding, ++ instead of the locale encoding. ++ ++- Issue #10653: On Windows, use strftime() instead of wcsftime() because ++ wcsftime() doesn't format time zone correctly. ++ ++- Issue #11171: Fix distutils.sysconfig.get_makefile_filename when Python was ++ configured with different prefix and exec-prefix. ++ ++- Issue #11254: Teach distutils to compile .pyc and .pyo files in ++ PEP 3147-compliant __pycache__ directories. ++ ++- Issue #11250: Back port fix from 3.3 branch, so that 2to3 can handle files ++ with line feeds. This was ported from the sandbox to the 3.3 branch, but ++ didn't make it into 3.2. ++ ++- Issue #7367: Fix pkgutil.walk_paths to skip directories whose ++ contents cannot be read. ++ ++- Issue #13099: Fix sqlite3.Cursor.lastrowid under a Turkish locale. ++ Reported and diagnosed by Thomas Kluyver. ++ ++- Issue #13087: BufferedReader.seek() now always raises UnsupportedOperation ++ if the underlying raw stream is unseekable, even if the seek could be ++ satisfied using the internal buffer. Patch by John O'Connor. ++ ++- Issue #7689: Allow pickling of dynamically created classes when their ++ metaclass is registered with copyreg. Patch by Nicolas M. Thiéry and Craig ++ Citro. ++ ++- Issue #4147: minidom's toprettyxml no longer adds whitespace to text nodes. ++ ++- Issue #13034: When decoding some SSL certificates, the subjectAltName ++ extension could be unreported. ++ ++- Issue #9871: Prevent IDLE 3 crash when given byte stings ++ with invalid hex escape sequences, like b'\x0'. ++ (Original patch by Claudiu Popa.) ++ ++- Issue #8933: distutils' PKG-INFO files will now correctly report ++ Metadata-Version: 1.1 instead of 1.0 if a Classifier or Download-URL field is ++ present. ++ ++- Issue #9561: distutils now reads and writes egg-info files using UTF-8, ++ instead of the locale encoding. ++ ++- Issue #12888: Fix a bug in HTMLParser.unescape that prevented it to escape ++ more than 128 entities. Patch by Peter Otten. ++ ++- Issue #12878: Expose a __dict__ attribute on io.IOBase and its subclasses. ++ ++- Issue #12636: IDLE reads the coding cookie when executing a Python script. ++ ++- Issue #12847: Fix a crash with negative PUT and LONG_BINPUT arguments in ++ the C pickle implementation. ++ ++- Issue #11564: Avoid crashes when trying to pickle huge objects or containers ++ (more than 2**31 items). Instead, in most cases, an OverflowError is raised. ++ ++- Issue #12287: Fix a stack corruption in ossaudiodev module when the FD is ++ greater than FD_SETSIZE. ++ ++- Issue #11657: Fix sending file descriptors over 255 over a multiprocessing ++ Pipe. ++ ++- Issue #13007: whichdb should recognize gdbm 1.9 magic numbers. ++ ++- Issue #12213: Fix a buffering bug with interleaved reads and writes that ++ could appear on BufferedRandom streams. ++ ++- Issue #12650: Fix a race condition where a subprocess.Popen could leak ++ resources (FD/zombie) when killed at the wrong time. ++ ++- Issue #10860: http.client now correctly handles an empty port after port ++ delimiter in URLs. ++ ++Build ++----- ++ ++- Issue #13326: Clean __pycache__ directories correctly on OpenBSD. ++ ++Tests ++----- ++ ++- Issue #13304: Skip test case if user site-packages disabled (-s or ++ PYTHONNOUSERSITE). (Patch by Carl Meyer) ++ ++- Issue #13218: Fix test_ssl failures on Debian/Ubuntu. ++ ++- Issue #12821: Fix test_fcntl failures on OpenBSD 5. ++ ++- Re-enable lib2to3's test_parser.py tests, though with an expected failure ++ (see issue 13125). ++ ++Extension Modules ++----------------- ++ ++- Issue #13159: FileIO and BZ2File now use a linear-time buffer growth ++ strategy instead of a quadratic-time one. ++ ++- Issue #13070: Fix a crash when a TextIOWrapper caught in a reference cycle ++ would be finalized after the reference to its underlying BufferedRWPair's ++ writer got cleared by the GC. ++ ++- Issue #12881: ctypes: Fix segfault with large structure field names. ++ ++- Issue #13058: ossaudiodev: fix a file descriptor leak on error. Patch by ++ Thomas Jarosch. ++ ++- Issue #13013: ctypes: Fix a reference leak in PyCArrayType_from_ctype. ++ Thanks to Suman Saha for finding the bug and providing a patch. ++ ++- Issue #13022: Fix: _multiprocessing.recvfd() doesn't check that ++ file descriptor was actually received. ++ ++- Issue #12483: ctypes: Fix a crash when the destruction of a callback ++ object triggers the garbage collector. ++ ++- Issue #12950: Fix passing file descriptors in multiprocessing, under ++ OpenIndiana/Illumos. ++ ++Documentation ++------------- ++ ++- Issue #13513: Fix io.IOBase documentation to correctly link to the ++ io.IOBase.readline method instead of the readline module. ++ ++- Issue #13237: Reorganise subprocess documentation to emphasise convenience ++ functions and the most commonly needed arguments to Popen. ++ ++- Issue #13141: Demonstrate recommended style for socketserver examples. ++ ++ + What's New in Python 3.2.2? + =========================== + +@@ -19,6 +383,14 @@ + Library + ------- + ++- Issue #8286: The distutils command sdist will print a warning message instead ++ of crashing when an invalid path is given in the manifest template. ++ ++- Issue #12841: tarfile unnecessarily checked the existence of numerical user ++ and group ids on extraction. If one of them did not exist the respective id ++ of the current user (i.e. root) was used for the file and ownership ++ information was lost. ++ + - Issue #10946: The distutils commands bdist_dumb, bdist_wininst and bdist_msi + now respect a --skip-build option given to bdist. + +@@ -60,7 +432,7 @@ + - Issue #11627: Fix segfault when __new__ on a exception returns a + non-exception class. + +-- Issue #12149: Update the method cache after a type's dictionnary gets ++- Issue #12149: Update the method cache after a type's dictionary gets + cleared by the garbage collector. This fixes a segfault when an instance + and its type get caught in a reference cycle, and the instance's + deallocator calls one of the methods on the type (e.g. when subclassing +@@ -163,6 +535,11 @@ + Extension Modules + ----------------- + ++- Issue #12764: Fix a crash in ctypes when the name of a Structure field is not ++ a string. ++ ++- Issue #11241: subclasses of ctypes.Array can now be subclassed. ++ + - Issue #10309: Define _GNU_SOURCE so that mremap() gets the proper + signature. Without this, architectures where sizeof void* != sizeof int are + broken. Patch given by Hallvard B Furuseth. +@@ -251,6 +628,11 @@ + - Skip network tests when getaddrinfo() returns EAI_AGAIN, meaning a temporary + failure in name resolution. + ++- Issue #11812: Solve transient socket failure to connect to 'localhost' ++ in test_telnetlib.py. ++ ++- Solved a potential deadlock in test_telnetlib.py. Related to issue #11812. ++ + - Avoid failing in test_urllibnet.test_bad_address when some overzealous + DNS service (e.g. OpenDNS) resolves a non-existent domain name. The test + is now skipped instead. +diff -r 137e45f15c0b Misc/python.man +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -420,7 +420,7 @@ + .br + Documentation: http://docs.python.org/py3k/ + .br +-Developer resources: http://www.python.org/dev/ ++Developer resources: http://docs.python.org/devguide/ + .br + Downloads: http://python.org/download/ + .br +diff -r 137e45f15c0b Modules/Setup.dist +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -291,7 +291,7 @@ + #syslog syslogmodule.c # syslog daemon interface + + +-# Curses support, requring the System V version of curses, often ++# Curses support, requiring the System V version of curses, often + # provided by the ncurses library. e.g. on Linux, link with -lncurses + # instead of -lcurses). + # +diff -r 137e45f15c0b Modules/_ctypes/_ctypes.c +--- a/Modules/_ctypes/_ctypes.c ++++ b/Modules/_ctypes/_ctypes.c +@@ -1256,49 +1256,57 @@ + PyTypeObject *result; + StgDictObject *stgdict; + StgDictObject *itemdict; +- PyObject *proto; +- PyObject *typedict; ++ PyObject *length_attr, *type_attr; + long length; + int overflow; + Py_ssize_t itemsize, itemalign; + char buf[32]; + +- typedict = PyTuple_GetItem(args, 2); +- if (!typedict) ++ /* create the new instance (which is a class, ++ since we are a metatype!) */ ++ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); ++ if (result == NULL) + return NULL; + +- proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */ +- if (!proto || !PyLong_Check(proto)) { ++ /* Initialize these variables to NULL so that we can simplify error ++ handling by using Py_XDECREF. */ ++ stgdict = NULL; ++ type_attr = NULL; ++ ++ length_attr = PyObject_GetAttrString((PyObject *)result, "_length_"); ++ if (!length_attr || !PyLong_Check(length_attr)) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_length_' attribute, " + "which must be a positive integer"); +- return NULL; +- } +- length = PyLong_AsLongAndOverflow(proto, &overflow); ++ Py_XDECREF(length_attr); ++ goto error; ++ } ++ length = PyLong_AsLongAndOverflow(length_attr, &overflow); + if (overflow) { + PyErr_SetString(PyExc_OverflowError, + "The '_length_' attribute is too large"); +- return NULL; +- } +- +- proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */ +- if (!proto) { ++ Py_DECREF(length_attr); ++ goto error; ++ } ++ Py_DECREF(length_attr); ++ ++ type_attr = PyObject_GetAttrString((PyObject *)result, "_type_"); ++ if (!type_attr) { + PyErr_SetString(PyExc_AttributeError, + "class must define a '_type_' attribute"); +- return NULL; ++ goto error; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) +- return NULL; +- +- itemdict = PyType_stgdict(proto); ++ goto error; ++ ++ itemdict = PyType_stgdict(type_attr); + if (!itemdict) { + PyErr_SetString(PyExc_TypeError, + "_type_ must have storage info"); +- Py_DECREF((PyObject *)stgdict); +- return NULL; ++ goto error; + } + + assert(itemdict->format); +@@ -1309,16 +1317,12 @@ + sprintf(buf, "(%ld)", length); + stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format); + } +- if (stgdict->format == NULL) { +- Py_DECREF((PyObject *)stgdict); +- return NULL; +- } ++ if (stgdict->format == NULL) ++ goto error; + stgdict->ndim = itemdict->ndim + 1; + stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim); +- if (stgdict->shape == NULL) { +- Py_DECREF((PyObject *)stgdict); +- return NULL; +- } ++ if (stgdict->shape == NULL) ++ goto error; + stgdict->shape[0] = length; + memmove(&stgdict->shape[1], itemdict->shape, + sizeof(Py_ssize_t) * (stgdict->ndim - 1)); +@@ -1327,7 +1331,7 @@ + if (length * itemsize < 0) { + PyErr_SetString(PyExc_OverflowError, + "array too large"); +- return NULL; ++ goto error; + } + + itemalign = itemdict->align; +@@ -1338,26 +1342,16 @@ + stgdict->size = itemsize * length; + stgdict->align = itemalign; + stgdict->length = length; +- Py_INCREF(proto); +- stgdict->proto = proto; ++ stgdict->proto = type_attr; + + stgdict->paramfunc = &PyCArrayType_paramfunc; + + /* Arrays are passed as pointers to function calls. */ + stgdict->ffi_type_pointer = ffi_type_pointer; + +- /* create the new instance (which is a class, +- since we are a metatype!) */ +- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds); +- if (result == NULL) +- return NULL; +- + /* replace the class dict by our updated spam dict */ +- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) { +- Py_DECREF(result); +- Py_DECREF((PyObject *)stgdict); +- return NULL; +- } ++ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) ++ goto error; + Py_DECREF(result->tp_dict); + result->tp_dict = (PyObject *)stgdict; + +@@ -1366,15 +1360,20 @@ + */ + if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) { + if (-1 == add_getset(result, CharArray_getsets)) +- return NULL; ++ goto error; + #ifdef CTYPES_UNICODE + } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) { + if (-1 == add_getset(result, WCharArray_getsets)) +- return NULL; ++ goto error; + #endif + } + + return (PyObject *)result; ++error: ++ Py_XDECREF((PyObject*)stgdict); ++ Py_XDECREF(type_attr); ++ Py_DECREF(result); ++ return NULL; + } + + PyTypeObject PyCArrayType_Type = { +@@ -4475,6 +4474,7 @@ + if (!PyType_Check(itemtype)) { + PyErr_SetString(PyExc_TypeError, + "Expected a type object"); ++ Py_DECREF(key); + return NULL; + } + #ifdef MS_WIN64 +diff -r 137e45f15c0b Modules/_ctypes/callbacks.c +--- a/Modules/_ctypes/callbacks.c ++++ b/Modules/_ctypes/callbacks.c +@@ -13,6 +13,7 @@ + CThunkObject_dealloc(PyObject *_self) + { + CThunkObject *self = (CThunkObject *)_self; ++ PyObject_GC_UnTrack(self); + Py_XDECREF(self->converters); + Py_XDECREF(self->callable); + Py_XDECREF(self->restype); +diff -r 137e45f15c0b Modules/_ctypes/stgdict.c +--- a/Modules/_ctypes/stgdict.c ++++ b/Modules/_ctypes/stgdict.c +@@ -482,14 +482,33 @@ + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = _PyUnicode_AsString(name); + char *ptr; +- Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt); +- char *buf = alloca(len + 2 + 1); ++ Py_ssize_t len; ++ char *buf; + ++ if (fieldname == NULL) ++ { ++ PyErr_Format(PyExc_TypeError, ++ "structure field name must be string not %s", ++ name->ob_type->tp_name); ++ ++ Py_DECREF(pair); ++ return -1; ++ } ++ ++ len = strlen(fieldname) + strlen(fieldfmt); ++ ++ buf = PyMem_Malloc(len + 2 + 1); ++ if (buf == NULL) { ++ Py_DECREF(pair); ++ PyErr_NoMemory(); ++ return -1; ++ } + sprintf(buf, "%s:%s:", fieldfmt, fieldname); + + ptr = stgdict->format; + stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); + PyMem_Free(ptr); ++ PyMem_Free(buf); + + if (stgdict->format == NULL) { + Py_DECREF(pair); +diff -r 137e45f15c0b Modules/_cursesmodule.c +--- a/Modules/_cursesmodule.c ++++ b/Modules/_cursesmodule.c +@@ -2379,7 +2379,8 @@ + { + char *str; + +- if (!PyArg_ParseTuple(args,"s;str", &str)) return NULL; ++ if (!PyArg_ParseTuple(args,"y;str", &str)) ++ return NULL; + return PyCursesCheckERR(putp(str), "putp"); + } + +@@ -2600,7 +2601,7 @@ + + PyCursesSetupTermCalled; + +- if (!PyArg_ParseTuple(args, "s|iiiiiiiii:tparm", ++ if (!PyArg_ParseTuple(args, "y|iiiiiiiii:tparm", + &fmt, &i1, &i2, &i3, &i4, + &i5, &i6, &i7, &i8, &i9)) { + return NULL; +diff -r 137e45f15c0b Modules/_elementtree.c +--- a/Modules/_elementtree.c ++++ b/Modules/_elementtree.c +@@ -3000,6 +3000,7 @@ + " self._file = file\n" + " self._events = []\n" + " self._index = 0\n" ++ " self._error = None\n" + " self.root = self._root = None\n" + " b = cElementTree.TreeBuilder()\n" + " self._parser = cElementTree.XMLParser(b)\n" +@@ -3008,24 +3009,31 @@ + " while 1:\n" + " try:\n" + " item = self._events[self._index]\n" ++ " self._index += 1\n" ++ " return item\n" + " except IndexError:\n" +- " if self._parser is None:\n" +- " self.root = self._root\n" +- " if self._close_file:\n" +- " self._file.close()\n" +- " raise StopIteration\n" +- " # load event buffer\n" +- " del self._events[:]\n" +- " self._index = 0\n" +- " data = self._file.read(16384)\n" +- " if data:\n" ++ " pass\n" ++ " if self._error:\n" ++ " e = self._error\n" ++ " self._error = None\n" ++ " raise e\n" ++ " if self._parser is None:\n" ++ " self.root = self._root\n" ++ " if self._close_file:\n" ++ " self._file.close()\n" ++ " raise StopIteration\n" ++ " # load event buffer\n" ++ " del self._events[:]\n" ++ " self._index = 0\n" ++ " data = self._file.read(16384)\n" ++ " if data:\n" ++ " try:\n" + " self._parser.feed(data)\n" +- " else:\n" +- " self._root = self._parser.close()\n" +- " self._parser = None\n" ++ " except SyntaxError as exc:\n" ++ " self._error = exc\n" + " else:\n" +- " self._index = self._index + 1\n" +- " return item\n" ++ " self._root = self._parser.close()\n" ++ " self._parser = None\n" + " def __iter__(self):\n" + " return self\n" + "cElementTree.iterparse = iterparse\n" +diff -r 137e45f15c0b Modules/_io/bufferedio.c +--- a/Modules/_io/bufferedio.c ++++ b/Modules/_io/bufferedio.c +@@ -581,7 +581,7 @@ + + /* Forward decls */ + static PyObject * +-_bufferedwriter_flush_unlocked(buffered *, int); ++_bufferedwriter_flush_unlocked(buffered *); + static Py_ssize_t + _bufferedreader_fill_buffer(buffered *self); + static void +@@ -602,6 +602,18 @@ + * Helpers + */ + ++/* Sets the current error to BlockingIOError */ ++static void ++_set_BlockingIOError(char *msg, Py_ssize_t written) ++{ ++ PyObject *err; ++ err = PyObject_CallFunction(PyExc_BlockingIOError, "isn", ++ errno, msg, written); ++ if (err) ++ PyErr_SetObject(PyExc_BlockingIOError, err); ++ Py_XDECREF(err); ++} ++ + /* Returns the address of the `written` member if a BlockingIOError was + raised, NULL otherwise. The error is always re-raised. */ + static Py_ssize_t * +@@ -752,6 +764,28 @@ + */ + + static PyObject * ++buffered_flush_and_rewind_unlocked(buffered *self) ++{ ++ PyObject *res; ++ ++ res = _bufferedwriter_flush_unlocked(self); ++ if (res == NULL) ++ return NULL; ++ Py_DECREF(res); ++ ++ if (self->readable) { ++ /* Rewind the raw stream so that its position corresponds to ++ the current logical position. */ ++ Py_off_t n; ++ n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1); ++ _bufferedreader_reset_buf(self); ++ if (n == -1) ++ return NULL; ++ } ++ Py_RETURN_NONE; ++} ++ ++static PyObject * + buffered_flush(buffered *self, PyObject *args) + { + PyObject *res; +@@ -761,16 +795,7 @@ + + if (!ENTER_BUFFERED(self)) + return NULL; +- res = _bufferedwriter_flush_unlocked(self, 0); +- if (res != NULL && self->readable) { +- /* Rewind the raw stream so that its position corresponds to +- the current logical position. */ +- Py_off_t n; +- n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1); +- if (n == -1) +- Py_CLEAR(res); +- _bufferedreader_reset_buf(self); +- } ++ res = buffered_flush_and_rewind_unlocked(self); + LEAVE_BUFFERED(self) + + return res; +@@ -791,7 +816,7 @@ + return NULL; + + if (self->writable) { +- res = _bufferedwriter_flush_unlocked(self, 1); ++ res = buffered_flush_and_rewind_unlocked(self); + if (res == NULL) + goto end; + Py_CLEAR(res); +@@ -826,19 +851,18 @@ + if (!ENTER_BUFFERED(self)) + return NULL; + res = _bufferedreader_read_all(self); +- LEAVE_BUFFERED(self) + } + else { + res = _bufferedreader_read_fast(self, n); +- if (res == Py_None) { +- Py_DECREF(res); +- if (!ENTER_BUFFERED(self)) +- return NULL; +- res = _bufferedreader_read_generic(self, n); +- LEAVE_BUFFERED(self) +- } ++ if (res != Py_None) ++ return res; ++ Py_DECREF(res); ++ if (!ENTER_BUFFERED(self)) ++ return NULL; ++ res = _bufferedreader_read_generic(self, n); + } + ++ LEAVE_BUFFERED(self) + return res; + } + +@@ -864,13 +888,6 @@ + if (!ENTER_BUFFERED(self)) + return NULL; + +- if (self->writable) { +- res = _bufferedwriter_flush_unlocked(self, 1); +- if (res == NULL) +- goto end; +- Py_CLEAR(res); +- } +- + /* Return up to n bytes. If at least one byte is buffered, we + only return buffered bytes. Otherwise, we do one raw read. */ + +@@ -890,6 +907,13 @@ + goto end; + } + ++ if (self->writable) { ++ res = buffered_flush_and_rewind_unlocked(self); ++ if (res == NULL) ++ goto end; ++ Py_DECREF(res); ++ } ++ + /* Fill the buffer from the raw stream, and copy it to the result. */ + _bufferedreader_reset_buf(self); + r = _bufferedreader_fill_buffer(self); +@@ -912,24 +936,10 @@ + static PyObject * + buffered_readinto(buffered *self, PyObject *args) + { +- PyObject *res = NULL; +- + CHECK_INITIALIZED(self) + +- /* TODO: use raw.readinto() instead! */ +- if (self->writable) { +- if (!ENTER_BUFFERED(self)) +- return NULL; +- res = _bufferedwriter_flush_unlocked(self, 0); +- LEAVE_BUFFERED(self) +- if (res == NULL) +- goto end; +- Py_DECREF(res); +- } +- res = bufferediobase_readinto((PyObject *)self, args); +- +-end: +- return res; ++ /* TODO: use raw.readinto() (or a direct copy from our buffer) instead! */ ++ return bufferediobase_readinto((PyObject *)self, args); + } + + static PyObject * +@@ -967,12 +977,6 @@ + goto end_unlocked; + + /* Now we try to get some more from the raw stream */ +- if (self->writable) { +- res = _bufferedwriter_flush_unlocked(self, 1); +- if (res == NULL) +- goto end; +- Py_CLEAR(res); +- } + chunks = PyList_New(0); + if (chunks == NULL) + goto end; +@@ -986,9 +990,16 @@ + } + Py_CLEAR(res); + written += n; ++ self->pos += n; + if (limit >= 0) + limit -= n; + } ++ if (self->writable) { ++ PyObject *r = buffered_flush_and_rewind_unlocked(self); ++ if (r == NULL) ++ goto end; ++ Py_DECREF(r); ++ } + + for (;;) { + _bufferedreader_reset_buf(self); +@@ -1087,6 +1098,9 @@ + + CHECK_CLOSED(self, "seek of closed file") + ++ if (_PyIOBase_check_seekable(self->raw, Py_True) == NULL) ++ return NULL; ++ + target = PyNumber_AsOff_t(targetobj, PyExc_ValueError); + if (target == -1 && PyErr_Occurred()) + return NULL; +@@ -1119,7 +1133,7 @@ + + /* Fallback: invoke raw seek() method and clear buffer */ + if (self->writable) { +- res = _bufferedwriter_flush_unlocked(self, 0); ++ res = _bufferedwriter_flush_unlocked(self); + if (res == NULL) + goto end; + Py_CLEAR(res); +@@ -1157,20 +1171,11 @@ + return NULL; + + if (self->writable) { +- res = _bufferedwriter_flush_unlocked(self, 0); ++ res = buffered_flush_and_rewind_unlocked(self); + if (res == NULL) + goto end; + Py_CLEAR(res); + } +- if (self->readable) { +- if (pos == Py_None) { +- /* Rewind the raw stream so that its position corresponds to +- the current logical position. */ +- if (_buffered_raw_seek(self, -RAW_OFFSET(self), 1) == -1) +- goto end; +- } +- _bufferedreader_reset_buf(self); +- } + res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_truncate, pos, NULL); + if (res == NULL) + goto end; +@@ -1367,17 +1372,18 @@ + Py_DECREF(chunks); + return NULL; + } ++ self->pos += current_size; + } +- _bufferedreader_reset_buf(self); + /* We're going past the buffer's bounds, flush it */ + if (self->writable) { +- res = _bufferedwriter_flush_unlocked(self, 1); ++ res = buffered_flush_and_rewind_unlocked(self); + if (res == NULL) { + Py_DECREF(chunks); + return NULL; + } + Py_CLEAR(res); + } ++ _bufferedreader_reset_buf(self); + while (1) { + if (data) { + if (PyList_Append(chunks, data) < 0) { +@@ -1460,6 +1466,14 @@ + memcpy(out, self->buffer + self->pos, current_size); + remaining -= current_size; + written += current_size; ++ self->pos += current_size; ++ } ++ /* Flush the write buffer if necessary */ ++ if (self->writable) { ++ PyObject *r = buffered_flush_and_rewind_unlocked(self); ++ if (r == NULL) ++ goto error; ++ Py_DECREF(r); + } + _bufferedreader_reset_buf(self); + while (remaining > 0) { +@@ -1712,6 +1726,7 @@ + Py_buffer buf; + PyObject *memobj, *res; + Py_ssize_t n; ++ int errnum; + /* NOTE: the buffer needn't be released as its object is NULL. */ + if (PyBuffer_FillInfo(&buf, NULL, start, len, 1, PyBUF_CONTIG_RO) == -1) + return -1; +@@ -1724,11 +1739,21 @@ + raised (see issue #10956). + */ + do { ++ errno = 0; + res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_write, memobj, NULL); ++ errnum = errno; + } while (res == NULL && _trap_eintr()); + Py_DECREF(memobj); + if (res == NULL) + return -1; ++ if (res == Py_None) { ++ /* Non-blocking stream would have blocked. Special return code! ++ Being paranoid we reset errno in case it is changed by code ++ triggered by a decref. errno is used by _set_BlockingIOError(). */ ++ Py_DECREF(res); ++ errno = errnum; ++ return -2; ++ } + n = PyNumber_AsSsize_t(res, PyExc_ValueError); + Py_DECREF(res); + if (n < 0 || n > len) { +@@ -1745,7 +1770,7 @@ + /* `restore_pos` is 1 if we need to restore the raw stream position at + the end, 0 otherwise. */ + static PyObject * +-_bufferedwriter_flush_unlocked(buffered *self, int restore_pos) ++_bufferedwriter_flush_unlocked(buffered *self) + { + Py_ssize_t written = 0; + Py_off_t n, rewind; +@@ -1767,14 +1792,11 @@ + Py_SAFE_DOWNCAST(self->write_end - self->write_pos, + Py_off_t, Py_ssize_t)); + if (n == -1) { +- Py_ssize_t *w = _buffered_check_blocking_error(); +- if (w == NULL) +- goto error; +- self->write_pos += *w; +- self->raw_pos = self->write_pos; +- written += *w; +- *w = written; +- /* Already re-raised */ ++ goto error; ++ } ++ else if (n == -2) { ++ _set_BlockingIOError("write could not complete without blocking", ++ 0); + goto error; + } + self->write_pos += n; +@@ -1787,16 +1809,6 @@ + goto error; + } + +- if (restore_pos) { +- Py_off_t forward = rewind - written; +- if (forward != 0) { +- n = _buffered_raw_seek(self, forward, 1); +- if (n < 0) { +- goto error; +- } +- self->raw_pos += forward; +- } +- } + _bufferedwriter_reset_buf(self); + + end: +@@ -1849,7 +1861,7 @@ + } + + /* First write the current buffer */ +- res = _bufferedwriter_flush_unlocked(self, 0); ++ res = _bufferedwriter_flush_unlocked(self); + if (res == NULL) { + Py_ssize_t *w = _buffered_check_blocking_error(); + if (w == NULL) +@@ -1872,14 +1884,19 @@ + PyErr_Clear(); + memcpy(self->buffer + self->write_end, buf.buf, buf.len); + self->write_end += buf.len; ++ self->pos += buf.len; + written = buf.len; + goto end; + } + /* Buffer as much as possible. */ + memcpy(self->buffer + self->write_end, buf.buf, avail); + self->write_end += avail; +- /* Already re-raised */ +- *w = avail; ++ self->pos += avail; ++ /* XXX Modifying the existing exception e using the pointer w ++ will change e.characters_written but not e.args[2]. ++ Therefore we just replace with a new error. */ ++ _set_BlockingIOError("write could not complete without blocking", ++ avail); + goto error; + } + Py_CLEAR(res); +@@ -1904,11 +1921,9 @@ + Py_ssize_t n = _bufferedwriter_raw_write( + self, (char *) buf.buf + written, buf.len - written); + if (n == -1) { +- Py_ssize_t *w = _buffered_check_blocking_error(); +- if (w == NULL) +- goto error; +- written += *w; +- remaining -= *w; ++ goto error; ++ } else if (n == -2) { ++ /* Write failed because raw file is non-blocking */ + if (remaining > self->buffer_size) { + /* Can't buffer everything, still buffer as much as possible */ + memcpy(self->buffer, +@@ -1916,8 +1931,9 @@ + self->raw_pos = 0; + ADJUST_POSITION(self, self->buffer_size); + self->write_end = self->buffer_size; +- *w = written + self->buffer_size; +- /* Already re-raised */ ++ written += self->buffer_size; ++ _set_BlockingIOError("write could not complete without " ++ "blocking", written); + goto error; + } + PyErr_Clear(); +@@ -2210,6 +2226,11 @@ + static PyObject * + bufferedrwpair_closed_get(rwpair *self, void *context) + { ++ if (self->writer == NULL) { ++ PyErr_SetString(PyExc_RuntimeError, ++ "the BufferedRWPair object is being garbage-collected"); ++ return NULL; ++ } + return PyObject_GetAttr((PyObject *) self->writer, _PyIO_str_closed); + } + +diff -r 137e45f15c0b Modules/_io/fileio.c +--- a/Modules/_io/fileio.c ++++ b/Modules/_io/fileio.c +@@ -43,12 +43,6 @@ + #define SMALLCHUNK BUFSIZ + #endif + +-#if SIZEOF_INT < 4 +-#define BIGCHUNK (512 * 32) +-#else +-#define BIGCHUNK (512 * 1024) +-#endif +- + typedef struct { + PyObject_HEAD + int fd; +@@ -512,6 +506,7 @@ + { + Py_buffer pbuf; + Py_ssize_t n, len; ++ int err; + + if (self->fd < 0) + return err_closed(); +@@ -535,10 +530,12 @@ + Py_END_ALLOW_THREADS + } else + n = -1; ++ err = errno; + PyBuffer_Release(&pbuf); + if (n < 0) { +- if (errno == EAGAIN) ++ if (err == EAGAIN) + Py_RETURN_NONE; ++ errno = err; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } +@@ -565,15 +562,10 @@ + } + } + #endif +- if (currentsize > SMALLCHUNK) { +- /* Keep doubling until we reach BIGCHUNK; +- then keep adding BIGCHUNK. */ +- if (currentsize <= BIGCHUNK) +- return currentsize + currentsize; +- else +- return currentsize + BIGCHUNK; +- } +- return currentsize + SMALLCHUNK; ++ /* Expand the buffer by an amount proportional to the current size, ++ giving us amortized linear-time behavior. Use a less-than-double ++ growth factor to avoid excessive allocation. */ ++ return currentsize + (currentsize >> 3) + 6; + } + + static PyObject * +@@ -686,9 +678,11 @@ + n = -1; + + if (n < 0) { ++ int err = errno; + Py_DECREF(bytes); +- if (errno == EAGAIN) ++ if (err == EAGAIN) + Py_RETURN_NONE; ++ errno = err; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } +@@ -708,6 +702,7 @@ + { + Py_buffer pbuf; + Py_ssize_t n, len; ++ int err; + + if (self->fd < 0) + return err_closed(); +@@ -738,12 +733,14 @@ + Py_END_ALLOW_THREADS + } else + n = -1; ++ err = errno; + + PyBuffer_Release(&pbuf); + + if (n < 0) { +- if (errno == EAGAIN) ++ if (err == EAGAIN) + Py_RETURN_NONE; ++ errno = err; + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } +diff -r 137e45f15c0b Modules/_io/iobase.c +--- a/Modules/_io/iobase.c ++++ b/Modules/_io/iobase.c +@@ -156,6 +156,19 @@ + return PyBool_FromLong(IS_CLOSED(self)); + } + ++static PyObject * ++iobase_get_dict(PyObject *self) ++{ ++ PyObject **dictptr = _PyObject_GetDictPtr(self); ++ PyObject *dict; ++ assert(dictptr); ++ dict = *dictptr; ++ if (dict == NULL) ++ dict = *dictptr = PyDict_New(); ++ Py_XINCREF(dict); ++ return dict; ++} ++ + PyObject * + _PyIOBase_check_closed(PyObject *self, PyObject *args) + { +@@ -691,6 +704,7 @@ + }; + + static PyGetSetDef iobase_getset[] = { ++ {"__dict__", (getter)iobase_get_dict, NULL, NULL}, + {"closed", (getter)iobase_closed_get, NULL, NULL}, + {NULL} + }; +diff -r 137e45f15c0b Modules/_multiprocessing/multiprocessing.c +--- a/Modules/_multiprocessing/multiprocessing.c ++++ b/Modules/_multiprocessing/multiprocessing.c +@@ -8,7 +8,7 @@ + + #include "multiprocessing.h" + +-#ifdef SCM_RIGHTS ++#if (defined(CMSG_LEN) && defined(SCM_RIGHTS)) + #define HAVE_FD_TRANSFER 1 + #else + #define HAVE_FD_TRANSFER 0 +@@ -97,32 +97,38 @@ + /* Functions for transferring file descriptors between processes. + Reimplements some of the functionality of the fdcred + module at http://www.mca-ltd.com/resources/fdcred_1.tgz. */ ++/* Based in http://resin.csoft.net/cgi-bin/man.cgi?section=3&topic=CMSG_DATA */ + + static PyObject * + multiprocessing_sendfd(PyObject *self, PyObject *args) + { + int conn, fd, res; ++ struct iovec dummy_iov; + char dummy_char; +- char buf[CMSG_SPACE(sizeof(int))]; +- struct msghdr msg = {0}; +- struct iovec dummy_iov; ++ struct msghdr msg; + struct cmsghdr *cmsg; ++ union { ++ struct cmsghdr hdr; ++ unsigned char buf[CMSG_SPACE(sizeof(int))]; ++ } cmsgbuf; + + if (!PyArg_ParseTuple(args, "ii", &conn, &fd)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; +- msg.msg_control = buf; +- msg.msg_controllen = sizeof(buf); ++ ++ memset(&msg, 0, sizeof(msg)); ++ msg.msg_control = &cmsgbuf.buf; ++ msg.msg_controllen = sizeof(cmsgbuf.buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; ++ + cmsg = CMSG_FIRSTHDR(&msg); ++ cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; +- cmsg->cmsg_len = CMSG_LEN(sizeof(int)); +- msg.msg_controllen = cmsg->cmsg_len; +- *CMSG_DATA(cmsg) = fd; ++ * (int *) CMSG_DATA(cmsg) = fd; + + Py_BEGIN_ALLOW_THREADS + res = sendmsg(conn, &msg, 0); +@@ -138,20 +144,26 @@ + { + int conn, fd, res; + char dummy_char; +- char buf[CMSG_SPACE(sizeof(int))]; ++ struct iovec dummy_iov; + struct msghdr msg = {0}; +- struct iovec dummy_iov; + struct cmsghdr *cmsg; ++ union { ++ struct cmsghdr hdr; ++ unsigned char buf[CMSG_SPACE(sizeof(int))]; ++ } cmsgbuf; + + if (!PyArg_ParseTuple(args, "i", &conn)) + return NULL; + + dummy_iov.iov_base = &dummy_char; + dummy_iov.iov_len = 1; +- msg.msg_control = buf; +- msg.msg_controllen = sizeof(buf); ++ ++ memset(&msg, 0, sizeof(msg)); ++ msg.msg_control = &cmsgbuf.buf; ++ msg.msg_controllen = sizeof(cmsgbuf.buf); + msg.msg_iov = &dummy_iov; + msg.msg_iovlen = 1; ++ + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; +@@ -165,7 +177,18 @@ + if (res < 0) + return PyErr_SetFromErrno(PyExc_OSError); + +- fd = *CMSG_DATA(cmsg); ++ if (msg.msg_controllen < CMSG_LEN(sizeof(int)) || ++ (cmsg = CMSG_FIRSTHDR(&msg)) == NULL || ++ cmsg->cmsg_level != SOL_SOCKET || ++ cmsg->cmsg_type != SCM_RIGHTS || ++ cmsg->cmsg_len < CMSG_LEN(sizeof(int))) { ++ /* If at least one control message is present, there should be ++ no room for any further data in the buffer. */ ++ PyErr_SetString(PyExc_RuntimeError, "No file descriptor received"); ++ return NULL; ++ } ++ ++ fd = * (int *) CMSG_DATA(cmsg); + return Py_BuildValue("i", fd); + } + +diff -r 137e45f15c0b Modules/_multiprocessing/semaphore.c +--- a/Modules/_multiprocessing/semaphore.c ++++ b/Modules/_multiprocessing/semaphore.c +@@ -267,7 +267,7 @@ + static PyObject * + semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds) + { +- int blocking = 1, res; ++ int blocking = 1, res, err = 0; + double timeout; + PyObject *timeout_obj = Py_None; + struct timespec deadline = {0}; +@@ -313,11 +313,13 @@ + else + res = sem_timedwait(self->handle, &deadline); + Py_END_ALLOW_THREADS ++ err = errno; + if (res == MP_EXCEPTION_HAS_BEEN_SET) + break; + } while (res < 0 && errno == EINTR && !PyErr_CheckSignals()); + + if (res < 0) { ++ errno = err; + if (errno == EAGAIN || errno == ETIMEDOUT) + Py_RETURN_FALSE; + else if (errno == EINTR) +diff -r 137e45f15c0b Modules/_pickle.c +--- a/Modules/_pickle.c ++++ b/Modules/_pickle.c +@@ -153,7 +153,7 @@ + static void + Pdata_dealloc(Pdata *self) + { +- int i = Py_SIZE(self); ++ Py_ssize_t i = Py_SIZE(self); + while (--i >= 0) { + Py_DECREF(self->data[i]); + } +@@ -190,9 +190,9 @@ + * number of items, this is a (non-erroneous) NOP. + */ + static int +-Pdata_clear(Pdata *self, int clearto) +-{ +- int i = Py_SIZE(self); ++Pdata_clear(Pdata *self, Py_ssize_t clearto) ++{ ++ Py_ssize_t i = Py_SIZE(self); + + if (clearto < 0) + return stack_underflow(); +@@ -303,7 +303,7 @@ + + typedef struct { + PyObject *me_key; +- long me_value; ++ Py_ssize_t me_value; + } PyMemoEntry; + + typedef struct { +@@ -328,7 +328,7 @@ + Py_ssize_t max_output_len; /* Allocation size of output_buffer. */ + int proto; /* Pickle protocol number, >= 0 */ + int bin; /* Boolean, true if proto > 0 */ +- int buf_size; /* Size of the current buffered pickle data */ ++ Py_ssize_t buf_size; /* Size of the current buffered pickle data */ + int fast; /* Enable fast mode if set to a true value. + The fast mode disable the usage of memo, + therefore speeding the pickling process by +@@ -369,7 +369,7 @@ + char *errors; /* Name of errors handling scheme to used when + decoding strings. The default value is + "strict". */ +- int *marks; /* Mark stack, used for unpickling container ++ Py_ssize_t *marks; /* Mark stack, used for unpickling container + objects. */ + Py_ssize_t num_marks; /* Number of marks in the mark stack. */ + Py_ssize_t marks_size; /* Current allocated size of the mark stack. */ +@@ -556,7 +556,7 @@ + } + + /* Returns NULL on failure, a pointer to the value otherwise. */ +-static long * ++static Py_ssize_t * + PyMemoTable_Get(PyMemoTable *self, PyObject *key) + { + PyMemoEntry *entry = _PyMemoTable_Lookup(self, key); +@@ -567,7 +567,7 @@ + + /* Returns -1 on failure, 0 on success. */ + static int +-PyMemoTable_Set(PyMemoTable *self, PyObject *key, long value) ++PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value) + { + PyMemoEntry *entry; + +@@ -700,7 +700,7 @@ + return (result == NULL) ? -1 : 0; + } + +-static int ++static Py_ssize_t + _Pickler_Write(PicklerObject *self, const char *s, Py_ssize_t n) + { + Py_ssize_t i, required; +@@ -735,7 +735,7 @@ + PyErr_NoMemory(); + return -1; + } +- self->max_output_len = (self->output_len + n) * 2; ++ self->max_output_len = (self->output_len + n) / 2 * 3; + if (_PyBytes_Resize(&self->output_buffer, self->max_output_len) < 0) + return -1; + } +@@ -1219,9 +1219,9 @@ + static int + memo_get(PicklerObject *self, PyObject *key) + { +- long *value; ++ Py_ssize_t *value; + char pdata[30]; +- int len; ++ Py_ssize_t len; + + value = PyMemoTable_Get(self->memo, key); + if (value == NULL) { +@@ -1231,8 +1231,9 @@ + + if (!self->bin) { + pdata[0] = GET; +- PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, "%ld\n", *value); +- len = (int)strlen(pdata); ++ PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, ++ "%" PY_FORMAT_SIZE_T "d\n", *value); ++ len = strlen(pdata); + } + else { + if (*value < 256) { +@@ -1266,9 +1267,9 @@ + static int + memo_put(PicklerObject *self, PyObject *obj) + { +- long x; ++ Py_ssize_t x; + char pdata[30]; +- int len; ++ Py_ssize_t len; + int status = 0; + + if (self->fast) +@@ -1280,7 +1281,8 @@ + + if (!self->bin) { + pdata[0] = PUT; +- PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, "%ld\n", x); ++ PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, ++ "%" PY_FORMAT_SIZE_T "d\n", x); + len = strlen(pdata); + } + else { +@@ -1482,7 +1484,7 @@ + save_int(PicklerObject *self, long x) + { + char pdata[32]; +- int len = 0; ++ Py_ssize_t len = 0; + + if (!self->bin + #if SIZEOF_LONG > 4 +@@ -1609,7 +1611,7 @@ + } + else { + header[0] = LONG4; +- size = (int)nbytes; ++ size = (Py_ssize_t) nbytes; + for (i = 1; i < 5; i++) { + header[i] = (unsigned char)(size & 0xff); + size >>= 8; +@@ -1698,34 +1700,66 @@ + if (self->proto < 3) { + /* Older pickle protocols do not have an opcode for pickling bytes + objects. Therefore, we need to fake the copy protocol (i.e., +- the __reduce__ method) to permit bytes object unpickling. */ ++ the __reduce__ method) to permit bytes object unpickling. ++ ++ Here we use a hack to be compatible with Python 2. Since in Python ++ 2 'bytes' is just an alias for 'str' (which has different ++ parameters than the actual bytes object), we use codecs.encode ++ to create the appropriate 'str' object when unpickled using ++ Python 2 *and* the appropriate 'bytes' object when unpickled ++ using Python 3. Again this is a hack and we don't need to do this ++ with newer protocols. */ ++ static PyObject *codecs_encode = NULL; + PyObject *reduce_value = NULL; +- PyObject *bytelist = NULL; + int status; + +- bytelist = PySequence_List(obj); +- if (bytelist == NULL) ++ if (codecs_encode == NULL) { ++ PyObject *codecs_module = PyImport_ImportModule("codecs"); ++ if (codecs_module == NULL) { ++ return -1; ++ } ++ codecs_encode = PyObject_GetAttrString(codecs_module, "encode"); ++ Py_DECREF(codecs_module); ++ if (codecs_encode == NULL) { ++ return -1; ++ } ++ } ++ ++ if (PyBytes_GET_SIZE(obj) == 0) { ++ reduce_value = Py_BuildValue("(O())", (PyObject*)&PyBytes_Type); ++ } ++ else { ++ static PyObject *latin1 = NULL; ++ PyObject *unicode_str = ++ PyUnicode_DecodeLatin1(PyBytes_AS_STRING(obj), ++ PyBytes_GET_SIZE(obj), ++ "strict"); ++ if (unicode_str == NULL) ++ return -1; ++ if (latin1 == NULL) { ++ latin1 = PyUnicode_InternFromString("latin1"); ++ if (latin1 == NULL) ++ return -1; ++ } ++ reduce_value = Py_BuildValue("(O(OO))", ++ codecs_encode, unicode_str, latin1); ++ Py_DECREF(unicode_str); ++ } ++ ++ if (reduce_value == NULL) + return -1; + +- reduce_value = Py_BuildValue("(O(O))", (PyObject *)&PyBytes_Type, +- bytelist); +- if (reduce_value == NULL) { +- Py_DECREF(bytelist); +- return -1; +- } +- + /* save_reduce() will memoize the object automatically. */ + status = save_reduce(self, reduce_value, obj); + Py_DECREF(reduce_value); +- Py_DECREF(bytelist); + return status; + } + else { + Py_ssize_t size; + char header[5]; +- int len; +- +- size = PyBytes_Size(obj); ++ Py_ssize_t len; ++ ++ size = PyBytes_GET_SIZE(obj); + if (size < 0) + return -1; + +@@ -1743,6 +1777,8 @@ + len = 5; + } + else { ++ PyErr_SetString(PyExc_OverflowError, ++ "cannot serialize a bytes object larger than 4GB"); + return -1; /* string too large */ + } + +@@ -1867,8 +1903,11 @@ + goto error; + + size = PyBytes_GET_SIZE(encoded); +- if (size < 0 || size > 0xffffffffL) ++ if (size > 0xffffffffL) { ++ PyErr_SetString(PyExc_OverflowError, ++ "cannot serialize a string larger than 4GB"); + goto error; /* string too large */ ++ } + + pdata[0] = BINUNICODE; + pdata[1] = (unsigned char)(size & 0xff); +@@ -1913,9 +1952,9 @@ + + /* A helper for save_tuple. Push the len elements in tuple t on the stack. */ + static int +-store_tuple_elements(PicklerObject *self, PyObject *t, int len) +-{ +- int i; ++store_tuple_elements(PicklerObject *self, PyObject *t, Py_ssize_t len) ++{ ++ Py_ssize_t i; + + assert(PyTuple_Size(t) == len); + +@@ -1940,7 +1979,7 @@ + static int + save_tuple(PicklerObject *self, PyObject *obj) + { +- int len, i; ++ Py_ssize_t len, i; + + const char mark_op = MARK; + const char tuple_op = TUPLE; +@@ -2163,7 +2202,7 @@ + batch_list_exact(PicklerObject *self, PyObject *obj) + { + PyObject *item = NULL; +- int this_batch, total; ++ Py_ssize_t this_batch, total; + + const char append_op = APPEND; + const char appends_op = APPENDS; +@@ -2208,7 +2247,7 @@ + save_list(PicklerObject *self, PyObject *obj) + { + char header[3]; +- int len; ++ Py_ssize_t len; + int status = 0; + + if (self->fast && !fast_save_enter(self, obj)) +@@ -2468,7 +2507,7 @@ + { + PyObject *items, *iter; + char header[3]; +- int len; ++ Py_ssize_t len; + int status = 0; + + if (self->fast && !fast_save_enter(self, obj)) +@@ -2603,7 +2642,7 @@ + PyObject *code_obj; /* extension code as Python object */ + long code; /* extension code as C value */ + char pdata[5]; +- int n; ++ Py_ssize_t n; + + PyTuple_SET_ITEM(two_tuple, 0, module_name); + PyTuple_SET_ITEM(two_tuple, 1, global_name); +@@ -2626,9 +2665,10 @@ + } + code = PyLong_AS_LONG(code_obj); + if (code <= 0 || code > 0x7fffffffL) { +- PyErr_Format(PicklingError, +- "Can't pickle %R: extension code %ld is out of range", +- obj, code); ++ if (!PyErr_Occurred()) ++ PyErr_Format(PicklingError, ++ "Can't pickle %R: extension code %ld is out of range", ++ obj, code); + goto error; + } + +@@ -3133,10 +3173,6 @@ + status = save_global(self, obj, NULL); + goto done; + } +- else if (PyType_IsSubtype(type, &PyType_Type)) { +- status = save_global(self, obj, NULL); +- goto done; +- } + + /* XXX: This part needs some unit tests. */ + +@@ -3155,6 +3191,10 @@ + Py_INCREF(obj); + reduce_value = _Pickler_FastCall(self, reduce_func, obj); + } ++ else if (PyType_IsSubtype(type, &PyType_Type)) { ++ status = save_global(self, obj, NULL); ++ goto done; ++ } + else { + static PyObject *reduce_str = NULL; + static PyObject *reduce_ex_str = NULL; +@@ -3477,7 +3517,7 @@ + PyObject *key, *value; + + key = PyLong_FromVoidPtr(entry.me_key); +- value = Py_BuildValue("lO", entry.me_value, entry.me_key); ++ value = Py_BuildValue("nO", entry.me_value, entry.me_key); + + if (key == NULL || value == NULL) { + Py_XDECREF(key); +@@ -3638,7 +3678,7 @@ + return -1; + + while (PyDict_Next(obj, &i, &key, &value)) { +- long memo_id; ++ Py_ssize_t memo_id; + PyObject *memo_obj; + + if (!PyTuple_Check(value) || Py_SIZE(value) != 2) { +@@ -3646,7 +3686,7 @@ + "'memo' values must be 2-item tuples"); + goto error; + } +- memo_id = PyLong_AsLong(PyTuple_GET_ITEM(value, 0)); ++ memo_id = PyLong_AsSsize_t(PyTuple_GET_ITEM(value, 0)); + if (memo_id == -1 && PyErr_Occurred()) + goto error; + memo_obj = PyTuple_GET_ITEM(value, 1); +@@ -3777,7 +3817,7 @@ + module_name, global_name); + } + +-static int ++static Py_ssize_t + marker(UnpicklerObject *self) + { + if (self->num_marks < 1) { +@@ -3855,6 +3895,28 @@ + return 0; + } + ++/* s contains x bytes of an unsigned little-endian integer. Return its value ++ * as a C Py_ssize_t, or -1 if it's higher than PY_SSIZE_T_MAX. ++ */ ++static Py_ssize_t ++calc_binsize(char *bytes, int size) ++{ ++ unsigned char *s = (unsigned char *)bytes; ++ size_t x = 0; ++ ++ assert(size == 4); ++ ++ x = (size_t) s[0]; ++ x |= (size_t) s[1] << 8; ++ x |= (size_t) s[2] << 16; ++ x |= (size_t) s[3] << 24; ++ ++ if (x > PY_SSIZE_T_MAX) ++ return -1; ++ else ++ return (Py_ssize_t) x; ++} ++ + /* s contains x bytes of a little-endian integer. Return its value as a + * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian + * int, but when x is 4 it's a signed one. This is an historical source +@@ -4099,16 +4161,18 @@ + load_binbytes(UnpicklerObject *self) + { + PyObject *bytes; +- long x; ++ Py_ssize_t x; + char *s; + + if (_Unpickler_Read(self, &s, 4) < 0) + return -1; + +- x = calc_binint(s, 4); ++ x = calc_binsize(s, 4); + if (x < 0) { +- PyErr_SetString(UnpicklingError, +- "BINBYTES pickle has negative byte count"); ++ PyErr_Format(PyExc_OverflowError, ++ "BINBYTES exceeds system's maximum size of %zd bytes", ++ PY_SSIZE_T_MAX ++ ); + return -1; + } + +@@ -4126,7 +4190,7 @@ + load_short_binbytes(UnpicklerObject *self) + { + PyObject *bytes; +- unsigned char x; ++ Py_ssize_t x; + char *s; + + if (_Unpickler_Read(self, &s, 1) < 0) +@@ -4149,7 +4213,7 @@ + load_binstring(UnpicklerObject *self) + { + PyObject *str; +- long x; ++ Py_ssize_t x; + char *s; + + if (_Unpickler_Read(self, &s, 4) < 0) +@@ -4178,7 +4242,7 @@ + load_short_binstring(UnpicklerObject *self) + { + PyObject *str; +- unsigned char x; ++ Py_ssize_t x; + char *s; + + if (_Unpickler_Read(self, &s, 1) < 0) +@@ -4222,19 +4286,22 @@ + load_binunicode(UnpicklerObject *self) + { + PyObject *str; +- long size; ++ Py_ssize_t size; + char *s; + + if (_Unpickler_Read(self, &s, 4) < 0) + return -1; + +- size = calc_binint(s, 4); ++ size = calc_binsize(s, 4); + if (size < 0) { +- PyErr_SetString(UnpicklingError, +- "BINUNICODE pickle has negative byte count"); ++ PyErr_Format(PyExc_OverflowError, ++ "BINUNICODE exceeds system's maximum size of %zd bytes", ++ PY_SSIZE_T_MAX ++ ); + return -1; + } + ++ + if (_Unpickler_Read(self, &s, size) < 0) + return -1; + +@@ -4250,7 +4317,7 @@ + load_tuple(UnpicklerObject *self) + { + PyObject *tuple; +- int i; ++ Py_ssize_t i; + + if ((i = marker(self)) < 0) + return -1; +@@ -4309,7 +4376,7 @@ + load_list(UnpicklerObject *self) + { + PyObject *list; +- int i; ++ Py_ssize_t i; + + if ((i = marker(self)) < 0) + return -1; +@@ -4325,7 +4392,7 @@ + load_dict(UnpicklerObject *self) + { + PyObject *dict, *key, *value; +- int i, j, k; ++ Py_ssize_t i, j, k; + + if ((i = marker(self)) < 0) + return -1; +@@ -4369,7 +4436,7 @@ + load_obj(UnpicklerObject *self) + { + PyObject *cls, *args, *obj = NULL; +- int i; ++ Py_ssize_t i; + + if ((i = marker(self)) < 0) + return -1; +@@ -4400,7 +4467,7 @@ + PyObject *module_name; + PyObject *class_name; + Py_ssize_t len; +- int i; ++ Py_ssize_t i; + char *s; + + if ((i = marker(self)) < 0) +@@ -4594,7 +4661,7 @@ + static int + load_pop(UnpicklerObject *self) + { +- int len = Py_SIZE(self->stack); ++ Py_ssize_t len = Py_SIZE(self->stack); + + /* Note that we split the (pickle.py) stack into two stacks, + * an object stack and a mark stack. We have to be clever and +@@ -4618,7 +4685,7 @@ + static int + load_pop_mark(UnpicklerObject *self) + { +- int i; ++ Py_ssize_t i; + + if ((i = marker(self)) < 0) + return -1; +@@ -4632,7 +4699,7 @@ + load_dup(UnpicklerObject *self) + { + PyObject *last; +- int len; ++ Py_ssize_t len; + + if ((len = Py_SIZE(self->stack)) <= 0) + return stack_underflow(); +@@ -4711,10 +4778,7 @@ + if (_Unpickler_Read(self, &s, 4) < 0) + return -1; + +- idx = (long)Py_CHARMASK(s[0]); +- idx |= (long)Py_CHARMASK(s[1]) << 8; +- idx |= (long)Py_CHARMASK(s[2]) << 16; +- idx |= (long)Py_CHARMASK(s[3]) << 24; ++ idx = calc_binsize(s, 4); + + value = _Unpickler_MemoGet(self, idx); + if (value == NULL) { +@@ -4821,8 +4885,12 @@ + return -1; + idx = PyLong_AsSsize_t(key); + Py_DECREF(key); +- if (idx == -1 && PyErr_Occurred()) ++ if (idx < 0) { ++ if (!PyErr_Occurred()) ++ PyErr_SetString(PyExc_ValueError, ++ "negative PUT argument"); + return -1; ++ } + + return _Unpickler_MemoPut(self, idx, value); + } +@@ -4860,20 +4928,22 @@ + return stack_underflow(); + value = self->stack->data[Py_SIZE(self->stack) - 1]; + +- idx = (long)Py_CHARMASK(s[0]); +- idx |= (long)Py_CHARMASK(s[1]) << 8; +- idx |= (long)Py_CHARMASK(s[2]) << 16; +- idx |= (long)Py_CHARMASK(s[3]) << 24; ++ idx = calc_binsize(s, 4); ++ if (idx < 0) { ++ PyErr_SetString(PyExc_ValueError, ++ "negative LONG_BINPUT argument"); ++ return -1; ++ } + + return _Unpickler_MemoPut(self, idx, value); + } + + static int +-do_append(UnpicklerObject *self, int x) ++do_append(UnpicklerObject *self, Py_ssize_t x) + { + PyObject *value; + PyObject *list; +- int len, i; ++ Py_ssize_t len, i; + + len = Py_SIZE(self->stack); + if (x > len || x <= 0) +@@ -4886,14 +4956,15 @@ + if (PyList_Check(list)) { + PyObject *slice; + Py_ssize_t list_len; ++ int ret; + + slice = Pdata_poplist(self->stack, x); + if (!slice) + return -1; + list_len = PyList_GET_SIZE(list); +- i = PyList_SetSlice(list, list_len, list_len, slice); ++ ret = PyList_SetSlice(list, list_len, list_len, slice); + Py_DECREF(slice); +- return i; ++ return ret; + } + else { + PyObject *append_func; +@@ -4932,11 +5003,11 @@ + } + + static int +-do_setitems(UnpicklerObject *self, int x) ++do_setitems(UnpicklerObject *self, Py_ssize_t x) + { + PyObject *value, *key; + PyObject *dict; +- int len, i; ++ Py_ssize_t len, i; + int status = 0; + + len = Py_SIZE(self->stack); +@@ -5104,20 +5175,21 @@ + + if ((self->num_marks + 1) >= self->marks_size) { + size_t alloc; +- int *marks; ++ Py_ssize_t *marks; + + /* Use the size_t type to check for overflow. */ + alloc = ((size_t)self->num_marks << 1) + 20; +- if (alloc > PY_SSIZE_T_MAX || ++ if (alloc > (PY_SSIZE_T_MAX / sizeof(Py_ssize_t)) || + alloc <= ((size_t)self->num_marks + 1)) { + PyErr_NoMemory(); + return -1; + } + + if (self->marks == NULL) +- marks = (int *)PyMem_Malloc(alloc * sizeof(int)); ++ marks = (Py_ssize_t *) PyMem_Malloc(alloc * sizeof(Py_ssize_t)); + else +- marks = (int *)PyMem_Realloc(self->marks, alloc * sizeof(int)); ++ marks = (Py_ssize_t *) PyMem_Realloc(self->marks, ++ alloc * sizeof(Py_ssize_t)); + if (marks == NULL) { + PyErr_NoMemory(); + return -1; +@@ -5258,13 +5330,12 @@ + case STOP: + break; + +- case '\0': +- PyErr_SetNone(PyExc_EOFError); +- return NULL; +- + default: +- PyErr_Format(UnpicklingError, +- "invalid load key, '%c'.", s[0]); ++ if (s[0] == '\0') ++ PyErr_SetNone(PyExc_EOFError); ++ else ++ PyErr_Format(UnpicklingError, ++ "invalid load key, '%c'.", s[0]); + return NULL; + } + +diff -r 137e45f15c0b Modules/_sqlite/cursor.c +--- a/Modules/_sqlite/cursor.c ++++ b/Modules/_sqlite/cursor.c +@@ -55,8 +55,8 @@ + + dst = buf; + *dst = 0; +- while (isalpha(*src) && dst - buf < sizeof(buf) - 2) { +- *dst++ = tolower(*src++); ++ while (Py_ISALPHA(*src) && dst - buf < sizeof(buf) - 2) { ++ *dst++ = Py_TOLOWER(*src++); + } + + *dst = 0; +diff -r 137e45f15c0b Modules/_sre.c +--- a/Modules/_sre.c ++++ b/Modules/_sre.c +@@ -2760,7 +2760,7 @@ + #if defined(VVERBOSE) + #define VTRACE(v) printf v + #else +-#define VTRACE(v) ++#define VTRACE(v) do {} while(0) /* do nothing */ + #endif + + /* Report failure */ +diff -r 137e45f15c0b Modules/_ssl.c +--- a/Modules/_ssl.c ++++ b/Modules/_ssl.c +@@ -578,7 +578,7 @@ + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + +- i = 0; ++ i = -1; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + +@@ -679,6 +679,7 @@ + } + Py_DECREF(t); + } ++ sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { +@@ -1023,10 +1024,8 @@ + #endif + + /* Guard against socket too large for select*/ +-#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE +- if (s->sock_fd >= FD_SETSIZE) ++ if (!_PyIsSelectable_fd(s->sock_fd)) + return SOCKET_TOO_LARGE_FOR_SELECT; +-#endif + + /* Construct the arguments to select */ + tv.tv_sec = (int)s->sock_timeout; +diff -r 137e45f15c0b Modules/_testcapimodule.c +--- a/Modules/_testcapimodule.c ++++ b/Modules/_testcapimodule.c +@@ -1438,6 +1438,51 @@ + } + + static PyObject * ++unicode_encodedecimal(PyObject *self, PyObject *args) ++{ ++ Py_UNICODE *unicode; ++ Py_ssize_t length; ++ char *errors = NULL; ++ PyObject *decimal; ++ Py_ssize_t decimal_length, new_length; ++ int res; ++ ++ if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors)) ++ return NULL; ++ ++ decimal_length = length * 7; /* len('€') */ ++ decimal = PyBytes_FromStringAndSize(NULL, decimal_length); ++ if (decimal == NULL) ++ return NULL; ++ ++ res = PyUnicode_EncodeDecimal(unicode, length, ++ PyBytes_AS_STRING(decimal), ++ errors); ++ if (res < 0) { ++ Py_DECREF(decimal); ++ return NULL; ++ } ++ ++ new_length = strlen(PyBytes_AS_STRING(decimal)); ++ assert(new_length <= decimal_length); ++ res = _PyBytes_Resize(&decimal, new_length); ++ if (res < 0) ++ return NULL; ++ ++ return decimal; ++} ++ ++static PyObject * ++unicode_transformdecimaltoascii(PyObject *self, PyObject *args) ++{ ++ Py_UNICODE *unicode; ++ Py_ssize_t length; ++ if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length)) ++ return NULL; ++ return PyUnicode_TransformDecimalToASCII(unicode, length); ++} ++ ++static PyObject * + getargs_w_star(PyObject *self, PyObject *args) + { + Py_buffer buffer; +@@ -2320,8 +2365,10 @@ + {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, + {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS}, + {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, +- {"unicode_aswidechar", unicode_aswidechar, METH_VARARGS}, +- {"unicode_aswidecharstring",unicode_aswidecharstring, METH_VARARGS}, ++ {"unicode_aswidechar", unicode_aswidechar, METH_VARARGS}, ++ {"unicode_aswidecharstring",unicode_aswidecharstring, METH_VARARGS}, ++ {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS}, ++ {"unicode_transformdecimaltoascii", unicode_transformdecimaltoascii, METH_VARARGS}, + #ifdef WITH_THREAD + {"_test_thread_state", test_thread_state, METH_VARARGS}, + {"_pending_threadfunc", pending_threadfunc, METH_VARARGS}, +diff -r 137e45f15c0b Modules/_tkinter.c +--- a/Modules/_tkinter.c ++++ b/Modules/_tkinter.c +@@ -661,8 +661,8 @@ + } + + strcpy(argv0, className); +- if (isupper(Py_CHARMASK(argv0[0]))) +- argv0[0] = tolower(Py_CHARMASK(argv0[0])); ++ if (Py_ISUPPER(Py_CHARMASK(argv0[0]))) ++ argv0[0] = Py_TOLOWER(Py_CHARMASK(argv0[0])); + Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY); + ckfree(argv0); + +@@ -993,8 +993,10 @@ + for (i = 0; i < size; i++) { + if (inbuf[i] >= 0x10000) { + /* Tcl doesn't do UTF-16, yet. */ +- PyErr_SetString(PyExc_ValueError, +- "unsupported character"); ++ PyErr_Format(PyExc_ValueError, ++ "character U+%x is above the range " ++ "(U+0000-U+FFFF) allowed by Tcl", ++ inbuf[i]); + ckfree(FREECAST outbuf); + return NULL; + } +diff -r 137e45f15c0b Modules/arraymodule.c +--- a/Modules/arraymodule.c ++++ b/Modules/arraymodule.c +@@ -1484,7 +1484,7 @@ + \n\ + Extends this array with data from the unicode string ustr.\n\ + The array must be a unicode type array; otherwise a ValueError\n\ +-is raised. Use array.frombytes(ustr.decode(...)) to\n\ ++is raised. Use array.frombytes(ustr.encode(...)) to\n\ + append Unicode data to an array of some other type."); + + +@@ -1506,7 +1506,7 @@ + \n\ + Convert the array to a unicode string. The array must be\n\ + a unicode type array; otherwise a ValueError is raised. Use\n\ +-array.tostring().decode() to obtain a unicode string from\n\ ++array.tobytes().decode() to obtain a unicode string from\n\ + an array of some other type."); + + +@@ -2543,7 +2543,7 @@ + \n\ + Return a new array whose items are restricted by typecode, and\n\ + initialized from the optional initializer value, which must be a list,\n\ +-string. or iterable over elements of the appropriate type.\n\ ++string or iterable over elements of the appropriate type.\n\ + \n\ + Arrays represent basic values and behave very much like lists, except\n\ + the type of objects stored in them is constrained.\n\ +@@ -2557,7 +2557,7 @@ + extend() -- extend array by appending multiple elements from an iterable\n\ + fromfile() -- read items from a file object\n\ + fromlist() -- append items from the list\n\ +-fromstring() -- append items from the string\n\ ++frombytes() -- append items from the string\n\ + index() -- return index of first occurrence of an object\n\ + insert() -- insert a new item into the array at a provided position\n\ + pop() -- remove and return item (default last)\n\ +@@ -2565,7 +2565,7 @@ + reverse() -- reverse the order of the items in the array\n\ + tofile() -- write all items to a file object\n\ + tolist() -- return the array converted to an ordinary list\n\ +-tostring() -- return the array converted to a string\n\ ++tobytes() -- return the array converted to a string\n\ + \n\ + Attributes:\n\ + \n\ +diff -r 137e45f15c0b Modules/binascii.c +--- a/Modules/binascii.c ++++ b/Modules/binascii.c +@@ -1102,8 +1102,8 @@ + if (isdigit(c)) + return c - '0'; + else { +- if (isupper(c)) +- c = tolower(c); ++ if (Py_ISUPPER(c)) ++ c = Py_TOLOWER(c); + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + } +diff -r 137e45f15c0b Modules/bz2module.c +--- a/Modules/bz2module.c ++++ b/Modules/bz2module.c +@@ -218,25 +218,14 @@ + #define SMALLCHUNK BUFSIZ + #endif + +-#if SIZEOF_INT < 4 +-#define BIGCHUNK (512 * 32) +-#else +-#define BIGCHUNK (512 * 1024) +-#endif +- + /* This is a hacked version of Python's fileobject.c:new_buffersize(). */ + static size_t + Util_NewBufferSize(size_t currentsize) + { +- if (currentsize > SMALLCHUNK) { +- /* Keep doubling until we reach BIGCHUNK; +- then keep adding BIGCHUNK. */ +- if (currentsize <= BIGCHUNK) +- return currentsize + currentsize; +- else +- return currentsize + BIGCHUNK; +- } +- return currentsize + SMALLCHUNK; ++ /* Expand the buffer by an amount proportional to the current size, ++ giving us amortized linear-time behavior. Use a less-than-double ++ growth factor to avoid excessive allocation. */ ++ return currentsize + (currentsize >> 3) + 6; + } + + /* This is a hacked version of Python's fileobject.c:get_line(). */ +diff -r 137e45f15c0b Modules/itertoolsmodule.c +--- a/Modules/itertoolsmodule.c ++++ b/Modules/itertoolsmodule.c +@@ -1234,7 +1234,9 @@ + return NULL; + lz->cnt++; + oldnext = lz->next; +- lz->next += lz->step; ++ /* The (size_t) cast below avoids the danger of undefined ++ behaviour from signed integer overflow. */ ++ lz->next += (size_t)lz->step; + if (lz->next < oldnext || (stop != -1 && lz->next > stop)) + lz->next = stop; + return item; +diff -r 137e45f15c0b Modules/main.c +--- a/Modules/main.c ++++ b/Modules/main.c +@@ -654,13 +654,14 @@ + if (fp == NULL) { + char *cfilename_buffer; + const char *cfilename; ++ int err = errno; + cfilename_buffer = _Py_wchar2char(filename, NULL); + if (cfilename_buffer != NULL) + cfilename = cfilename_buffer; + else + cfilename = ""; + fprintf(stderr, "%ls: can't open file '%s': [Errno %d] %s\n", +- argv[0], cfilename, errno, strerror(errno)); ++ argv[0], cfilename, err, strerror(err)); + if (cfilename_buffer) + PyMem_Free(cfilename_buffer); + return 2; +diff -r 137e45f15c0b Modules/ossaudiodev.c +--- a/Modules/ossaudiodev.c ++++ b/Modules/ossaudiodev.c +@@ -129,6 +129,7 @@ + } + + if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) { ++ close(fd); + PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename); + return NULL; + } +@@ -425,6 +426,11 @@ + if (!PyArg_ParseTuple(args, "y#:write", &cp, &size)) + return NULL; + ++ if (!_PyIsSelectable_fd(self->fd)) { ++ PyErr_SetString(PyExc_ValueError, ++ "file descriptor out of range for select"); ++ return NULL; ++ } + /* use select to wait for audio device to be available */ + FD_ZERO(&write_set_fds); + FD_SET(self->fd, &write_set_fds); +diff -r 137e45f15c0b Modules/posixmodule.c +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -4001,7 +4001,7 @@ + static PyObject * + posix_spawnvpe(PyObject *self, PyObject *args) + { +- PyObject *opath ++ PyObject *opath; + char *path; + PyObject *argv, *env; + char **argvlist; +@@ -5687,7 +5687,8 @@ + + PyDoc_STRVAR(posix_lseek__doc__, + "lseek(fd, pos, how) -> newpos\n\n\ +-Set the current position of a file descriptor."); ++Set the current position of a file descriptor.\n\ ++Return the new cursor position in bytes, starting from the beginning."); + + static PyObject * + posix_lseek(PyObject *self, PyObject *args) +@@ -6106,6 +6107,12 @@ + PyBytes_FromStringAndSize does not count that */ + #ifdef MS_WINDOWS + len = wcslen(s1) + wcslen(s2) + 2; ++ if (_MAX_ENV < (len - 1)) { ++ PyErr_Format(PyExc_ValueError, ++ "the environment variable is longer than %u characters", ++ _MAX_ENV); ++ goto error; ++ } + newstr = PyUnicode_FromUnicode(NULL, (int)len - 1); + #else + len = PyBytes_GET_SIZE(os1) + PyBytes_GET_SIZE(os2) + 2; +@@ -6177,42 +6184,38 @@ + static PyObject * + posix_unsetenv(PyObject *self, PyObject *args) + { +-#ifdef MS_WINDOWS +- char *s1; +- +- if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) +- return NULL; +-#else + PyObject *os1; + char *s1; ++#ifndef HAVE_BROKEN_UNSETENV ++ int err; ++#endif + + if (!PyArg_ParseTuple(args, "O&:unsetenv", + PyUnicode_FSConverter, &os1)) + return NULL; + s1 = PyBytes_AsString(os1); +-#endif +- ++ ++#ifdef HAVE_BROKEN_UNSETENV + unsetenv(s1); ++#else ++ err = unsetenv(s1); ++ if (err) { ++ Py_DECREF(os1); ++ return posix_error(); ++ } ++#endif + + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to + * happen after the real unsetenv() call because the + * old value was still accessible until then. + */ +- if (PyDict_DelItem(posix_putenv_garbage, +-#ifdef MS_WINDOWS +- PyTuple_GET_ITEM(args, 0) +-#else +- os1 +-#endif +- )) { ++ if (PyDict_DelItem(posix_putenv_garbage, os1)) { + /* really not much we can do; just leak */ + PyErr_Clear(); + } + +-#ifndef MS_WINDOWS + Py_DECREF(os1); +-#endif + Py_RETURN_NONE; + } + #endif /* unsetenv */ +diff -r 137e45f15c0b Modules/python.c +--- a/Modules/python.c ++++ b/Modules/python.c +@@ -50,8 +50,12 @@ + #else + argv_copy[i] = _Py_char2wchar(argv[i], NULL); + #endif +- if (!argv_copy[i]) ++ if (!argv_copy[i]) { ++ fprintf(stderr, "Fatal Python error: " ++ "unable to decode the command line argument #%i\n", ++ i + 1); + return 1; ++ } + argv_copy2[i] = argv_copy[i]; + } + setlocale(LC_ALL, oldloc); +diff -r 137e45f15c0b Modules/readline.c +--- a/Modules/readline.c ++++ b/Modules/readline.c +@@ -154,6 +154,7 @@ + { + PyObject *filename_obj = Py_None, *filename_bytes; + char *filename; ++ int err; + if (!PyArg_ParseTuple(args, "|O:write_history_file", &filename_obj)) + return NULL; + if (filename_obj != Py_None) { +@@ -164,10 +165,11 @@ + filename_bytes = NULL; + filename = NULL; + } +- errno = write_history(filename); +- if (!errno && _history_length >= 0) ++ errno = err = write_history(filename); ++ if (!err && _history_length >= 0) + history_truncate_file(filename, _history_length); + Py_XDECREF(filename_bytes); ++ errno = err; + if (errno) + return PyErr_SetFromErrno(PyExc_IOError); + Py_RETURN_NONE; +@@ -970,7 +972,7 @@ + completed_input_string = not_done_reading; + + while (completed_input_string == not_done_reading) { +- int has_input = 0; ++ int has_input = 0, err = 0; + + while (!has_input) + { struct timeval timeout = {0, 100000}; /* 0.1 seconds */ +@@ -984,13 +986,14 @@ + /* select resets selectset if no input was available */ + has_input = select(fileno(rl_instream) + 1, &selectset, + NULL, NULL, timeoutp); ++ err = errno; + if(PyOS_InputHook) PyOS_InputHook(); + } + +- if(has_input > 0) { ++ if (has_input > 0) { + rl_callback_read_char(); + } +- else if (errno == EINTR) { ++ else if (err == EINTR) { + int s; + #ifdef WITH_THREAD + PyEval_RestoreThread(_PyOS_ReadlineTState); +diff -r 137e45f15c0b Modules/selectmodule.c +--- a/Modules/selectmodule.c ++++ b/Modules/selectmodule.c +@@ -110,7 +110,7 @@ + #if defined(_MSC_VER) + max = 0; /* not used for Win32 */ + #else /* !_MSC_VER */ +- if (v < 0 || v >= FD_SETSIZE) { ++ if (!_PyIsSelectable_fd(v)) { + PyErr_SetString(PyExc_ValueError, + "filedescriptor out of range in select()"); + goto finally; +@@ -160,13 +160,6 @@ + for (j = 0; fd2obj[j].sentinel >= 0; j++) { + fd = fd2obj[j].fd; + if (FD_ISSET(fd, set)) { +-#ifndef _MSC_VER +- if (fd > FD_SETSIZE) { +- PyErr_SetString(PyExc_SystemError, +- "filedescriptor out of range returned in select()"); +- goto finally; +- } +-#endif + o = fd2obj[j].obj; + fd2obj[j].obj = NULL; + /* transfer ownership */ +diff -r 137e45f15c0b Modules/socketmodule.c +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -455,18 +455,14 @@ + #include + #endif + +-#ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE +-/* Platform can select file descriptors beyond FD_SETSIZE */ +-#define IS_SELECTABLE(s) 1 +-#elif defined(HAVE_POLL) ++#ifdef HAVE_POLL + /* Instead of select(), we'll use poll() since poll() works on any fd. */ + #define IS_SELECTABLE(s) 1 + /* Can we call select() with this socket without a buffer overrun? */ + #else +-/* POSIX says selecting file descriptors beyond FD_SETSIZE +- has undefined behaviour. If there's no timeout left, we don't have to +- call select, so it's a safe, little white lie. */ +-#define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0) ++/* If there's no timeout left, we don't have to call select, so it's a safe, ++ * little white lie. */ ++#define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0) + #endif + + static PyObject* +diff -r 137e45f15c0b Modules/timemodule.c +--- a/Modules/timemodule.c ++++ b/Modules/timemodule.c +@@ -3,8 +3,6 @@ + #include "Python.h" + #include "_time.h" + +-#define TZNAME_ENCODING "utf-8" +- + #include + + #ifdef HAVE_SYS_TYPES_H +@@ -48,8 +46,6 @@ + #if defined(MS_WINDOWS) && !defined(__BORLANDC__) + /* Win32 has better clock replacement; we have our own version below. */ + #undef HAVE_CLOCK +-#undef TZNAME_ENCODING +-#define TZNAME_ENCODING "mbcs" + #endif /* MS_WINDOWS && !defined(__BORLANDC__) */ + + #if defined(PYOS_OS2) +@@ -431,6 +427,11 @@ + return 1; + } + ++#ifdef MS_WINDOWS ++ /* wcsftime() doesn't format correctly time zones, see issue #10653 */ ++# undef HAVE_WCSFTIME ++#endif ++ + #ifdef HAVE_STRFTIME + #ifdef HAVE_WCSFTIME + #define time_char wchar_t +@@ -497,22 +498,22 @@ + fmt = format; + #else + /* Convert the unicode string to an ascii one */ +- format = PyUnicode_AsEncodedString(format_arg, TZNAME_ENCODING, NULL); ++ format = PyUnicode_EncodeFSDefault(format_arg); + if (format == NULL) + return NULL; + fmt = PyBytes_AS_STRING(format); + #endif + +-#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME) ++#if defined(MS_WINDOWS) + /* check that the format string contains only valid directives */ +- for(outbuf = wcschr(fmt, L'%'); ++ for(outbuf = strchr(fmt, '%'); + outbuf != NULL; +- outbuf = wcschr(outbuf+2, L'%')) ++ outbuf = strchr(outbuf+2, '%')) + { + if (outbuf[1]=='#') + ++outbuf; /* not documented by python, */ + if (outbuf[1]=='\0' || +- !wcschr(L"aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1])) ++ !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1])) + { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + return 0; +@@ -526,12 +527,18 @@ + * will be ahead of time... + */ + for (i = 1024; ; i += i) { ++#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) ++ int err; ++#endif + outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char)); + if (outbuf == NULL) { + PyErr_NoMemory(); + break; + } + buflen = format_time(outbuf, i, fmt, &buf); ++#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) ++ err = errno; ++#endif + if (buflen > 0 || i >= 256 * fmtlen) { + /* If the buffer is 256 times as long as the format, + it's probably not failing for lack of room! +@@ -541,8 +548,7 @@ + #ifdef HAVE_WCSFTIME + ret = PyUnicode_FromWideChar(outbuf, buflen); + #else +- ret = PyUnicode_Decode(outbuf, buflen, +- TZNAME_ENCODING, NULL); ++ ret = PyUnicode_DecodeFSDefaultAndSize(outbuf, buflen); + #endif + PyMem_Free(outbuf); + break; +@@ -550,7 +556,7 @@ + PyMem_Free(outbuf); + #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) + /* VisualStudio .NET 2005 does this properly */ +- if (buflen == 0 && errno == EINVAL) { ++ if (buflen == 0 && err == EINVAL) { + PyErr_SetString(PyExc_ValueError, "Invalid format string"); + break; + } +@@ -784,8 +790,8 @@ + #endif /* PYOS_OS2 */ + #endif + PyModule_AddIntConstant(m, "daylight", daylight); +- otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL); +- otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL); ++ otz0 = PyUnicode_DecodeFSDefaultAndSize(tzname[0], strlen(tzname[0])); ++ otz1 = PyUnicode_DecodeFSDefaultAndSize(tzname[1], strlen(tzname[1])); + PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)); + #else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/ + #ifdef HAVE_STRUCT_TM_TM_ZONE +diff -r 137e45f15c0b Modules/unicodedata.c +--- a/Modules/unicodedata.c ++++ b/Modules/unicodedata.c +@@ -1,8 +1,9 @@ + /* ------------------------------------------------------------------------ + +- unicodedata -- Provides access to the Unicode 5.2 data base. ++ unicodedata -- Provides access to the Unicode database. + +- Data was extracted from the Unicode 5.2 UnicodeData.txt file. ++ Data was extracted from the UnicodeData.txt file. ++ The current version number is reported in the unidata_version constant. + + Written by Marc-Andre Lemburg (mal@lemburg.com). + Modified for Python 2.0 by Fredrik Lundh (fredrik@pythonware.com) +@@ -830,7 +831,7 @@ + unsigned long h = 0; + unsigned long ix; + for (i = 0; i < len; i++) { +- h = (h * scale) + (unsigned char) toupper(Py_CHARMASK(s[i])); ++ h = (h * scale) + (unsigned char) Py_TOUPPER(Py_CHARMASK(s[i])); + ix = h & 0xff000000; + if (ix) + h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff; +@@ -980,7 +981,7 @@ + if (!_getucname(self, code, buffer, sizeof(buffer))) + return 0; + for (i = 0; i < namelen; i++) { +- if (toupper(Py_CHARMASK(name[i])) != buffer[i]) ++ if (Py_TOUPPER(Py_CHARMASK(name[i])) != buffer[i]) + return 0; + } + return buffer[namelen] == '\0'; +@@ -1241,11 +1242,11 @@ + "This module provides access to the Unicode Character Database which\n\ + defines character properties for all Unicode characters. The data in\n\ + this database is based on the UnicodeData.txt file version\n\ +-5.2.0 which is publically available from ftp://ftp.unicode.org/.\n\ ++6.0.0 which is publically available from ftp://ftp.unicode.org/.\n\ + \n\ + The module uses the same names and symbols as defined by the\n\ +-UnicodeData File Format 5.2.0 (see\n\ +-http://www.unicode.org/reports/tr44/tr44-4.html)."); ++UnicodeData File Format 6.0.0 (see\n\ ++http://www.unicode.org/reports/tr44/tr44-6.html)."); + + + static struct PyModuleDef unicodedatamodule = { +diff -r 137e45f15c0b Modules/zipimport.c +--- a/Modules/zipimport.c ++++ b/Modules/zipimport.c +@@ -736,7 +736,8 @@ + + fp = _Py_fopen(archive_obj, "rb"); + if (fp == NULL) { +- PyErr_Format(ZipImportError, "can't open Zip file: '%U'", archive_obj); ++ if (!PyErr_Occurred()) ++ PyErr_Format(ZipImportError, "can't open Zip file: '%U'", archive_obj); + return NULL; + } + fseek(fp, -22, SEEK_END); +@@ -909,8 +910,9 @@ + + fp = _Py_fopen(archive, "rb"); + if (!fp) { +- PyErr_Format(PyExc_IOError, +- "zipimport: can not open file %U", archive); ++ if (!PyErr_Occurred()) ++ PyErr_Format(PyExc_IOError, ++ "zipimport: can not open file %U", archive); + return NULL; + } + +diff -r 137e45f15c0b Objects/accu.c +--- /dev/null ++++ b/Objects/accu.c +@@ -0,0 +1,114 @@ ++/* Accumulator struct implementation */ ++ ++#include "Python.h" ++ ++static PyObject * ++join_list_unicode(PyObject *lst) ++{ ++ /* return ''.join(lst) */ ++ PyObject *sep, *ret; ++ sep = PyUnicode_FromStringAndSize("", 0); ++ ret = PyUnicode_Join(sep, lst); ++ Py_DECREF(sep); ++ return ret; ++} ++ ++int ++_PyAccu_Init(_PyAccu *acc) ++{ ++ /* Lazily allocated */ ++ acc->large = NULL; ++ acc->small = PyList_New(0); ++ if (acc->small == NULL) ++ return -1; ++ return 0; ++} ++ ++static int ++flush_accumulator(_PyAccu *acc) ++{ ++ Py_ssize_t nsmall = PyList_GET_SIZE(acc->small); ++ if (nsmall) { ++ int ret; ++ PyObject *joined; ++ if (acc->large == NULL) { ++ acc->large = PyList_New(0); ++ if (acc->large == NULL) ++ return -1; ++ } ++ joined = join_list_unicode(acc->small); ++ if (joined == NULL) ++ return -1; ++ if (PyList_SetSlice(acc->small, 0, nsmall, NULL)) { ++ Py_DECREF(joined); ++ return -1; ++ } ++ ret = PyList_Append(acc->large, joined); ++ Py_DECREF(joined); ++ return ret; ++ } ++ return 0; ++} ++ ++int ++_PyAccu_Accumulate(_PyAccu *acc, PyObject *unicode) ++{ ++ Py_ssize_t nsmall; ++ assert(PyUnicode_Check(unicode)); ++ ++ if (PyList_Append(acc->small, unicode)) ++ return -1; ++ nsmall = PyList_GET_SIZE(acc->small); ++ /* Each item in a list of unicode objects has an overhead (in 64-bit ++ * builds) of: ++ * - 8 bytes for the list slot ++ * - 56 bytes for the header of the unicode object ++ * that is, 64 bytes. 100000 such objects waste more than 6MB ++ * compared to a single concatenated string. ++ */ ++ if (nsmall < 100000) ++ return 0; ++ return flush_accumulator(acc); ++} ++ ++PyObject * ++_PyAccu_FinishAsList(_PyAccu *acc) ++{ ++ int ret; ++ PyObject *res; ++ ++ ret = flush_accumulator(acc); ++ Py_CLEAR(acc->small); ++ if (ret) { ++ Py_CLEAR(acc->large); ++ return NULL; ++ } ++ res = acc->large; ++ acc->large = NULL; ++ return res; ++} ++ ++PyObject * ++_PyAccu_Finish(_PyAccu *acc) ++{ ++ PyObject *list, *res; ++ if (acc->large == NULL) { ++ list = acc->small; ++ acc->small = NULL; ++ } ++ else { ++ list = _PyAccu_FinishAsList(acc); ++ if (!list) ++ return NULL; ++ } ++ res = join_list_unicode(list); ++ Py_DECREF(list); ++ return res; ++} ++ ++void ++_PyAccu_Destroy(_PyAccu *acc) ++{ ++ Py_CLEAR(acc->small); ++ Py_CLEAR(acc->large); ++} +diff -r 137e45f15c0b Objects/bytearrayobject.c +--- a/Objects/bytearrayobject.c ++++ b/Objects/bytearrayobject.c +@@ -2797,18 +2797,16 @@ + PyDoc_STRVAR(bytearray_doc, + "bytearray(iterable_of_ints) -> bytearray\n\ + bytearray(string, encoding[, errors]) -> bytearray\n\ +-bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray\n\ +-bytearray(memory_view) -> bytearray\n\ ++bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\ ++bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\ ++bytearray() -> empty bytes array\n\ + \n\ + Construct an mutable bytearray object from:\n\ + - an iterable yielding integers in range(256)\n\ + - a text string encoded using the specified encoding\n\ +- - a bytes or a bytearray object\n\ ++ - a bytes or a buffer object\n\ + - any object implementing the buffer API.\n\ +-\n\ +-bytearray(int) -> bytearray\n\ +-\n\ +-Construct a zero-initialized bytearray of the given length."); ++ - an integer"); + + + static PyObject *bytearray_iter(PyObject *seq); +diff -r 137e45f15c0b Objects/bytesobject.c +--- a/Objects/bytesobject.c ++++ b/Objects/bytesobject.c +@@ -2721,13 +2721,14 @@ + "bytes(iterable_of_ints) -> bytes\n\ + bytes(string, encoding[, errors]) -> bytes\n\ + bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\ +-bytes(memory_view) -> bytes\n\ ++bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\ ++bytes() -> empty bytes object\n\ + \n\ + Construct an immutable array of bytes from:\n\ + - an iterable yielding integers in range(256)\n\ + - a text string encoded using the specified encoding\n\ +- - a bytes or a buffer object\n\ +- - any object implementing the buffer API."); ++ - any object implementing the buffer API.\n\ ++ - an integer"); + + static PyObject *bytes_iter(PyObject *seq); + +diff -r 137e45f15c0b Objects/descrobject.c +--- a/Objects/descrobject.c ++++ b/Objects/descrobject.c +@@ -846,16 +846,13 @@ + /* This has no reason to be in this file except that adding new files is a + bit of a pain */ + +-/* forward */ +-static PyTypeObject wrappertype; +- + typedef struct { + PyObject_HEAD + PyWrapperDescrObject *descr; + PyObject *self; + } wrapperobject; + +-#define Wrapper_Check(v) (Py_TYPE(v) == &wrappertype) ++#define Wrapper_Check(v) (Py_TYPE(v) == &_PyMethodWrapper_Type) + + static void + wrapper_dealloc(wrapperobject *wp) +@@ -1021,7 +1018,7 @@ + return 0; + } + +-static PyTypeObject wrappertype = { ++PyTypeObject _PyMethodWrapper_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) + "method-wrapper", /* tp_name */ + sizeof(wrapperobject), /* tp_basicsize */ +@@ -1070,7 +1067,7 @@ + assert(_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self), + (PyObject *)PyDescr_TYPE(descr))); + +- wp = PyObject_GC_New(wrapperobject, &wrappertype); ++ wp = PyObject_GC_New(wrapperobject, &_PyMethodWrapper_Type); + if (wp != NULL) { + Py_INCREF(descr); + wp->descr = descr; +diff -r 137e45f15c0b Objects/dictobject.c +--- a/Objects/dictobject.c ++++ b/Objects/dictobject.c +@@ -1314,14 +1314,18 @@ + PyObject *key; + Py_hash_t hash; + +- if (dictresize(mp, Py_SIZE(seq))) ++ if (dictresize(mp, Py_SIZE(seq))) { ++ Py_DECREF(d); + return NULL; ++ } + + while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) { + Py_INCREF(key); + Py_INCREF(value); +- if (insertdict(mp, key, hash, value)) ++ if (insertdict(mp, key, hash, value)) { ++ Py_DECREF(d); + return NULL; ++ } + } + return d; + } +@@ -1332,14 +1336,18 @@ + PyObject *key; + Py_hash_t hash; + +- if (dictresize(mp, PySet_GET_SIZE(seq))) ++ if (dictresize(mp, PySet_GET_SIZE(seq))) { ++ Py_DECREF(d); + return NULL; ++ } + + while (_PySet_NextEntry(seq, &pos, &key, &hash)) { + Py_INCREF(key); + Py_INCREF(value); +- if (insertdict(mp, key, hash, value)) ++ if (insertdict(mp, key, hash, value)) { ++ Py_DECREF(d); + return NULL; ++ } + } + return d; + } +@@ -1965,9 +1973,9 @@ + 2-tuple; but raise KeyError if D is empty."); + + PyDoc_STRVAR(update__doc__, +-"D.update(E, **F) -> None. Update D from dict/iterable E and F.\n" +-"If E has a .keys() method, does: for k in E: D[k] = E[k]\n\ +-If E lacks .keys() method, does: for (k, v) in E: D[k] = v\n\ ++"D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n" ++"If E present and has a .keys() method, does: for k in E: D[k] = E[k]\n\ ++If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v\n\ + In either case, this is followed by: for k in F: D[k] = F[k]"); + + PyDoc_STRVAR(fromkeys__doc__, +diff -r 137e45f15c0b Objects/genobject.c +--- a/Objects/genobject.c ++++ b/Objects/genobject.c +@@ -100,6 +100,17 @@ + + if (!result || f->f_stacktop == NULL) { + /* generator can't be rerun, so release the frame */ ++ /* first clean reference cycle through stored exception traceback */ ++ PyObject *t, *v, *tb; ++ t = f->f_exc_type; ++ v = f->f_exc_value; ++ tb = f->f_exc_traceback; ++ f->f_exc_type = NULL; ++ f->f_exc_value = NULL; ++ f->f_exc_traceback = NULL; ++ Py_XDECREF(t); ++ Py_XDECREF(v); ++ Py_XDECREF(tb); + Py_DECREF(f); + gen->gi_frame = NULL; + } +@@ -221,8 +232,9 @@ + + /* First, check the traceback argument, replacing None with + NULL. */ +- if (tb == Py_None) ++ if (tb == Py_None) { + tb = NULL; ++ } + else if (tb != NULL && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "throw() third argument must be a traceback object"); +@@ -233,9 +245,8 @@ + Py_XINCREF(val); + Py_XINCREF(tb); + +- if (PyExceptionClass_Check(typ)) { ++ if (PyExceptionClass_Check(typ)) + PyErr_NormalizeException(&typ, &val, &tb); +- } + + else if (PyExceptionInstance_Check(typ)) { + /* Raising an instance. The value should be a dummy. */ +@@ -250,6 +261,10 @@ + val = typ; + typ = PyExceptionInstance_Class(typ); + Py_INCREF(typ); ++ ++ if (tb == NULL) ++ /* Returns NULL if there's no traceback */ ++ tb = PyException_GetTraceback(val); + } + } + else { +diff -r 137e45f15c0b Objects/listobject.c +--- a/Objects/listobject.c ++++ b/Objects/listobject.c +@@ -58,7 +58,7 @@ + if (newsize == 0) + new_allocated = 0; + items = self->ob_item; +- if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *))) ++ if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *))) + PyMem_RESIZE(items, PyObject *, new_allocated); + else + items = NULL; +@@ -321,70 +321,59 @@ + list_repr(PyListObject *v) + { + Py_ssize_t i; +- PyObject *s, *temp; +- PyObject *pieces = NULL, *result = NULL; ++ PyObject *s = NULL; ++ _PyAccu acc; ++ static PyObject *sep = NULL; ++ ++ if (Py_SIZE(v) == 0) { ++ return PyUnicode_FromString("[]"); ++ } ++ ++ if (sep == NULL) { ++ sep = PyUnicode_FromString(", "); ++ if (sep == NULL) ++ return NULL; ++ } + + i = Py_ReprEnter((PyObject*)v); + if (i != 0) { + return i > 0 ? PyUnicode_FromString("[...]") : NULL; + } + +- if (Py_SIZE(v) == 0) { +- result = PyUnicode_FromString("[]"); +- goto Done; +- } ++ if (_PyAccu_Init(&acc)) ++ goto error; + +- pieces = PyList_New(0); +- if (pieces == NULL) +- goto Done; ++ s = PyUnicode_FromString("["); ++ if (s == NULL || _PyAccu_Accumulate(&acc, s)) ++ goto error; ++ Py_CLEAR(s); + + /* Do repr() on each element. Note that this may mutate the list, + so must refetch the list size on each iteration. */ + for (i = 0; i < Py_SIZE(v); ++i) { +- int status; + if (Py_EnterRecursiveCall(" while getting the repr of a list")) +- goto Done; ++ goto error; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); +- if (s == NULL) +- goto Done; +- status = PyList_Append(pieces, s); +- Py_DECREF(s); /* append created a new ref */ +- if (status < 0) +- goto Done; ++ if (i > 0 && _PyAccu_Accumulate(&acc, sep)) ++ goto error; ++ if (s == NULL || _PyAccu_Accumulate(&acc, s)) ++ goto error; ++ Py_CLEAR(s); + } ++ s = PyUnicode_FromString("]"); ++ if (s == NULL || _PyAccu_Accumulate(&acc, s)) ++ goto error; ++ Py_CLEAR(s); + +- /* Add "[]" decorations to the first and last items. */ +- assert(PyList_GET_SIZE(pieces) > 0); +- s = PyUnicode_FromString("["); +- if (s == NULL) +- goto Done; +- temp = PyList_GET_ITEM(pieces, 0); +- PyUnicode_AppendAndDel(&s, temp); +- PyList_SET_ITEM(pieces, 0, s); +- if (s == NULL) +- goto Done; ++ Py_ReprLeave((PyObject *)v); ++ return _PyAccu_Finish(&acc); + +- s = PyUnicode_FromString("]"); +- if (s == NULL) +- goto Done; +- temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1); +- PyUnicode_AppendAndDel(&temp, s); +- PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp); +- if (temp == NULL) +- goto Done; +- +- /* Paste them all together with ", " between. */ +- s = PyUnicode_FromString(", "); +- if (s == NULL) +- goto Done; +- result = PyUnicode_Join(s, pieces); +- Py_DECREF(s); +- +-Done: +- Py_XDECREF(pieces); ++error: ++ _PyAccu_Destroy(&acc); ++ Py_XDECREF(s); + Py_ReprLeave((PyObject *)v); +- return result; ++ return NULL; + } + + static Py_ssize_t +@@ -510,9 +499,9 @@ + PyObject *elem; + if (n < 0) + n = 0; ++ if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) ++ return PyErr_NoMemory(); + size = Py_SIZE(a) * n; +- if (n && size/n != Py_SIZE(a)) +- return PyErr_NoMemory(); + if (size == 0) + return PyList_New(0); + np = (PyListObject *) PyList_New(size); +diff -r 137e45f15c0b Objects/longobject.c +--- a/Objects/longobject.c ++++ b/Objects/longobject.c +@@ -525,8 +525,8 @@ + return x; + } + +-/* Get a C unsigned long int from a long int object. +- Returns -1 and sets an error condition if overflow occurs. */ ++/* Get a C size_t from a long int object. Returns (size_t)-1 and sets ++ an error condition if overflow occurs. */ + + size_t + PyLong_AsSize_t(PyObject *vv) +@@ -562,7 +562,7 @@ + if ((x >> PyLong_SHIFT) != prev) { + PyErr_SetString(PyExc_OverflowError, + "Python int too large to convert to C size_t"); +- return (unsigned long) -1; ++ return (size_t) -1; + } + } + return x; +diff -r 137e45f15c0b Objects/object.c +--- a/Objects/object.c ++++ b/Objects/object.c +@@ -1625,6 +1625,9 @@ + if (PyType_Ready(&PyWrapperDescr_Type) < 0) + Py_FatalError("Can't initialize wrapper type"); + ++ if (PyType_Ready(&_PyMethodWrapper_Type) < 0) ++ Py_FatalError("Can't initialize method wrapper type"); ++ + if (PyType_Ready(&PyEllipsis_Type) < 0) + Py_FatalError("Can't initialize ellipsis type"); + +diff -r 137e45f15c0b Objects/setobject.c +--- a/Objects/setobject.c ++++ b/Objects/setobject.c +@@ -1877,7 +1877,7 @@ + tmpkey = make_new_set(&PyFrozenSet_Type, key); + if (tmpkey == NULL) + return -1; +- rv = set_contains(so, tmpkey); ++ rv = set_contains_key(so, tmpkey); + Py_DECREF(tmpkey); + } + return rv; +@@ -1931,7 +1931,7 @@ + static PyObject * + set_discard(PySetObject *so, PyObject *key) + { +- PyObject *tmpkey, *result; ++ PyObject *tmpkey; + int rv; + + rv = set_discard_key(so, key); +@@ -1942,9 +1942,10 @@ + tmpkey = make_new_set(&PyFrozenSet_Type, key); + if (tmpkey == NULL) + return NULL; +- result = set_discard(so, tmpkey); ++ rv = set_discard_key(so, tmpkey); + Py_DECREF(tmpkey); +- return result; ++ if (rv == -1) ++ return NULL; + } + Py_RETURN_NONE; + } +diff -r 137e45f15c0b Objects/sliceobject.c +--- a/Objects/sliceobject.c ++++ b/Objects/sliceobject.c +@@ -320,9 +320,13 @@ + } + + t1 = PyTuple_New(3); ++ if (t1 == NULL) ++ return NULL; + t2 = PyTuple_New(3); +- if (t1 == NULL || t2 == NULL) ++ if (t2 == NULL) { ++ Py_DECREF(t1); + return NULL; ++ } + + PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); + PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); +diff -r 137e45f15c0b Objects/tupleobject.c +--- a/Objects/tupleobject.c ++++ b/Objects/tupleobject.c +@@ -240,13 +240,20 @@ + tuplerepr(PyTupleObject *v) + { + Py_ssize_t i, n; +- PyObject *s, *temp; +- PyObject *pieces, *result = NULL; ++ PyObject *s = NULL; ++ _PyAccu acc; ++ static PyObject *sep = NULL; + + n = Py_SIZE(v); + if (n == 0) + return PyUnicode_FromString("()"); + ++ if (sep == NULL) { ++ sep = PyUnicode_FromString(", "); ++ if (sep == NULL) ++ return NULL; ++ } ++ + /* While not mutable, it is still possible to end up with a cycle in a + tuple through an object that stores itself within a tuple (and thus + infinitely asks for the repr of itself). This should only be +@@ -256,52 +263,42 @@ + return i > 0 ? PyUnicode_FromString("(...)") : NULL; + } + +- pieces = PyTuple_New(n); +- if (pieces == NULL) +- return NULL; ++ if (_PyAccu_Init(&acc)) ++ goto error; ++ ++ s = PyUnicode_FromString("("); ++ if (s == NULL || _PyAccu_Accumulate(&acc, s)) ++ goto error; ++ Py_CLEAR(s); + + /* Do repr() on each element. */ + for (i = 0; i < n; ++i) { + if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) +- goto Done; ++ goto error; + s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); +- if (s == NULL) +- goto Done; +- PyTuple_SET_ITEM(pieces, i, s); ++ if (i > 0 && _PyAccu_Accumulate(&acc, sep)) ++ goto error; ++ if (s == NULL || _PyAccu_Accumulate(&acc, s)) ++ goto error; ++ Py_CLEAR(s); + } ++ if (n > 1) ++ s = PyUnicode_FromString(")"); ++ else ++ s = PyUnicode_FromString(",)"); ++ if (s == NULL || _PyAccu_Accumulate(&acc, s)) ++ goto error; ++ Py_CLEAR(s); + +- /* Add "()" decorations to the first and last items. */ +- assert(n > 0); +- s = PyUnicode_FromString("("); +- if (s == NULL) +- goto Done; +- temp = PyTuple_GET_ITEM(pieces, 0); +- PyUnicode_AppendAndDel(&s, temp); +- PyTuple_SET_ITEM(pieces, 0, s); +- if (s == NULL) +- goto Done; ++ Py_ReprLeave((PyObject *)v); ++ return _PyAccu_Finish(&acc); + +- s = PyUnicode_FromString(n == 1 ? ",)" : ")"); +- if (s == NULL) +- goto Done; +- temp = PyTuple_GET_ITEM(pieces, n-1); +- PyUnicode_AppendAndDel(&temp, s); +- PyTuple_SET_ITEM(pieces, n-1, temp); +- if (temp == NULL) +- goto Done; +- +- /* Paste them all together with ", " between. */ +- s = PyUnicode_FromString(", "); +- if (s == NULL) +- goto Done; +- result = PyUnicode_Join(s, pieces); +- Py_DECREF(s); +- +-Done: +- Py_DECREF(pieces); ++error: ++ _PyAccu_Destroy(&acc); ++ Py_XDECREF(s); + Py_ReprLeave((PyObject *)v); +- return result; ++ return NULL; + } + + /* The addend 82520, was selected from the range(0, 1000000) for +diff -r 137e45f15c0b Objects/typeobject.c +--- a/Objects/typeobject.c ++++ b/Objects/typeobject.c +@@ -967,8 +967,6 @@ + assert(basedealloc); + basedealloc(self); + +- PyType_Modified(type); +- + /* Can't reference self beyond this point */ + Py_DECREF(type); + +@@ -1912,53 +1910,20 @@ + return type->tp_flags; + } + +-static PyObject * +-type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) +-{ +- PyObject *name, *bases, *dict; +- static char *kwlist[] = {"name", "bases", "dict", 0}; +- PyObject *slots, *tmp, *newslots; +- 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; +- +- assert(args != NULL && PyTuple_Check(args)); +- assert(kwds == NULL || PyDict_Check(kwds)); +- +- /* Special case: type(x) should return x->ob_type */ +- { +- const Py_ssize_t nargs = PyTuple_GET_SIZE(args); +- const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); +- +- if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { +- PyObject *x = PyTuple_GET_ITEM(args, 0); +- Py_INCREF(Py_TYPE(x)); +- return (PyObject *) Py_TYPE(x); +- } +- +- /* SF bug 475327 -- if that didn't trigger, we need 3 +- arguments. but PyArg_ParseTupleAndKeywords below may give +- a msg saying type() needs exactly 3. */ +- if (nargs + nkwds != 3) { +- PyErr_SetString(PyExc_TypeError, +- "type() takes 1 or 3 arguments"); +- return NULL; +- } +- } +- +- /* Check arguments: (name, bases, dict) */ +- if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, +- &name, +- &PyTuple_Type, &bases, +- &PyDict_Type, &dict)) +- return NULL; ++/* Determine the most derived metatype. */ ++PyTypeObject * ++_PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases) ++{ ++ Py_ssize_t i, nbases; ++ PyTypeObject *winner; ++ PyObject *tmp; ++ PyTypeObject *tmptype; + + /* Determine the proper metatype to deal with this, + and check for metatype conflicts while we're at it. + Note that if some other metatype wins to contract, + it's possible that its instances are not types. */ ++ + nbases = PyTuple_GET_SIZE(bases); + winner = metatype; + for (i = 0; i < nbases; i++) { +@@ -1970,6 +1935,7 @@ + winner = tmptype; + continue; + } ++ /* else: */ + PyErr_SetString(PyExc_TypeError, + "metaclass conflict: " + "the metaclass of a derived class " +@@ -1977,6 +1943,58 @@ + "of the metaclasses of all its bases"); + return NULL; + } ++ return winner; ++} ++ ++static PyObject * ++type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) ++{ ++ PyObject *name, *bases, *dict; ++ static char *kwlist[] = {"name", "bases", "dict", 0}; ++ PyObject *slots, *tmp, *newslots; ++ 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; ++ ++ assert(args != NULL && PyTuple_Check(args)); ++ assert(kwds == NULL || PyDict_Check(kwds)); ++ ++ /* Special case: type(x) should return x->ob_type */ ++ { ++ const Py_ssize_t nargs = PyTuple_GET_SIZE(args); ++ const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds); ++ ++ if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) { ++ PyObject *x = PyTuple_GET_ITEM(args, 0); ++ Py_INCREF(Py_TYPE(x)); ++ return (PyObject *) Py_TYPE(x); ++ } ++ ++ /* SF bug 475327 -- if that didn't trigger, we need 3 ++ arguments. but PyArg_ParseTupleAndKeywords below may give ++ a msg saying type() needs exactly 3. */ ++ if (nargs + nkwds != 3) { ++ PyErr_SetString(PyExc_TypeError, ++ "type() takes 1 or 3 arguments"); ++ return NULL; ++ } ++ } ++ ++ /* Check arguments: (name, bases, dict) */ ++ if (!PyArg_ParseTupleAndKeywords(args, kwds, "UO!O!:type", kwlist, ++ &name, ++ &PyTuple_Type, &bases, ++ &PyDict_Type, &dict)) ++ return NULL; ++ ++ /* Determine the proper metatype to deal with this: */ ++ winner = _PyType_CalculateMetaclass(metatype, bases); ++ if (winner == NULL) { ++ return NULL; ++ } ++ + if (winner != metatype) { + if (winner->tp_new != type_new) /* Pass it to the winner */ + return winner->tp_new(winner, args, kwds); +@@ -1984,6 +2002,7 @@ + } + + /* Adjust for empty tuple bases */ ++ nbases = PyTuple_GET_SIZE(bases); + if (nbases == 0) { + bases = PyTuple_Pack(1, &PyBaseObject_Type); + if (bases == NULL) +@@ -2093,8 +2112,10 @@ + PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0)) + continue; + tmp =_Py_Mangle(name, tmp); +- if (!tmp) ++ if (!tmp) { ++ Py_DECREF(newslots); + goto bad_slots; ++ } + PyList_SET_ITEM(newslots, j, tmp); + j++; + } +@@ -2622,15 +2643,16 @@ + for heaptypes. */ + assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); + +- /* The only field we need to clear is tp_mro, which is part of a +- hard cycle (its first element is the class itself) that won't +- be broken otherwise (it's a tuple and tuples don't have a ++ /* We need to invalidate the method cache carefully before clearing ++ the dict, so that other objects caught in a reference cycle ++ don't start calling destroyed methods. ++ ++ Otherwise, the only field we need to clear is tp_mro, which is ++ part of a hard cycle (its first element is the class itself) that ++ won't be broken otherwise (it's a tuple and tuples don't have a + tp_clear handler). None of the other fields need to be + cleared, and here's why: + +- tp_dict: +- It is a dict, so the collector will call its tp_clear. +- + tp_cache: + Not used; if it were, it would be a dict. + +@@ -2647,6 +2669,9 @@ + A tuple of strings can't be part of a cycle. + */ + ++ PyType_Modified(type); ++ if (type->tp_dict) ++ PyDict_Clear(type->tp_dict); + Py_CLEAR(type->tp_mro); + + return 0; +@@ -5533,25 +5558,25 @@ + NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, + "x[y:z] <==> x[y.__index__():z.__index__()]"), + IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, +- wrap_binaryfunc, "+"), ++ wrap_binaryfunc, "+="), + IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, +- wrap_binaryfunc, "-"), ++ wrap_binaryfunc, "-="), + IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, +- wrap_binaryfunc, "*"), ++ wrap_binaryfunc, "*="), + IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, +- wrap_binaryfunc, "%"), ++ wrap_binaryfunc, "%="), + IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, +- wrap_binaryfunc, "**"), ++ wrap_binaryfunc, "**="), + IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, +- wrap_binaryfunc, "<<"), ++ wrap_binaryfunc, "<<="), + IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, +- wrap_binaryfunc, ">>"), ++ wrap_binaryfunc, ">>="), + IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, +- wrap_binaryfunc, "&"), ++ wrap_binaryfunc, "&="), + IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, +- wrap_binaryfunc, "^"), ++ wrap_binaryfunc, "^="), + IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, +- wrap_binaryfunc, "|"), ++ wrap_binaryfunc, "|="), + BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), + BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), +diff -r 137e45f15c0b Objects/unicodeobject.c +--- a/Objects/unicodeobject.c ++++ b/Objects/unicodeobject.c +@@ -1187,12 +1187,12 @@ + /* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString(): + convert a Unicode object to a wide character string. + +- - If w is NULL: return the number of wide characters (including the nul ++ - If w is NULL: return the number of wide characters (including the null + character) required to convert the unicode object. Ignore size argument. + +- - Otherwise: return the number of wide characters (excluding the nul ++ - Otherwise: return the number of wide characters (excluding the null + character) written into w. Write at most size wide characters (including +- the nul character). */ ++ the null character). */ + static Py_ssize_t + unicode_aswidechar(PyUnicodeObject *unicode, + wchar_t *w, +@@ -1240,7 +1240,7 @@ + return w - worig; + } + else { +- nchar = 1; /* nul character at the end */ ++ nchar = 1; /* null character at the end */ + while (u != uend) { + if (0xD800 <= u[0] && u[0] <= 0xDBFF + && 0xDC00 <= u[1] && u[1] <= 0xDFFF) +@@ -1278,7 +1278,7 @@ + return w - worig; + } + else { +- nchar = 1; /* nul character */ ++ nchar = 1; /* null character */ + while (u != uend) { + if (*u > 0xffff) + nchar += 2; +@@ -2282,21 +2282,17 @@ + *p++ = outCh; + #endif + surrogate = 0; ++ continue; + } + else { ++ *p++ = surrogate; + surrogate = 0; +- errmsg = "second surrogate missing"; +- goto utf7Error; + } + } +- else if (outCh >= 0xD800 && outCh <= 0xDBFF) { ++ if (outCh >= 0xD800 && outCh <= 0xDBFF) { + /* first surrogate */ + surrogate = outCh; + } +- else if (outCh >= 0xDC00 && outCh <= 0xDFFF) { +- errmsg = "unexpected second surrogate"; +- goto utf7Error; +- } + else { + *p++ = outCh; + } +@@ -2306,8 +2302,8 @@ + inShift = 0; + s++; + if (surrogate) { +- errmsg = "second surrogate missing at end of shift sequence"; +- goto utf7Error; ++ *p++ = surrogate; ++ surrogate = 0; + } + if (base64bits > 0) { /* left-over bits */ + if (base64bits >= 6) { +@@ -6327,11 +6323,10 @@ + } + /* All other characters are considered unencodable */ + collstart = p; +- collend = p+1; +- while (collend < end) { ++ for (collend = p+1; collend < end; collend++) { + if ((0 < *collend && *collend < 256) || +- !Py_UNICODE_ISSPACE(*collend) || +- Py_UNICODE_TODECIMAL(*collend)) ++ Py_UNICODE_ISSPACE(*collend) || ++ 0 <= Py_UNICODE_TODECIMAL(*collend)) + break; + } + /* cache callback name lookup +@@ -6442,6 +6437,37 @@ + start = 0; \ + } + ++/* _Py_UNICODE_NEXT is a private macro used to retrieve the character pointed ++ * by 'ptr', possibly combining surrogate pairs on narrow builds. ++ * 'ptr' and 'end' must be Py_UNICODE*, with 'ptr' pointing at the character ++ * that should be returned and 'end' pointing to the end of the buffer. ++ * ('end' is used on narrow builds to detect a lone surrogate at the ++ * end of the buffer that should be returned unchanged.) ++ * The ptr and end arguments should be side-effect free and ptr must an lvalue. ++ * The type of the returned char is always Py_UCS4. ++ * ++ * Note: the macro advances ptr to next char, so it might have side-effects ++ * (especially if used with other macros). ++ */ ++ ++/* helper macros used by _Py_UNICODE_NEXT */ ++#define _Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= ch && ch <= 0xDBFF) ++#define _Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= ch && ch <= 0xDFFF) ++/* Join two surrogate characters and return a single Py_UCS4 value. */ ++#define _Py_UNICODE_JOIN_SURROGATES(high, low) \ ++ (((((Py_UCS4)(high) & 0x03FF) << 10) | \ ++ ((Py_UCS4)(low) & 0x03FF)) + 0x10000) ++ ++#ifdef Py_UNICODE_WIDE ++#define _Py_UNICODE_NEXT(ptr, end) *(ptr)++ ++#else ++#define _Py_UNICODE_NEXT(ptr, end) \ ++ (((_Py_UNICODE_IS_HIGH_SURROGATE(*(ptr)) && (ptr) < (end)) && \ ++ _Py_UNICODE_IS_LOW_SURROGATE((ptr)[1])) ? \ ++ ((ptr) += 2,_Py_UNICODE_JOIN_SURROGATES((ptr)[-2], (ptr)[-1])) : \ ++ (Py_UCS4)*(ptr)++) ++#endif ++ + Py_ssize_t PyUnicode_Count(PyObject *str, + PyObject *substr, + Py_ssize_t start, +@@ -6658,13 +6684,13 @@ + + if (len == 0) + return 0; +- if (Py_UNICODE_ISLOWER(*s)) { ++ if (!Py_UNICODE_ISUPPER(*s)) { + *s = Py_UNICODE_TOUPPER(*s); + status = 1; + } + s++; + while (--len > 0) { +- if (Py_UNICODE_ISUPPER(*s)) { ++ if (!Py_UNICODE_ISLOWER(*s)) { + *s = Py_UNICODE_TOLOWER(*s); + status = 1; + } +@@ -6977,7 +7003,7 @@ + } + } else { + +- Py_ssize_t n, i, j, e; ++ Py_ssize_t n, i, j; + Py_ssize_t product, new_size, delta; + Py_UNICODE *p; + +@@ -7009,7 +7035,6 @@ + return NULL; + i = 0; + p = u->str; +- e = self->length - str1->length; + if (str1->length > 0) { + while (n-- > 0) { + /* look for next match */ +@@ -7705,8 +7730,8 @@ + + e = p + PyUnicode_GET_SIZE(self); + cased = 0; +- for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ while (p < e) { ++ const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e); + + if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) + return PyBool_FromLong(0); +@@ -7739,8 +7764,8 @@ + + e = p + PyUnicode_GET_SIZE(self); + cased = 0; +- for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ while (p < e) { ++ const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e); + + if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch)) + return PyBool_FromLong(0); +@@ -7777,8 +7802,8 @@ + e = p + PyUnicode_GET_SIZE(self); + cased = 0; + previous_is_cased = 0; +- for (; p < e; p++) { +- register const Py_UNICODE ch = *p; ++ while (p < e) { ++ const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e); + + if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) { + if (previous_is_cased) +@@ -7820,8 +7845,9 @@ + return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISSPACE(*p)) ++ while (p < e) { ++ const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e); ++ if (!Py_UNICODE_ISSPACE(ch)) + return PyBool_FromLong(0); + } + return PyBool_FromLong(1); +@@ -7849,8 +7875,8 @@ + return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISALPHA(*p)) ++ while (p < e) { ++ if (!Py_UNICODE_ISALPHA(_Py_UNICODE_NEXT(p, e))) + return PyBool_FromLong(0); + } + return PyBool_FromLong(1); +@@ -7878,8 +7904,9 @@ + return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISALNUM(*p)) ++ while (p < e) { ++ const Py_UCS4 ch = _Py_UNICODE_NEXT(p, e); ++ if (!Py_UNICODE_ISALNUM(ch)) + return PyBool_FromLong(0); + } + return PyBool_FromLong(1); +@@ -7907,8 +7934,8 @@ + return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISDECIMAL(*p)) ++ while (p < e) { ++ if (!Py_UNICODE_ISDECIMAL(_Py_UNICODE_NEXT(p, e))) + return PyBool_FromLong(0); + } + return PyBool_FromLong(1); +@@ -7936,8 +7963,8 @@ + return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISDIGIT(*p)) ++ while (p < e) { ++ if (!Py_UNICODE_ISDIGIT(_Py_UNICODE_NEXT(p, e))) + return PyBool_FromLong(0); + } + return PyBool_FromLong(1); +@@ -7965,37 +7992,22 @@ + return PyBool_FromLong(0); + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISNUMERIC(*p)) ++ while (p < e) { ++ if (!Py_UNICODE_ISNUMERIC(_Py_UNICODE_NEXT(p, e))) + return PyBool_FromLong(0); + } + return PyBool_FromLong(1); + } + +-static Py_UCS4 +-decode_ucs4(const Py_UNICODE *s, Py_ssize_t *i, Py_ssize_t size) +-{ +- Py_UCS4 ch; +- assert(*i < size); +- ch = s[(*i)++]; +-#ifndef Py_UNICODE_WIDE +- if ((ch & 0xfffffc00) == 0xd800 && +- *i < size +- && (s[*i] & 0xFFFFFC00) == 0xDC00) +- ch = ((Py_UCS4)ch << 10UL) + (Py_UCS4)(s[(*i)++]) - 0x35fdc00; +-#endif +- return ch; +-} +- + int + PyUnicode_IsIdentifier(PyObject *self) + { +- Py_ssize_t i = 0, size = PyUnicode_GET_SIZE(self); ++ const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self); ++ const Py_UNICODE *e; + Py_UCS4 first; +- const Py_UNICODE *p = PyUnicode_AS_UNICODE((PyUnicodeObject*)self); + + /* Special case for empty strings */ +- if (!size) ++ if (PyUnicode_GET_SIZE(self) == 0) + return 0; + + /* PEP 3131 says that the first character must be in +@@ -8006,12 +8018,13 @@ + definition of XID_Start and XID_Continue, it is sufficient + to check just for these, except that _ must be allowed + as starting an identifier. */ +- first = decode_ucs4(p, &i, size); ++ e = p + PyUnicode_GET_SIZE(self); ++ first = _Py_UNICODE_NEXT(p, e); + if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */) + return 0; + +- while (i < size) +- if (!_PyUnicode_IsXidContinue(decode_ucs4(p, &i, size))) ++ while (p < e) ++ if (!_PyUnicode_IsXidContinue(_Py_UNICODE_NEXT(p, e))) + return 0; + return 1; + } +@@ -8046,8 +8059,8 @@ + } + + e = p + PyUnicode_GET_SIZE(self); +- for (; p < e; p++) { +- if (!Py_UNICODE_ISPRINTABLE(*p)) { ++ while (p < e) { ++ if (!Py_UNICODE_ISPRINTABLE(_Py_UNICODE_NEXT(p, e))) { + Py_RETURN_FALSE; + } + } +diff -r 137e45f15c0b PC/VC6/pythoncore.dsp +--- a/PC/VC6/pythoncore.dsp ++++ b/PC/VC6/pythoncore.dsp +@@ -205,6 +205,10 @@ + # End Source File + # Begin Source File + ++SOURCE=..\..\Objects\accu.c ++# End Source File ++# Begin Source File ++ + SOURCE=..\..\Parser\acceler.c + # End Source File + # Begin Source File +diff -r 137e45f15c0b PC/VS7.1/pythoncore.vcproj +--- a/PC/VS7.1/pythoncore.vcproj ++++ b/PC/VS7.1/pythoncore.vcproj +@@ -445,6 +445,9 @@ + RelativePath="..\..\Objects\abstract.c"> + + ++ ++ + + + + ++ ++ + +@@ -1447,6 +1451,10 @@ + > + + ++ ++ + +diff -r 137e45f15c0b PC/errmap.h +--- a/PC/errmap.h ++++ b/PC/errmap.h +@@ -72,6 +72,8 @@ + case 202: return 8; + case 206: return 2; + case 215: return 11; ++ case 232: return 32; ++ case 267: return 20; + case 1816: return 12; + default: return EINVAL; + } +diff -r 137e45f15c0b PC/generrmap.c +--- a/PC/generrmap.c ++++ b/PC/generrmap.c +@@ -1,3 +1,6 @@ ++#include ++#include ++#include + #include + #include + +@@ -6,15 +9,24 @@ + int main() + { + int i; ++ _setmode(fileno(stdout), O_BINARY); + printf("/* Generated file. Do not edit. */\n"); + printf("int winerror_to_errno(int winerror)\n"); +- printf("{\n\tswitch(winerror) {\n"); ++ printf("{\n switch(winerror) {\n"); + for(i=1; i < 65000; i++) { + _dosmaperr(i); +- if (errno == EINVAL) +- continue; +- printf("\t\tcase %d: return %d;\n", i, errno); ++ if (errno == EINVAL) { ++ /* Issue #12802 */ ++ if (i == ERROR_DIRECTORY) ++ errno = ENOTDIR; ++ /* Issue #13063 */ ++ else if (i == ERROR_NO_DATA) ++ errno = EPIPE; ++ else ++ continue; ++ } ++ printf(" case %d: return %d;\n", i, errno); + } +- printf("\t\tdefault: return EINVAL;\n"); +- printf("\t}\n}\n"); ++ printf(" default: return EINVAL;\n"); ++ printf(" }\n}\n"); + } +diff -r 137e45f15c0b PC/pyconfig.h +--- a/PC/pyconfig.h ++++ b/PC/pyconfig.h +@@ -648,6 +648,9 @@ + #define HAVE_WCSXFRM 1 + #endif + ++/* Define if the zlib library has inflateCopy */ ++#define HAVE_ZLIB_COPY 1 ++ + /* Define if you have the header file. */ + /* #undef HAVE_DLFCN_H */ + +diff -r 137e45f15c0b PCbuild/pythoncore.vcproj +--- a/PCbuild/pythoncore.vcproj ++++ b/PCbuild/pythoncore.vcproj +@@ -635,6 +635,10 @@ + > + + ++ ++ + +@@ -1447,6 +1451,10 @@ + > + + ++ ++ + +diff -r 137e45f15c0b Parser/asdl_c.py +--- a/Parser/asdl_c.py ++++ b/Parser/asdl_c.py +@@ -816,11 +816,7 @@ + { + int i; + if (!PyLong_Check(obj)) { +- PyObject *s = PyObject_Repr(obj); +- if (s == NULL) return 1; +- PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s", +- PyBytes_AS_STRING(s)); +- Py_DECREF(s); ++ PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj); + return 1; + } + +diff -r 137e45f15c0b Parser/myreadline.c +--- a/Parser/myreadline.c ++++ b/Parser/myreadline.c +@@ -36,6 +36,7 @@ + my_fgets(char *buf, int len, FILE *fp) + { + char *p; ++ int err; + while (1) { + if (PyOS_InputHook != NULL) + (void)(PyOS_InputHook)(); +@@ -44,6 +45,7 @@ + p = fgets(buf, len, fp); + if (p != NULL) + return 0; /* No error */ ++ err = errno; + #ifdef MS_WINDOWS + /* In the case of a Ctrl+C or some other external event + interrupting the operation: +@@ -78,7 +80,7 @@ + return -1; /* EOF */ + } + #ifdef EINTR +- if (errno == EINTR) { ++ if (err == EINTR) { + int s; + #ifdef WITH_THREAD + PyEval_RestoreThread(_PyOS_ReadlineTState); +diff -r 137e45f15c0b Parser/parsetok.c +--- a/Parser/parsetok.c ++++ b/Parser/parsetok.c +@@ -183,11 +183,13 @@ + if (type == NOTEQUAL) { + if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "!=")) { ++ PyObject_FREE(str); + err_ret->error = E_SYNTAX; + break; + } + else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && + strcmp(str, "<>")) { ++ PyObject_FREE(str); + err_ret->text = "with Barry as BDFL, use '<>' " + "instead of '!='"; + err_ret->error = E_SYNTAX; +diff -r 137e45f15c0b Python/Python-ast.c +--- a/Python/Python-ast.c ++++ b/Python/Python-ast.c +@@ -622,11 +622,7 @@ + { + int i; + if (!PyLong_Check(obj)) { +- PyObject *s = PyObject_Repr(obj); +- if (s == NULL) return 1; +- PyErr_Format(PyExc_ValueError, "invalid integer value: %.400s", +- PyBytes_AS_STRING(s)); +- Py_DECREF(s); ++ PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj); + return 1; + } + +diff -r 137e45f15c0b Python/_warnings.c +--- a/Python/_warnings.c ++++ b/Python/_warnings.c +@@ -888,7 +888,6 @@ + static PyObject * + init_filters(void) + { +- /* Don't silence DeprecationWarning if -3 was used. */ + PyObject *filters = PyList_New(5); + unsigned int pos = 0; /* Post-incremented in each use. */ + unsigned int x; +diff -r 137e45f15c0b Python/bltinmodule.c +--- a/Python/bltinmodule.c ++++ b/Python/bltinmodule.c +@@ -35,9 +35,10 @@ + static PyObject * + builtin___build_class__(PyObject *self, PyObject *args, PyObject *kwds) + { +- PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell; ++ PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns, *cell; + PyObject *cls = NULL; +- Py_ssize_t nargs, nbases; ++ Py_ssize_t nargs; ++ int isclass; + + assert(args != NULL); + if (!PyTuple_Check(args)) { +@@ -61,7 +62,6 @@ + bases = PyTuple_GetSlice(args, 2, nargs); + if (bases == NULL) + return NULL; +- nbases = nargs - 2; + + if (kwds == NULL) { + meta = NULL; +@@ -82,17 +82,42 @@ + Py_DECREF(bases); + return NULL; + } ++ /* metaclass is explicitly given, check if it's indeed a class */ ++ isclass = PyType_Check(meta); + } + } + if (meta == NULL) { +- if (PyTuple_GET_SIZE(bases) == 0) ++ /* if there are no bases, use type: */ ++ if (PyTuple_GET_SIZE(bases) == 0) { + meta = (PyObject *) (&PyType_Type); ++ } ++ /* else get the type of the first base */ + else { + PyObject *base0 = PyTuple_GET_ITEM(bases, 0); + meta = (PyObject *) (base0->ob_type); + } + Py_INCREF(meta); ++ isclass = 1; /* meta is really a class */ + } ++ if (isclass) { ++ /* meta is really a class, so check for a more derived ++ metaclass, or possible metaclass conflicts: */ ++ winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta, ++ bases); ++ if (winner == NULL) { ++ Py_DECREF(meta); ++ Py_XDECREF(mkw); ++ Py_DECREF(bases); ++ return NULL; ++ } ++ if (winner != meta) { ++ Py_DECREF(meta); ++ meta = winner; ++ Py_INCREF(meta); ++ } ++ } ++ /* else: meta is not a class, so we cannot do the metaclass ++ calculation, so we will use the explicitly given object as it is */ + prep = PyObject_GetAttrString(meta, "__prepare__"); + if (prep == NULL) { + if (PyErr_ExceptionMatches(PyExc_AttributeError)) { +@@ -1615,76 +1640,65 @@ + + /* If we're interactive, use (GNU) readline */ + if (tty) { +- PyObject *po; ++ PyObject *po = NULL; + char *prompt; +- char *s; +- PyObject *stdin_encoding; +- char *stdin_encoding_str; ++ char *s = NULL; ++ PyObject *stdin_encoding = NULL, *stdin_errors = NULL; ++ PyObject *stdout_encoding = NULL, *stdout_errors = NULL; ++ char *stdin_encoding_str, *stdin_errors_str; + PyObject *result; + size_t len; + + stdin_encoding = PyObject_GetAttrString(fin, "encoding"); +- if (!stdin_encoding) ++ stdin_errors = PyObject_GetAttrString(fin, "errors"); ++ if (!stdin_encoding || !stdin_errors) + /* stdin is a text stream, so it must have an + encoding. */ +- return NULL; ++ goto _readline_errors; + stdin_encoding_str = _PyUnicode_AsString(stdin_encoding); +- if (stdin_encoding_str == NULL) { +- Py_DECREF(stdin_encoding); +- return NULL; +- } ++ stdin_errors_str = _PyUnicode_AsString(stdin_errors); ++ if (!stdin_encoding_str || !stdin_errors_str) ++ goto _readline_errors; + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); + else + Py_DECREF(tmp); + if (promptarg != NULL) { ++ /* We have a prompt, encode it as stdout would */ ++ char *stdout_encoding_str, *stdout_errors_str; + PyObject *stringpo; +- PyObject *stdout_encoding; +- char *stdout_encoding_str; + stdout_encoding = PyObject_GetAttrString(fout, "encoding"); +- if (stdout_encoding == NULL) { +- Py_DECREF(stdin_encoding); +- return NULL; +- } ++ stdout_errors = PyObject_GetAttrString(fout, "errors"); ++ if (!stdout_encoding || !stdout_errors) ++ goto _readline_errors; + stdout_encoding_str = _PyUnicode_AsString(stdout_encoding); +- if (stdout_encoding_str == NULL) { +- Py_DECREF(stdin_encoding); +- Py_DECREF(stdout_encoding); +- return NULL; +- } ++ stdout_errors_str = _PyUnicode_AsString(stdout_errors); ++ if (!stdout_encoding_str || !stdout_errors_str) ++ goto _readline_errors; + stringpo = PyObject_Str(promptarg); +- if (stringpo == NULL) { +- Py_DECREF(stdin_encoding); +- Py_DECREF(stdout_encoding); +- return NULL; +- } ++ if (stringpo == NULL) ++ goto _readline_errors; + po = PyUnicode_AsEncodedString(stringpo, +- stdout_encoding_str, NULL); +- Py_DECREF(stdout_encoding); +- Py_DECREF(stringpo); +- if (po == NULL) { +- Py_DECREF(stdin_encoding); +- return NULL; +- } ++ stdout_encoding_str, stdout_errors_str); ++ Py_CLEAR(stdout_encoding); ++ Py_CLEAR(stdout_errors); ++ Py_CLEAR(stringpo); ++ if (po == NULL) ++ goto _readline_errors; + prompt = PyBytes_AsString(po); +- if (prompt == NULL) { +- Py_DECREF(stdin_encoding); +- Py_DECREF(po); +- return NULL; +- } ++ if (prompt == NULL) ++ goto _readline_errors; + } + else { + po = NULL; + prompt = ""; + } + s = PyOS_Readline(stdin, stdout, prompt); +- Py_XDECREF(po); + if (s == NULL) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_KeyboardInterrupt); +- Py_DECREF(stdin_encoding); +- return NULL; ++ goto _readline_errors; + } + + len = strlen(s); +@@ -1702,12 +1716,22 @@ + len--; /* strip trailing '\n' */ + if (len != 0 && s[len-1] == '\r') + len--; /* strip trailing '\r' */ +- result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL); ++ result = PyUnicode_Decode(s, len, stdin_encoding_str, ++ stdin_errors_str); + } + } + Py_DECREF(stdin_encoding); ++ Py_DECREF(stdin_errors); ++ Py_XDECREF(po); + PyMem_FREE(s); + return result; ++ _readline_errors: ++ Py_XDECREF(stdin_encoding); ++ Py_XDECREF(stdout_encoding); ++ Py_XDECREF(stdin_errors); ++ Py_XDECREF(stdout_errors); ++ Py_XDECREF(po); ++ return NULL; + } + + /* Fallback if we're not interactive */ +diff -r 137e45f15c0b Python/import.c +--- a/Python/import.c ++++ b/Python/import.c +@@ -252,16 +252,6 @@ + Py_DECREF(path_hooks); + } + +-void +-_PyImport_Fini(void) +-{ +- Py_XDECREF(extensions); +- extensions = NULL; +- PyMem_DEL(_PyImport_Filetab); +- _PyImport_Filetab = NULL; +-} +- +- + /* Locking primitives to prevent parallel imports of the same module + in different threads to return with a partially loaded module. + These calls are serialized by the global interpreter lock. */ +@@ -374,6 +364,21 @@ + return Py_None; + } + ++void ++_PyImport_Fini(void) ++{ ++ Py_XDECREF(extensions); ++ extensions = NULL; ++ PyMem_DEL(_PyImport_Filetab); ++ _PyImport_Filetab = NULL; ++#ifdef WITH_THREAD ++ if (import_lock != NULL) { ++ PyThread_free_lock(import_lock); ++ import_lock = NULL; ++ } ++#endif ++} ++ + static void + imp_modules_reloading_clear(void) + { +@@ -1591,7 +1596,7 @@ + + meta_path = PySys_GetObject("meta_path"); + if (meta_path == NULL || !PyList_Check(meta_path)) { +- PyErr_SetString(PyExc_ImportError, ++ PyErr_SetString(PyExc_RuntimeError, + "sys.meta_path must be a list of " + "import hooks"); + return NULL; +@@ -1641,14 +1646,14 @@ + } + + if (path == NULL || !PyList_Check(path)) { +- PyErr_SetString(PyExc_ImportError, ++ PyErr_SetString(PyExc_RuntimeError, + "sys.path must be a list of directory names"); + return NULL; + } + + path_hooks = PySys_GetObject("path_hooks"); + if (path_hooks == NULL || !PyList_Check(path_hooks)) { +- PyErr_SetString(PyExc_ImportError, ++ PyErr_SetString(PyExc_RuntimeError, + "sys.path_hooks must be a list of " + "import hooks"); + return NULL; +@@ -1656,7 +1661,7 @@ + path_importer_cache = PySys_GetObject("path_importer_cache"); + if (path_importer_cache == NULL || + !PyDict_Check(path_importer_cache)) { +- PyErr_SetString(PyExc_ImportError, ++ PyErr_SetString(PyExc_RuntimeError, + "sys.path_importer_cache must be a dict"); + return NULL; + } +@@ -1763,6 +1768,7 @@ + saved_namelen = namelen; + #endif /* PYOS_OS2 */ + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { ++ struct stat statbuf; + #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING) + /* OS/2 limits DLLs to 8 character names (w/o + extension) +@@ -1791,10 +1797,16 @@ + strcpy(buf+len, fdp->suffix); + if (Py_VerboseFlag > 1) + PySys_WriteStderr("# trying %s\n", buf); ++ + filemode = fdp->mode; + if (filemode[0] == 'U') + filemode = "r" PY_STDIOTEXTMODE; +- fp = fopen(buf, filemode); ++ ++ if (stat(buf, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) ++ /* it's a directory */ ++ fp = NULL; ++ else ++ fp = fopen(buf, filemode); + if (fp != NULL) { + if (case_ok(buf, len, namelen, name)) + break; +@@ -2349,7 +2361,9 @@ + { + PyObject *result; + PyObject *modules; ++#ifdef WITH_THREAD + long me; ++#endif + + /* Try to get the module from sys.modules[name] */ + modules = PyImport_GetModuleDict(); +@@ -3520,7 +3534,8 @@ + } + + PyDoc_STRVAR(doc_cache_from_source, +-"Given the path to a .py file, return the path to its .pyc/.pyo file.\n\ ++"cache_from_source(path, [debug_override]) -> path\n\ ++Given the path to a .py file, return the path to its .pyc/.pyo file.\n\ + \n\ + The .py file does not need to exist; this simply returns the path to the\n\ + .pyc/.pyo file calculated as if the .py file were imported. The extension\n\ +@@ -3555,7 +3570,8 @@ + } + + PyDoc_STRVAR(doc_source_from_cache, +-"Given the path to a .pyc./.pyo file, return the path to its .py file.\n\ ++"source_from_cache(path) -> path\n\ ++Given the path to a .pyc./.pyo file, return the path to its .py file.\n\ + \n\ + The .pyc/.pyo file does not need to exist; this simply returns the path to\n\ + the .py file calculated to correspond to the .pyc/.pyo file. If path\n\ +diff -r 137e45f15c0b Python/pystate.c +--- a/Python/pystate.c ++++ b/Python/pystate.c +@@ -150,6 +150,12 @@ + *p = interp->next; + HEAD_UNLOCK(); + free(interp); ++#ifdef WITH_THREAD ++ if (interp_head == NULL && head_mutex != NULL) { ++ PyThread_free_lock(head_mutex); ++ head_mutex = NULL; ++ } ++#endif + } + + +@@ -586,9 +592,9 @@ + autoInterpreterState = NULL; + } + +-/* Reset the TLS key - called by PyOS_AfterFork. ++/* Reset the TLS key - called by PyOS_AfterFork(). + * This should not be necessary, but some - buggy - pthread implementations +- * don't flush TLS on fork, see issue #10517. ++ * don't reset TLS upon fork(), see issue #10517. + */ + void + _PyGILState_Reinit(void) +@@ -598,8 +604,9 @@ + if ((autoTLSkey = PyThread_create_key()) == -1) + Py_FatalError("Could not allocate TLS entry"); + +- /* re-associate the current thread state with the new key */ +- if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) ++ /* If the thread had an associated auto thread state, reassociate it with ++ * the new key. */ ++ if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) + Py_FatalError("Couldn't create autoTLSkey mapping"); + } + +diff -r 137e45f15c0b Python/pythonrun.c +--- a/Python/pythonrun.c ++++ b/Python/pythonrun.c +@@ -332,6 +332,22 @@ + + /* Flush stdout and stderr */ + ++static int ++file_is_closed(PyObject *fobj) ++{ ++ int r; ++ PyObject *tmp = PyObject_GetAttrString(fobj, "closed"); ++ if (tmp == NULL) { ++ PyErr_Clear(); ++ return 0; ++ } ++ r = PyObject_IsTrue(tmp); ++ Py_DECREF(tmp); ++ if (r < 0) ++ PyErr_Clear(); ++ return r > 0; ++} ++ + static void + flush_std_files(void) + { +@@ -339,7 +355,7 @@ + PyObject *ferr = PySys_GetObject("stderr"); + PyObject *tmp; + +- if (fout != NULL && fout != Py_None) { ++ if (fout != NULL && fout != Py_None && !file_is_closed(fout)) { + tmp = PyObject_CallMethod(fout, "flush", ""); + if (tmp == NULL) + PyErr_WriteUnraisable(fout); +@@ -347,7 +363,7 @@ + Py_DECREF(tmp); + } + +- if (ferr != NULL && ferr != Py_None) { ++ if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) { + tmp = PyObject_CallMethod(ferr, "flush", ""); + if (tmp == NULL) + PyErr_Clear(); +@@ -876,6 +892,19 @@ + return NULL; + } + ++static int ++is_valid_fd(int fd) ++{ ++ int dummy_fd; ++ if (fd < 0 || !_PyVerify_fd(fd)) ++ return 0; ++ dummy_fd = dup(fd); ++ if (dummy_fd < 0) ++ return 0; ++ close(dummy_fd); ++ return 1; ++} ++ + /* Initialize sys.stdin, stdout, stderr and builtins.open */ + static int + initstdio(void) +@@ -935,13 +964,9 @@ + * and fileno() may point to an invalid file descriptor. For example + * GUI apps don't have valid standard streams by default. + */ +- if (fd < 0) { +-#ifdef MS_WINDOWS ++ if (!is_valid_fd(fd)) { + std = Py_None; + Py_INCREF(std); +-#else +- goto error; +-#endif + } + else { + std = create_stdio(iomod, fd, 0, "", encoding, errors); +@@ -954,13 +979,9 @@ + + /* Set sys.stdout */ + fd = fileno(stdout); +- if (fd < 0) { +-#ifdef MS_WINDOWS ++ if (!is_valid_fd(fd)) { + std = Py_None; + Py_INCREF(std); +-#else +- goto error; +-#endif + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, errors); +@@ -974,13 +995,9 @@ + #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ + /* Set sys.stderr, replaces the preliminary stderr */ + fd = fileno(stderr); +- if (fd < 0) { +-#ifdef MS_WINDOWS ++ if (!is_valid_fd(fd)) { + std = Py_None; + Py_INCREF(std); +-#else +- goto error; +-#endif + } + else { + std = create_stdio(iomod, fd, 1, "", encoding, "backslashreplace"); +@@ -1241,8 +1258,10 @@ + Py_DECREF(f); + return -1; + } +- if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) ++ if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) { ++ Py_DECREF(f); + return -1; ++ } + set_file_name = 1; + Py_DECREF(f); + } +diff -r 137e45f15c0b Python/symtable.c +--- a/Python/symtable.c ++++ b/Python/symtable.c +@@ -1334,6 +1334,9 @@ + return 0; + if (e->v.Lambda.args->defaults) + VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); ++ if (e->v.Lambda.args->kw_defaults) ++ VISIT_KWONLYDEFAULTS(st, ++ e->v.Lambda.args->kw_defaults); + if (!symtable_enter_block(st, lambda, + FunctionBlock, (void *)e, e->lineno, + e->col_offset)) +diff -r 137e45f15c0b Tools/iobench/iobench.py +--- a/Tools/iobench/iobench.py ++++ b/Tools/iobench/iobench.py +@@ -358,7 +358,7 @@ + with text_open(name, "r") as f: + return f.read() + run_test_family(modify_tests, "b", text_files, +- lambda fn: open(fn, "r+"), make_test_source) ++ lambda fn: text_open(fn, "r+"), make_test_source) + + + def prepare_files(): +diff -r 137e45f15c0b Tools/msi/uuids.py +--- a/Tools/msi/uuids.py ++++ b/Tools/msi/uuids.py +@@ -90,4 +90,9 @@ + '3.2.1121':'{4f90de4a-83dd-4443-b625-ca130ff361dd}', # 3.2.1rc1 + '3.2.1122':'{dc5eb04d-ff8a-4bed-8f96-23942fd59e5f}', # 3.2.1rc2 + '3.2.1150':'{34b2530c-6349-4292-9dc3-60bda4aed93c}', # 3.2.1 ++ '3.2.2121':'{DFB29A53-ACC4-44e6-85A6-D0DA26FE8E4E}', # 3.2.2rc1 ++ '3.2.2150':'{4CDE3168-D060-4b7c-BC74-4D8F9BB01AFD}', # 3.2.2 ++ '3.2.3121':'{B8E8CFF7-E4C6-4a7c-9F06-BB3A8B75DDA8}', # 3.2.3rc1 ++ '3.2.3150':'{789C9644-9F82-44d3-B4CA-AC31F46F5882}', # 3.2.3 ++ + } +diff -r 137e45f15c0b configure.in +--- a/configure.in ++++ b/configure.in +@@ -926,6 +926,13 @@ + if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then + WRAP="-fwrapv" + fi ++ ++ # Clang also needs -fwrapv ++ case $CC in ++ *clang*) WRAP="-fwrapv" ++ ;; ++ esac ++ + case $ac_cv_prog_cc_g in + yes) + if test "$Py_DEBUG" = 'true' ; then +@@ -2690,6 +2697,15 @@ + [AC_MSG_RESULT(no) + ]) + ++AC_MSG_CHECKING(for broken unsetenv) ++AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ ++#include ++]], [[int res = unsetenv("DUMMY")]])], ++ [AC_MSG_RESULT(no)], ++ [AC_DEFINE(HAVE_BROKEN_UNSETENV, 1, Define if `unsetenv` does not return an int.) ++ AC_MSG_RESULT(yes) ++]) ++ + dnl check for true + AC_CHECK_PROGS(TRUE, true, /bin/true) + +diff -r 137e45f15c0b pyconfig.h.in +--- a/pyconfig.h.in ++++ b/pyconfig.h.in +@@ -98,6 +98,9 @@ + /* define to 1 if your sem_getvalue is broken. */ + #undef HAVE_BROKEN_SEM_GETVALUE + ++/* Define if `unsetenv` does not return an int. */ ++#undef HAVE_BROKEN_UNSETENV ++ + /* Define this if you have the type _Bool. */ + #undef HAVE_C99_BOOL + --- python3.2-3.2.2.orig/debian/patches/enable-fpectl.diff +++ python3.2-3.2.2/debian/patches/enable-fpectl.diff @@ -0,0 +1,14 @@ +# DP: Enable the build of the fpectl module. + +--- a/setup.py ++++ b/setup.py +@@ -1190,6 +1190,9 @@ + else: + missing.append('_curses_panel') + ++ #fpectl fpectlmodule.c ... ++ exts.append( Extension('fpectl', ['fpectlmodule.c']) ) ++ + # Andrew Kuchling's zlib module. Note that some versions of zlib + # 1.1.3 have security problems. See CERT Advisory CA-2002-07: + # http://www.cert.org/advisories/CA-2002-07.html --- python3.2-3.2.2.orig/debian/patches/series.in +++ python3.2-3.2.2/debian/patches/series.in @@ -0,0 +1,60 @@ +hg-updates.diff +autoconf-version.diff +deb-setup.diff +deb-locations.diff +site-locations.diff +distutils-install-layout.diff +locale-module.diff +distutils-link.diff +// FIXME update patch +//distutils-sysconfig.diff +test-sundry.diff +tkinter-import.diff +link-opt.diff +// debug-build.diff +webbrowser.diff +linecache.diff +setup-modules.diff +platform-lsbrelease.diff +bdist-wininst-notfound.diff +no-zip-on-sys.path.diff +doc-nodownload.diff +profiled-build.diff +makesetup-bashism.diff +hurd-broken-poll.diff +hurd-disable-nonworking-constants.diff +enable-fpectl.diff +statvfs-f_flag-constants.diff +#if defined (arch_alpha) +plat-linux2_alpha.diff +#elif defined (arch_hppa) +plat-linux2_hppa.diff +#elif defined (arch_mips) || defined(arch_mipsel) +plat-linux2_mips.diff +#elif defined (arch_sparc) || defined (arch_sparc64) +plat-linux2_sparc.diff +#endif +#if defined (BROKEN_UTIMES) +disable-utimes.diff +#endif +#if defined (Ubuntu) +langpack-gettext.diff +#endif +#if defined (arch_os_hurd) +no-large-file-support.diff +hurd-path_max.diff +cthreads.diff +#endif +issue9012a.diff +#ifdef OLD_SPHINX +doc-build.diff +revert-r83234.diff +revert-r83274.diff +#endif +link-system-expat.diff +plat-gnukfreebsd.diff +disable-sem-check.diff +lib-argparse.diff +bsddb-libpath.diff +ncursesw-include.diff +ctypes-arm.diff --- python3.2-3.2.2.orig/debian/patches/locale-module.diff +++ python3.2-3.2.2/debian/patches/locale-module.diff @@ -0,0 +1,17 @@ +# DP: * Lib/locale.py: +# DP: - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding +# DP: for glibc. + +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -1534,8 +1534,8 @@ + 'uk_ua.iso88595': 'uk_UA.ISO8859-5', + 'uk_ua.koi8u': 'uk_UA.KOI8-U', + 'uk_ua.microsoftcp1251': 'uk_UA.CP1251', +- 'univ': 'en_US.utf', +- 'universal': 'en_US.utf', ++ 'univ': 'en_US.UTF-8', ++ 'universal': 'en_US.UTF-8', + 'universal.utf8@ucs4': 'en_US.UTF-8', + 'ur': 'ur_PK.CP1256', + 'ur_pk': 'ur_PK.CP1256', --- python3.2-3.2.2.orig/debian/patches/webbrowser.diff +++ python3.2-3.2.2/debian/patches/webbrowser.diff @@ -0,0 +1,27 @@ +# DP: Recognize other browsers: www-browser, x-www-browser, iceweasel, iceape. + +--- a/Lib/webbrowser.py ++++ b/Lib/webbrowser.py +@@ -444,9 +444,13 @@ + if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"): + register("kfmclient", Konqueror, Konqueror("kfmclient")) + ++ if _iscommand("x-www-browser"): ++ register("x-www-browser", None, BackgroundBrowser("x-www-browser")) ++ + # The Mozilla/Netscape browsers + for browser in ("mozilla-firefox", "firefox", + "mozilla-firebird", "firebird", ++ "iceweasel", "iceape", + "seamonkey", "mozilla", "netscape"): + if _iscommand(browser): + register(browser, None, Mozilla(browser)) +@@ -484,6 +488,8 @@ + + # Also try console browsers + if os.environ.get("TERM"): ++ if _iscommand("www-browser"): ++ register("www-browser", None, GenericBrowser("www-browser")) + # The Links/elinks browsers + if _iscommand("links"): + register("links", None, GenericBrowser("links")) --- python3.2-3.2.2.orig/debian/patches/bsddb-libpath.diff +++ python3.2-3.2.2/debian/patches/bsddb-libpath.diff @@ -0,0 +1,19 @@ +# DP: Don't add the bsddb multilib path, if already in the standard lib path + +--- a/setup.py ++++ b/setup.py +@@ -943,7 +943,13 @@ + if db_setup_debug: + print("bsddb using BerkeleyDB lib:", db_ver, dblib) + print("bsddb lib dir:", dblib_dir, " inc dir:", db_incdir) +- db_incs = [db_incdir] ++ # only add db_incdir/dblib_dir if not in the standard paths ++ if db_incdir in inc_dirs: ++ db_incs = [] ++ else: ++ db_incs = [db_incdir] ++ if dblib_dir[0] in lib_dirs: ++ dblib_dir = [] + dblibs = [dblib] + else: + if db_setup_debug: print("db: no appropriate library found") --- python3.2-3.2.2.orig/debian/patches/langpack-gettext.diff +++ python3.2-3.2.2/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 +@@ -394,11 +394,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 + + --- python3.2-3.2.2.orig/debian/patches/plat-linux2_alpha.diff +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/patches/issue9012a.diff +++ python3.2-3.2.2/debian/patches/issue9012a.diff @@ -0,0 +1,11 @@ +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -163,7 +163,7 @@ + #cmath cmathmodule.c _math.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 ++#time timemodule.c _time.c # -lm # time operations and variables + #_weakref _weakref.c # basic weak reference support + #_testcapi _testcapimodule.c # Python C API test module + #_random _randommodule.c # Random number generator --- python3.2-3.2.2.orig/debian/patches/hurd-disable-nonworking-constants.diff +++ python3.2-3.2.2/debian/patches/hurd-disable-nonworking-constants.diff @@ -0,0 +1,34 @@ +# DP: Comment out constant exposed on the API which are not implemented on +# DP: GNU/Hurd. They would not work at runtime anyway. + +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -8248,12 +8248,14 @@ + #ifdef O_LARGEFILE + if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1; + #endif ++#ifndef __GNU__ + #ifdef O_SHLOCK + if (ins(d, "O_SHLOCK", (long)O_SHLOCK)) return -1; + #endif + #ifdef O_EXLOCK + if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1; + #endif ++#endif + + /* MS Windows */ + #ifdef O_NOINHERIT +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -4741,9 +4741,11 @@ + #ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); + #endif ++#ifndef __GNU__ + #ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); + #endif ++#endif + #ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); + #endif --- python3.2-3.2.2.orig/debian/patches/deb-setup.diff +++ python3.2-3.2.2/debian/patches/deb-setup.diff @@ -0,0 +1,28 @@ +# DP: Don't include /usr/local/include and /usr/local/lib as gcc search paths + +--- a/setup.py ++++ b/setup.py +@@ -393,11 +393,9 @@ + os.unlink(tmpfile) + + def detect_modules(self): +- # Ensure that /usr/local is always used, but the local build +- # directories (i.e. '.' and 'Include') must be first. See issue +- # 10520. +- 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 ++ #add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') ++ #add_dir_to_list(self.compiler.include_dirs, '/usr/local/include') + self.add_multiarch_paths() + + # Add paths specified in the environment variables LDFLAGS and +@@ -606,7 +604,7 @@ + os.unlink(tmpfile) + # Issue 7384: If readline is already linked against curses, + # use the same library for the readline and curses modules. +- if 'curses' in readline_termcap_library: ++ if False and 'curses' in readline_termcap_library: + curses_library = readline_termcap_library + elif self.compiler.find_library_file(lib_dirs, 'ncursesw'): + curses_library = 'ncursesw' --- python3.2-3.2.2.orig/debian/patches/hurd-broken-poll.diff +++ python3.2-3.2.2/debian/patches/hurd-broken-poll.diff @@ -0,0 +1,23 @@ +# DP: Fix build failure on hurd, working around poll() on systems +# DP: on which it returns an error on invalid FDs. + +--- a/Modules/selectmodule.c ++++ b/Modules/selectmodule.c +@@ -1747,7 +1747,7 @@ + + static PyMethodDef select_methods[] = { + {"select", select_select, METH_VARARGS, select_doc}, +-#ifdef HAVE_POLL ++#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) + {"poll", select_poll, METH_NOARGS, poll_doc}, + #endif /* HAVE_POLL */ + {0, 0}, /* sentinel */ +@@ -1792,7 +1792,7 @@ + PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF); + #endif + +-#if defined(HAVE_POLL) ++#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL) + #ifdef __APPLE__ + if (select_have_broken_poll()) { + if (PyObject_DelAttrString(m, "poll") == -1) { --- python3.2-3.2.2.orig/debian/patches/makesetup-bashism.diff +++ python3.2-3.2.2/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 --- python3.2-3.2.2.orig/debian/source/format +++ python3.2-3.2.2/debian/source/format @@ -0,0 +1 @@ +1.0