--- python2.7-2.7.2.orig/debian/mkbinfmt.py +++ python2.7-2.7.2/debian/mkbinfmt.py @@ -0,0 +1,17 @@ +# mkbinfmt.py +import imp, sys, string, os.path + +magic = string.join(["\\x%.2x" % ord(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) + +print binfmt --- python2.7-2.7.2.orig/debian/PVER-minimal.preinst.in +++ python2.7-2.7.2/debian/PVER-minimal.preinst.in @@ -0,0 +1,39 @@ +#!/bin/sh + +set -e + +syssite=/usr/lib/@PVER@/site-packages +oldsite=/usr/lib/@PVER@/old-site-packages +localsite=/usr/local/lib/@PVER@/dist-packages +syslink=../../${localsite#/usr/*} + +case "$1" in + install) + if [ -z "$2" ] && [ -d $syssite ] && [ ! -h $syssite ]; then + echo "new installation of @PVER@-minimal; $syssite is a directory" + echo "which is expected a symlink to $localsite." + echo "please find the package shipping files in $syssite and" + echo "file a bug report to ship these in /usr/lib/@PVER@/dist-packages instead" + echo "aborting installation of @PVER@-minimal" + exit 1 + fi + + # remember newly installed runtime + mkdir -p /var/lib/python + touch /var/lib/python/@PVER@_installed + ;; + upgrade) + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.2.orig/debian/README.idle-PVER.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/pyhtml2devhelp.py +++ python2.7-2.7.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() --- python2.7-2.7.2.orig/debian/pymindeps.py +++ python2.7-2.7.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 = { + 'codecs': set(('encodings',)), + 'collections': set(('doctest', 'dummy_thread', 'cPickle')), + 'copy': set(('reprlib',)), + 'difflib': set(('doctest',)), + 'hashlib': set(('logging',)), + #'hashlib': set(('_hashlib', '_md5', '_sha', '_sha256','_sha512',)), + 'heapq': set(('doctest',)), + 'inspect': set(('compiler',)), + 'os': set(('nt', 'ntpath', 'os2', 'os2emxpath', 'mac', 'macpath', + 'riscos', 'riscospath', 'riscosenviron')), + 'optparse': set(('gettext',)), + 'pickle': set(('doctest',)), + 'platform': set(('plistlib', 'tempfile')), + #'socket': set(('_ssl', 'ssl')), + 'tempfile': set(('dummy_thread',)), + 'subprocess': set(('threading',)), + 'shutil': set(('distutils', 'tarfile', 'zipfile')), + } + +def main(argv): + # Parse command line + import getopt + try: + opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") + except getopt.error as msg: + print(msg) + return + + # Process options + debug = 1 + domods = 0 + addpath = [] + exclude = [] + for o, a in opts: + if o == '-d': + debug = debug + 1 + if o == '-m': + domods = 1 + if o == '-p': + addpath = addpath + a.split(os.pathsep) + if o == '-q': + debug = 0 + if o == '-x': + exclude.append(a) + + path = sys.path[:] + path = addpath + path + + if debug > 1: + print("version:", sys.version) + print("path:") + for item in path: + print(" ", repr(item)) + + #exclude = ['__builtin__', 'sys', 'os'] + exclude = [] + mf = mymf(path, debug, exclude) + for arg in args: + mf.run_script(arg) + + depgraph = reduce_depgraph(mf._depgraph) + + pprint.pprint({'depgraph':mf._depgraph, 'types':mf._types}) + +if __name__=='__main__': + main(sys.argv[1:]) --- python2.7-2.7.2.orig/debian/argparse.egg-info +++ python2.7-2.7.2/debian/argparse.egg-info @@ -0,0 +1,8 @@ +Metadata-Version: 1.0 +Name: argparse +Version: 1.2.1 +Summary: Python command-line parsing library +Author: Steven Bethard +Author-email: steven.bethard@gmail.com +License: Python Software Foundation License +Platform: any --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/pydoc.1.in +++ python2.7-2.7.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" --- python2.7-2.7.2.orig/debian/dh_doclink +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/PVER.desktop.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/sitecustomize.py.in +++ python2.7-2.7.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() --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/pylogo.xpm +++ python2.7-2.7.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@ "}; --- python2.7-2.7.2.orig/debian/2to3-2.7.1 +++ python2.7-2.7.2/debian/2to3-2.7.1 @@ -0,0 +1,41 @@ +.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.40.4. +.TH 2TO3-2.7 "1" "January 2012" "2to3-2.7 2.7" "User Commands" +.SH NAME +2to3-2.7 \- Python2 to Python3 converter +.SH SYNOPSIS +.B 2to3 +[\fIoptions\fR] \fIfile|dir \fR... +.SH OPTIONS +.TP +\fB\-h\fR, \fB\-\-help\fR +show this help message and exit +.TP +\fB\-d\fR, \fB\-\-doctests_only\fR +Fix up doctests only +.TP +\fB\-f\fR FIX, \fB\-\-fix\fR=\fIFIX\fR +Each FIX specifies a transformation; default: all +.TP +\fB\-j\fR PROCESSES, \fB\-\-processes\fR=\fIPROCESSES\fR +Run 2to3 concurrently +.TP +\fB\-x\fR NOFIX, \fB\-\-nofix\fR=\fINOFIX\fR +Prevent a transformation from being run +.TP +\fB\-l\fR, \fB\-\-list\-fixes\fR +List available transformations +.TP +\fB\-p\fR, \fB\-\-print\-function\fR +Modify the grammar so that print() is a function +.TP +\fB\-v\fR, \fB\-\-verbose\fR +More verbose logging +.TP +\fB\-\-no\-diffs\fR +Don't show diffs of the refactoring +.TP +\fB\-w\fR, \fB\-\-write\fR +Write back modified files +.TP +\fB\-n\fR, \fB\-\-nobackups\fR +Don't write backups for modified files --- python2.7-2.7.2.orig/debian/PVER.overrides.in +++ python2.7-2.7.2/debian/PVER.overrides.in @@ -0,0 +1,14 @@ +# idlelib images +@PVER@ binary: image-file-in-usr-lib + +# yes, we have to +@PVER@ binary: depends-on-python-minimal + +@PVER@ binary: desktop-command-not-in-package +@PVER@ binary: menu-command-not-in-package + +# license file referred by the standard library +@PVER@ binary: extra-license-file + +# no, not useless +@PVER@ binary: manpage-has-useless-whatis-entry --- python2.7-2.7.2.orig/debian/idle-PVER.prerm.in +++ python2.7-2.7.2/debian/idle-PVER.prerm.in @@ -0,0 +1,15 @@ +#! /bin/sh -e +# +# sample prerm script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +PACKAGE=`basename $0 .prerm` + +dpkg --listfiles $PACKAGE | + awk '$0~/\.py$/ {print $0"c\n" $0"o"}' | + xargs rm -f >&2 + +#DEBHELPER# + +exit 0 --- python2.7-2.7.2.orig/debian/PVER.menu.in +++ python2.7-2.7.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@" --- python2.7-2.7.2.orig/debian/PVER-dbg.symbols.in +++ python2.7-2.7.2/debian/PVER-dbg.symbols.in @@ -0,0 +1,32 @@ +libpython@VER@_d.so.1.0 python@VER@-dbg #MINVER# + Py_InitModule4TraceRefs@Base @VER@ +#include "libpython.symbols" + _PyDict_Dummy@Base @VER@ + _PyMem_DebugFree@Base @VER@ + _PyMem_DebugMalloc@Base @VER@ + _PyMem_DebugRealloc@Base @VER@ + _PyObject_DebugCheckAddress@Base @VER@ + _PyObject_DebugCheckAddressApi@Base @VER@ + _PyObject_DebugDumpAddress@Base @VER@ + _PyObject_DebugFree@Base @VER@ + _PyObject_DebugFreeApi@Base @VER@ + _PyObject_DebugMalloc@Base @VER@ + _PyObject_DebugMallocApi@Base @VER@ + _PyObject_DebugMallocStats@Base @VER@ + _PyObject_DebugRealloc@Base @VER@ + _PyObject_DebugReallocApi@Base @VER@ + _PySet_Dummy@Base @VER@ + _Py_AddToAllObjects@Base @VER@ + _Py_Dealloc@Base @VER@ + _Py_ForgetReference@Base @VER@ + _Py_GetObjects@Base @VER@ + _Py_GetRefTotal@Base @VER@ + _Py_NegativeRefcount@Base @VER@ + _Py_NewReference@Base @VER@ + _Py_PrintReferenceAddresses@Base @VER@ + _Py_PrintReferences@Base @VER@ + _Py_RefTotal@Base @VER@ + _Py_dumptree@Base @VER@ + _Py_printtree@Base @VER@ + _Py_showtree@Base @VER@ + _Py_tok_dump@Base @VER@ --- python2.7-2.7.2.orig/debian/compat +++ python2.7-2.7.2/debian/compat @@ -0,0 +1 @@ +5 --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-new.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/PVER-minimal.postinst.in +++ python2.7-2.7.2/debian/PVER-minimal.postinst.in @@ -0,0 +1,76 @@ +#! /bin/sh + +set -e + +if [ ! -f /etc/@PVER@/sitecustomize.py ]; then + cat <<-EOF + # Empty sitecustomize.py to avoid a dangling symlink +EOF +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.7-9 \ + || [ -f /var/lib/python/@PVER@_installed ]; then + bc=yes + fi + if grep -sq '^unsupported-versions[^#]*@PVER@' /usr/share/python/debian_defaults + then + # FIXME: byte compile anyway? + bc=no + fi + if [ "$bc" = yes ]; then + # new installation or installation of first version with hook support + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Linking and byte-compiling packages for runtime @PVER@..." + fi + version=$(dpkg -s @PVER@-minimal | awk '/^Version:/ {print $2}') + for hook in /usr/share/python/runtime.d/*.rtinstall; do + [ -x $hook ] || continue + $hook rtinstall @PVER@ "$2" "$version" + done + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi + fi +fi + +#DEBHELPER# + +exit 0 --- python2.7-2.7.2.orig/debian/README.dbm +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/README.Debian.in +++ python2.7-2.7.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. --- python2.7-2.7.2.orig/debian/PVER-minimal.postrm.in +++ python2.7-2.7.2/debian/PVER-minimal.postrm.in @@ -0,0 +1,27 @@ +#! /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 +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 --- python2.7-2.7.2.orig/debian/watch +++ python2.7-2.7.2/debian/watch @@ -0,0 +1,3 @@ +version=3 +opts=dversionmangle=s/.*\+//,uversionmangle=s/([abcr]+[1-9])$/~$1/ \ + http://www.python.org/ftp/python/2\.7(\.\d)?/Python-(2\.7[.\dabcr]*)\.tgz --- python2.7-2.7.2.orig/debian/libpython.symbols.in +++ python2.7-2.7.2/debian/libpython.symbols.in @@ -0,0 +1,1257 @@ + PyAST_Check@Base @VER@ + PyAST_Compile@Base @VER@ + PyAST_FromNode@Base @VER@ + PyAST_mod2obj@Base @VER@ + PyAST_obj2mod@Base @VER@ + PyArena_AddPyObject@Base @VER@ + PyArena_Free@Base @VER@ + PyArena_Malloc@Base @VER@ + PyArena_New@Base @VER@ + PyArg_Parse@Base @VER@ + PyArg_ParseTuple@Base @VER@ + PyArg_ParseTupleAndKeywords@Base @VER@ + PyArg_UnpackTuple@Base @VER@ + PyArg_VaParse@Base @VER@ + PyArg_VaParseTupleAndKeywords@Base @VER@ + PyBaseObject_Type@Base @VER@ + PyBaseString_Type@Base @VER@ + PyBool_FromLong@Base @VER@ + PyBool_Type@Base @VER@ + PyBuffer_FillContiguousStrides@Base @VER@ + PyBuffer_FillInfo@Base @VER@ + PyBuffer_FromContiguous@Base @VER@ + PyBuffer_FromMemory@Base @VER@ + PyBuffer_FromObject@Base @VER@ + PyBuffer_FromReadWriteMemory@Base @VER@ + PyBuffer_FromReadWriteObject@Base @VER@ + PyBuffer_GetPointer@Base @VER@ + PyBuffer_IsContiguous@Base @VER@ + PyBuffer_New@Base @VER@ + PyBuffer_Release@Base @VER@ + PyBuffer_ToContiguous@Base @VER@ + PyBuffer_Type@Base @VER@ + PyByteArrayIter_Type@Base @VER@ + PyByteArray_AsString@Base @VER@ + PyByteArray_Concat@Base @VER@ + PyByteArray_Fini@Base @VER@ + PyByteArray_FromObject@Base @VER@ + PyByteArray_FromStringAndSize@Base @VER@ + PyByteArray_Init@Base @VER@ + PyByteArray_Resize@Base @VER@ + PyByteArray_Size@Base @VER@ + PyByteArray_Type@Base @VER@ + PyCFunction_Call@Base @VER@ + PyCFunction_ClearFreeList@Base @VER@ + PyCFunction_Fini@Base @VER@ + PyCFunction_GetFlags@Base @VER@ + PyCFunction_GetFunction@Base @VER@ + PyCFunction_GetSelf@Base @VER@ + PyCFunction_New@Base @VER@ + PyCFunction_NewEx@Base @VER@ + PyCFunction_Type@Base @VER@ + PyCObject_AsVoidPtr@Base @VER@ + PyCObject_FromVoidPtr@Base @VER@ + PyCObject_FromVoidPtrAndDesc@Base @VER@ + PyCObject_GetDesc@Base @VER@ + PyCObject_Import@Base @VER@ + PyCObject_SetVoidPtr@Base @VER@ + PyCObject_Type@Base @VER@ + PyCallIter_New@Base @VER@ + PyCallIter_Type@Base @VER@ + PyCallable_Check@Base @VER@ + PyCapsule_GetContext@Base @VER@ + PyCapsule_GetDestructor@Base @VER@ + PyCapsule_GetName@Base @VER@ + PyCapsule_GetPointer@Base @VER@ + PyCapsule_Import@Base @VER@ + PyCapsule_IsValid@Base @VER@ + PyCapsule_New@Base @VER@ + PyCapsule_SetContext@Base @VER@ + PyCapsule_SetDestructor@Base @VER@ + PyCapsule_SetName@Base @VER@ + PyCapsule_SetPointer@Base @VER@ + PyCapsule_Type@Base @VER@ + PyCell_Get@Base @VER@ + PyCell_New@Base @VER@ + PyCell_Set@Base @VER@ + PyCell_Type@Base @VER@ + PyClassMethod_New@Base @VER@ + PyClassMethod_Type@Base @VER@ + PyClass_IsSubclass@Base @VER@ + PyClass_New@Base @VER@ + PyClass_Type@Base @VER@ + PyCode_Addr2Line@Base @VER@ + PyCode_New@Base @VER@ + PyCode_NewEmpty@Base @VER@ + PyCode_Optimize@Base @VER@ + PyCode_Type@Base @VER@ + PyCodec_BackslashReplaceErrors@Base @VER@ + PyCodec_Decode@Base @VER@ + PyCodec_Decoder@Base @VER@ + PyCodec_Encode@Base @VER@ + PyCodec_Encoder@Base @VER@ + PyCodec_IgnoreErrors@Base @VER@ + PyCodec_IncrementalDecoder@Base @VER@ + PyCodec_IncrementalEncoder@Base @VER@ + PyCodec_LookupError@Base @VER@ + PyCodec_Register@Base @VER@ + PyCodec_RegisterError@Base @VER@ + PyCodec_ReplaceErrors@Base @VER@ + PyCodec_StreamReader@Base @VER@ + PyCodec_StreamWriter@Base @VER@ + PyCodec_StrictErrors@Base @VER@ + PyCodec_XMLCharRefReplaceErrors@Base @VER@ + PyComplex_AsCComplex@Base @VER@ + PyComplex_FromCComplex@Base @VER@ + PyComplex_FromDoubles@Base @VER@ + PyComplex_ImagAsDouble@Base @VER@ + PyComplex_RealAsDouble@Base @VER@ + PyComplex_Type@Base @VER@ + PyDescr_NewClassMethod@Base @VER@ + PyDescr_NewGetSet@Base @VER@ + PyDescr_NewMember@Base @VER@ + PyDescr_NewMethod@Base @VER@ + PyDescr_NewWrapper@Base @VER@ + PyDictItems_Type@Base @VER@ + PyDictIterItem_Type@Base @VER@ + PyDictIterKey_Type@Base @VER@ + PyDictIterValue_Type@Base @VER@ + PyDictKeys_Type@Base @VER@ + PyDictProxy_New@Base @VER@ + PyDictProxy_Type@Base @VER@ + PyDictValues_Type@Base @VER@ + PyDict_Clear@Base @VER@ + PyDict_Contains@Base @VER@ + PyDict_Copy@Base @VER@ + PyDict_DelItem@Base @VER@ + PyDict_DelItemString@Base @VER@ + PyDict_Fini@Base @VER@ + PyDict_GetItem@Base @VER@ + PyDict_GetItemString@Base @VER@ + PyDict_Items@Base @VER@ + PyDict_Keys@Base @VER@ + PyDict_Merge@Base @VER@ + PyDict_MergeFromSeq2@Base @VER@ + PyDict_New@Base @VER@ + PyDict_Next@Base @VER@ + PyDict_SetItem@Base @VER@ + PyDict_SetItemString@Base @VER@ + PyDict_Size@Base @VER@ + PyDict_Type@Base @VER@ + PyDict_Update@Base @VER@ + PyDict_Values@Base @VER@ + PyEllipsis_Type@Base @VER@ + PyEnum_Type@Base @VER@ + PyErr_BadArgument@Base @VER@ + PyErr_BadInternalCall@Base @VER@ + PyErr_CheckSignals@Base @VER@ + PyErr_Clear@Base @VER@ + PyErr_Display@Base @VER@ + PyErr_ExceptionMatches@Base @VER@ + PyErr_Fetch@Base @VER@ + PyErr_Format@Base @VER@ + PyErr_GivenExceptionMatches@Base @VER@ + PyErr_NewException@Base @VER@ + PyErr_NewExceptionWithDoc@Base @VER@ + PyErr_NoMemory@Base @VER@ + PyErr_NormalizeException@Base @VER@ + PyErr_Occurred@Base @VER@ + PyErr_Print@Base @VER@ + PyErr_PrintEx@Base @VER@ + PyErr_ProgramText@Base @VER@ + PyErr_Restore@Base @VER@ + PyErr_SetFromErrno@Base @VER@ + PyErr_SetFromErrnoWithFilename@Base @VER@ + PyErr_SetFromErrnoWithFilenameObject@Base @VER@ + PyErr_SetInterrupt@Base @VER@ + PyErr_SetNone@Base @VER@ + PyErr_SetObject@Base @VER@ + PyErr_SetString@Base @VER@ + PyErr_SyntaxLocation@Base @VER@ + PyErr_Warn@Base @VER@ + PyErr_WarnEx@Base @VER@ + PyErr_WarnExplicit@Base @VER@ + PyErr_WriteUnraisable@Base @VER@ + PyEval_AcquireLock@Base @VER@ + PyEval_AcquireThread@Base @VER@ + PyEval_CallFunction@Base @VER@ + PyEval_CallMethod@Base @VER@ + PyEval_CallObjectWithKeywords@Base @VER@ + PyEval_EvalCode@Base @VER@ + PyEval_EvalCodeEx@Base @VER@ + PyEval_EvalFrame@Base @VER@ + PyEval_EvalFrameEx@Base @VER@ + PyEval_GetBuiltins@Base @VER@ + PyEval_GetCallStats@Base @VER@ + PyEval_GetFrame@Base @VER@ + PyEval_GetFuncDesc@Base @VER@ + PyEval_GetFuncName@Base @VER@ + PyEval_GetGlobals@Base @VER@ + PyEval_GetLocals@Base @VER@ + PyEval_GetRestricted@Base @VER@ + PyEval_InitThreads@Base @VER@ + PyEval_MergeCompilerFlags@Base @VER@ + PyEval_ReInitThreads@Base @VER@ + PyEval_ReleaseLock@Base @VER@ + PyEval_ReleaseThread@Base @VER@ + PyEval_RestoreThread@Base @VER@ + PyEval_SaveThread@Base @VER@ + PyEval_SetProfile@Base @VER@ + PyEval_SetTrace@Base @VER@ + PyEval_ThreadsInitialized@Base @VER@ + PyExc_ArithmeticError@Base @VER@ + PyExc_AssertionError@Base @VER@ + PyExc_AttributeError@Base @VER@ + PyExc_BaseException@Base @VER@ + PyExc_BufferError@Base @VER@ + PyExc_BytesWarning@Base @VER@ + PyExc_DeprecationWarning@Base @VER@ + PyExc_EOFError@Base @VER@ + PyExc_EnvironmentError@Base @VER@ + PyExc_Exception@Base @VER@ + PyExc_FloatingPointError@Base @VER@ + PyExc_FutureWarning@Base @VER@ + PyExc_GeneratorExit@Base @VER@ + PyExc_IOError@Base @VER@ + PyExc_ImportError@Base @VER@ + PyExc_ImportWarning@Base @VER@ + PyExc_IndentationError@Base @VER@ + PyExc_IndexError@Base @VER@ + PyExc_KeyError@Base @VER@ + PyExc_KeyboardInterrupt@Base @VER@ + PyExc_LookupError@Base @VER@ + PyExc_MemoryError@Base @VER@ + PyExc_MemoryErrorInst@Base @VER@ + PyExc_NameError@Base @VER@ + PyExc_NotImplementedError@Base @VER@ + PyExc_OSError@Base @VER@ + PyExc_OverflowError@Base @VER@ + PyExc_PendingDeprecationWarning@Base @VER@ + PyExc_RecursionErrorInst@Base @VER@ + PyExc_ReferenceError@Base @VER@ + PyExc_RuntimeError@Base @VER@ + PyExc_RuntimeWarning@Base @VER@ + PyExc_StandardError@Base @VER@ + PyExc_StopIteration@Base @VER@ + PyExc_SyntaxError@Base @VER@ + PyExc_SyntaxWarning@Base @VER@ + PyExc_SystemError@Base @VER@ + PyExc_SystemExit@Base @VER@ + PyExc_TabError@Base @VER@ + PyExc_TypeError@Base @VER@ + PyExc_UnboundLocalError@Base @VER@ + PyExc_UnicodeDecodeError@Base @VER@ + PyExc_UnicodeEncodeError@Base @VER@ + PyExc_UnicodeError@Base @VER@ + PyExc_UnicodeTranslateError@Base @VER@ + PyExc_UnicodeWarning@Base @VER@ + PyExc_UserWarning@Base @VER@ + PyExc_ValueError@Base @VER@ + PyExc_Warning@Base @VER@ + PyExc_ZeroDivisionError@Base @VER@ + PyFile_AsFile@Base @VER@ + PyFile_DecUseCount@Base @VER@ + PyFile_FromFile@Base @VER@ + PyFile_FromString@Base @VER@ + PyFile_GetLine@Base @VER@ + PyFile_IncUseCount@Base @VER@ + PyFile_Name@Base @VER@ + PyFile_SetBufSize@Base @VER@ + PyFile_SetEncoding@Base @VER@ + PyFile_SetEncodingAndErrors@Base @VER@ + PyFile_SoftSpace@Base @VER@ + PyFile_Type@Base @VER@ + PyFile_WriteObject@Base @VER@ + PyFile_WriteString@Base @VER@ + PyFloat_AsDouble@Base @VER@ + PyFloat_AsReprString@Base @VER@ + PyFloat_AsString@Base @VER@ + PyFloat_ClearFreeList@Base @VER@ + PyFloat_Fini@Base @VER@ + PyFloat_FromDouble@Base @VER@ + PyFloat_FromString@Base @VER@ + PyFloat_GetInfo@Base @VER@ + PyFloat_GetMax@Base @VER@ + PyFloat_GetMin@Base @VER@ + PyFloat_Type@Base @VER@ + PyFrame_BlockPop@Base @VER@ + PyFrame_BlockSetup@Base @VER@ + PyFrame_ClearFreeList@Base @VER@ + PyFrame_FastToLocals@Base @VER@ + PyFrame_Fini@Base @VER@ + PyFrame_GetLineNumber@Base @VER@ + PyFrame_LocalsToFast@Base @VER@ + PyFrame_New@Base @VER@ + PyFrame_Type@Base @VER@ + PyFrozenSet_New@Base @VER@ + PyFrozenSet_Type@Base @VER@ + PyFunction_GetClosure@Base @VER@ + PyFunction_GetCode@Base @VER@ + PyFunction_GetDefaults@Base @VER@ + PyFunction_GetGlobals@Base @VER@ + PyFunction_GetModule@Base @VER@ + PyFunction_New@Base @VER@ + PyFunction_SetClosure@Base @VER@ + PyFunction_SetDefaults@Base @VER@ + PyFunction_Type@Base @VER@ + PyFuture_FromAST@Base @VER@ + PyGC_Collect@Base @VER@ + PyGILState_Ensure@Base @VER@ + PyGILState_GetThisThreadState@Base @VER@ + PyGILState_Release@Base @VER@ + PyGen_NeedsFinalizing@Base @VER@ + PyGen_New@Base @VER@ + PyGen_Type@Base @VER@ + PyGetSetDescr_Type@Base @VER@ + PyGrammar_AddAccelerators@Base @VER@ + PyGrammar_FindDFA@Base @VER@ + PyGrammar_LabelRepr@Base @VER@ + PyGrammar_RemoveAccelerators@Base @VER@ + PyImport_AddModule@Base @VER@ + PyImport_AppendInittab@Base @VER@ + PyImport_Cleanup@Base @VER@ + PyImport_ExecCodeModule@Base @VER@ + PyImport_ExecCodeModuleEx@Base @VER@ + PyImport_ExtendInittab@Base @VER@ + PyImport_FrozenModules@Base @VER@ + PyImport_GetImporter@Base @VER@ + PyImport_GetMagicNumber@Base @VER@ + PyImport_GetModuleDict@Base @VER@ + PyImport_Import@Base @VER@ + PyImport_ImportFrozenModule@Base @VER@ + PyImport_ImportModule@Base @VER@ + PyImport_ImportModuleLevel@Base @VER@ + PyImport_ImportModuleNoBlock@Base @VER@ + PyImport_Inittab@Base @VER@ + PyImport_ReloadModule@Base @VER@ + PyInstance_New@Base @VER@ + PyInstance_NewRaw@Base @VER@ + PyInstance_Type@Base @VER@ + PyInt_AsLong@Base @VER@ + PyInt_AsSsize_t@Base @VER@ + PyInt_AsUnsignedLongLongMask@Base @VER@ + PyInt_AsUnsignedLongMask@Base @VER@ + PyInt_ClearFreeList@Base @VER@ + PyInt_Fini@Base @VER@ + PyInt_FromLong@Base @VER@ + PyInt_FromSize_t@Base @VER@ + PyInt_FromSsize_t@Base @VER@ + PyInt_FromString@Base @VER@ + PyInt_FromUnicode@Base @VER@ + PyInt_GetMax@Base @VER@ + PyInt_Type@Base @VER@ + PyInterpreterState_Clear@Base @VER@ + PyInterpreterState_Delete@Base @VER@ + PyInterpreterState_Head@Base @VER@ + PyInterpreterState_New@Base @VER@ + PyInterpreterState_Next@Base @VER@ + PyInterpreterState_ThreadHead@Base @VER@ + PyIter_Next@Base @VER@ + PyListIter_Type@Base @VER@ + PyListRevIter_Type@Base @VER@ + PyList_Append@Base @VER@ + PyList_AsTuple@Base @VER@ + PyList_Fini@Base @VER@ + PyList_GetItem@Base @VER@ + PyList_GetSlice@Base @VER@ + PyList_Insert@Base @VER@ + PyList_New@Base @VER@ + PyList_Reverse@Base @VER@ + PyList_SetItem@Base @VER@ + PyList_SetSlice@Base @VER@ + PyList_Size@Base @VER@ + PyList_Sort@Base @VER@ + PyList_Type@Base @VER@ + PyLong_AsDouble@Base @VER@ + PyLong_AsLong@Base @VER@ + PyLong_AsLongAndOverflow@Base @VER@ + PyLong_AsLongLong@Base @VER@ + PyLong_AsLongLongAndOverflow@Base @VER@ + PyLong_AsSsize_t@Base @VER@ + PyLong_AsUnsignedLong@Base @VER@ + PyLong_AsUnsignedLongLong@Base @VER@ + PyLong_AsUnsignedLongLongMask@Base @VER@ + PyLong_AsUnsignedLongMask@Base @VER@ + PyLong_AsVoidPtr@Base @VER@ + PyLong_FromDouble@Base @VER@ + PyLong_FromLong@Base @VER@ + PyLong_FromLongLong@Base @VER@ + PyLong_FromSize_t@Base @VER@ + PyLong_FromSsize_t@Base @VER@ + PyLong_FromString@Base @VER@ + PyLong_FromUnicode@Base @VER@ + PyLong_FromUnsignedLong@Base @VER@ + PyLong_FromUnsignedLongLong@Base @VER@ + PyLong_FromVoidPtr@Base @VER@ + PyLong_GetInfo@Base @VER@ + PyLong_Type@Base @VER@ + PyMapping_Check@Base @VER@ + PyMapping_GetItemString@Base @VER@ + PyMapping_HasKey@Base @VER@ + PyMapping_HasKeyString@Base @VER@ + PyMapping_Length@Base @VER@ + PyMapping_SetItemString@Base @VER@ + PyMapping_Size@Base @VER@ + PyMarshal_Init@Base @VER@ + PyMarshal_ReadLastObjectFromFile@Base @VER@ + PyMarshal_ReadLongFromFile@Base @VER@ + PyMarshal_ReadObjectFromFile@Base @VER@ + PyMarshal_ReadObjectFromString@Base @VER@ + PyMarshal_ReadShortFromFile@Base @VER@ + PyMarshal_WriteLongToFile@Base @VER@ + PyMarshal_WriteObjectToFile@Base @VER@ + PyMarshal_WriteObjectToString@Base @VER@ + PyMem_Free@Base @VER@ + PyMem_Malloc@Base @VER@ + PyMem_Realloc@Base @VER@ + PyMemberDescr_Type@Base @VER@ + PyMember_Get@Base @VER@ + PyMember_GetOne@Base @VER@ + PyMember_Set@Base @VER@ + PyMember_SetOne@Base @VER@ + PyMemoryView_FromBuffer@Base @VER@ + PyMemoryView_FromObject@Base @VER@ + PyMemoryView_GetContiguous@Base @VER@ + PyMemoryView_Type@Base @VER@ + PyMethod_Class@Base @VER@ + PyMethod_ClearFreeList@Base @VER@ + PyMethod_Fini@Base @VER@ + PyMethod_Function@Base @VER@ + PyMethod_New@Base @VER@ + PyMethod_Self@Base @VER@ + PyMethod_Type@Base @VER@ + PyModule_AddIntConstant@Base @VER@ + PyModule_AddObject@Base @VER@ + PyModule_AddStringConstant@Base @VER@ + PyModule_GetDict@Base @VER@ + PyModule_GetFilename@Base @VER@ + PyModule_GetName@Base @VER@ + PyModule_GetWarningsModule@Base @VER@ + PyModule_New@Base @VER@ + PyModule_Type@Base @VER@ + PyNode_AddChild@Base @VER@ + PyNode_Compile@Base @VER@ + PyNode_Free@Base @VER@ + PyNode_ListTree@Base @VER@ + PyNode_New@Base @VER@ + PyNullImporter_Type@Base @VER@ + PyNumber_Absolute@Base @VER@ + PyNumber_Add@Base @VER@ + PyNumber_And@Base @VER@ + PyNumber_AsSsize_t@Base @VER@ + PyNumber_Check@Base @VER@ + PyNumber_Coerce@Base @VER@ + PyNumber_CoerceEx@Base @VER@ + PyNumber_Divide@Base @VER@ + PyNumber_Divmod@Base @VER@ + PyNumber_Float@Base @VER@ + PyNumber_FloorDivide@Base @VER@ + PyNumber_InPlaceAdd@Base @VER@ + PyNumber_InPlaceAnd@Base @VER@ + PyNumber_InPlaceDivide@Base @VER@ + PyNumber_InPlaceFloorDivide@Base @VER@ + PyNumber_InPlaceLshift@Base @VER@ + PyNumber_InPlaceMultiply@Base @VER@ + PyNumber_InPlaceOr@Base @VER@ + PyNumber_InPlacePower@Base @VER@ + PyNumber_InPlaceRemainder@Base @VER@ + PyNumber_InPlaceRshift@Base @VER@ + PyNumber_InPlaceSubtract@Base @VER@ + PyNumber_InPlaceTrueDivide@Base @VER@ + PyNumber_InPlaceXor@Base @VER@ + PyNumber_Index@Base @VER@ + PyNumber_Int@Base @VER@ + PyNumber_Invert@Base @VER@ + PyNumber_Long@Base @VER@ + PyNumber_Lshift@Base @VER@ + PyNumber_Multiply@Base @VER@ + PyNumber_Negative@Base @VER@ + PyNumber_Or@Base @VER@ + PyNumber_Positive@Base @VER@ + PyNumber_Power@Base @VER@ + PyNumber_Remainder@Base @VER@ + PyNumber_Rshift@Base @VER@ + PyNumber_Subtract@Base @VER@ + PyNumber_ToBase@Base @VER@ + PyNumber_TrueDivide@Base @VER@ + PyNumber_Xor@Base @VER@ + PyOS_AfterFork@Base @VER@ + PyOS_FiniInterrupts@Base @VER@ + PyOS_InitInterrupts@Base @VER@ + PyOS_InputHook@Base @VER@ + PyOS_InterruptOccurred@Base @VER@ + PyOS_Readline@Base @VER@ + PyOS_ReadlineFunctionPointer@Base @VER@ + PyOS_StdioReadline@Base @VER@ + PyOS_ascii_atof@Base @VER@ + PyOS_ascii_formatd@Base @VER@ + PyOS_ascii_strtod@Base @VER@ + PyOS_double_to_string@Base @VER@ + PyOS_getsig@Base @VER@ + PyOS_mystricmp@Base @VER@ + PyOS_mystrnicmp@Base @VER@ + PyOS_setsig@Base @VER@ + PyOS_snprintf@Base @VER@ + PyOS_string_to_double@Base @VER@ + PyOS_strtol@Base @VER@ + PyOS_strtoul@Base @VER@ + PyOS_vsnprintf@Base @VER@ + PyObject_AsCharBuffer@Base @VER@ + PyObject_AsFileDescriptor@Base @VER@ + PyObject_AsReadBuffer@Base @VER@ + PyObject_AsWriteBuffer@Base @VER@ + PyObject_Call@Base @VER@ + PyObject_CallFunction@Base @VER@ + PyObject_CallFunctionObjArgs@Base @VER@ + PyObject_CallMethod@Base @VER@ + PyObject_CallMethodObjArgs@Base @VER@ + PyObject_CallObject@Base @VER@ + PyObject_CheckReadBuffer@Base @VER@ + PyObject_ClearWeakRefs@Base @VER@ + PyObject_Cmp@Base @VER@ + PyObject_Compare@Base @VER@ + PyObject_CopyData@Base @VER@ + PyObject_DelItem@Base @VER@ + PyObject_DelItemString@Base @VER@ + PyObject_Dir@Base @VER@ + PyObject_Format@Base @VER@ + PyObject_Free@Base @VER@ + PyObject_GC_Del@Base @VER@ + PyObject_GC_Track@Base @VER@ + PyObject_GC_UnTrack@Base @VER@ + PyObject_GenericGetAttr@Base @VER@ + PyObject_GenericSetAttr@Base @VER@ + PyObject_GetAttr@Base @VER@ + PyObject_GetAttrString@Base @VER@ + PyObject_GetBuffer@Base @VER@ + PyObject_GetItem@Base @VER@ + PyObject_GetIter@Base @VER@ + PyObject_HasAttr@Base @VER@ + PyObject_HasAttrString@Base @VER@ + PyObject_Hash@Base @VER@ + PyObject_HashNotImplemented@Base @VER@ + PyObject_Init@Base @VER@ + PyObject_InitVar@Base @VER@ + PyObject_IsInstance@Base @VER@ + PyObject_IsSubclass@Base @VER@ + PyObject_IsTrue@Base @VER@ + PyObject_Length@Base @VER@ + PyObject_Malloc@Base @VER@ + PyObject_Not@Base @VER@ + PyObject_Print@Base @VER@ + PyObject_Realloc@Base @VER@ + PyObject_Repr@Base @VER@ + PyObject_RichCompare@Base @VER@ + PyObject_RichCompareBool@Base @VER@ + PyObject_SelfIter@Base @VER@ + PyObject_SetAttr@Base @VER@ + PyObject_SetAttrString@Base @VER@ + PyObject_SetItem@Base @VER@ + PyObject_Size@Base @VER@ + PyObject_Str@Base @VER@ + PyObject_Type@Base @VER@ + PyObject_Unicode@Base @VER@ + PyParser_ASTFromFile@Base @VER@ + PyParser_ASTFromString@Base @VER@ + PyParser_AddToken@Base @VER@ + PyParser_Delete@Base @VER@ + PyParser_New@Base @VER@ + PyParser_ParseFile@Base @VER@ + PyParser_ParseFileFlags@Base @VER@ + PyParser_ParseFileFlagsEx@Base @VER@ + PyParser_ParseString@Base @VER@ + PyParser_ParseStringFlags@Base @VER@ + PyParser_ParseStringFlagsFilename@Base @VER@ + PyParser_ParseStringFlagsFilenameEx@Base @VER@ + PyParser_SetError@Base @VER@ + PyParser_SimpleParseFile@Base @VER@ + PyParser_SimpleParseFileFlags@Base @VER@ + PyParser_SimpleParseString@Base @VER@ + PyParser_SimpleParseStringFilename@Base @VER@ + PyParser_SimpleParseStringFlags@Base @VER@ + PyParser_SimpleParseStringFlagsFilename@Base @VER@ + PyProperty_Type@Base @VER@ + PyRange_Type@Base @VER@ + PyReversed_Type@Base @VER@ + PyRun_AnyFile@Base @VER@ + PyRun_AnyFileEx@Base @VER@ + PyRun_AnyFileExFlags@Base @VER@ + PyRun_AnyFileFlags@Base @VER@ + PyRun_File@Base @VER@ + PyRun_FileEx@Base @VER@ + PyRun_FileExFlags@Base @VER@ + PyRun_FileFlags@Base @VER@ + PyRun_InteractiveLoop@Base @VER@ + PyRun_InteractiveLoopFlags@Base @VER@ + PyRun_InteractiveOne@Base @VER@ + PyRun_InteractiveOneFlags@Base @VER@ + PyRun_SimpleFile@Base @VER@ + PyRun_SimpleFileEx@Base @VER@ + PyRun_SimpleFileExFlags@Base @VER@ + PyRun_SimpleString@Base @VER@ + PyRun_SimpleStringFlags@Base @VER@ + PyRun_String@Base @VER@ + PyRun_StringFlags@Base @VER@ + PySTEntry_Type@Base @VER@ + PyST_GetScope@Base @VER@ + PySeqIter_New@Base @VER@ + PySeqIter_Type@Base @VER@ + PySequence_Check@Base @VER@ + PySequence_Concat@Base @VER@ + PySequence_Contains@Base @VER@ + PySequence_Count@Base @VER@ + PySequence_DelItem@Base @VER@ + PySequence_DelSlice@Base @VER@ + PySequence_Fast@Base @VER@ + PySequence_GetItem@Base @VER@ + PySequence_GetSlice@Base @VER@ + PySequence_In@Base @VER@ + PySequence_InPlaceConcat@Base @VER@ + PySequence_InPlaceRepeat@Base @VER@ + PySequence_Index@Base @VER@ + PySequence_Length@Base @VER@ + PySequence_List@Base @VER@ + PySequence_Repeat@Base @VER@ + PySequence_SetItem@Base @VER@ + PySequence_SetSlice@Base @VER@ + PySequence_Size@Base @VER@ + PySequence_Tuple@Base @VER@ + PySet_Add@Base @VER@ + PySet_Clear@Base @VER@ + PySet_Contains@Base @VER@ + PySet_Discard@Base @VER@ + PySet_Fini@Base @VER@ + PySet_New@Base @VER@ + PySet_Pop@Base @VER@ + PySet_Size@Base @VER@ + PySet_Type@Base @VER@ + PySignal_SetWakeupFd@Base @VER@ + PySlice_GetIndices@Base @VER@ + PySlice_GetIndicesEx@Base @VER@ + PySlice_New@Base @VER@ + PySlice_Type@Base @VER@ + PyStaticMethod_New@Base @VER@ + PyStaticMethod_Type@Base @VER@ + PyString_AsDecodedObject@Base @VER@ + PyString_AsDecodedString@Base @VER@ + PyString_AsEncodedObject@Base @VER@ + PyString_AsEncodedString@Base @VER@ + PyString_AsString@Base @VER@ + PyString_AsStringAndSize@Base @VER@ + PyString_Concat@Base @VER@ + PyString_ConcatAndDel@Base @VER@ + PyString_Decode@Base @VER@ + PyString_DecodeEscape@Base @VER@ + PyString_Encode@Base @VER@ + PyString_Fini@Base @VER@ + PyString_Format@Base @VER@ + PyString_FromFormat@Base @VER@ + PyString_FromFormatV@Base @VER@ + PyString_FromString@Base @VER@ + PyString_FromStringAndSize@Base @VER@ + PyString_InternFromString@Base @VER@ + PyString_InternImmortal@Base @VER@ + PyString_InternInPlace@Base @VER@ + PyString_Repr@Base @VER@ + PyString_Size@Base @VER@ + PyString_Type@Base @VER@ + PyStructSequence_InitType@Base @VER@ + PyStructSequence_New@Base @VER@ + PyStructSequence_UnnamedField@Base @VER@ + PySuper_Type@Base @VER@ + PySymtable_Build@Base @VER@ + PySymtable_Free@Base @VER@ + PySymtable_Lookup@Base @VER@ + PySys_AddWarnOption@Base @VER@ + PySys_GetFile@Base @VER@ + PySys_GetObject@Base @VER@ + PySys_HasWarnOptions@Base @VER@ + PySys_ResetWarnOptions@Base @VER@ + PySys_SetArgv@Base @VER@ + PySys_SetArgvEx@Base @VER@ + PySys_SetObject@Base @VER@ + PySys_SetPath@Base @VER@ + PySys_WriteStderr@Base @VER@ + PySys_WriteStdout@Base @VER@ + PyThreadState_Clear@Base @VER@ + PyThreadState_Delete@Base @VER@ + PyThreadState_DeleteCurrent@Base @VER@ + PyThreadState_Get@Base @VER@ + PyThreadState_GetDict@Base @VER@ + PyThreadState_New@Base @VER@ + PyThreadState_Next@Base @VER@ + PyThreadState_SetAsyncExc@Base @VER@ + PyThreadState_Swap@Base @VER@ + PyThread_ReInitTLS@Base @VER@ + PyThread_acquire_lock@Base @VER@ + PyThread_allocate_lock@Base @VER@ + PyThread_create_key@Base @VER@ + PyThread_delete_key@Base @VER@ + PyThread_delete_key_value@Base @VER@ + PyThread_exit_thread@Base @VER@ + PyThread_free_lock@Base @VER@ + PyThread_get_key_value@Base @VER@ + PyThread_get_stacksize@Base @VER@ + PyThread_get_thread_ident@Base @VER@ + PyThread_init_thread@Base @VER@ + PyThread_release_lock@Base @VER@ + PyThread_set_key_value@Base @VER@ + PyThread_set_stacksize@Base @VER@ + PyThread_start_new_thread@Base @VER@ + PyToken_OneChar@Base @VER@ + PyToken_ThreeChars@Base @VER@ + PyToken_TwoChars@Base @VER@ + PyTokenizer_Free@Base @VER@ + PyTokenizer_FromFile@Base @VER@ + PyTokenizer_FromString@Base @VER@ + PyTokenizer_Get@Base @VER@ + PyTokenizer_RestoreEncoding@Base @VER@ + PyTraceBack_Here@Base @VER@ + PyTraceBack_Print@Base @VER@ + PyTraceBack_Type@Base @VER@ + PyTupleIter_Type@Base @VER@ + PyTuple_ClearFreeList@Base @VER@ + PyTuple_Fini@Base @VER@ + PyTuple_GetItem@Base @VER@ + PyTuple_GetSlice@Base @VER@ + PyTuple_New@Base @VER@ + PyTuple_Pack@Base @VER@ + PyTuple_SetItem@Base @VER@ + PyTuple_Size@Base @VER@ + PyTuple_Type@Base @VER@ + PyType_ClearCache@Base @VER@ + PyType_GenericAlloc@Base @VER@ + PyType_GenericNew@Base @VER@ + PyType_IsSubtype@Base @VER@ + PyType_Modified@Base @VER@ + PyType_Ready@Base @VER@ + PyType_Type@Base @VER@ + PyUnicodeDecodeError_Create@Base @VER@ + PyUnicodeDecodeError_GetEncoding@Base @VER@ + PyUnicodeDecodeError_GetEnd@Base @VER@ + PyUnicodeDecodeError_GetObject@Base @VER@ + PyUnicodeDecodeError_GetReason@Base @VER@ + PyUnicodeDecodeError_GetStart@Base @VER@ + PyUnicodeDecodeError_SetEnd@Base @VER@ + PyUnicodeDecodeError_SetReason@Base @VER@ + PyUnicodeDecodeError_SetStart@Base @VER@ + PyUnicodeEncodeError_Create@Base @VER@ + PyUnicodeEncodeError_GetEncoding@Base @VER@ + PyUnicodeEncodeError_GetEnd@Base @VER@ + PyUnicodeEncodeError_GetObject@Base @VER@ + PyUnicodeEncodeError_GetReason@Base @VER@ + PyUnicodeEncodeError_GetStart@Base @VER@ + PyUnicodeEncodeError_SetEnd@Base @VER@ + PyUnicodeEncodeError_SetReason@Base @VER@ + PyUnicodeEncodeError_SetStart@Base @VER@ + PyUnicodeTranslateError_Create@Base @VER@ + PyUnicodeTranslateError_GetEnd@Base @VER@ + PyUnicodeTranslateError_GetObject@Base @VER@ + PyUnicodeTranslateError_GetReason@Base @VER@ + PyUnicodeTranslateError_GetStart@Base @VER@ + PyUnicodeTranslateError_SetEnd@Base @VER@ + PyUnicodeTranslateError_SetReason@Base @VER@ + PyUnicodeTranslateError_SetStart@Base @VER@ + PyUnicodeUCS4_AsASCIIString@Base @VER@ + PyUnicodeUCS4_AsCharmapString@Base @VER@ + PyUnicodeUCS4_AsEncodedObject@Base @VER@ + PyUnicodeUCS4_AsEncodedString@Base @VER@ + PyUnicodeUCS4_AsLatin1String@Base @VER@ + PyUnicodeUCS4_AsRawUnicodeEscapeString@Base @VER@ + PyUnicodeUCS4_AsUTF16String@Base @VER@ + PyUnicodeUCS4_AsUTF32String@Base @VER@ + PyUnicodeUCS4_AsUTF8String@Base @VER@ + PyUnicodeUCS4_AsUnicode@Base @VER@ + PyUnicodeUCS4_AsUnicodeEscapeString@Base @VER@ + PyUnicodeUCS4_AsWideChar@Base @VER@ + PyUnicodeUCS4_ClearFreelist@Base @VER@ + PyUnicodeUCS4_Compare@Base @VER@ + PyUnicodeUCS4_Concat@Base @VER@ + PyUnicodeUCS4_Contains@Base @VER@ + PyUnicodeUCS4_Count@Base @VER@ + PyUnicodeUCS4_Decode@Base @VER@ + PyUnicodeUCS4_DecodeASCII@Base @VER@ + PyUnicodeUCS4_DecodeCharmap@Base @VER@ + PyUnicodeUCS4_DecodeLatin1@Base @VER@ + PyUnicodeUCS4_DecodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS4_DecodeUTF16@Base @VER@ + PyUnicodeUCS4_DecodeUTF16Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUTF32@Base @VER@ + PyUnicodeUCS4_DecodeUTF32Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUTF8@Base @VER@ + PyUnicodeUCS4_DecodeUTF8Stateful@Base @VER@ + PyUnicodeUCS4_DecodeUnicodeEscape@Base @VER@ + PyUnicodeUCS4_Encode@Base @VER@ + PyUnicodeUCS4_EncodeASCII@Base @VER@ + PyUnicodeUCS4_EncodeCharmap@Base @VER@ + PyUnicodeUCS4_EncodeDecimal@Base @VER@ + PyUnicodeUCS4_EncodeLatin1@Base @VER@ + PyUnicodeUCS4_EncodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS4_EncodeUTF16@Base @VER@ + PyUnicodeUCS4_EncodeUTF32@Base @VER@ + PyUnicodeUCS4_EncodeUTF8@Base @VER@ + PyUnicodeUCS4_EncodeUnicodeEscape@Base @VER@ + PyUnicodeUCS4_Find@Base @VER@ + PyUnicodeUCS4_Format@Base @VER@ + PyUnicodeUCS4_FromEncodedObject@Base @VER@ + PyUnicodeUCS4_FromFormat@Base @VER@ + PyUnicodeUCS4_FromFormatV@Base @VER@ + PyUnicodeUCS4_FromObject@Base @VER@ + PyUnicodeUCS4_FromOrdinal@Base @VER@ + PyUnicodeUCS4_FromString@Base @VER@ + PyUnicodeUCS4_FromStringAndSize@Base @VER@ + PyUnicodeUCS4_FromUnicode@Base @VER@ + PyUnicodeUCS4_FromWideChar@Base @VER@ + PyUnicodeUCS4_GetDefaultEncoding@Base @VER@ + PyUnicodeUCS4_GetMax@Base @VER@ + PyUnicodeUCS4_GetSize@Base @VER@ + PyUnicodeUCS4_Join@Base @VER@ + PyUnicodeUCS4_Partition@Base @VER@ + PyUnicodeUCS4_RPartition@Base @VER@ + PyUnicodeUCS4_RSplit@Base @VER@ + PyUnicodeUCS4_Replace@Base @VER@ + PyUnicodeUCS4_Resize@Base @VER@ + PyUnicodeUCS4_RichCompare@Base @VER@ + PyUnicodeUCS4_SetDefaultEncoding@Base @VER@ + PyUnicodeUCS4_Split@Base @VER@ + PyUnicodeUCS4_Splitlines@Base @VER@ + PyUnicodeUCS4_Tailmatch@Base @VER@ + PyUnicodeUCS4_Translate@Base @VER@ + PyUnicodeUCS4_TranslateCharmap@Base @VER@ + PyUnicode_AsDecodedObject@Base @VER@ + PyUnicode_BuildEncodingMap@Base @VER@ + PyUnicode_DecodeUTF7@Base @VER@ + PyUnicode_DecodeUTF7Stateful@Base @VER@ + PyUnicode_EncodeUTF7@Base @VER@ + PyUnicode_Type@Base @VER@ + PyWeakref_GetObject@Base @VER@ + PyWeakref_NewProxy@Base @VER@ + PyWeakref_NewRef@Base @VER@ + PyWrapperDescr_Type@Base @VER@ + PyWrapper_New@Base @VER@ + Py_AddPendingCall@Base @VER@ + Py_AtExit@Base @VER@ + Py_BuildValue@Base @VER@ + Py_BytesWarningFlag@Base @VER@ + Py_CompileString@Base @VER@ + Py_CompileStringFlags@Base @VER@ + Py_DebugFlag@Base @VER@ + Py_DecRef@Base @VER@ + Py_DivisionWarningFlag@Base @VER@ + Py_DontWriteBytecodeFlag@Base @VER@ + Py_EndInterpreter@Base @VER@ + Py_Exit@Base @VER@ + Py_FatalError@Base @VER@ + Py_FdIsInteractive@Base @VER@ + Py_FileSystemDefaultEncoding@Base @VER@ + Py_Finalize@Base @VER@ + Py_FindMethod@Base @VER@ + Py_FindMethodInChain@Base @VER@ + Py_FlushLine@Base @VER@ + Py_FrozenFlag@Base @VER@ + Py_FrozenMain@Base @VER@ + Py_GetArgcArgv@Base @VER@ + Py_GetBuildInfo@Base @VER@ + Py_GetCompiler@Base @VER@ + Py_GetCopyright@Base @VER@ + Py_GetExecPrefix@Base @VER@ + Py_GetPath@Base @VER@ + Py_GetPlatform@Base @VER@ + Py_GetPrefix@Base @VER@ + Py_GetProgramFullPath@Base @VER@ + Py_GetProgramName@Base @VER@ + Py_GetPythonHome@Base @VER@ + Py_GetRecursionLimit@Base @VER@ + Py_GetVersion@Base @VER@ + Py_IgnoreEnvironmentFlag@Base @VER@ + Py_IncRef@Base @VER@ + Py_Initialize@Base @VER@ + Py_InitializeEx@Base @VER@ + Py_InspectFlag@Base @VER@ + Py_InteractiveFlag@Base @VER@ + Py_IsInitialized@Base @VER@ + Py_Main@Base @VER@ + Py_MakePendingCalls@Base @VER@ + Py_NewInterpreter@Base @VER@ + Py_NoSiteFlag@Base @VER@ + Py_NoUserSiteDirectory@Base @VER@ + Py_OptimizeFlag@Base @VER@ + Py_Py3kWarningFlag@Base @VER@ + Py_ReprEnter@Base @VER@ + Py_ReprLeave@Base @VER@ + Py_SetProgramName@Base @VER@ + Py_SetPythonHome@Base @VER@ + Py_SetRecursionLimit@Base @VER@ + Py_SubversionRevision@Base @VER@ + Py_SubversionShortBranch@Base @VER@ + Py_SymtableString@Base @VER@ + Py_TabcheckFlag@Base @VER@ + Py_UnicodeFlag@Base @VER@ + Py_UniversalNewlineFgets@Base @VER@ + Py_UniversalNewlineFread@Base @VER@ + Py_UseClassExceptionsFlag@Base @VER@ + Py_VaBuildValue@Base @VER@ + Py_VerboseFlag@Base @VER@ + Py_meta_grammar@Base @VER@ + Py_pgen@Base @VER@ + _PyArg_NoKeywords@Base @VER@ + _PyArg_ParseTupleAndKeywords_SizeT@Base @VER@ + _PyArg_ParseTuple_SizeT@Base @VER@ + _PyArg_Parse_SizeT@Base @VER@ + _PyArg_VaParseTupleAndKeywords_SizeT@Base @VER@ + _PyArg_VaParse_SizeT@Base @VER@ + _PyBuiltin_Init@Base @VER@ + _PyByteArray_empty_string@Base @VER@ + _PyBytes_FormatAdvanced@Base @VER@ + _PyCode_CheckLineNumber@Base @VER@ + _PyCodec_Lookup@Base @VER@ + _PyComplex_FormatAdvanced@Base @VER@ + _PyDict_Contains@Base @VER@ + _PyDict_MaybeUntrack@Base @VER@ + _PyDict_NewPresized@Base @VER@ + _PyDict_Next@Base @VER@ + _PyErr_BadInternalCall@Base @VER@ + _PyEval_CallTracing@Base @VER@ + _PyEval_SliceIndex@Base @VER@ + _PyExc_Fini@Base @VER@ + _PyExc_Init@Base @VER@ + _PyFile_SanitizeMode@Base @VER@ + _PyFloat_FormatAdvanced@Base @VER@ + _PyFloat_Init@Base @VER@ + _PyFloat_Pack4@Base @VER@ + _PyFloat_Pack8@Base @VER@ + _PyFloat_Unpack4@Base @VER@ + _PyFloat_Unpack8@Base @VER@ + _PyFrame_Init@Base @VER@ + _PyGC_Dump@Base @VER@ + _PyGC_generation0@Base @VER@ + _PyGILState_Fini@Base @VER@ + _PyGILState_Init@Base @VER@ + _PyImportHooks_Init@Base @VER@ + _PyImport_AcquireLock@Base @VER@ + _PyImport_DynLoadFiletab@Base @VER@ + _PyImport_Filetab@Base @VER@ + _PyImport_FindExtension@Base @VER@ + _PyImport_FindModule@Base @VER@ + _PyImport_Fini@Base @VER@ + _PyImport_FixupExtension@Base @VER@ + _PyImport_GetDynLoadFunc@Base @VER@ + _PyImport_Init@Base @VER@ + _PyImport_Inittab@Base @VER@ + _PyImport_IsScript@Base @VER@ + _PyImport_LoadDynamicModule@Base @VER@ + _PyImport_ReleaseLock@Base @VER@ + _PyImport_ReInitLock@Base @VER@ + _PyInstance_Lookup@Base @VER@ + _PyInt_Format@Base @VER@ + _PyInt_FormatAdvanced@Base @VER@ + _PyInt_Init@Base @VER@ + _PyList_Extend@Base @VER@ + _PyLong_AsByteArray@Base @VER@ + _PyLong_Copy@Base @VER@ + _PyLong_DigitValue@Base @VER@ + _PyLong_Format@Base @VER@ + _PyLong_FormatAdvanced@Base @VER@ + _PyLong_Frexp@Base @VER@ + _PyLong_FromByteArray@Base @VER@ + _PyLong_Init@Base @VER@ + _PyLong_New@Base @VER@ + _PyLong_NumBits@Base @VER@ + _PyLong_Sign@Base @VER@ + _PyModule_Clear@Base @VER@ + _PyNumber_ConvertIntegralToInt@Base @VER@ + _PyOS_GetOpt@Base @VER@ + _PyOS_ReadlineTState@Base @VER@ + _PyOS_ascii_formatd@Base @VER@ + _PyOS_ascii_strtod@Base @VER@ + _PyOS_optarg@Base @VER@ + _PyOS_opterr@Base @VER@ + _PyOS_optind@Base @VER@ + _PyObject_CallFunction_SizeT@Base @VER@ + _PyObject_CallMethod_SizeT@Base @VER@ + _PyObject_Del@Base @VER@ + _PyObject_Dump@Base @VER@ + _PyObject_GC_Del@Base @VER@ + _PyObject_GC_Malloc@Base @VER@ + _PyObject_GC_New@Base @VER@ + _PyObject_GC_NewVar@Base @VER@ + _PyObject_GC_Resize@Base @VER@ + _PyObject_GC_Track@Base @VER@ + _PyObject_GC_UnTrack@Base @VER@ + _PyObject_GenericGetAttrWithDict@Base @VER@ + _PyObject_GenericSetAttrWithDict@Base @VER@ + _PyObject_GetDictPtr@Base @VER@ + _PyObject_LengthHint@Base @VER@ + _PyObject_LookupSpecial@Base @VER@ + _PyObject_New@Base @VER@ + _PyObject_NewVar@Base @VER@ + _PyObject_NextNotImplemented@Base @VER@ + _PyObject_RealIsInstance@Base @VER@ + _PyObject_RealIsSubclass@Base @VER@ + _PyObject_SlotCompare@Base @VER@ + _PyObject_Str@Base @VER@ + _PyParser_Grammar@Base @VER@ + _PyParser_TokenNames@Base @VER@ + _PySequence_IterSearch@Base @VER@ + _PySet_Next@Base @VER@ + _PySet_NextEntry@Base @VER@ + _PySet_Update@Base @VER@ + _PySlice_FromIndices@Base @VER@ + _PyString_Eq@Base @VER@ + _PyString_FormatLong@Base @VER@ + _PyString_InsertThousandsGrouping@Base @VER@ + _PyString_Join@Base @VER@ + _PyString_Resize@Base @VER@ + _PySys_Init@Base @VER@ + _PyThreadState_Current@Base @VER@ + _PyThreadState_GetFrame@Base @VER@ + _PyThreadState_Init@Base @VER@ + _PyThreadState_Prealloc@Base @VER@ + _PyThread_CurrentFrames@Base @VER@ + _PyTime_DoubleToTimet@Base @VER@ + _PyTrash_delete_later@Base @VER@ + _PyTrash_delete_nesting@Base @VER@ + _PyTrash_deposit_object@Base @VER@ + _PyTrash_destroy_chain@Base @VER@ + _PyTuple_MaybeUntrack@Base @VER@ + _PyTuple_Resize@Base @VER@ + _PyType_Lookup@Base @VER@ + _PyUnicodeUCS4_AsDefaultEncodedString@Base @VER@ + _PyUnicodeUCS4_Fini@Base @VER@ + _PyUnicodeUCS4_Init@Base @VER@ + _PyUnicodeUCS4_IsAlpha@Base @VER@ + _PyUnicodeUCS4_IsDecimalDigit@Base @VER@ + _PyUnicodeUCS4_IsDigit@Base @VER@ + _PyUnicodeUCS4_IsLinebreak@Base @VER@ + _PyUnicodeUCS4_IsLowercase@Base @VER@ + _PyUnicodeUCS4_IsNumeric@Base @VER@ + _PyUnicodeUCS4_IsTitlecase@Base @VER@ + _PyUnicodeUCS4_IsUppercase@Base @VER@ + _PyUnicodeUCS4_IsWhitespace@Base @VER@ + _PyUnicodeUCS4_ToDecimalDigit@Base @VER@ + _PyUnicodeUCS4_ToDigit@Base @VER@ + _PyUnicodeUCS4_ToLowercase@Base @VER@ + _PyUnicodeUCS4_ToNumeric@Base @VER@ + _PyUnicodeUCS4_ToTitlecase@Base @VER@ + _PyUnicodeUCS4_ToUppercase@Base @VER@ + _PyUnicode_BidirectionalNames@Base @VER@ + _PyUnicode_CategoryNames@Base @VER@ + _PyUnicode_Database_Records@Base @VER@ + _PyUnicode_DecodeUnicodeInternal@Base @VER@ + _PyUnicode_EastAsianWidthNames@Base @VER@ + _PyUnicode_FormatAdvanced@Base @VER@ + _PyUnicode_TypeRecords@Base @VER@ + _PyUnicode_XStrip@Base @VER@ + _PyWarnings_Init@Base @VER@ + _PyWeakref_CallableProxyType@Base @VER@ + _PyWeakref_ClearRef@Base @VER@ + _PyWeakref_GetWeakrefCount@Base @VER@ + _PyWeakref_ProxyType@Base @VER@ + _PyWeakref_RefType@Base @VER@ + _Py_Assert@Base @VER@ + _Py_Assign@Base @VER@ + _Py_Attribute@Base @VER@ + _Py_AugAssign@Base @VER@ + _Py_BinOp@Base @VER@ + _Py_BoolOp@Base @VER@ + _Py_Break@Base @VER@ + _Py_BuildValue_SizeT@Base @VER@ + _Py_Call@Base @VER@ + _Py_CheckInterval@Base @VER@ + _Py_CheckRecursionLimit@Base @VER@ + _Py_CheckRecursiveCall@Base @VER@ + _Py_ClassDef@Base @VER@ + _Py_Compare@Base @VER@ + _Py_Continue@Base @VER@ + _Py_Delete@Base @VER@ + _Py_Dict@Base @VER@ + _Py_DictComp@Base @VER@ + _Py_DisplaySourceLine@Base @VER@ + _Py_Ellipsis@Base @VER@ + _Py_EllipsisObject@Base @VER@ + _Py_ExceptHandler@Base @VER@ + _Py_Exec@Base @VER@ + _Py_Expr@Base @VER@ + _Py_Expression@Base @VER@ + _Py_ExtSlice@Base @VER@ + _Py_For@Base @VER@ + _Py_FunctionDef@Base @VER@ + _Py_GeneratorExp@Base @VER@ + _Py_Global@Base @VER@ + _Py_HashDouble@Base @VER@ + _Py_HashPointer@Base @VER@ + _Py_If@Base @VER@ + _Py_IfExp@Base @VER@ + _Py_Import@Base @VER@ + _Py_ImportFrom@Base @VER@ + _Py_Index@Base @VER@ + _Py_InsertThousandsGroupingLocale@Base @VER@ + _Py_Interactive@Base @VER@ + _Py_Lambda@Base @VER@ + _Py_List@Base @VER@ + _Py_ListComp@Base @VER@ + _Py_Mangle@Base @VER@ + _Py_Module@Base @VER@ + _Py_Name@Base @VER@ + _Py_NoneStruct@Base @VER@ + _Py_NotImplementedStruct@Base @VER@ + _Py_Num@Base @VER@ + _Py_PackageContext@Base @VER@ + _Py_Pass@Base @VER@ + _Py_Print@Base @VER@ + _Py_QnewFlag@Base @VER@ + _Py_Raise@Base @VER@ + _Py_ReadyTypes@Base @VER@ + _Py_ReleaseInternedStrings@Base @VER@ + _Py_Repr@Base @VER@ + _Py_Return@Base @VER@ + _Py_Set@Base @VER@ + _Py_SetComp@Base @VER@ + _Py_Slice@Base @VER@ + _Py_Str@Base @VER@ + _Py_Subscript@Base @VER@ + _Py_Suite@Base @VER@ + _Py_SwappedOp@Base @VER@ + _Py_Ticker@Base @VER@ + _Py_TrueStruct@Base @VER@ + _Py_TryExcept@Base @VER@ + _Py_TryFinally@Base @VER@ + _Py_Tuple@Base @VER@ + _Py_UnaryOp@Base @VER@ + _Py_VaBuildValue_SizeT@Base @VER@ + _Py_While@Base @VER@ + _Py_With@Base @VER@ + _Py_Yield@Base @VER@ + _Py_ZeroStruct@Base @VER@ + _Py_abstract_hack@Base @VER@ + _Py_add_one_to_index_C@Base @VER@ + _Py_add_one_to_index_F@Base @VER@ + (optional)_Py_acosh@Base @VER@ + _Py_addarc@Base @VER@ + _Py_addbit@Base @VER@ + _Py_adddfa@Base @VER@ + _Py_addfirstsets@Base @VER@ + _Py_addlabel@Base @VER@ + _Py_addstate@Base @VER@ + _Py_alias@Base @VER@ + _Py_arguments@Base @VER@ + _Py_ascii_whitespace@Base @VER@ + (optional)_Py_asinh@Base @VER@ + (optional)_Py_atanh@Base @VER@ + _Py_bytes_capitalize@Base @VER@ + _Py_bytes_isalnum@Base @VER@ + _Py_bytes_isalpha@Base @VER@ + _Py_bytes_isdigit@Base @VER@ + _Py_bytes_islower@Base @VER@ + _Py_bytes_isspace@Base @VER@ + _Py_bytes_istitle@Base @VER@ + _Py_bytes_isupper@Base @VER@ + _Py_bytes_lower@Base @VER@ + _Py_bytes_swapcase@Base @VER@ + _Py_bytes_title@Base @VER@ + _Py_bytes_upper@Base @VER@ + _Py_c_abs@Base @VER@ + _Py_c_diff@Base @VER@ + _Py_c_neg@Base @VER@ + _Py_c_pow@Base @VER@ + _Py_c_prod@Base @VER@ + _Py_c_quot@Base @VER@ + _Py_c_sum@Base @VER@ + _Py_capitalize__doc__@Base @VER@ + _Py_capsule_hack@Base @VER@ + _Py_cobject_hack@Base @VER@ + _Py_comprehension@Base @VER@ + _Py_ctype_table@Base @VER@ + _Py_ctype_tolower@Base @VER@ + _Py_ctype_toupper@Base @VER@ + _Py_delbitset@Base @VER@ + (arch=!m68k)_Py_dg_dtoa@Base @VER@ + (arch=!m68k)_Py_dg_freedtoa@Base @VER@ + (arch=!m68k)_Py_dg_strtod@Base @VER@ + _Py_double_round@Base @VER@ + (optional)_Py_expm1@Base @VER@ + _Py_findlabel@Base @VER@ + (arch=i386 lpia m68k)_Py_force_double@Base @VER@ + (arch=amd64 i386 lpia)_Py_get_387controlword@Base @VER@ + _Py_hgidentifier@Base 2.7.1 + _Py_hgversion@Base 2.7.1 + _Py_isalnum__doc__@Base @VER@ + _Py_isalpha__doc__@Base @VER@ + _Py_isdigit__doc__@Base @VER@ + _Py_islower__doc__@Base @VER@ + _Py_isspace__doc__@Base @VER@ + _Py_istitle__doc__@Base @VER@ + _Py_isupper__doc__@Base @VER@ + _Py_keyword@Base @VER@ + (optional)_Py_log1p@Base @VER@ + _Py_lower__doc__@Base @VER@ + _Py_mergebitset@Base @VER@ + _Py_meta_grammar@Base @VER@ + _Py_newbitset@Base @VER@ + _Py_newgrammar@Base @VER@ + (optional)_Py_parse_inf_or_nan@Base @VER@ + _Py_pgen@Base @VER@ + _Py_samebitset@Base @VER@ + (arch=amd64 i386 lpia)_Py_set_387controlword@Base @VER@ + _Py_svnversion@Base @VER@ + _Py_swapcase__doc__@Base @VER@ + _Py_title__doc__@Base @VER@ + _Py_translatelabels@Base @VER@ + _Py_upper__doc__@Base @VER@ + + PyFPE_counter@Base @VER@ + PyFPE_dummy@Base @VER@ + PyFPE_jbuf@Base @VER@ + + asdl_int_seq_new@Base @VER@ + asdl_seq_new@Base @VER@ + +# don't check for the following symbols, found in extensions +# which either can be built as builtin or extension. + + (optional)fast_save_leave@Base @VER@ + (optional)partial_reduce@Base @VER@ + (optional)partial_setstate@Base @VER@ + +# _check_for_multiple_distdirs@Base @VER@ + (optional)init_ast@Base @VER@ + (optional)init_bisect@Base @VER@ + (optional)init_codecs@Base @VER@ + (optional)init_collections@Base @VER@ + (optional)init_functools@Base @VER@ + (optional)init_hashlib@Base @VER@ + (optional)init_locale@Base @VER@ + (optional)init_random@Base @VER@ + (optional)init_socket@Base @VER@ + (optional)init_sockobject@Base @VER@ + (optional)init_sre@Base @VER@ + (optional)init_ssl@Base @VER@ + (optional)init_struct@Base @VER@ + (optional)init_symtable@Base @VER@ + (optional)init_weakref@Base @VER@ + (optional)initarray@Base @VER@ + (optional)initbinascii@Base @VER@ + (optional)initcPickle@Base @VER@ + (optional)initcStringIO@Base @VER@ + (optional)initcmath@Base @VER@ + (optional)initerrno@Base @VER@ + (optional)initfcntl@Base @VER@ + (optional)initgc@Base @VER@ + (optional)initgrp@Base @VER@ + (optional)initimp@Base @VER@ + (optional)inititertools@Base @VER@ + (optional)initmath@Base @VER@ + (optional)initoperator@Base @VER@ + (optional)initposix@Base @VER@ + (optional)initpwd@Base @VER@ + (optional)initselect@Base @VER@ + (optional)initsignal@Base @VER@ + (optional)initspwd@Base @VER@ + (optional)initstrop@Base @VER@ + (optional)initsyslog@Base @VER@ + (optional)initthread@Base @VER@ + (optional)inittime@Base @VER@ + (optional)initunicodedata@Base @VER@ + (optional)initxxsubtype@Base @VER@ + (optional)initzipimport@Base @VER@ + (optional)initzlib@Base @VER@ --- python2.7-2.7.2.orig/debian/control +++ python2.7-2.7.2/debian/control @@ -0,0 +1,111 @@ +Source: python2.7 +Section: python +Priority: optional +Maintainer: Ubuntu Core Developers +XSBC-Original-Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5), quilt, autoconf, libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), tk8.5-dev, zlib1g-dev, blt-dev (>= 2.4z), libssl-dev, libexpat1-dev, sharutils, libbz2-dev, libbluetooth-dev [linux-any], locales [!armel !avr32 !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [linux-any], netbase, lsb-release, bzip2, libdb5.1-dev, libgdbm-dev, gdb, python, help2man, xvfb, xauth +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, python2.7-xml, python-xml, autoconf2.13, python-cxx-dev +Standards-Version: 3.9.2 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg2.7-debian +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg2.7-debian + +Package: python2.7 +Architecture: any +Priority: optional +Depends: python2.7-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: python2.7-doc, binutils +Provides: python2.7-cjkcodecs, python2.7-ctypes, python2.7-elementtree, python2.7-celementtree, python2.7-wsgiref, python2.7-profiler, python2.7-argparse +Conflicts: python-profiler (<= 2.7.1-2) +Replaces: python-profiler (<= 2.7.1-2) +Description: Interactive high-level object-oriented language (version 2.7) + Version 2.7 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: python2.7-minimal +Architecture: any +Priority: optional +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: python2.7 +Suggests: binfmt-support +Replaces: python2.7 (<< 2.7.1~rc1-2~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version 2.7) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/python2.7-minimal/README.Debian for a list of the modules + contained in this package. + +Package: libpython2.7 +Architecture: any +Section: libs +Priority: optional +Depends: python2.7 (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: python2.7 (<< 2.6) +Description: Shared Python runtime library (version 2.7) + Version 2.7 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: python2.7-examples +Architecture: all +Depends: python2.7 (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v2.7) + Examples, Demos and Tools for Python (v2.7). These are files included in + the upstream Python distribution (v2.7). + +Package: python2.7-dev +Architecture: any +Depends: python2.7 (= ${binary:Version}), libpython2.7 (= ${binary:Version}), libexpat1-dev, libssl-dev, ${shlibs:Depends}, ${misc:Depends} +Recommends: libc6-dev | libc-dev +Replaces: python2.7 (<< 2.7-3) +Description: Header files and a static library for Python (v2.7) + Header files, a static library and development tools for building + Python (v2.7) modules, extending the Python interpreter or embedding + Python (v2.7) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-python2.7 +Architecture: all +Depends: python2.7, python-tk (>= 2.6~a3), python2.7-tk, ${misc:Depends} +Enhances: python2.7 +Replaces: python2.7 (<< 2.6.1-2) +Description: IDE for Python (v2.7) using Tkinter + IDLE is an Integrated Development Environment for Python (v2.7). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: python2.7-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: python2.7 +Description: Documentation for the high-level object-oriented language Python (v2.7) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v2.7). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python2.7 + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: python2.7-dbg +Section: debug +Architecture: any +Priority: extra +Depends: python2.7 (>= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python-gdbm-dbg, python-tk-dbg +Description: Debug Build of the Python Interpreter (version 2.7) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/python2.7/lib-dynload/debug first. --- python2.7-2.7.2.orig/debian/PVER-dbg.prerm.in +++ python2.7-2.7.2/debian/PVER-dbg.prerm.in @@ -0,0 +1,22 @@ +#! /bin/sh + +set -e + +case "$1" in + remove) + rm -f /usr/lib/debug/usr/bin/@PVER@-gdb.py[co] + rm -f /usr/lib/debug/usr/lib/lib@PVER@.so.1.0-gdb.py[co] + ;; + upgrade) + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.2.orig/debian/source.lintian-overrides.in +++ python2.7-2.7.2/debian/source.lintian-overrides.in @@ -0,0 +1,5 @@ +# this is conditional in the rules file +@PVER@ source: debhelper-script-needs-versioned-build-depends dh_icons (>= 5.0.51~) + +# generated during the build +@PVER@ source: quilt-build-dep-but-no-series-file --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/copyright +++ python2.7-2.7.2/debian/copyright @@ -0,0 +1,732 @@ +This package was put together by Klee Dienes from +sources from ftp.python.org:/pub/python, based on the Debianization by +the previous maintainers Bernd S. Brentrup and +Bruce Perens. Current maintainer is Matthias Klose . + +It was downloaded from http://python.org/ + +Copyright: + +Upstream Author: Guido van Rossum and others. + +License: + +The following text includes the Python license and licenses and +acknowledgements for incorporated software. The licenses can be read +in the HTML and texinfo versions of the documentation as well, after +installing the pythonx.y-doc package. Licenses for files not licensed +under the Python Licenses are found at the end of this file. + + +Python License +============== + +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations (now Zope +Corporation, see http://www.zope.com). In 2001, the Python Software +Foundation (PSF, see http://www.python.org/psf/) was formed, a +non-profit organization created specifically to own Python-related +Intellectual Property. Zope Corporation is a sponsoring member of +the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.2 2.1.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2.1 2.2 2002 PSF yes + 2.2.2 2.2.1 2002 PSF yes + 2.2.3 2.2.2 2003 PSF yes + 2.3 2.2.2 2002-2003 PSF yes + 2.3.1 2.3 2002-2003 PSF yes + 2.3.2 2.3.1 2002-2003 PSF yes + 2.3.3 2.3.2 2002-2003 PSF yes + 2.3.4 2.3.3 2004 PSF yes + 2.3.5 2.3.4 2005 PSF yes + 2.4 2.3 2004 PSF yes + 2.4.1 2.4 2005 PSF yes + 2.4.2 2.4.1 2005 PSF yes + 2.4.3 2.4.2 2006 PSF yes + 2.5 2.4 2006 PSF yes + 2.5.1 2.5 2007 PSF yes + 2.5.2 2.5.1 2008 PSF yes + 2.5.3 2.5.2 2008 PSF yes + 2.6 2.5 2008 PSF yes + 2.6.1 2.6 2008 PSF yes + 2.6.2 2.6.1 2009 PSF yes + 2.6.3 2.6.2 2009 PSF yes + 2.6.4 2.6.3 2009 PSF yes + 2.6.5 2.6.4 2010 PSF yes + 2.7 2.6 2010 PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python +alone or in any derivative version, provided, however, that PSF's +License Agreement and PSF's notice of copyright, i.e., "Copyright (c) +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Licenses and Acknowledgements for Incorporated Software +======================================================= + +Mersenne Twister +---------------- + +The `_random' module includes code based on a download from +`http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html'. The +following are the verbatim comments from the original code: + + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Any feedback is very welcome. + http://www.math.keio.ac.jp/matumoto/emt.html + email: matumoto@math.keio.ac.jp + + +Sockets +------- + +The `socket' module uses the functions, `getaddrinfo', and +`getnameinfo', which are coded in separate source files from the WIDE +Project, `http://www.wide.ad.jp/about/index.html'. + + Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + FOR GAI_ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON GAI_ANY THEORY OF LIABILITY, WHETHER + IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN GAI_ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + + +Floating point exception control +-------------------------------- + +The source for the `fpectl' module includes the following notice: + + --------------------------------------------------------------------- + / Copyright (c) 1996. \ + | The Regents of the University of California. | + | All rights reserved. | + | | + | Permission to use, copy, modify, and distribute this software for | + | any purpose without fee is hereby granted, provided that this en- | + | tire notice is included in all copies of any software which is or | + | includes a copy or modification of this software and in all | + | copies of the supporting documentation for such software. | + | | + | This work was produced at the University of California, Lawrence | + | Livermore National Laboratory under contract no. W-7405-ENG-48 | + | between the U.S. Department of Energy and The Regents of the | + | University of California for the operation of UC LLNL. | + | | + | DISCLAIMER | + | | + | This software was prepared as an account of work sponsored by an | + | agency of the United States Government. Neither the United States | + | Government nor the University of California nor any of their em- | + | ployees, makes any warranty, express or implied, or assumes any | + | liability or responsibility for the accuracy, completeness, or | + | usefulness of any information, apparatus, product, or process | + | disclosed, or represents that its use would not infringe | + | privately-owned rights. Reference herein to any specific commer- | + | cial products, process, or service by trade name, trademark, | + | manufacturer, or otherwise, does not necessarily constitute or | + | imply its endorsement, recommendation, or favoring by the United | + | States Government or the University of California. The views and | + | opinions of authors expressed herein do not necessarily state or | + | reflect those of the United States Government or the University | + | of California, and shall not be used for advertising or product | + \ endorsement purposes. / + --------------------------------------------------------------------- + + +Cookie management +----------------- + +The `Cookie' module contains the following notice: + + Copyright 2000 by Timothy O'Malley + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software + and its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Timothy O'Malley not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR + ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +Execution tracing +----------------- + +The `trace' module contains the following notice: + + portions copyright 2001, Autonomous Zones Industries, Inc., all rights... + err... reserved and offered to the public under the terms of the + Python 2.2 license. + Author: Zooko O'Whielacronx + http://zooko.com/ + mailto:zooko@zooko.com + + Copyright 2000, Mojam Media, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1999, Bioreason, Inc., all rights reserved. + Author: Andrew Dalke + + Copyright 1995-1997, Automatrix, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. + + Permission to use, copy, modify, and distribute this Python software and + its associated documentation for any purpose without fee is hereby + granted, provided that the above copyright notice appears in all copies, + and that both that copyright notice and this permission notice appear in + supporting documentation, and that the name of neither Automatrix, + Bioreason or Mojam Media be used in advertising or publicity pertaining + to distribution of the software without specific, written prior + permission. + + +UUencode and UUdecode functions +------------------------------- + +The `uu' module contains the following notice: + + Copyright 1994 by Lance Ellinghouse + Cathedral City, California Republic, United States of America. + All Rights Reserved + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Lance Ellinghouse + not be used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Modified by Jack Jansen, CWI, July 1995: + - Use binascii module to do the actual line-by-line conversion + between ascii and binary. This results in a 1000-fold speedup. The C + version is still 5 times faster, though. + - Arguments more compliant with python standard + + +XML Remote Procedure Calls +-------------------------- + +The `xmlrpclib' module contains the following notice: + + The XML-RPC client interface is + + Copyright (c) 1999-2002 by Secret Labs AB + Copyright (c) 1999-2002 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, + and will comply with the following terms and conditions: + + Permission to use, copy, modify, and distribute this software and + its associated documentation for any purpose and without fee is + hereby granted, provided that the above copyright notice appears in + all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Secret Labs AB or the author not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD + TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- + ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR + BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + OF THIS SOFTWARE. + +Licenses for Software linked to +=============================== + +Note that the choice of GPL compatibility outlined above doesn't extend +to modules linked to particular libraries, since they change the +effective License of the module binary. + + +GNU Readline +------------ + +The 'readline' module makes use of GNU Readline. + + The GNU Readline Library is free software; you can redistribute it + and/or modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2, or (at + your option) any later version. + + On Debian systems, you can find the complete statement in + /usr/share/doc/readline-common/copyright'. A copy of the GNU General + Public License is available in /usr/share/common-licenses/GPL-2'. + + +OpenSSL +------- + +The '_ssl' module makes use of OpenSSL. + + The OpenSSL toolkit stays under a dual license, i.e. both the + conditions of the OpenSSL License and the original SSLeay license + apply to the toolkit. Actually both licenses are BSD-style Open + Source licenses. Note that both licenses are incompatible with + the GPL. + + On Debian systems, you can find the complete license text in + /usr/share/doc/openssl/copyright'. + + +Files with other licenses than the Python License +------------------------------------------------- + +Files: Lib/profile.py Lib/pstats.py +Copyright: Disney Enterprises, Inc. All Rights Reserved. +License: # Licensed to PSF under a Contributor Agreement + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied. See the License for the specific language + overning permissions and limitations under the License. + + On Debian systems, the Apache 2.0 license can be found in + /usr/share/common-licenses/Apache-2.0. + +Files: Modules/zlib/* +Copyright: (C) 1995-2010 Jean-loup Gailly and Mark Adler +License: This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + If you use the zlib library in a product, we would appreciate *not* receiving + lengthy legal documents to sign. The sources are provided for free but without + warranty of any kind. The library has been entirely written by Jean-loup + Gailly and Mark Adler; it does not include third-party code. + +Files: Modules/_ctypes/libffi/* +Copyright: Copyright (C) 1996-2009 Red Hat, Inc and others. +License: Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + Documentation: + Permission is granted to copy, distribute and/or modify this document + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 2, or (at your option) any + later version. A copy of the license is included in the + section entitled ``GNU General Public License''. + +Files: Modules/expat/* +Copyright: Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper + Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers +License: Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Files: Misc/python-mode.el +Copyright: Copyright (C) 1992,1993,1994 Tim Peters +License: This software is provided as-is, without express or implied + warranty. Permission to use, copy, modify, distribute or sell this + software, without fee, for any purpose and by any individual or + organization, is hereby granted, provided that the above copyright + notice and this paragraph appear in all copies. + +Files: PC/_subprocess.c +Copyright: Copyright (c) 2004 by Fredrik Lundh + Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com + Copyright (c) 2004 by Peter Astrand +License: + * Permission to use, copy, modify, and distribute this software and + * its associated documentation for any purpose and without fee is + * hereby granted, provided that the above copyright notice appears in + * all copies, and that both that copyright notice and this permission + * notice appear in supporting documentation, and that the name of the + * authors not be used in advertising or publicity pertaining to + * distribution of the software without specific, written prior + * permission. + * + * THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION + * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Files: PC/winsound.c +Copyright: Copyright (c) 1999 Toby Dickenson +License: * Permission to use this software in any way is granted without + * fee, provided that the copyright notice above appears in all + * copies. This software is provided "as is" without any warranty. + */ + +/* Modified by Guido van Rossum */ +/* Beep added by Mark Hammond */ +/* Win9X Beep and platform identification added by Uncle Timmy */ --- python2.7-2.7.2.orig/debian/README.source +++ python2.7-2.7.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. --- python2.7-2.7.2.orig/debian/PVER-dbg.overrides.in +++ python2.7-2.7.2/debian/PVER-dbg.overrides.in @@ -0,0 +1,8 @@ +@PVER@-dbg binary: package-name-doesnt-match-sonames +@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink + +# no, it's not unusual +@PVER@-dbg binary: unusual-interpreter + +# just the gdb debug file +@PVER@-dbg binary: python-script-but-no-python-dep --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/idle-PVER.postrm.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/PVER.pycentral.in +++ python2.7-2.7.2/debian/PVER.pycentral.in @@ -0,0 +1,4 @@ +[@PVER@] +runtime: @PVER@ +interpreter: /usr/bin/@PVER@ +prefix: /usr/lib/@PVER@ --- python2.7-2.7.2.orig/debian/PVER.postinst.in +++ python2.7-2.7.2/debian/PVER.postinst.in @@ -0,0 +1,37 @@ +#! /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 + +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + + # Create empty directories in /usr/local + if [ ! -e /usr/local/lib/python@VER@ ]; then + mkdir -p /usr/local/lib/python@VER@ 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@ 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@ 2> /dev/null || true + fi + if [ ! -e /usr/local/lib/python@VER@/site-packages ]; then + mkdir -p /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chmod 2775 /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + chown root:staff /usr/local/lib/python@VER@/site-packages 2> /dev/null || true + fi + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python2.7-2.7.2.orig/debian/README.python +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/pdb.1.in +++ python2.7-2.7.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. --- python2.7-2.7.2.orig/debian/script.py +++ python2.7-2.7.2/debian/script.py @@ -0,0 +1,51 @@ +#! /usr/bin/python + +# Copyright (C) 2012 Colin Watson . +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +"""Trivial script(1) workalike, but without reading from standard input.""" + +import os +import pty +import select +import sys + +filename = sys.argv[1] +command = sys.argv[2] + +pid, master = pty.fork() +if pid == 0: # child + os.execlp("sh", "sh", "-c", command) + +# parent +with open(filename, "w") as logfile: + try: + while True: + rfds, _, _ = select.select([master], [], []) + if master in rfds: + data = os.read(master, 65536) + os.write(1, data) + logfile.write(data) + logfile.flush() + except (IOError, OSError): + pass + +os.close(master) --- python2.7-2.7.2.orig/debian/locale-gen +++ python2.7-2.7.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 <&2 + + 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) + dpkg -L @PVER@-minimal \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs rm -f >&2 + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# --- python2.7-2.7.2.orig/debian/idle.desktop.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/idle-PVER.overrides.in +++ python2.7-2.7.2/debian/idle-PVER.overrides.in @@ -0,0 +1,3 @@ +# icon in dependent package +idle-@PVER@ binary: menu-icon-missing +idle-@PVER@ binary: image-file-in-usr-lib --- python2.7-2.7.2.orig/debian/PVER-dbg.README.Debian.in +++ python2.7-2.7.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. --- python2.7-2.7.2.orig/debian/libPVER.overrides.in +++ python2.7-2.7.2/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python2.7-2.7.2.orig/debian/FAQ.html +++ python2.7-2.7.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
+ + --- python2.7-2.7.2.orig/debian/python-config.1 +++ python2.7-2.7.2/debian/python-config.1 @@ -0,0 +1,90 @@ +.TH PYTHON\-CONFIG 1 "November 27, 2011" +.SH NAME +python\-config \- output build options for python C/C++ extensions or embedding +.SH SYNOPSIS +.BI "python\-config" +[ +.BI "\-\-prefix" +] +[ +.BI "\-\-exec\-prefix" +] +[ +.BI "\-\-includes" +] +[ +.BI "\-\-libs" +] +[ +.BI "\-\-cflags" +] +[ +.BI "\-\-ldflags" +] +[ +.BI "\-\-help" +] +.SH DESCRIPTION +.B python\-config +helps compiling and linking programs, which embed the Python interpreter, or +extension modules that can be loaded dynamically (at run time) into +the interpreter. +.SH OPTIONS +.TP +.BI "\-\-cflags" +print the C compiler flags. +.TP +.BI "\-\-ldflags" +print the flags that should be passed to the linker. +.TP +.BI "\-\-includes" +similar to \fI\-\-cflags\fP but only with \-I options (path to python header files). +.TP +.BI "\-\-libs" +similar to \fI\-\-ldflags\fP but only with \-l options (used libraries). +.TP +.BI "\-\-prefix" +prints the prefix (base directory) under which python can be found. +.TP +.BI "\-\-exec\-prefix" +print the prefix used for executable program directories (such as bin, sbin, etc). +.TP +.BI "\-\-help" +print the usage message. +.PP + +.SH EXAMPLES +To build the singe\-file c program \fIprog\fP against the python library, use +.PP +.RS +gcc $(python\-config \-\-cflags \-\-ldflags) progr.cpp \-o progr.cpp +.RE +.PP +The same in a makefile: +.PP +.RS +CFLAGS+=$(shell python\-config \-\-cflags) +.RE +.RS +LDFLAGS+=$(shell python\-config \-\-ldflags) +.RE +.RS +all: progr +.RE + +To build a dynamically loadable python module, use +.PP +.RS +gcc $(python\-config \-\-cflags \-\-ldflags) \-shared \-fPIC progr.cpp \-o progr.so +.RE + +.SH "SEE ALSO" +python (1) +.br +http://docs.python.org/extending/extending.html +.br +/usr/share/doc/python/faq/extending.html + +.SH AUTHORS +This manual page was written by Johann Felix Soden +for the Debian project (and may be used by others). --- python2.7-2.7.2.orig/debian/libPVER.symbols.in +++ python2.7-2.7.2/debian/libPVER.symbols.in @@ -0,0 +1,3 @@ +libpython@VER@.so.1.0 libpython@VER@ #MINVER# + Py_InitModule4@Base @VER@ +#include "libpython.symbols" --- python2.7-2.7.2.orig/debian/rules +++ python2.7-2.7.2/debian/rules @@ -0,0 +1,1094 @@ +#!/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 LDFLAGS + +export SHELL = /bin/bash + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +vafilt = $(subst $(2)=,,$(filter $(2)=%,$(1))) + +DPKG_VARS := $(shell dpkg-architecture) +DEB_HOST_ARCH ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH) +DEB_HOST_ARCH_BITS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_BITS) +DEB_HOST_ARCH_OS ?= $(call vafilt,$(DPKG_VARS),DEB_HOST_ARCH_OS) + +changelog_values := $(shell dpkg-parsechangelog \ + | awk '/^(Version|Source):/ {print $$2}') +PKGSOURCE := $(word 1, $(changelog_values)) +PKGVERSION := $(word 2, $(changelog_values)) + +on_buildd := $(shell [ -f /CurrentlyBuilding -o "$$LOGNAME" = buildd ] && echo yes) + +ifneq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS))) + WITHOUT_CHECK := yes +endif +WITHOUT_BENCH := +ifneq (,$(findstring nobench, $(DEB_BUILD_OPTIONS))) + WITHOUT_BENCH := yes +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + WITHOUT_BENCH := disabled on $(DEB_HOST_ARCH) +endif +ifeq ($(on_buildd),yes) + ifneq (,$(findstring $(DEB_HOST_ARCH), hppa mips mipsel s390)) +# WITHOUT_CHECK := yes + endif +endif +WITHOUT_CHECK := 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 + +VER=2.7 +NVER=2.8 +PVER=python2.7 +PRIORITY=$(shell echo $(VER) | tr -d '.')0 + +PREVVER := $(shell awk '/^python/ && NR > 1 {print substr($$2,2,length($$2)-2); exit}' debian/changelog) + +# default versions are built from the python-defaults source package +# keep the definition to adjust package priorities. +DEFAULT_VERSION = 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_gdbm := no +with_interp := static +#with_interp := shared + +PY_INTERPRETER = /usr/bin/python$(VER) + +ifeq ($(DEFAULT_VERSION),yes) + PY_PRIO = standard + #PYSTDDEP = , python (>= $(VER)) + ifeq ($(distribution),Ubuntu) + PY_MINPRIO = required + else + PY_MINPRIO = $(PY_PRIO) + endif +else + PY_PRIO = optional + PY_MINPRIO = $(PY_PRIO) +endif +with_fpectl = yes + +CC = gcc + +DPKG_CFLAGS := $(shell dpkg-buildflags --get CFLAGS) +DPKG_LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) +OPT_CFLAGS := $(filter-out -O%,$(DPKG_CFLAGS)) # default is -O3 +DEBUG_CFLAGS := $(patsubst -O%,-O0,$(DPKG_CFLAGS)) + +# on alpha, use -O2 only, use -mieee +ifeq ($(DEB_HOST_ARCH),alpha) + OPT_CFLAGS += -mieee + DEBUG_CFLAGS += -mieee + EXTRA_OPT_FLAGS += -O2 +endif +# issues with ia64 and m68k with -O3 +ifeq ($(DEB_HOST_ARCH),m68k) + EXTRA_OPT_FLAGS += -O2 +endif + +ifeq ($(DEB_HOST_ARCH_OS),linux) + ifneq (,$(findstring $(DEB_HOST_ARCH), amd64 armel armhf i386 powerpc ppc64)) + with_pgo := yes + endif +endif + +ifneq (,$(findstring $(DEB_HOST_ARCH), amd64 armel armhf i386)) + with_lto := yes +endif + +ifneq (,$(findstring noopt, $(DEB_BUILD_OPTIONS))) + OPT_CFLAGS := $(filter-out -O%, $(OPT_CFLAGS)) + EXTRA_OPT_CFLAGS = -O0 + with_pgo = + with_lto = +endif + +ifeq ($(with_lto),yes) + EXTRA_OPT_CFLAGS += -g1 -flto -fuse-linker-plugin +endif + +make_build_target = $(if $(with_pgo),profile-opt) + +buildd_static := $(CURDIR)/build-static +buildd_shared := $(CURDIR)/build-shared +buildd_debug := $(CURDIR)/build-debug +buildd_shdebug := $(CURDIR)/build-shdebug + +d := debian/tmp +scriptdir = usr/share/lib/python$(VER) +scriptdir = usr/share/python$(VER) +scriptdir = usr/lib/python$(VER) + +# package names and directories +p_base := $(PVER) +p_min := $(PVER)-minimal +p_lib := lib$(PVER) +p_tk := $(PVER)-tk +p_gdbm := $(PVER)-gdbm +p_dev := $(PVER)-dev +p_exam := $(PVER)-examples +p_idle := idle-$(PVER) +p_doc := $(PVER)-doc +p_dbg := $(PVER)-dbg + +d_base := debian/$(p_base) +d_min := debian/$(p_min) +d_lib := debian/$(p_lib) +d_tk := debian/$(p_tk) +d_gdbm := debian/$(p_gdbm) +d_dev := debian/$(p_dev) +d_exam := debian/$(p_exam) +d_idle := debian/$(p_idle) +d_doc := debian/$(p_doc) +d_dbg := debian/$(p_dbg) + +build-arch: stamps/stamp-build +build-indep: stamps/stamp-build-doc +build: build-arch +stamps/stamp-build: stamps/stamp-build-static stamps/stamp-mincheck \ + stamps/stamp-build-shared stamps/stamp-build-debug \ + stamps/stamp-build-shared-debug \ + stamps/stamp-check stamps/stamp-pystone stamps/stamp-pybench + touch $@ + +PROFILE_EXCLUDES = test_compiler test_distutils test_platform test_subprocess \ + test_multiprocessing test_cprofile \ + test_thread test_threaded_import test_threadedtempfile \ + test_socketserver \ + test_threading test_threading_local test_threadsignals \ + test_dbm_dumb test_dbm_ndbm test_pydoc test_sundry test_gdb \ + +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel)) + PROFILE_EXCLUDES += test_float +endif +ifneq (,$(filter $(DEB_HOST_ARCH), kfreebsd-amd64 kfreebsd-i386)) + PROFILE_EXCLUDES += test_io +endif +PROFILE_EXCLUDES += test_zipfile +PROFILE_EXCLUDES += test_xmlrpc +PROFILE_EXCLUDES += test_bsddb3 + +PROFILE_TASK = ../Lib/test/regrtest.py \ + -x $(sort $(TEST_EXCLUDES) $(PROFILE_EXCLUDES)) + +stamps/stamp-build-static: stamps/stamp-configure-static + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_static) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" \ + PROFILE_TASK='$(PROFILE_TASK)' $(make_build_target) + touch stamps/stamp-build-static + +stamps/stamp-build-shared: stamps/stamp-configure-shared + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" +# : # build the shared library +# $(MAKE) $(NJOBS) -C $(buildd_shared) \ +# libpython$(VER).so + : # build a static library with PIC objects + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" \ + LIBRARY=libpython$(VER)-pic.a libpython$(VER)-pic.a + touch stamps/stamp-build-shared + +stamps/stamp-build-debug: stamps/stamp-configure-debug + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_debug) + EXTRA_CFLAGS="$(DEBUG_CFLAGS)" + touch stamps/stamp-build-debug + +stamps/stamp-build-shared-debug: stamps/stamp-configure-shared-debug + dh_testdir + : # build the shared debug library + $(MAKE) $(NJOBS) -C $(buildd_shdebug) \ + libpython$(VER)_d.so + touch stamps/stamp-build-shared-debug + +common_configure_args = \ + --prefix=/usr \ + --enable-ipv6 \ + --enable-unicode=ucs4 \ + --with-dbmliborder=bdb:gdbm \ + --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)" CFLAGS="$(OPT_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + ../configure \ + --enable-shared \ + $(common_configure_args) + + $(call __post_configure,$(buildd_shared)) + + touch stamps/stamp-configure-shared + +stamps/stamp-configure-static: stamps/stamp-patch + rm -rf $(buildd_static) + mkdir -p $(buildd_static) + cd $(buildd_static) && \ + CC="$(CC)" CFLAGS="$(OPT_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + ../configure \ + $(common_configure_args) + + $(call __post_configure,$(buildd_static)) + + touch stamps/stamp-configure-static + +stamps/stamp-configure-debug: stamps/stamp-patch + rm -rf $(buildd_debug) + mkdir -p $(buildd_debug) + cd $(buildd_debug) && \ + CC="$(CC)" CFLAGS="$(DEBUG_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + ../configure \ + $(common_configure_args) \ + --with-pydebug + + $(call __post_configure,$(buildd_debug)) + + touch stamps/stamp-configure-debug + +stamps/stamp-configure-shared-debug: stamps/stamp-patch + rm -rf $(buildd_shdebug) + mkdir -p $(buildd_shdebug) + cd $(buildd_shdebug) && \ + CC="$(CC)" CFLAGS="$(DEBUG_CFLAGS)" LDFLAGS="$(DPKG_LDFLAGS)" \ + ../configure \ + $(common_configure_args) \ + --enable-shared \ + --with-pydebug + + $(call __post_configure,$(buildd_shdebug)) + + touch stamps/stamp-configure-shared-debug + +define __post_configure + egrep \ + "^#($$(awk -v ORS='|' '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in)XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(1)/Modules/Setup.local + + : # unconditionally run makesetup + cd $(1) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(1)/config.c $(1)/Modules/ + + : # and fix the timestamps + $(MAKE) -C $(1) Makefile Modules/config.c + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(1)/pyconfig.h \ + > $(1)/pyconfig.h.new + touch -r $(1)/pyconfig.h $(1)/pyconfig.h.new + mv -f $(1)/pyconfig.h.new $(1)/pyconfig.h +endef + +stamps/stamp-mincheck: stamps/stamp-build-static debian/PVER-minimal.README.Debian.in + 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 = -w -l -u$(TEST_RESOURCES) +TEST_EXCLUDES = +ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_codecmaps_cn test_codecmaps_hk \ + test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw \ + test_normalization test_ossaudiodev + ifneq (,$(filter $(DEB_HOST_ARCH), mips mipsel powerpc kfreebsd-i386)) + TEST_EXCLUDES += test_threading + endif + ifeq (,$(wildcard $(HOME))) + TEST_EXCLUDES += test_site + endif +endif +ifeq (,$(wildcard /dev/dsp)) + TEST_EXCLUDES += test_linuxaudiodev test_ossaudiodev +endif +ifneq (,$(filter $(DEB_HOST_ARCH), armel hppa powerpc)) + TEST_EXCLUDES += test_multiprocessing +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hppa)) + TEST_EXCLUDES += test_fork1 test_socketserver test_threading test_wait3 test_wait4 test_gdb +endif +ifneq (,$(filter $(DEB_HOST_ARCH), arm avr32)) + TEST_EXCLUDES += test_ctypes +endif +ifneq (,$(filter $(DEB_HOST_ARCH), m68k avr32 kfreebsd-amd64 kfreebsd-i386)) + TEST_EXCLUDES += test_bsddb3 +endif +ifneq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 m68k)) + ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_compiler + endif +endif +TEST_EXCLUDES += test_gdb +ifneq (,$(filter $(DEB_HOST_ARCH), kfreebsd-amd64 kfreebsd-i386)) + TEST_EXCLUDES += test_io +endif +ifneq (,$(filter $(DEB_HOST_ARCH), hurd-i386)) + TEST_EXCLUDES += test_io test_random test_signal test_socketserver test_ssl test_threading +endif +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 ======================================== + + ifeq (,$(findstring $(DEB_HOST_ARCH), alpha)) + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test TESTOPTS="$(filter-out test_gdb,$(TESTOPTS))"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_debug)/run_tests + chmod 755 $(buildd_debug)/run_tests + @echo "BEGIN test debug" + -cd $(buildd_debug) && time xvfb-run -a -e xvfb-run.log ./run_tests + @echo "END test debug" + endif + + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo 'export $(SET_LOCPATH)'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" TESTOPTS="$(TESTOPTS)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_static)/run_tests + chmod 755 $(buildd_static)/run_tests + @echo "BEGIN test static" + -cd $(buildd_static) && time xvfb-run -a -e xvfb-run.log ./run_tests + @echo "END test static" + + ( \ + echo '#! /bin/sh'; \ + echo 'set -x'; \ + echo 'export TERM=$${TERM:-dumb}'; \ + echo 'export $(SET_LOCPATH)'; \ + echo '$(buildd_static)/python $(CURDIR)/debian/script.py test_results '\''make test EXTRA_CFLAGS="$(EXTRA_OPT_CFLAGS)" TESTOPTS="$(TESTOPTS)"'\'; \ + echo 'echo DONE'; \ + ) > $(buildd_shared)/run_tests + chmod 755 $(buildd_shared)/run_tests + @echo "BEGIN test shared" + -cd $(buildd_shared) && time xvfb-run -a -e xvfb-run.log ./run_tests + @echo "END test shared" +endif + cp -p $(buildd_static)/test_results debian/ + touch stamps/stamp-check + +stamps/stamp-pystone: + @echo "BEGIN pystone static" + cd $(buildd_static) && ./python ../Lib/test/pystone.py + cd $(buildd_static) && ./python ../Lib/test/pystone.py + @echo "END pystone static" + @echo "BEGIN pystone shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. ./python ../Lib/test/pystone.py + @echo "END pystone shared" + @echo "BEGIN pystone debug" + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + @echo "END pystone debug" + touch stamps/stamp-pystone + +#ifeq (,$(filter $(DEB_HOST_ARCH), arm armel avr32 hppa mips mipsel m68k)) + pybench_options = -C 2 -n 5 -w 4 +#endif + +stamps/stamp-pybench: +ifeq ($(WITHOUT_BENCH),yes) + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log +else + @echo "BEGIN pybench static" + cd $(buildd_static) \ + && time ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_static) \ + && ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench static" + @echo "BEGIN pybench shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. \ + ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}. \ + ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench shared" + @echo "BEGIN shared/static comparision" + $(buildd_static)/python Tools/pybench/pybench.py \ + -s $(buildd_static)/run2.pybench -c $(buildd_shared)/run2.pybench \ + | tee $(buildd_static)/pybench.log + @echo "END shared/static comparision" +endif + touch stamps/stamp-pybench + +minimal-test: + rm -rf mintest + mkdir -p mintest/lib mintest/dynlib mintest/testlib mintest/all-lib + cp -p $(buildd_static)/python mintest/ + cp -p $(foreach i,$(MIN_MODS),Lib/$(i).py) \ + mintest/lib/ + cp -a $(foreach i,$(MIN_PACKAGES),Lib/$(i)) \ + mintest/lib/ +# cp -p $(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 Lib/test/db_home + rm -rf $(buildd_static) $(buildd_shared) $(buildd_debug) $(buildd_shdebug) + find -name '*.py[co]' | xargs -r rm -f + rm -f Lib/lib2to3/*.pickle + rm -rf 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" \ + -e "s/@PRIORITY@/$(PRIORITY)/g" \ + -e "s,@SCRIPTDIR@,/$(scriptdir),g" \ + -e "s,@INFO@,$(info_docs),g" \ + <$$f >$$f2; \ + fi; \ + done +ifeq ($(DEB_HOST_ARCH_BITS),64) + sed -i 's/\(Py_InitModule4[^@]*\)@/\1_64@/' \ + debian/lib$(PVER).symbols debian/$(PVER)-dbg.symbols +endif + +2to3-man: + help2man --no-info --version-string=$(VER) --no-discard-stderr \ + --name 'Python2 to Python3 converter' \ + 2to3-$(VER) > debian/2to3-$(VER).1 + +install: build-arch stamps/stamp-install +stamps/stamp-install: stamps/stamp-build control-file stamps/stamp-control + dh_testdir + dh_testroot + dh_clean -k + dh_installdirs + + : # make install into tmp and subsequently move the files into + : # their packages' directories. + install -d $(d)/usr +ifeq ($(with_interp),static) + $(MAKE) -C $(buildd_static) install prefix=$(CURDIR)/$(d)/usr +else + $(MAKE) -C $(buildd_shared) install prefix=$(CURDIR)/$(d)/usr +endif + -find $(d)/usr/lib/python$(VER) -name '*_failed*.so' + find $(d)/usr/lib/python$(VER) -name '*_failed*.so' | xargs -r rm -f + + mv $(d)/usr/lib/python$(VER)/site-packages \ + $(d)/usr/lib/python$(VER)/dist-packages + + : # remove files, which are not packaged + rm -f $(d)/usr/bin/smtpd.py + rm -rf $(d)/usr/lib/python$(VER)/ctypes/macholib + rm -f $(d)/usr/lib/pkgconfig/python.pc + + : # fix some file permissions + chmod a-x $(d)/$(scriptdir)/{fractions,lib-tk/Tix}.py + + : # move manpages to new names + if [ -d $(d)/usr/man/man1 ]; then \ + mkdir -p $(d)/usr/share/man; \ + mv $(d)/usr/man/man1/* $(d)/usr/share/man/man1/; \ + rm -rf $(d)/usr/man/; \ + fi + cp -p debian/pydoc.1 $(d)/usr/share/man/man1/pydoc$(VER).1 + + : # Symlinks to /usr/bin for some tools + ln -sf ../lib/python$(VER)/pdb.py $(d)/usr/bin/pdb$(VER) + cp -p debian/pdb.1 $(d)/usr/share/man/man1/pdb$(VER).1 + + : # versioned install only + rm -f $(d)/usr/bin/python-config + + mv $(d)/usr/bin/2to3 $(d)/usr/bin/2to3-$(VER) + cp debian/2to3-$(VER).1 $(d)/usr/share/man/man1/2to3-$(VER).1 + +# : # remove the bsddb stuff +# rm -rf $(d)/$(scriptdir)/bsddb +# rm -f $(d)/$(scriptdir)/lib-dynload/_bsddb.so + + : # Remove version information from the egg-info file + mv $(d)/$(scriptdir)/lib-dynload/Python-$(VER)*.egg-info \ + $(d)/$(scriptdir)/lib-dynload/Python-$(VER).egg-info + + dh_installdirs -p$(p_lib) \ + $(scriptdir)/config \ + usr/share/doc + : # install the shared library + cp -p $(buildd_shared)/libpython$(VER).so.1.0 $(d_lib)/usr/lib/ + ln -sf libpython$(VER).so.1.0 $(d_lib)/usr/lib/libpython$(VER).so.1 + ln -sf ../../libpython$(VER).so.1 \ + $(d_lib)/$(scriptdir)/config/libpython$(VER).so + ln -sf $(p_base) $(d_lib)/usr/share/doc/$(p_lib) + + ln -sf libpython$(VER).so.1 $(d)/usr/lib/libpython$(VER).so + +ifeq ($(with_interp),shared) + : # install the statically linked runtime + install -m755 $(buildd_static)/python $(d)/usr/bin/python$(VER)-static +endif + + mv $(d)/usr/bin/pydoc $(d)/usr/bin/pydoc$(VER) + cp -p Tools/i18n/pygettext.py $(d)/usr/bin/pygettext$(VER) + cp -p debian/pygettext.1 $(d)/usr/share/man/man1/pygettext$(VER).1 + + : # install the Makefile of the shared python build + sed -e '/^OPT/s,-O3,-O2,' \ + -e 's,^RUNSHARED *=.*,RUNSHARED=,' \ + build-shared/Makefile > $(d)/$(scriptdir)/config/Makefile + + : # Move the binary and the minimal libraries into $(p_min). + dh_installdirs -p$(p_min) \ + etc/$(PVER) \ + usr/bin \ + usr/include/$(PVER) \ + usr/share/man/man1 \ + $(scriptdir)/lib-dynload \ + $(scriptdir)/config + DH_COMPAT=2 dh_movefiles -p$(p_min) --sourcedir=$(d) \ + usr/bin/python$(VER) \ + 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/Makefile \ + usr/include/$(PVER)/pyconfig.h \ + $(scriptdir)/site.py + +# $(foreach i,$(MIN_EXTS),$(scriptdir)/lib-dynload/$(i).so) \ + + : # Install sitecustomize.py. + cp -p debian/sitecustomize.py $(d_min)/etc/$(PVER)/ + patch --no-backup -d $(d_min)/$(scriptdir) < debian/patches/site-builddir.diff + 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/share/man/man1 \ + 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 \ + usr/include/python$(VER) \ + usr/lib/libpython$(VER).so \ + usr/lib/libpython$(VER).a \ + usr/lib/pkgconfig/python-$(VER).pc \ + usr/bin/python$(VER)-config \ + usr/lib/python$(VER)/distutils/command/wininst-*.exe + + ln -sf config/libpython$(VER).a \ + $(d_dev)/usr/lib/libpython$(VER).a + + cp -p debian/python-config.1 \ + $(d_dev)/usr/share/man/man1/python$(VER)-config.1 + cp -p $(buildd_shared)/libpython$(VER)-pic.a \ + $(d_dev)/usr/lib/python$(VER)/config/ + +ifeq ($(with_tk),yes) + : # Move the Tkinter files into $(p_tk). + dh_installdirs -p$(p_tk) \ + $(scriptdir) \ + usr/lib/python$(VER)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_tk) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/_tkinter.so +endif + +ifeq ($(with_gdbm),yes) + : # gdbm and dbm modules into $(p_gdbm). + dh_installdirs -p$(p_gdbm) \ + usr/lib/python$(VER)/lib-dynload + DH_COMPAT=2 dh_movefiles -p$(p_gdbm) --sourcedir=$(d) \ + usr/lib/python$(VER)/lib-dynload/gdbm.so +endif + +# : # The test framework into $(p_base), regression tests dropped + DH_COMPAT=2 dh_movefiles -p$(p_base) --sourcedir=$(d) \ + $(scriptdir)/test/{regrtest.py,test_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)/email/test + rm -rf $(d)/$(scriptdir)/json/tests + rm -rf $(d)/$(scriptdir)/sqlite3/test + rm -rf $(d)/$(scriptdir)/distutils/tests + rm -rf $(d)/$(scriptdir)/lib2to3/tests + rm -rf $(d)/$(scriptdir)/unittest/test + rm -rf $(d)/$(scriptdir)/lib-tk/test + + : # IDLE + mv $(d)/usr/bin/idle $(d)/usr/bin/idle-python$(VER) + rm -f $(d)/usr/lib/python$(VER)/idlelib/idle.bat + dh_installdirs -p$(p_idle) \ + usr/bin \ + usr/share/man/man1 + DH_COMPAT=2 dh_movefiles -p$(p_idle) \ + usr/lib/python$(VER)/idlelib \ + usr/bin/idle-python$(VER) + cp -p debian/idle-$(PVER).1 $(d_idle)/usr/share/man/man1/ + + : # Move the demos and tools into $(p_exam)'s doc directory + dh_installdirs -p$(p_exam) \ + usr/share/doc/python$(VER)/examples + + cp -rp Demo Tools $(d_exam)/usr/share/doc/python$(VER)/examples/ + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Demo/sgi + : # IDLE is in its own package: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/idle + : # XXX: We don't need rgb.txt, we'll use our own: + rm -rf $(d_exam)/usr/share/doc/python$(VER)/examples/Tools/pynche/X + + : # XXX: Some files in upstream Demo and Tools have strange + : # exec permissions, make lintian glad: + -chmod 644 $(d_tk)/$(scriptdir)/lib-tk/Tix.py + -chmod 644 $(d)/$(scriptdir)/runpy.py + + cd $(d_exam)/usr/share/doc/python$(VER)/examples && chmod 644 \ + Demo/{classes/*.py*,comparisons/patterns} \ + Demo/{rpc/test,threads/*.py*,md5test/*} \ + Demo/pdist/{client.py,cmdfw.py,cmptree.py,cvslib.py,cvslock.py,FSProxy.py,mac.py,rcsclient.py,rcslib.py,security.py,server.py,sumtree.py} \ + Demo/scripts/{morse.py,newslist.doc} \ + Demo/sockets/{broadcast.py,ftp.py,mcast.py,radio.py} \ + Demo/tix/{bitmaps/{tix.gif,*x[pb]m*},samples/*.py} \ + Demo/tkinter/guido/{AttrDialog.py,hanoi.py,hello.py,imagedraw.py,imageview.py,listtree.py,ManPage.py,ShellWindow.py,wish.py} \ + Tools/scripts/pydocgui.pyw \ + Tools/scripts/mailerdaemon.py + + : # Replace all '#!' calls to python with $(PY_INTERPRETER) + : # and make them executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch'`; do \ + sed '1s,#!.*python[^ ]*\(.*\),#! $(PY_INTERPRETER)\1,' \ + $$i > $$i.temp; \ + if cmp --quiet $$i $$i.temp; then \ + rm -f $$i.temp; \ + else \ + mv -f $$i.temp $$i; \ + chmod 755 $$i; \ + echo "fixed interpreter: $$i"; \ + fi; \ + done + + : # Move the docs into $(p_base)'s /usr/share/doc/$(PVER) directory, + : # all other packages only have a copyright file. + dh_installdocs -p$(p_base) \ + README Misc/NEWS Misc/ACKS + ln -sf NEWS.gz $(d_base)/usr/share/doc/$(p_base)/changelog.gz + dh_installdocs --all -N$(p_base) -N$(p_dev) -N$(p_dbg) -N$(p_lib) debian/README.Debian + + : # IDLE has its own changelogs, docs... + dh_installchangelogs -p$(p_idle) Lib/idlelib/ChangeLog + dh_installdocs -p$(p_idle) Lib/idlelib/{NEWS,README,TODO,extend}.txt + + mkdir -p $(d_idle)/usr/share/applications + cp -p debian/idle.desktop \ + $(d_idle)/usr/share/applications/idle-$(PVER).desktop + + : # those packages have own README.Debian's + install -m 644 -p debian/README.$(p_base) \ + $(d_base)/usr/share/doc/$(PVER)/README.Debian + install -m 644 -p debian/README.$(p_idle) \ + $(d_idle)/usr/share/doc/$(p_idle)/README.Debian +ifeq ($(with_tk),yes) + cp -p debian/README.Tk $(d_tk)/usr/share/doc/$(p_tk)/ +endif + + : # The rest goes into $(p_base) + mkdir -p $(d)/usr/lib/python$(VER)/dist-packages + (cd $(d) && tar cf - .) | (cd $(d_base) && tar xpf -) + sh debian/dh_rmemptydirs -p$(p_base) + rm -f $(d_base)/usr/bin/python + + : # install egg-info for arparse + install -m 644 debian/argparse.egg-info $(d_base)/$(scriptdir)/ + + : # Install menu icon + dh_installdirs -p$(p_base) usr/share/pixmaps + cp -p debian/pylogo.xpm $(d_base)/usr/share/pixmaps/$(PVER).xpm + + : # generate binfmt file + mkdir -p $(d_min)/usr/share/binfmts + $(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 -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)_d \ + 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)-dbg + sed '1s,#!.*python[^ ]*\(.*\),#! $(PY_INTERPRETER)-dbg\1,' \ + $(d)-dbg/usr/bin/$(PVER)-config \ + > $(d_dbg)/usr/bin/$(PVER)-dbg-config + chmod 755 $(d_dbg)/usr/bin/$(PVER)-dbg-config + cp -p $(buildd_debug)/build/lib*/*_d.so \ + $(d_dbg)/$(scriptdir)/lib-dynload/ + cp -p $(buildd_shdebug)/libpython$(VER)_d.so.1.0 $(d_dbg)/usr/lib/ + ln -sf libpython$(VER)_d.so.1.0 $(d_dbg)/usr/lib/libpython$(VER)_d.so.1 + ln -sf libpython$(VER)_d.so.1 $(d_dbg)/usr/lib/libpython$(VER)_d.so + sed -e '/^Libs:/s,-lpython$(VER),-lpython$(VER)_d,' \ + -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_gdbm),yes) + rm -f $(d_dbg)/$(scriptdir)/lib-dynload/gdbm_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/gdbm.so +endif +ifneq ($(with_tk),yes) + rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_tkinter_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_tkinter.so +endif +# rm -f $(d_dbg)/$(scriptdir)/lib-dynload/_bsddb_d.so + + cp -a $(d)-dbg/$(scriptdir)/config_d $(d_dbg)/$(scriptdir)/ + ln -sf ../../libpython$(VER)_d.so \ + $(d_dbg)/$(scriptdir)/config_d/libpython$(VER)_d.so + ln -sf libpython$(VER)_d.so \ + $(d_dbg)/$(scriptdir)/config_d/libpython$(VER).so + ln -sf libpython$(VER)_d.a \ + $(d_dbg)/$(scriptdir)/config_d/libpython$(VER).a + + for i in $(d_dev)/usr/include/$(PVER)/*; do \ + i=$$(basename $$i); \ + case $$i in pyconfig.h) continue; esac; \ + ln -sf ../$(PVER)/$$i $(d_dbg)/usr/include/$(PVER)_d/$$i; \ + done + cp -p $(buildd_debug)/pyconfig.h $(d_dbg)/usr/include/$(PVER)_d/ + ln -sf $(PVER).1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg.1.gz + ln -sf $(PVER)-config.1.gz $(d_dbg)/usr/share/man/man1/$(PVER)-dbg-config.1.gz + + for i in debian/*.overrides; do \ + b=$$(basename $$i .overrides); \ + install -D -m 644 $$i debian/$$b/usr/share/lintian/overrides/$$b; \ + done + + touch stamps/stamp-install + +# Build architecture-independent files here. +binary-indep: build-indep install stamps/stamp-control + dh_testdir -i + dh_testroot -i + + : # $(p_doc) package + dh_installdirs -p$(p_doc) \ + usr/share/doc/$(p_base) \ + usr/share/doc/$(p_doc) + dh_installdocs -p$(p_doc) + cp -a Doc/build/html $(d_doc)/usr/share/doc/$(p_base)/ + rm -f $(d_doc)/usr/share/doc/$(p_base)/html/_static/jquery.js + 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-arch install + dh_testdir -a + dh_testroot -a +# dh_installdebconf -a + dh_installexamples -a + dh_installmenu -a + -dh_icons -a || dh_iconcache -a +# dh_installmime -a + dh_installchangelogs -a + for i in $(p_dev) $(p_dbg) $(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)-gdb.py + ln -sf $(PVER)-gdb.py $(d_dbg)/usr/lib/debug/usr/bin/$(PVER)-dbg-gdb.py + ln -sf ../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/lib/debug/usr/lib/lib$(PVER).so.1.0-gdb.py + ln -sf ../bin/$(PVER)-gdb.py \ + $(d_dbg)/usr/lib/lib$(PVER)_d.so.1.0-gdb.py + dh_link -a + dh_compress -a -X.py + dh_fixperms -a + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + + dh_makeshlibs -p$(p_lib) -V '$(p_lib)' + dh_makeshlibs -p$(p_dbg) -V '$(p_dbg)' +# don't include the following symbols, found in extensions +# which either can be built as builtin or extension. + sed -ri '/^ (_check_|asdl_|fast_save_|init)/d' \ + $(d_lib)/DEBIAN/symbols $(d_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) + +$(patchdir)/series: $(patchdir)/series.in + cpp -E \ + -D$(distribution) \ + $(if $(filter $(broken_utimes),yes),-DBROKEN_UTIMES) \ + $(if $(filter $(with_fpectl),yes),-DWITH_FPECTL) \ + -Darch_os_$(DEB_HOST_ARCH_OS) -Darch_$(DEB_HOST_ARCH) \ + -o - $(patchdir)/series.in \ + | egrep -v '^(#.*|$$)' > $(patchdir)/series + +patch: stamps/stamp-patch +stamps/stamp-patch: $(patchdir)/series + dh_testdir + 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: --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-doc.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/changelog.shared +++ python2.7-2.7.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%. --- python2.7-2.7.2.orig/debian/source.lintian-overrides +++ python2.7-2.7.2/debian/source.lintian-overrides @@ -0,0 +1,5 @@ +# this is conditional in the rules file +python2.7 source: debhelper-script-needs-versioned-build-depends dh_icons (>= 5.0.51~) + +# generated during the build +python2.7 source: quilt-build-dep-but-no-series-file --- python2.7-2.7.2.orig/debian/PVER.prerm.in +++ python2.7-2.7.2/debian/PVER.prerm.in @@ -0,0 +1,27 @@ +#! /bin/sh -e +# +# prerm script for the Debian @PVER@-base package. +# Written 1998 by Gregor Hoffleit . +# + +case "$1" in + remove|upgrade) + dpkg -L @PVER@ \ + | awk '/\.py$/ {print $0"c\n" $0"o"}' \ + | xargs rm -f >&2 + ;; + deconfigure) + ;; + failed-upgrade) + ;; + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +rmdir /usr/local/lib/python@VER@/site-packages 2>/dev/null && \ + rmdir /usr/local/lib/python@VER@ 2>/dev/null || \ + true + +#DEBHELPER# --- python2.7-2.7.2.orig/debian/control.in +++ python2.7-2.7.2/debian/control.in @@ -0,0 +1,110 @@ +Source: @PVER@ +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5), quilt, autoconf, libreadline-dev, libtinfo-dev, libncursesw5-dev (>= 5.3), tk8.5-dev, zlib1g-dev, blt-dev (>= 2.4z), libssl-dev, libexpat1-dev, sharutils, libbz2-dev, libbluetooth-dev [linux-any], locales [!armel !avr32 !hppa !ia64 !mipsel], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [linux-any], netbase, lsb-release, bzip2, libdb5.1-dev, libgdbm-dev, gdb, python, help2man, xvfb, xauth +Build-Depends-Indep: python-sphinx +Build-Conflicts: tcl8.4-dev, tk8.4-dev, @PVER@-xml, python-xml, autoconf2.13, python-cxx-dev +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: @PVER@-cjkcodecs, @PVER@-ctypes, @PVER@-elementtree, @PVER@-celementtree, @PVER@-wsgiref, @PVER@-profiler, @PVER@-argparse +Conflicts: python-profiler (<= 2.7.1-2) +Replaces: python-profiler (<= 2.7.1-2) +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@ (<< 2.7.1~rc1-2~) +Conflicts: binfmt-support (<< 1.1.2) +Description: Minimal subset of the Python language (version @VER@) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/@PVER@-minimal/README.Debian for a list of the modules + contained in this package. + +Package: lib@PVER@ +Architecture: any +Section: libs +Priority: optional +Depends: @PVER@ (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 2.6) +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}), libexpat1-dev, libssl-dev, ${shlibs:Depends}, ${misc:Depends} +Recommends: libc6-dev | libc-dev +Replaces: @PVER@ (<< 2.7-3) +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-@PVER@ +Architecture: all +Depends: @PVER@, python-tk (>= 2.6~a3), @PVER@-tk, ${misc:Depends} +Enhances: @PVER@ +Replaces: @PVER@ (<< 2.6.1-2) +Description: IDE for Python (v@VER@) using Tkinter + IDLE is an Integrated Development Environment for Python (v@VER@). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: @PVER@-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: @PVER@ +Description: Documentation for the high-level object-oriented language Python (v@VER@) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v@VER@). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python@VER@ + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: @PVER@-dbg +Section: debug +Architecture: any +Priority: extra +Depends: @PVER@ (>= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python-gdbm-dbg, python-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. --- python2.7-2.7.2.orig/debian/PVER-examples.overrides.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/idle-PVER.postinst.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/README.maintainers.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/dh_rmemptydirs +++ python2.7-2.7.2/debian/dh_rmemptydirs @@ -0,0 +1,10 @@ +#! /bin/sh -e + +pkg=`echo $1 | sed 's/^-p//'` + +: # remove empty directories, when all components are in place +for d in `find debian/$pkg -depth -type d -empty 2> /dev/null`; do \ + while rmdir $$d 2> /dev/null; do d=`dirname $$d`; done; \ +done + +exit 0 --- python2.7-2.7.2.orig/debian/control.stdlib +++ python2.7-2.7.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. + --- python2.7-2.7.2.orig/debian/depgraph.py +++ python2.7-2.7.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() + + + --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/changelog +++ python2.7-2.7.2/debian/changelog @@ -0,0 +1,2604 @@ +python2.7 (2.7.2-13ubuntu5) precise; urgency=low + + * Update to 20120216, taken from the 2.7 branch. + * Install an egg-info file for arparse. + + -- Matthias Klose Thu, 16 Feb 2012 17:33:01 +0100 + +python2.7 (2.7.2-13ubuntu4) precise; urgency=low + + * Really apply the db5.1 patch. LP: #440889 (why is such an old and + unrelated issue number used?). + + -- Matthias Klose Sat, 21 Jan 2012 23:09:45 +0100 + +python2.7 (2.7.2-13ubuntu2) precise; urgency=low + + * Stop providing python-argparse. LP: #916188. + + -- Matthias Klose Fri, 20 Jan 2012 19:13:15 +0100 + +python2.7 (2.7.2-13ubuntu1) precise; urgency=low + + * Build using libdb5.1. + + -- Matthias Klose Fri, 20 Jan 2012 18:05:34 +0100 + +python2.7 (2.7.2-13) unstable; urgency=low + + * Update to 20120120, taken from the 2.7 branch. + * Remove patch integrated upstream (issue9054.diff). + * Backport Issue #9189 to distutils/sysconfig.py as well. + Closes: #656118. + * Disable test_io on kfreebsd again. Closes: #654783. + * Disable test_bsddb3 tests on kfreebsd again. + + -- Matthias Klose Fri, 20 Jan 2012 16:33:47 +0100 + +python2.7 (2.7.2-12) unstable; urgency=low + + * Run the tests with a script command which doesn't exit immediatly + when stdin is /dev/null (Colin Watson). + + -- Matthias Klose Fri, 13 Jan 2012 11:04:31 +0100 + +python2.7 (2.7.2-11ubuntu1) precise; urgency=low + + * Upload to precise. + + -- Matthias Klose Wed, 11 Jan 2012 16:54:55 +0100 + +python2.7 (2.7.2-11) unstable; urgency=low + + * Don't run the test_site tests when $HOME doesn't exist. + + -- Matthias Klose Wed, 11 Jan 2012 09:19:00 +0100 + +python2.7 (2.7.2-10) unstable; urgency=low + + * Update to 20120110, taken from the 2.7 branch. + * Overwrite some lintian warnings: + - The -dbg interpreters are not unusual. + - The -gdb.py files don't need a python dependency. + - lintian can't handle a whatis entry starting with one word on the line. + * Fix test failures related to distutils debian installation layout. + * Add build-arch/build-indep targets. + * Regenerate Setup and Makefiles after correcting Setup.local. + * profiled-build.diff: Pass PY_CFLAGS instead of CFLAGS for the profiled + build. + * Pass dpkg-buildflags to the build process, and build third party + extensions with these flags. + * Add support to build using -flto (and -g1) on some architectures. + * Disable pgo builds for some architectures (for now, keep just + amd64 armel armhf i386 powerpc ppc64). + * Build-depend on libgdbm-dev to build and run the gdbm tests. + * Build-depend on xvfb to run the tkinter tests. + * python2.7: Provide python2.7-argparse and python-argparse. + * Don't run test_threading on mips/mipsel. + * Run the test_gdb test for the debug build only. + * Add build conflict to python-cxx-dev (pydoc test failures). + * Disable test_ssl certificate check, certificate expired on python.org. + + -- Matthias Klose Tue, 10 Jan 2012 16:44:56 +0100 + +python2.7 (2.7.2-9) unstable; urgency=low + + * Update to 20111217, taken from the 2.7 branch. + + -- Matthias Klose Sat, 17 Dec 2011 17:36:27 +0100 + +python2.7 (2.7.2-8) unstable; urgency=low + + * Update to 20111130, taken from the 2.7 branch. + * New patch, ctypes-arm, allow for ",hard-float" after libc6 in ldconfig -p + output (Loic Minier). LP: #898172. + * debian/rules: Define DPKG_VARS (Alban Browaeys). Closes: #647419). + * Add python-config man page (Johann Felix Soden). Closes: #650181). + + -- Matthias Klose Wed, 30 Nov 2011 19:16:23 +0100 + +python2.7 (2.7.2-7) unstable; urgency=low + + * Adjust patches for removed Lib/plat-linux3. + * Add build conflict to libncurses5-dev, let configure search for + ncurses headers in /usr/include/ncursesw too. + + -- Matthias Klose Wed, 05 Oct 2011 11:30:16 +0200 + +python2.7 (2.7.2-6) unstable; urgency=low + + * Update to 20111004, taken from the 2.7 branch. + * Use the ncursesw include directory when linking with ncursesw. + * Rebuild with libreadline not linked with libncurses*. Closes: #643816. + * Fix typos in the multiprocessing module. Closes: #643856. + + -- Matthias Klose Tue, 04 Oct 2011 16:09:29 +0200 + +python2.7 (2.7.2-5) unstable; urgency=low + + * Update to 20110816, taken from the 2.7 branch. + - Fix issue#12752. LP: #824734. + * Don't run test_threading on the kfreebsd-i386 buildd. + + -- Matthias Klose Tue, 16 Aug 2011 08:33:31 +0200 + +python2.7 (2.7.2-4) unstable; urgency=low + + * Update to 20110803, taken from the 2.7 branch. + * Fix build on s390x. Closes: #636033. + * Use linux-any for some build dependencies. Closes: #634809. + * Revert previous change to treat Linux 3.x as Linux 2. Use the + plat-linux3 directory instead. + + -- Matthias Klose Wed, 03 Aug 2011 12:36:05 +0200 + +python2.7 (2.7.2-3) unstable; urgency=low + + * Update to 20110709, taken from the 2.7 branch. + * Make the conflict against python-profiler a versioned conflict. + * Don't run the bsddb3 tests on kfreebsd-i386. + * Don't add the bsddb multilib path, if already in the standard lib path. + * Treat Linux 3.x as Linux 2. Closes: #633015. + * Assume working semaphores on Linux, don't rely on running kernel + for the check. Closes: #631188. + + -- Matthias Klose Sat, 09 Jul 2011 13:19:47 +0200 + +python2.7 (2.7.2-2) unstable; urgency=low + + * Update to 20110628, taken from the 2.7 branch. + * Add profile/pstats to the python2.7 package, update debian copyright. + * Don't run the bsddb3 tests on kfreebsd-amd64. + * Don't run the benchmark on hurd-i386. + + -- Matthias Klose Tue, 28 Jun 2011 23:05:21 +0200 + +python2.7 (2.7.2-1) unstable; urgency=low + + * Python 2.7.2 release. + + -- Matthias Klose Sun, 12 Jun 2011 21:04:24 +0200 + +python2.7 (2.7.2~rc1-2) unstable; urgency=medium + + * Set pyexpat dummy version string. + + -- Matthias Klose Tue, 31 May 2011 12:05:56 +0200 + +python2.7 (2.7.2~rc1-1) unstable; urgency=low + + * Python 2.7.2 release candidate 1. + * Update libpython symbols file for m68k (Thorsten Glaser). Closes: #627458. + * Apply proposed patch for issue #670664. LP: #357067. + + -- Matthias Klose Mon, 30 May 2011 06:44:23 +0200 + +python2.7 (2.7.1-9) unstable; urgency=low + + * Update to 20110520, taken from the 2.7 branch. + + -- Matthias Klose Fri, 20 May 2011 13:43:12 +0200 + +python2.7 (2.7.1-8) unstable; urgency=low + + * Keep the ssl.PROTOCOL_SSLv2 module constant , just raise an exception + when trying to create a PySSL object. Closes: #623423. + + -- Matthias Klose Wed, 20 Apr 2011 12:31:03 +0200 + +python2.7 (2.7.1-7) unstable; urgency=low + + * Update to 20110419, taken from the 2.7 branch. + * Build without OpenSSL v2 support. Closes: #620581. + * Force linking the curses module against libncursesw. Closes: #622064. + * Link libpython with --whole-archive. Closes: #614711. + * Re-enable running the testsuite during the build. + + -- Matthias Klose Tue, 19 Apr 2011 17:36:56 +0200 + +python2.7 (2.7.1-6) unstable; urgency=low + + * Update to 20110307, taken from the 2.7 branch. + * Disable the profile guided build on ia64, sparc. + + -- Matthias Klose Mon, 07 Mar 2011 02:19:02 +0100 + +python2.7 (2.7.1-5) experimental; urgency=low + + * Update to 20110224, taken from the 2.7 branch. + * Update patches. + * Re-enable profile guided build. + + -- Matthias Klose Thu, 24 Feb 2011 06:01:42 +0100 + +python2.7 (2.7.1-4) experimental; urgency=low + + * Update to 20110119, taken from the 2.7 branch. + + -- Matthias Klose Wed, 19 Jan 2011 04:21:14 +0100 + +python2.7 (2.7.1-3) experimental; urgency=low + + * Do not run test_multiprocessing when running the testsuite. + Fails on armel and powerpc on some buildds. + + -- Matthias Klose Fri, 24 Dec 2010 01:46:55 +0100 + +python2.7 (2.7.1-2) experimental; urgency=low + + * Update to 20101222, taken from the 2.7 branch. + * Re-enable the distutils-sysconfig.diff patch, apparently + lost when updating the patches for 2.7. + * Disable the profiled builds on all architectures. + + -- Matthias Klose Wed, 22 Dec 2010 15:39:48 +0100 + +python2.7 (2.7.1-1) experimental; urgency=low + + * Python 2.7.1 release. + + -- Matthias Klose Sun, 28 Nov 2010 12:05:23 +0100 + +python2.7 (2.7.1~rc1-2) experimental; urgency=low + + * Move the pyconfig.h file into the -min package, required by sysconfig. + Closes: #603237. + + -- Matthias Klose Sun, 14 Nov 2010 09:40:09 +0100 + +python2.7 (2.7.1~rc1-1) experimental; urgency=low + + * Python 2.7.1 release candidate 1. + * Move the Makefile into the -min package, required by sysconfig. + Closes: #603237. + + -- Matthias Klose Sun, 14 Nov 2010 00:33:48 +0100 + +python2.7 (2.7-9) experimental; urgency=low + + * Update to 20101016, taken from the 2.7 branch. + + -- Matthias Klose Sat, 16 Oct 2010 12:46:57 +0200 + +python2.7 (2.7-8) experimental; urgency=low + + * Disabled the profiled build on armel. + + -- Matthias Klose Thu, 23 Sep 2010 15:06:06 +0200 + +python2.7 (2.7-7) experimental; urgency=low + + * Update to 20100922, taken from the 2.7 branch. + * Update GNU/Hurd patches (Pino Toscano). Closes: #597419. + + -- Matthias Klose Wed, 22 Sep 2010 20:35:24 +0200 + +python2.7 (2.7-6) experimental; urgency=low + + * Update to 20100915, taken from the 2.7 branch. + - Fix issue #9729, Unconnected SSLSocket.{send,recv} raises TypeError + (Andrew Bennetts). LP: #637821. + * Add copyright information for expat, libffi and zlib. Addresses: #596276. + * Apply proposed fix for issue 9054, configure --with-system-expat. + * Provide Lib/plat-gnukfreebsd[78] (Jakub Wilk). Addresses: #593818. + + -- Matthias Klose Wed, 15 Sep 2010 17:43:18 +0200 + +python2.7 (2.7-5) experimental; urgency=low + + * Update to 20100829, taken from the 2.7 branch. + * Don't configure --with-system-expat, segfaults the interpreter in the + testsuite. + * Disable more tests on hppa and hurd-i386, which fail on the buildds. + + -- Matthias Klose Sun, 29 Aug 2010 16:22:37 +0200 + +python2.7 (2.7-4) experimental; urgency=low + + * Update to 20100822, taken from the 2.7 branch. + * Fixed in previous 2.7 uploads: Multiple integer overflows in audioop.c + in the audioop module (CVE-2010-1634). + * Fix some lintian warnings. + * Configure --with-system-expat. + + -- Matthias Klose Mon, 23 Aug 2010 13:03:40 +0200 + +python2.7 (2.7-3) experimental; urgency=low + + * Update to 20100807, taken from the 2.7 branch. + * Move '/usr/local/.../dist-packages' before '/usr/lib/.../dist-packages' + in sys.path. Adresses: #588342. + * Fix detection of ffi.h header file. Closes: #591408. + * python2-7-dev: Depend on libssl-dev. LP: #611845. + + -- Matthias Klose Sat, 07 Aug 2010 21:28:04 +0200 + +python2.7 (2.7-2) experimental; urgency=low + + * Complete debug-build.diff, some parts lost in quilt conversion. + * Move the pkgconfig file into the -dev package. + + -- Matthias Klose Tue, 06 Jul 2010 21:07:48 +0200 + +python2.7 (2.7-1) experimental; urgency=low + + * Python 2.7 release. + * Update to 20100706, taken from the trunk. + * Update symbols files. + + -- Matthias Klose Tue, 06 Jul 2010 07:21:23 +0200 + +python2.7 (2.7~rc2-3) experimental; urgency=low + + * Update to 20100703, taken from the trunk. + * Move the _weakrefset module, not extension to -minimal. Closes: #587568. + * Move the sysconfig module to -minimal. Closes: #586113. + * Move the shutil module to python2.6-minimal. Addresses: #587628. + + -- Matthias Klose Sat, 03 Jul 2010 13:27:36 +0200 + +python2.7 (2.7~rc2-2) experimental; urgency=low + + * Fix applying plat-linux2* patches. + * Use the profiled build on armel, sparc and sparc64. + + -- Matthias Klose Tue, 29 Jun 2010 08:04:59 +0200 + +python2.7 (2.7~rc2-1) experimental; urgency=low + + * Python 2.7 release candidate 2. + * Update to 20100628, taken from the trunk. + * Merge packaging changes from python2.6 (2.6.5+20100628-1). + + -- Matthias Klose Tue, 29 Jun 2010 00:57:00 +0200 + +python2.7 (2.7~b1-2) experimental; urgency=low + + * Update to 20100508, taken from the trunk. + + -- Matthias Klose Sat, 08 May 2010 17:34:07 +0200 + +python2.7 (2.7~b1-1) experimental; urgency=low + + * Python 2.7 beta1. + * Update to 20100420, taken from the trunk. + * Update libpython symbols files. + * Apply proposed patch for issue #7332, segfaults in + PyMarshal_ReadLastObjectFromFile in import_submodule. + * Don't build-depend on locales on avr32. Closes: #575144. + + -- Matthias Klose Tue, 20 Apr 2010 23:53:42 +0200 + +python2.7 (2.7~a4-1) experimental; urgency=low + + * Python 2.7 alpha4. + * Update to 20100316, taken from the trunk. + * Point distutils.sysconfig to the system installation. Closes: #573363. + + -- Matthias Klose Tue, 16 Mar 2010 15:45:07 +0100 + +python2.7 (2.7~a3-1) experimental; urgency=low + + * Python 2.7 alpha3. + + -- Matthias Klose Tue, 16 Feb 2010 03:04:01 +0100 + +python2.7 (2.7~a2-1) experimental; urgency=low + + * Python 2.7 alpha2. + + -- Matthias Klose Sat, 16 Jan 2010 14:49:59 +0100 + +python2.6 (2.6.5+20100628-1) unstable; urgency=low + + * Update to 20100614, taken from the 2.6 release branch (r82337). + * Apply plat-linux2- patch for alpha, hppa, mips, mipsel, sparc + and sparc64. + + -- Matthias Klose Mon, 28 Jun 2010 21:26:43 +0200 + +python2.6 (2.6.5+20100626-1) unstable; urgency=low + + * Update to 20100614, taken from the 2.6 release branch (r82245). + * Update libpython symbols files. Closes: #587012. + * Move the logging package and the runpy module to python2.6-minimal. + + -- Matthias Klose Sat, 26 Jun 2010 14:29:41 +0200 + +python2.6 (2.6.5+20100616-1) unstable; urgency=medium + + * Update to 20100614, taken from the 2.6 release branch (r81601). + * Reapply the backport for issue #8233, lost in the conversion to + quilt. + * Disable the profiled build on alpha. + * Make pydoc more robust not to fail on exceptions other than import + exceptions. + * posixmodule: Add flags for statvfs.f_flag to constant list. + + -- Matthias Klose Wed, 16 Jun 2010 07:56:40 +0200 + +python2.6 (2.6.5+20100529-1) unstable; urgency=low + + * Update to 20100529, taken from the 2.6 release branch (r81601). + - Fix issue #5753, CVE-2008-5983 python: untrusted python modules + search path. Closes: #572010. + * Convert internal dpatch system to quilt. + * Build the ossaudio extension on GNU/kFreeBSD. Closes: #574696. + + -- Matthias Klose Sat, 29 May 2010 15:07:51 +0200 + +python2.6 (2.6.5-2) unstable; urgency=low + + * Update libpython symbols files. + * debian/patches/issue8032.dpatch: Update to version from the + trunk. + * Fix issue #8329: Don't return the same lists from select.select + when no fds are changed. + * Fix issue #8310: Allow dis to examine new style classes. + * Fix issues #8279: Fix test_gdb failures. + * Fix issue #8233: When run as a script, py_compile.py optionally + takes a single argument `-`. + * Apply proposed patch for issue #7332, segfaults in + PyMarshal_ReadLastObjectFromFile in import_submodule. + * Don't build-depend on locales on avr32. Closes: #575144. + + -- Matthias Klose Tue, 20 Apr 2010 19:41:36 +0200 + +python2.6 (2.6.5-1ubuntu6) lucid; urgency=low + + * Fix applying patch for issue #8310. + + -- Matthias Klose Fri, 16 Apr 2010 14:20:35 +0200 + +python2.6 (2.6.5-1ubuntu5) lucid; urgency=low + + * Fix issue #8329: Don't return the same lists from select.select + when no fds are changed. + * Fix issue #8310: Allow dis to examine new style classes. + + -- Matthias Klose Thu, 15 Apr 2010 01:21:07 +0200 + +python2.6 (2.6.5-1ubuntu4) lucid; urgency=low + + * debian/patches/issue8032.dpatch: Update to version from the + trunk. Upload for beta2 to avoid apport errors. + - Handle PyFrameObject's: LP: #543624, #548723. + - Detect cycles in object reference graph and add extra + protection: LP: #544823, LP: #552356. + + -- Matthias Klose Thu, 01 Apr 2010 22:53:06 +0200 + +python2.6 (2.6.5-1ubuntu3) lucid; urgency=low + + * debian/patches/issue8140.dpatch: Incomplete patch; regenerate. + * debian/patches/issue8032.dpatch: Update to v4: + - Add support for PySetObject (set/frozenset). + - Add support for PyBaseExceptionObject (BaseException). + - Fix a signed vs unsigned char issue that led to exceptions + in gdb for PyStringObject instances. + - Handle the case of loops in the object reference graph. + - Unit tests for all of the above. + + -- Matthias Klose Wed, 31 Mar 2010 18:52:32 +0200 + +python2.6 (2.6.5-1ubuntu2) lucid; urgency=low + + * Disable profiled build on powerpc. + + -- Matthias Klose Sat, 20 Mar 2010 15:17:18 +0100 + +python2.6 (2.6.5-1ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.5-1). + + -- Matthias Klose Sat, 20 Mar 2010 03:57:17 +0100 + +python2.6 (2.6.5-1) unstable; urgency=low + + * Python 2.6.5 final release. + * Fix issue #4961: Inconsistent/wrong result of askyesno function in + tkMessageBox with Tcl8.5. LP: #462950. + * Issue #8154, fix segfault with os.execlp('true'). LP: #418848. + * Apply proposed patch for issue #8032, gdb7 hooks for debugging. + + -- Matthias Klose Fri, 19 Mar 2010 00:12:55 +0100 + +python2.6 (2.6.5~rc2-2) unstable; urgency=low + + * Add copyright notices for the readline and _ssl extensions. + Closes: #573866. + * Backport issue #8140: Extend compileall to compile single files. + Add -i option. + * Backport issue #6949, build _bsddb extension with db-4.8.x. + + -- Matthias Klose Tue, 16 Mar 2010 03:02:21 +0100 + +python2.6 (2.6.5~rc2-1) unstable; urgency=low + + * Python 2.6.5 release candidate 2. + - Replace the Monty Python audio test file. Closes: #568674. + * Fix build failure on sparc64. Closes: #570845. + + -- Matthias Klose Thu, 11 Mar 2010 16:50:03 +0100 + +python2.6 (2.6.5~rc2-0ubuntu1) lucid; urgency=low + + * Python 2.6.5 release candidate 2. + + -- Matthias Klose Thu, 11 Mar 2010 13:30:19 +0100 + +python2.6 (2.6.4-6ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.4-6). + + -- Matthias Klose Tue, 16 Feb 2010 01:08:50 +0100 + +python2.6 (2.6.4-6) unstable; urgency=low + + * Update to 20100215, taken from the 2.6 release branch. + * python2.6-minimal: Skip moving syssite contents to new location, if + /usr/local/lib/python2.6 cannot be written. Closes: #569532. LP: #338227. + * libpython2.6: Fix symlink in /usr/lib/python2.6/config. LP: #521050. + + -- Matthias Klose Mon, 15 Feb 2010 22:12:18 +0100 + +python2.6 (2.6.4-5ubuntu1) lucid; urgency=low + + * Merge with Debian (2.6.4-5). + + -- Matthias Klose Sun, 31 Jan 2010 22:31:41 +0100 + +python2.6 (2.6.4-5) unstable; urgency=low + + * Update to 20100131, taken from the 2.6 release branch. + - Fix typo in os.execvp docstring. Closes: #558764. + * distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment and if --user option is not present. LP: #476005. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present, without changing the install prefix. + LP: #510211. + + -- Matthias Klose Sun, 31 Jan 2010 21:16:51 +0100 + +python2.6 (2.6.4-4ubuntu1) lucid; urgency=low + + * Update to 20100122, taken from the 2.6 release branch. + - Fix DoS via XML document with malformed UTF-8 sequences (CVE_2009_3560). + Closes: #566233. + - Fix typo in os.execvp docstring. Closes: #558764. + * python2.6-doc: Fix searching in local documentation. LP: #456025. + * Update locale module from the trunk. LP: #223281. + * Merge with Debian (2.6.4-4). + + -- Matthias Klose Fri, 22 Jan 2010 11:37:29 +0100 + +python2.6 (2.6.4-4) unstable; urgency=low + + * Update to 20100122, taken from the 2.6 release branch. + - Fix DoS via XML document with malformed UTF-8 sequences (CVE_2009_3560). + Closes: #566233. + * Hurd fixes (Pino Toscano). Closes: #565693: + - hurd-broken-poll.dpatch: ported from 2.5. + - hurd-disable-nonworking-constants.dpatch: disable a few constants from + the public API whose C counterparts are not implemented, so using them + either always blocks or always fails (caused issues in the test suite). + - Exclude the profiled build for hurd. + - Disable four blocking tests from the test suite. + + -- Matthias Klose Fri, 22 Jan 2010 11:10:41 +0100 + +python2.6 (2.6.4-3) unstable; urgency=low + + * Disable the profiled build on s390, mips, mipsel. + * Fix symbol files for kfreebsd-amd64 and sparc64. + + -- Matthias Klose Sat, 16 Jan 2010 16:12:17 +0100 + +python2.6 (2.6.4-2) unstable; urgency=low + + * Update to 20100116, taken from the 2.6 release branch. + * Fix bashism in makesetup shell script. Closes: #530170, #530171. + * Fix build issues on avr (Bradley Smith). Closes: #528439. + - Configure --without-ffi. + - Don't run lengthly tests. + * locale.py: Update locale aliases from the 2.7 branch. + + -- Matthias Klose Sat, 16 Jan 2010 11:05:12 +0100 + +python2.6 (2.6.4-1) experimental; urgency=low + + * Python 2.6.4 final release. + - Issue #7120: logging: Removed import of multiprocessing which is causing + crash in GAE. + - Issue #7149: fix exception in urllib when detecting proxy settings + on OSX. + - Issue #7115: Fixed the extension module builds that is failing when + using paths in the extension name instead of dotted names. LP: #449734. + - Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" + environment. + - Issue #7052: Removed nonexisting NullHandler from logging.__all__. + - Issue #7039: Fixed distutils.tests.test_sysconfig when running on + installation with no build. + - Issue #7019: Raise ValueError when unmarshalling bad long data, instead + of producing internally inconsistent Python longs. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present. + + -- Matthias Klose Tue, 27 Oct 2009 01:22:21 +0100 + +python2.6 (2.6.4~rc1-1) experimental; urgency=low + + * Python 2.6.4 release candidate 1. + - Issue #7052: Removed nonexisting NullHandler from logging.__all__. + - Issue #7039: Fixed distutils.tests.test_sysconfig when running on + installation with no build. + - Issue #7019: Raise ValueError when unmarshalling bad long data, instead + of producing internally inconsistent Python longs. + - Issue #7068: Fixed the partial renaming that occured in r72594. + - Issue #7042: Fix test_signal (test_itimer_virtual) failure on OS X 10.6. + * Remove the conflict with python-setuptools (fixed in issue #7068). + * Build _hashlib as a builtin. + * python2.6-doc: Don't compress the sphinx inventory. + * python2.6-doc: Fix jquery.js symlink. + + -- Matthias Klose Sat, 10 Oct 2009 10:21:02 +0200 + +python2.6 (2.6.3-1) experimental; urgency=low + + * Final Python 2.6.3 release. + - Issue #5329: Fix os.popen* regression from 2.5 with commands as a + sequence running through the shell. + - Issue #6990: Fix threading.local subclasses leaving old state around + after a reference cycle GC which could be recycled by new locals. + - Issue #6790: Make it possible again to pass an `array.array` to + `httplib.HTTPConnection.send`. + - Issue #6922: Fix an infinite loop when trying to decode an invalid + UTF-32 stream with a non-raising error handler like "replace" or + "ignore". + - Issue #1590864: Fix potential deadlock when mixing threads and fork(). + - Issue #6844: Do not emit DeprecationWarnings when accessing a "message" + attribute on exceptions that was set explicitly. + - Issue #6236, #6348: Fix various failures in the `io` module under AIX + and other platforms, when using a non-gcc compiler. Patch by egreen. + - Issue #6851: Fix urllib.urlopen crash on secondairy threads on OSX 10.6 + - Issue #6947: Fix distutils test on windows. Patch by Hirokazu Yamamoto. + - Issue #4606: Passing 'None' if ctypes argtype is set to POINTER(...) + does now always result in NULL. + - Issue #5042: ctypes Structure sub-subclass does now initialize + correctly with base class positional arguments. + - Issue #6938: Fix a TypeError in string formatting of a multiprocessing + debug message. + - Issue #6944: Fix a SystemError when socket.getnameinfo() was called + with something other than a tuple as first argument. + - Issue #6980: Fix ctypes build failure on armel-linux-gnueabi with + -mfloat-abi=softfp. + * python2.6-dbg: Don't create debug subdirectory in /usr/local. No + separate debug directory needed anymore. + * Run the benchmark with -C 2 -n 5 -w 4 on all architectures. + * Build-depend on the versioned db4.x-dev to avoid unexpected updates + for anydbm databases. + + -- Matthias Klose Sat, 03 Oct 2009 13:19:56 +0200 + +python2.6 (2.6.2-3) experimental; urgency=low + + * Update to 20090919, taken from the 2.6 release branch. + * Add a conflict to python-setuptools (<< 0.6c9-3), C extension + builds broken. + * Add new symbols for update from the branch. + + -- Matthias Klose Sat, 19 Sep 2009 10:36:34 +0200 + +python2.6 (2.6.2-2) experimental; urgency=low + + * Symbol _Py_force_double@Base is i386 only. Closes: #534208. + + -- Matthias Klose Tue, 23 Jun 2009 06:14:40 +0200 + +python2.6 (2.6.2-1) experimental; urgency=low + + * Final Python 2.6.2 release. + - Update Doc/tools/sphinxext/download.html. Closes: #526797. + * Update to 20090621, taken from the 2.6 release branch. + + * Address issues when working with PYTHONUSERBASE and non standard prefix + (pointed out by Larry Hastings): + - distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment. + - site.addusersitepackages(): Add USER_BASE/.../dist-packages to sys.path. + * Always use the `unix_prefix' scheme for setup.py install in a virtualenv + setup. LP: #339904. + * Don't make the setup.py install options --install-layout=deb and --prefix + conflict with each other. + * distutils: Always install into `/usr/local/lib/python2.6/dist-packages' + if an option `--prefix=/usr/local' is present (except for virtualenv + and PYTHONUSERBASE installations). LP: #362570. + * Always use `site-packages' as site directory name in virtualenv. + + * Do not add /usr/lib/pythonXY.zip on sys.path. + * Add symbols files for libpython2.6 and python2.6-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python2.6-minimal to avoid a warning on + startup. + * Build a shared library configured --with-pydebug. LP: #322580. + * Fix some lintian warnings. + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * Move the bdist_wininst files into the -dev package (only needed to build + windows installers). + * Document changes to the site directory name in the installation manual. + * Fix issue #1113244: Py_XINCREF, Py_DECREF, Py_XDECREF: Add + `do { ... } while (0)' to avoid compiler warnings. Closes: #516956. + * debian/pyhtml2devhelp.py: update for python 2.6 (Marc Deslauriers). + * debian/rules: re-enable documentation files for devhelp. LP: #338791. + * python2.6-doc: Depend on libjs-jquery, use jquery.js from this package. + Closes: #523482. + + -- Matthias Klose Sun, 21 Jun 2009 16:12:15 +0200 + +python2.6 (2.6.1-3) experimental; urgency=low + + * Update to 20090318, taken from the 2.6 release branch. + * Use the information in /etc/lsb-release for platform.dist(). + * Update installation schemes: LP: #338395. Closes: #520278. + - When the --prefix option is used for setup.py install, Use the + `unix_prefix' scheme. + - Use the `deb_system' scheme if --install-layout=deb is specified. + - Use the the `unix_local' scheme if neither --install-layout=deb + nor --prefix is specified. + - The options --install-layout=deb and --prefix are exclusive. + * Don't fail installation/removal if directories in /usr/local cannot + be created. LP: #338227. + * Don't try to move away the site-packages directory. There never was a + python2.6 upload using site-packages. Closes: #518780. + * Fix build failure on mips/mipsel. Closes: #519386. + + -- Matthias Klose Wed, 18 Mar 2009 22:17:20 +0100 + +python2.6 (2.6.1-2) experimental; urgency=low + + * Move libpython2.6.a into the python2.6-dev package. + * Move idlelib into the idle-python2.6 package. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-1) experimental; urgency=low + + * New upstream version, upload to experimental. + * Update to 20090225, taken from the 2.6 release branch. + * Don't build-depend on locales on armel, hppa, ia64 and mipsel; package is + currently not installable. + + -- Matthias Klose Wed, 25 Feb 2009 18:42:19 +0100 + +python2.6 (2.6.1-0ubuntu9) jaunty; urgency=low + + * Don't build pyexpat, _elementtree and _ctypes as builtin extensions, + third party packages make too many assumptions about these not built + as builtins. + + -- Matthias Klose Tue, 24 Feb 2009 16:34:27 +0100 + +python2.6 (2.6.1-0ubuntu8) jaunty; urgency=low + + * Link the shared libpython with $(MODLIBS). + + -- Matthias Klose Sun, 22 Feb 2009 16:38:49 +0100 + +python2.6 (2.6.1-0ubuntu7) jaunty; urgency=low + + * Update to 20090222, taken from the 2.6 release branch. + + -- Matthias Klose Sun, 22 Feb 2009 10:35:29 +0100 + +python2.6 (2.6.1-0ubuntu6) jaunty; urgency=low + + * Don't build the gdbm extension from the python2.6 source. + * Build the dbm extension using libdb. + * Don't build-depend on locales on sparc (currently not installable), only + needed by the testsuite. + * Update to 20090219, taken from the 2.6 release branch. + + -- Matthias Klose Thu, 19 Feb 2009 12:43:20 +0100 + +python2.6 (2.6.1-0ubuntu5) jaunty; urgency=low + + * Add build dependency on libdb-dev. + + -- Matthias Klose Mon, 16 Feb 2009 13:34:41 +0100 + +python2.6 (2.6.1-0ubuntu4) jaunty; urgency=low + + * Disable the profiled build on all architectures. + + -- Matthias Klose Mon, 16 Feb 2009 11:18:51 +0100 + +python2.6 (2.6.1-0ubuntu3) jaunty; urgency=low + + * Disable the profiled build on armel as well. + + -- Matthias Klose Sun, 15 Feb 2009 10:38:02 +0100 + +python2.6 (2.6.1-0ubuntu2) jaunty; urgency=low + + * Don't use the profiled build on amd64, lpia and sparc (GCC + PR profile/38292). + + -- Matthias Klose Sat, 14 Feb 2009 14:09:34 +0100 + +python2.6 (2.6.1-0ubuntu1) jaunty; urgency=low + + * Update to 20090211, taken from the 2.6 release branch. + + -- Matthias Klose Fri, 13 Feb 2009 12:51:00 +0100 + +python2.6 (2.6.1-0ubuntu1~ppa1) jaunty; urgency=low + + * Python 2.6.1 release. + * Update to 20081206, taken from the 2.6 release branch. + * Ensure that all extensions from the -minimal package are statically + linked into the interpreter. + * Include expat, _elementtree, datetime, bisect, _bytesio, _locale, + _fileio in -minimal to link these extensions statically. + + -- Matthias Klose Fri, 05 Dec 2008 20:43:51 +0100 + +python2.6 (2.6-0ubuntu1~ppa5) intrepid; urgency=low + + * Test build + + -- Matthias Klose Fri, 14 Nov 2008 10:14:38 +0100 + +python2.6 (2.6-0ubuntu1~ppa4) intrepid; urgency=low + + * Do not build the bsddb3 module from this source, but recommend the + python-bsddb3 package (will be a dependency after python-bsddb3 is in + the archive). + * For locally installed packages, create a directory + /usr/local/lib/python2.6/dist-packages. This is the default for + installations done with distutils and setuptools. Third party stuff + packaged within the distribution goes to /usr/lib/python2.6/dist-packages. + There is no /usr/lib/python2.6/site-packages in the file system and + on sys.path. No package within the distribution must not install + anything in this location. + * Place the gdbm extension into the python2.6 package. + * distutils: Add an option --install-layout=deb, which + - installs into $prefix/dist-packages instead of $prefix/site-packages. + - doesn't encode the python version into the egg name. + + -- Matthias Klose Sat, 25 Oct 2008 11:12:24 +0000 + +python2.6 (2.6-0ubuntu1~ppa3) intrepid; urgency=low + + * Build-depend on libdb4.6-dev, instead of libdb-dev (4.7). Test suite + hangs in the bsddb tests. + + -- Matthias Klose Wed, 22 Oct 2008 11:05:13 +0200 + +python2.6 (2.6-0ubuntu1~ppa2) intrepid; urgency=low + + * Update to 20081021, taken from the 2.6 release branch. + * Fix typos and section names in doc-base files. LP: #273344. + * Build a new package libpython2.6. + * For locally installed packages, create a directory + /usr/local/lib/python2.6/system-site-packages, which is symlinked + from /usr/lib/python2.6/site-packages. Third party stuff packaged + within the distribution goes to /usr/lib/python2.6/dist-packages. + + -- Matthias Klose Tue, 21 Oct 2008 18:09:31 +0200 + +python2.6 (2.6-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 release. + * Update to current branch 20081009. + + -- Matthias Klose Thu, 09 Oct 2008 14:28:26 +0200 + +python2.6 (2.6~b3-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta3 release. + + -- Matthias Klose Sun, 24 Aug 2008 01:34:54 +0000 + +python2.6 (2.6~b2-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta2 release. + + -- Matthias Klose Thu, 07 Aug 2008 16:45:56 +0200 + +python2.6 (2.6~b1-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 2.6 beta1 release. + + -- Matthias Klose Tue, 15 Jul 2008 12:57:20 +0000 + +python2.6 (2.6~a3-0ubuntu1~ppa2) hardy; urgency=low + + * Test build + + -- Matthias Klose Thu, 29 May 2008 18:08:48 +0200 + +python2.6 (2.6~a3-0ubuntu1~ppa1) hardy; urgency=low + + * Python 2.6 alpha3 release. + * Update to current trunk 20080523. + + -- Matthias Klose Thu, 22 May 2008 17:37:46 +0200 + +python2.5 (2.5.2-5) unstable; urgency=low + + * Backport new function signal.set_wakeup_fd from the trunk. + Background: http://bugzilla.gnome.org/show_bug.cgi?id=481569 + + -- Matthias Klose Wed, 30 Apr 2008 12:05:10 +0000 + +python2.5 (2.5.2-4) unstable; urgency=low + + * Update to 20080427, taken from the 2.5 release branch. + - Fix issues #2670, #2682. + * Disable running pybench on the hppa buildd (ftbfs). + * Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, + CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + * Support parallel= in DEB_BUILD_OPTIONS (see #209008). + + -- Matthias Klose Sun, 27 Apr 2008 10:40:51 +0200 + +python2.5 (2.5.2-3) unstable; urgency=medium + + * Update to 20080416, taken from the 2.5 release branch. + - Fix CVE-2008-1721, integer signedness error in the zlib extension module. + - Fix urllib2 file descriptor happens byte-at-a-time, reverting + a fix for excessively large memory allocations when calling .read() + on a socket object wrapped with makefile(). + * Disable some regression tests on some architectures: + - arm: test_compiler, test_ctypes. + - armel: test_compiler. + - hppa: test_fork1, test_wait3. + - m68k: test_bsddb3, test_compiler. + * Build-depend on libffi-dev instead of libffi4-dev. + * Fix CVE-2008-1679, integer overflows in the imageop module. + + -- Matthias Klose Wed, 16 Apr 2008 23:37:46 +0200 + +python2.5 (2.5.2-2) unstable; urgency=low + + * Use site.addsitedir() to add directories in /usr/local to sys.path. + Addresses: #469157, #469818. + + -- Matthias Klose Sat, 08 Mar 2008 16:11:23 +0100 + +python2.5 (2.5.2-1) unstable; urgency=low + + * Python 2.5.2 release. + * Merge from Ubuntu: + - Move site customization into sitecustomize.py, don't make site.py + a config file. Addresses: #309719, #413172, #457361. + - Move site.py to python2.4-minimal, remove `addbuilddir' from site.py, + which is unnecessary for installed builds. + - python2.5-dev: Recommend libc-dev instead of suggesting it. LP: #164909. + - Fix issue 961805, Tk Text.edit_modified() fails. LP: #84720. + + -- Matthias Klose Thu, 28 Feb 2008 23:18:52 +0100 + +python2.5 (2.5.1-7) unstable; urgency=low + + * Update to 20080209, taken from the 2.5 release branch. + * Build the _bsddb extension with db-4.5 again; 4.6 is seriously + broken when used with the _bsddb extension. + * Do not run pybench on arm and armel. + * python2.5: Provide python2.5-wsgiref. + * Fix a pseudo RC report with duplicated attributes in the control + file. Closes: #464307. + + -- Matthias Klose Sun, 10 Feb 2008 00:22:57 +0100 + +python2.5 (2.5.1-6) unstable; urgency=low + + * Update to 20080102, taken from the 2.5 release branch. + - Only define _BSD_SOURCE on OpenBSD systems. Closes: #455400. + * Fix handling of packages in linecache.py (Kevin Goodsell). LP: #70902. + * Bump debhelper to v5. + * Register binfmt for .py[co] files. + * Use absolute paths when byte-compiling files. Addresses: #453346. + Closes: #413566, LP: #177722. + * CVE-2007-4965, http://bugs.python.org/issue1179: + Multiple integer overflows in the imageop module in Python 2.5.1 and + earlier allow context-dependent attackers to cause a denial of service + (application crash) and possibly obtain sensitive information (memory + contents) via crafted arguments to (1) the tovideo method, and unspecified + other vectors related to (2) imageop.c, (3) rbgimgmodule.c, and other + files, which trigger heap-based buffer overflows. + Patch prepared by Stephan Herrmann. Closes: #443333, LP: #163845. + * Register info docs when doing source only uploads. LP: #174786. + * Remove deprecated value from categories in desktop file. LP: #172874. + * python2.5-dbg: Don't include the gdbm and _tkinter extensions, now provided + in separate packages. + * Provide a symlink changelog -> NEWS. Closes: #439271. + * Fix build failure on hurd, working around poll() on systems on which it + returns an error on invalid FDs. Closes: #438914. + * Configure --with-system-ffi on all architectures. Closes: #448520. + * Fix version numbers in copyright and README files (Dan O'Huiginn). + Closes: #446682. + * Move some documents from python2.5 to python2.5-dev. + + -- Matthias Klose Wed, 02 Jan 2008 22:22:19 +0100 + +python2.5 (2.5.1-5) unstable; urgency=low + + * Build the _bsddb extension with db-4.6. + + -- Matthias Klose Fri, 17 Aug 2007 00:39:35 +0200 + +python2.5 (2.5.1-4) unstable; urgency=low + + * Update to 20070813, taken from the 2.5 release branch. + * Include plat-mac/plistlib.py (plat-mac is not in sys.path by default. + Closes: #435826. + * Use emacs22 to build the documentation in info format. Closes: #434969. + * Build-depend on db-dev (>= 4.6). Closes: #434965. + + -- Matthias Klose Mon, 13 Aug 2007 22:22:44 +0200 + +python2.5 (2.5.1-3) unstable; urgency=high + + * Support mixed-endian IEEE floating point, as found in the ARM old-ABI + (Aurelien Jarno). Closes: #434905. + + -- Matthias Klose Fri, 27 Jul 2007 20:01:35 +0200 + +python2.5 (2.5.1-2) unstable; urgency=low + + * Update to 20070717, taken from the 2.5 release branch. + * Fix reference count for sys.pydebug variable. Addresses: #431393. + * Build depend on libbluetooth-dev instead of libbluetooth2-dev. + + -- Matthias Klose Tue, 17 Jul 2007 14:09:47 +0200 + +python2.5 (2.5.1-1) unstable; urgency=low + + * Python-2.5.1 release. + * Build-depend on gcc-4.1 (>= 4.1.2-4) on alpha, powerpc, s390, sparc. + * Merge from Ubuntu: + - Add debian/patches/subprocess-eintr-safety.dpatch (LP: #87292): + - Create and use wrappers around read(), write(), and os.waitpid() in the + subprocess module which retry the operation on an EINTR (which happens + if e. g. an alarm was raised while the system call was in progress). + It is incredibly hard and inconvenient to sensibly handle this in + applications, so let's fix this at the right level. + - Patch based on original proposal of Peter <85>strand + in http://python.org/sf/1068268. + - Add two test cases. + - Change the interpreter to build and install python extensions + built with the python-dbg interpreter with a different name into + the same path (by appending `_d' to the extension name). The debug build + of the interpreter tries to first load a foo_d.so or foomodule_d.so + extension, then tries again with the normal name. + - When trying to import the profile and pstats modules, don't + exit, add a hint to the exception pointing to the python-profiler + package, don't exit. + - Keep the module version in the .egg-info name, only remove the + python version. + - python2.5-dbg: Install Misc/SpecialBuilds.txt, document the + debug changes in README.debug. + * Update to 20070425, taken from the 2.5 release branch. + + -- Matthias Klose Wed, 25 Apr 2007 22:12:50 +0200 + +python2.5 (2.5-6) unstable; urgency=medium + + * webbrowser.py: Recognize other browsers: www-browser, x-www-browser, + iceweasel, iceape. + * Move pyconfig.h from the python2.5-dev into the python2.5 package; + required by builds for pure python modules without having python2.5-dev + installed (matching the functionality in python2.4). + * Move the unicodedata module into python2.5-minimal; allows byte compilation + of UTF8 encoded files. + * Do not install anymore outdated debhelper sample scripts. + * Install Misc/SpecialBuilds.txt as python2.5-dbg document. + + -- Matthias Klose Wed, 21 Feb 2007 01:17:12 +0100 + +python2.5 (2.5-5) unstable; urgency=high + + * Do not run the python benchmark on m68k. Timer problems. + Fixes FTBFS on m68k. + * Update to 20061209, taken from the 2.5 release branch. + - Fixes building the library reference in info format. + + -- Matthias Klose Sat, 9 Dec 2006 13:40:48 +0100 + +python2.5 (2.5-4) unstable; urgency=medium + + * Update to 20061203, taken from the 2.5 release branch. + - Fixes build failures on knetfreebsd and the hurd. Closes: #397000. + * Clarify README about distutils. Closes: #396394. + * Move python2.5-config to python2.5-dev. Closes: #401451. + * Cleanup build-conflicts. Addresses: #394512. + + -- Matthias Klose Sun, 3 Dec 2006 18:22:49 +0100 + +python2.5 (2.5-3.1) unstable; urgency=low + + * Non-maintainer upload. + * python2.5-minimal depends on python-minimal (>= 2.4.4-1) because it's the + first version which lists python2.5 as an unsupported runtime (ie a + runtime that is available but for which modules are not auto-compiled). + And being listed there is required for python-central to accept the + installation of python2.5-minimal. Closes: #397006 + + -- Raphael Hertzog Wed, 22 Nov 2006 15:41:06 +0100 + +python2.5 (2.5-3) unstable; urgency=medium + + * Update to 20061029 (2.4.4 was released on 20061019), taken from + the 2.5 release branch. We do not want to have regressions in + 2.5 compared to the 2.4.4 release. + * Don't run pybench on m68k, fails in the calibration loop. Closes: #391030. + * Run the installation/removal hooks. Closes: #383292, #391036. + + -- Matthias Klose Sun, 29 Oct 2006 11:35:19 +0100 + +python2.5 (2.5-2) unstable; urgency=medium + + * Update to 20061003, taken from the 2.5 release branch. + * On arm and m68k, don't run the pybench in debug mode. + * Fix building the source within exec_prefix (Alexander Wirt). + Closes: #385336. + + -- Matthias Klose Tue, 3 Oct 2006 10:08:36 +0200 + +python2.5 (2.5-1) unstable; urgency=low + + * Python 2.5 release. + * Update to 20060926, taken from the 2.5 release branch. + * Run the Python benchmark during the build, compare the results + of the static and shared builds. + * Fix invalid html in python2.5.devhelp.gz. + * Add a python2.5 console entry to the menu (hidden by default). + * python2.5: Suggest python-profiler. + + -- Matthias Klose Tue, 26 Sep 2006 02:36:11 +0200 + +python2.5 (2.5~c1-1) unstable; urgency=low + + * Python 2.5 release candidate 1. + * Update to trunk 20060818. + + -- Matthias Klose Sat, 19 Aug 2006 19:21:05 +0200 + +python2.5 (2.5~b3-1) unstable; urgency=low + + * Build the _ctypes module for m68k-linux. + + -- Matthias Klose Fri, 11 Aug 2006 18:19:19 +0000 + +python2.5 (2.5~b3-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta3 release. + * Update to trunk 20060811. + * Rebuild the documentation. + * Fix value of sys.exec_prefix in the debug build. + * Do not build the library reference in info format; fails to build. + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 6%. + * Install the statically linked version of the interpreter as + python2.5-static for now. + * Link the shared libpython with -O1. + + -- Matthias Klose Thu, 10 Aug 2006 14:04:48 +0000 + +python2.5 (2.4.3+2.5b2-3) unstable; urgency=low + + * Disable the testsuite on s390; don't care about "minimally configured" + buildd's. + + -- Matthias Klose Sun, 23 Jul 2006 11:45:03 +0200 + +python2.5 (2.4.3+2.5b2-2) unstable; urgency=low + + * Update to trunk 20060722. + * Merge idle-lib from idle-python2.5 into python2.5. + * Merge lib-tk from python-tk into python2.5. + * Tkinter.py: Suggest installation of python-tk package on failed + import of the _tkinter extension. + * Don't run the testsuite for the debug build on alpha. + * Don't run the test_compiler test on m68k. Just takes too long. + * Disable building ctypes on m68k (requires support for closures). + + -- Matthias Klose Sat, 22 Jul 2006 22:26:42 +0200 + +python2.5 (2.4.3+2.5b2-1) unstable; urgency=low + + * Python 2.5 beta2 release. + * Update to trunk 20060716. + * When built on a buildd, do not run the following test which try to + access the network: test_codecmaps_cn, test_codecmaps_hk, test_codecmaps_jp, + test_codecmaps_kr, test_codecmaps_tw, test_normalization. + * When built on a buildd, do not run tests requiring missing write permissions: + test_ossaudiodev. + + -- Matthias Klose Sun, 16 Jul 2006 02:53:50 +0000 + +python2.5 (2.4.3+2.5b2-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta2 release. + + -- Matthias Klose Thu, 13 Jul 2006 17:16:52 +0000 + +python2.5 (2.4.3+2.5b1-1ubuntu2) edgy; urgency=low + + * Fix python-dev dependencies. + * Update to trunk 20060709. + + -- Matthias Klose Sun, 9 Jul 2006 18:50:32 +0200 + +python2.5 (2.4.3+2.5b1-1ubuntu1) edgy; urgency=low + + * Python 2.5 beta1 release. + * Update to trunk 20060623. + * Merge changes from the python2.4 packages. + * python2.5-minimal: Add _struct. + + -- Matthias Klose Fri, 23 Jun 2006 16:04:46 +0200 + +python2.5 (2.4.3+2.5a1-1) experimental; urgency=low + + * Update to trunk 20060409. + * Run testsuite for debug build as well. + * Build-depend on gcc-4.1. + + -- Matthias Klose Sun, 9 Apr 2006 22:27:05 +0200 + +python2.5 (2.4.3+2.5a1-0ubuntu1) dapper; urgency=low + + * Python 2.5 alpha1 release. + * Drop integrated patches. + * Add build dependencies on libsqlite3-dev and libffi4-dev. + * Add (build-)dependency on mime-support, libgpmg1 (test suite). + * Build using the system FFI. + * python2.5 provides python2.5-ctypes and python2.5-pysqlite2, + python2.5-elementtree. + * Move hashlib.py to python-minimal. + * Lib/hotshot/pstats.py: Error out on missing profile/pstats modules. + + -- Matthias Klose Wed, 5 Apr 2006 14:56:15 +0200 + +python2.4 (2.4.3-8ubuntu1) edgy; urgency=low + + * Resynchronize with Debian unstable. Remaining changes: + - Apply langpack-gettext patch. + - diff.gz contains pregenerated html and info docs. + - Build the -doc package from this source. + + -- Matthias Klose Thu, 22 Jun 2006 18:39:57 +0200 + +python2.4 (2.4.3-8) unstable; urgency=low + + * Remove python2.4's dependency on python-central. On installation of + the runtime, call hooks /usr/share/python/runtime.d/*.rtinstall. + On removal, call hooks /usr/share/python/runtime.d/*.rtremove. + Addresses: #372658. + * Call the rtinstall hooks only, if it's a new installation, or the first + installation using the hooks. Adresses: #373677. + + -- Matthias Klose Sun, 18 Jun 2006 00:56:13 +0200 + +python2.4 (2.4.3-7) unstable; urgency=medium + + * Reupload, depend on python-central (>= 0.4.15). + * Add build-conflict on python-xml. + + -- Matthias Klose Wed, 14 Jun 2006 18:56:57 +0200 + +python2.4 (2.4.3-6) medium; urgency=low + + * idle-python2.4: Remove the old postinst and prerm scripts. + * Name the runtime correctly in python2.4-minimal's installation + scripts. + + -- Matthias Klose Mon, 12 Jun 2006 17:39:56 +0000 + +python2.4 (2.4.3-5) unstable; urgency=low + + * python2.4-prerm: Handle the case, when python-central is not installed. + * idle-python2.4: Depend on python-tk instead of python2.4-tk. + + -- Matthias Klose Fri, 9 Jun 2006 05:17:17 +0200 + +python2.4 (2.4.3-4) unstable; urgency=low + + * SVN update up to 2006-06-07 + * Use python-central. + * Don't build the -tk and -gdbm packages from this source; now built + from the python-stdlib-extensions source. + * Remove leftover build dependency on libgmp3-dev. + * Do not build-depend on libbluetooth1-dev and libgpmg1-dev on + hurd-i386, kfreebsd-i386, kfreebsd-amd64. Closes: #365830. + * Do not run the test_tcl test; hangs for unknown reasons on at least + the following buildds: vivaldi(m68k), goedel (alpha), mayer (mipsel). + And no virtual package to file bug reports for the buildds ... + Closes: #364419. + * Move the Makefile from python2.4-dev to python2.4. Closes: #366473. + * Fix typo in pdb(1). Closes: #365772. + * New autoconf likes the mandir in /usr/share instead of /usr; work + with both locations. Closes: #367618. + + -- Matthias Klose Wed, 7 Jun 2006 21:37:20 +0200 + +python2.4 (2.4.3-3) unstable; urgency=low + + * SVN update up to 2006-04-21 + * Update locale aliases from /usr/share/X11/locale/locale.alias. + * Start idle with option -n from the desktop menu, so that the program + can be started in parallel. + * Testsuite related changes only: + - Add build dependencies mime-support, libgpmg1 (needed by test cases). + - Run the testsuite with bsddb, audio and curses resources enabled. + - Re-run the failed tests in verbose mode. + - Run the test suite for the debug build as well. + - Build depend on netbase, needed by test_socketmodule. + - Build depend on libgpmg1, needed by test_curses. + - On the buildds do not run the tests needing the network resource. + * Update python logo. + * Check for the availability of the profile and pstats modules when + importing hotshot.pstats. Closes: #334067. + * Don't build the -doc package from the python2.4 source. + * Set OPT in the installed Makefile to -O2. + + -- Matthias Klose Fri, 21 Apr 2006 19:58:43 +0200 + +python2.4 (2.4.3-2) unstable; urgency=low + + * Add (build-)dependency on mime-support. + + -- Matthias Klose Tue, 4 Apr 2006 22:21:41 +0200 + +python2.4 (2.4.3-1) unstable; urgency=low + + * Python 2.4.3 release. + + -- Matthias Klose Thu, 30 Mar 2006 23:42:37 +0200 + +python2.4 (2.4.3-0ubuntu1) dapper; urgency=low + + * Python 2.4.3 release. + - Fixed a bug that the gb18030 codec raises RuntimeError on encoding + surrogate pair area on UCS4 build. Ubuntu: #29289. + + -- Matthias Klose Thu, 30 Mar 2006 10:57:32 +0200 + +python2.4 (2.4.2+2.4.3c1-0ubuntu1) dapper; urgency=low + + * SVN update up to 2006-03-25 (2.4.3 candidate 1). + - Regenerate the documentation. + + -- Matthias Klose Mon, 27 Mar 2006 12:03:05 +0000 + +python2.4 (2.4.2-1ubuntu3) dapper; urgency=low + + * SVN update up to 2006-03-04 + - Regenerate the documentation. + - map.mmap(-1, size, ...) can return anonymous memory again on Unix. + Ubuntu #26201. + * Build-depend on libncursesw5-dev, ncursesw5 is preferred for linking. + Provides UTF-8 compliant curses bindings. + * Fix difflib where certain patterns of differences were making difflib + touch the recursion limit. + + -- Matthias Klose Sat, 4 Mar 2006 21:38:24 +0000 + +python2.4 (2.4.2-1ubuntu2) dapper; urgency=low + + * SVN update up to 2006-01-17 + - pwd is now a builtin module, remove it from python-minimal. + - Regenerate the documentation. + * python2.4-tk: Suggest tix instead of tix8.1. + * Move config/Makefile from the -dev package into the runtime package + to be able to use the bdist_wininst distutils command. Closes: #348335. + + -- Matthias Klose Tue, 17 Jan 2006 11:02:24 +0000 + +python2.4 (2.4.2-1ubuntu1) dapper; urgency=low + + * Temporarily remove build dependency on lsb-release. + + -- Matthias Klose Sun, 20 Nov 2005 17:40:18 +0100 + +python2.4 (2.4.2-1build1) dapper; urgency=low + + * Rebuild (openssl-0.9.8). + + -- Matthias Klose Sun, 20 Nov 2005 15:27:24 +0000 + +python2.4 (2.4.2-1) unstable; urgency=low + + * Python 2.4.2 release. + + -- Matthias Klose Thu, 29 Sep 2005 01:49:28 +0200 + +python2.4 (2.4.1+2.4.2rc1-1) unstable; urgency=low + + * Python 2.4.2 release candidate 1. + * Fix "Fatal Python error" from cStringIO's writelines. + Patch by Andrew Bennetts. + + -- Matthias Klose Thu, 22 Sep 2005 10:33:22 +0200 + +python2.4 (2.4.1-5) unstable; urgency=low + + * CVS update up to 2005-09-14 + - Regenerate the html and info docs. + * Add some more locale aliases. + * Fix substitution pf python version in README.python2.4-minimal. + Closes: #327487. + * On m68k, build using -O2 (closes: #326903). + * On Debian, don't configure --with-fpectl, which stopped working with + glibc-2.3.5. + + -- Matthias Klose Wed, 14 Sep 2005 17:32:56 +0200 + +python2.4 (2.4.1-4) unstable; urgency=low + + * CVS update up to 2005-09-04 + - teTeX 3.0 related fixes (closes: #322407). + - Regenerate the html and info docs. + * Add entry for IDLE in the Gnome menus. + * Don't build-depend on libbluetooth-dev on the Hurd (closes: #307037). + * Reenable the cthreads patch for the Hurd (closes: #307052). + + -- Matthias Klose Sun, 4 Sep 2005 18:31:42 +0200 + +python2.4 (2.4.1-3) unstable; urgency=low + + * Synchronise with Ubuntu: + - Build a python2.4-minimal package. + + -- Matthias Klose Tue, 12 Jul 2005 00:23:10 +0000 + +python2.4 (2.4.1-2ubuntu3) breezy; urgency=low + + * CVS update up to 2005-07-07 + * Regenerate the documentation. + + -- Matthias Klose Thu, 7 Jul 2005 09:21:28 +0200 + +python2.4 (2.4.1-2ubuntu2) breezy; urgency=low + + * CVS update up to 2005-06-15 + * Regenerate the documentation. + * Synchronize with Debian. Ubuntu 10485. + * idle-python2.4 enhances python2.4. Ubuntu 11562. + * README.Debian: Fix reference to the doc directory (closes: #311677). + + -- Matthias Klose Wed, 15 Jun 2005 08:56:57 +0200 + +python2.4 (2.4.1-2ubuntu1) breezy; urgency=low + + * Update build dependencies: + db4.2-dev -> db4.3-dev, + libreadline4-dev -> libreadline5-dev. + * python2.4-dev: Add missing templates to generate HTML docs. Ubuntu 11531. + + -- Matthias Klose Sun, 29 May 2005 00:01:05 +0200 + +python2.4 (2.4.1-2) unstable; urgency=low + + * Add the debug symbols for the python2.4, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. + * Add gdbinit example to doc directory. + + -- Matthias Klose Thu, 5 May 2005 11:12:32 +0200 + +python2.4 (2.4.1-1ubuntu2) breezy; urgency=low + + * Add the debug symbols for the python2.4, python2.4-minimal, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. Ubuntu 10261, + * Add gdbinit example to doc directory. + * For os.utime, use utimes(2), correctly working with glibc-2.3.5. + Ubuntu 10294. + + -- Matthias Klose Thu, 5 May 2005 09:06:07 +0200 + +python2.4 (2.4.1-1ubuntu1) breezy; urgency=low + + * Reupload as 2.4.1-1ubuntu1. + + -- Matthias Klose Thu, 14 Apr 2005 10:46:32 +0200 + +python2.4 (2.4.1-1) unstable; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 19:42:03 +0200 + +python2.4 (2.4.1-0) hoary; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 16:35:34 +0200 + +python2.4 (2.4+2.4.1rc2-2) unstable; urgency=low + + * Add the valgrind support file to /etc/python2.4 + * Build the -dbg package with -DPy_USING_MEMORY_DEBUGGER. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * Fix two typos in python(1). Addresses: #300124. + + -- Matthias Klose Sat, 19 Mar 2005 21:50:14 +0100 + +python2.4 (2.4+2.4.1rc2-1) unstable; urgency=low + + * Python 2.4.1 release candidate 2. + * Build-depend on libbluetooth1-dev. + + -- Matthias Klose Sat, 19 Mar 2005 00:57:14 +0100 + +python2.4 (2.4dfsg-2) unstable; urgency=low + + * CVS update up to 2005-03-03 + + -- Matthias Klose Thu, 3 Mar 2005 22:22:16 +0100 + +python2.4 (2.4dfsg-1ubuntu4) hoary; urgency=medium + + * Move exception finalisation later in the shutdown process - this + fixes the crash seen in bug #1165761, taken from CVS. + * codecs.StreamReader: Reset codec when seeking. Ubuntu #6972. + * Apply fix for SF1124295, fixing an obscure bit of Zope's security machinery. + * distutils: Don't add standard library dirs to library_dirs + and runtime_library_dirs. On amd64, runtime paths pointing to /usr/lib64 + aren't recognized by dpkg-shlibdeps, and the packages containing these + libraries aren't added to ${shlibs:Depends}. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * os.py: Avoid using items() in environ.update(). Fixes #1124513. + * Python/pythonrun.c: + * Build depend on locales, generate the locales needed for the + testsuite. + * Add build dependency on libbluetooth1-dev, adding some bluetooth + functionality to the socket module. + * Lib/test/test_sundry.py: Don't fail on import of profile & pstats, + which are separated out to the python-profiler package. + * Fix typos in manpage. + + -- Matthias Klose Tue, 29 Mar 2005 13:35:53 +0200 + + +python2.4 (2.4dfsg-1ubuntu3) hoary; urgency=low + + * debian/patches/langpack-gettext.dpatch: + - langpack support for python-gettext added + + -- Michael Vogt Tue, 1 Mar 2005 13:13:36 +0100 + +python2.4 (2.4dfsg-1ubuntu2) hoary; urgency=low + + * Revert 'essential' status on python2.4-minimal. This status on + on python-minimal is sufficient (Ubuntu #6392). + + -- Matthias Klose Wed, 9 Feb 2005 23:09:42 +0100 + +python2.4 (2.4dfsg-1ubuntu1) hoary; urgency=low + + * Resyncronise with Debian. + * Mark the python2.4-minimal package as 'essential'. + + -- Matthias Klose Wed, 9 Feb 2005 13:31:09 +0100 + +python2.4 (2.4dfsg-1) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Remove the profile.py and pstats.py modules from the source package, + not having a DFSG conforming license. The modules can be found in + the python2.x-profile package in the non-free section. + Addresses: #293932. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7ubuntu1) hoary; urgency=low + + * Fix the name of the python-dbg man page. + * Resyncronise with Debian. + * Move more modules to -minimal (new code in copy.py requires these): + dis, inspect, opcode, token, tokenize. + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-6) unstable; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Apply the pydebug-path patch. The package was already built in -5. + + -- Matthias Klose Fri, 4 Feb 2005 22:15:13 +0100 + +python2.4 (2.4-5) unstable; urgency=high + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + * CVS updates of the release24-maint branch upto 2005-02-04. + + -- Matthias Klose Fri, 4 Feb 2005 08:12:10 +0100 + +python2.4 (2.4-4) unstable; urgency=medium + + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Remove /usr/bin/smtpd.py (closes: #291049). + + -- Matthias Klose Mon, 17 Jan 2005 23:54:37 +0100 + +python2.4 (2.4-3ubuntu6) hoary; urgency=low + + * Use old-style dpatches instead of dpatch-run. + + -- Tollef Fog Heen Mon, 7 Feb 2005 15:58:05 +0100 + +python2.4 (2.4-3ubuntu5) hoary; urgency=low + + * Actually apply the patch as well (add to list of patches in + debian/rules) + + -- Tollef Fog Heen Sun, 6 Feb 2005 15:12:58 +0100 + +python2.4 (2.4-3ubuntu4) hoary; urgency=low + + * Add nb_NO and nn_NO locales to Lib/locale.py + + -- Tollef Fog Heen Sun, 6 Feb 2005 14:33:05 +0100 + +python2.4 (2.4-3ubuntu3) hoary; urgency=low + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + + -- Matthias Klose Wed, 2 Feb 2005 09:08:20 +0000 + +python2.4 (2.4-3ubuntu2) hoary; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Add operator and copy to the -minimal package. + + -- Matthias Klose Mon, 17 Jan 2005 23:19:47 +0100 + +python2.4 (2.4-3ubuntu1) hoary; urgency=low + + * Resynchronise with Debian. + * python2.4: Depend on the very same version of python2.4-minimal. + * Docment, that time.strptime currently cannot be used, if the + python-minimal package is installed without the python package. + + -- Matthias Klose Sun, 9 Jan 2005 19:35:48 +0100 + +python2.4 (2.4-3) unstable; urgency=medium + + * Build the fpectl module. + * Updated to CVS release24-maint 20050107. + + -- Matthias Klose Sat, 8 Jan 2005 19:05:21 +0100 + +python2.4 (2.4-2ubuntu5) hoary; urgency=low + + * Updated to CVS release24-maint 20050102. + * python-minimal: + - os.py: Use dict instead of UserDict, remove UserDict from -minimal. + - add pickle, threading, needed for subprocess module. + - optparse.py: conditionally import gettext, if not available, + define _ as the identity function. Patch taken from the trunk. + Avoids import of _locale, locale, gettext, copy, repr, itertools, + collections, token, tokenize. + - Add a build check to make sure that the minimal module list is + closed under dependency. + * Fix lintian warnings. + + -- Matthias Klose Sun, 2 Jan 2005 22:00:14 +0100 + +python2.4 (2.4-2ubuntu4) hoary; urgency=low + + * Add UserDict.py to the -minimal package, since os.py needs it. + + -- Colin Watson Thu, 30 Dec 2004 20:41:28 +0000 + +python2.4 (2.4-2ubuntu3) hoary; urgency=low + + * Add os.py and traceback.py to the -minimal package, get the list + of modules from the README. + + -- Matthias Klose Mon, 27 Dec 2004 08:20:45 +0100 + +python2.4 (2.4-2ubuntu2) hoary; urgency=low + + * Add compileall.py and py_compile.py to the -minimal package, not + just to the README ... + + -- Matthias Klose Sat, 25 Dec 2004 22:24:56 +0100 + +python2.4 (2.4-2ubuntu1) hoary; urgency=low + + * Separate the interpreter and a minimal subset of modules into + a python2.4-minimal package. See the README.Debian.gz in this + package. + * Move site.py to python2.4-minimal as well. + * Add documentation files for devhelp. + + -- Matthias Klose Sun, 19 Dec 2004 22:47:32 +0100 + +python2.4 (2.4-2) unstable; urgency=medium + + * Updated patch for #283108. Thanks to Jim Meyering. + + -- Matthias Klose Fri, 3 Dec 2004 17:00:16 +0100 + +python2.4 (2.4-1) unstable; urgency=low + + * Final 2.4 release. + * Flush stdout/stderr if closed (SF #1074011). + + -- Matthias Klose Wed, 1 Dec 2004 07:54:34 +0100 + +python2.4 (2.3.97-2) unstable; urgency=low + + * Don't run test_tcl, hanging on the buildds. + + -- Matthias Klose Fri, 19 Nov 2004 23:48:42 +0100 + +python2.4 (2.3.97-1) unstable; urgency=low + + * Python 2.4 Release Candidate 1. + + -- Matthias Klose Fri, 19 Nov 2004 21:27:02 +0100 + +python2.4 (2.3.96-1) experimental; urgency=low + + * Updated to CVS release24-maint 20041113. + * Build the docs in info format again. + + -- Matthias Klose Sat, 13 Nov 2004 21:21:10 +0100 + +python2.4 (2.3.95-2) experimental; urgency=low + + * Move distutils package from the python2.4-dev into the python2.4 + package. + + -- Matthias Klose Thu, 11 Nov 2004 22:56:14 +0100 + +python2.4 (2.3.95-1) experimental; urgency=low + + * Python 2.4 beta2 release. + + -- Matthias Klose Thu, 4 Nov 2004 23:43:47 +0100 + +python2.4 (2.3.94-1) experimental; urgency=low + + * Python 2.4 beta1 release. + + -- Matthias Klose Sat, 16 Oct 2004 08:33:57 +0200 + +python2.4 (2.3.93-1) experimental; urgency=low + + * Python 2.4 alpha3 release. + + -- Matthias Klose Fri, 3 Sep 2004 21:53:47 +0200 + +python2.4 (2.3.92-1) experimental; urgency=low + + * Python 2.4 alpha2 release. + + -- Matthias Klose Thu, 5 Aug 2004 23:53:18 +0200 + +python2.4 (2.3.91-1) experimental; urgency=low + + * Python 2.4 alpha1 release. + Highlights: http://www.python.org/2.4/highlights.html + + -- Matthias Klose Fri, 9 Jul 2004 17:38:54 +0200 + +python2.4 (2.3.90-1) experimental; urgency=low + + * Package HEAD branch (pre alpha ..). + + -- Matthias Klose Mon, 14 Jun 2004 23:19:57 +0200 + +python2.3 (2.3.4-1) unstable; urgency=medium + + * Final Python 2.3.4 Release. + * In the API docs, fix signature of PyModule_AddIntConstant (closes: #250826). + * locale.getdefaultlocale: don't fail with empty environment variables. + Closes: #249816. + * Include distutils/command/wininst.exe in -dev package (closes: #249006). + * Disable cthreads on the Hurd (Michael Banck). Closes: #247211. + * Add a note to pygettext(1), that this program is deprecated in favour + of xgettext, which now includes support for Python as well. + Closes: #246332. + + -- Matthias Klose Fri, 28 May 2004 22:59:42 +0200 + +python2.3 (2.3.3.91-1) unstable; urgency=low + + * Python 2.3.4 Release Candidate 1. + * Do not use the default namespace for attributes. Patch taken from the + 2.3 maintenance branch. + The xmllib module is obsolete. Use xml.sax instead. + * http://python.org/sf/945642 - fix nonblocking i/o with ssl socket. + + -- Matthias Klose Thu, 13 May 2004 21:24:52 +0200 + +python2.3 (2.3.3-7) unstable; urgency=low + + * Add a workaround for GNU libc nl_langinfo()'s returning NULL. + Closes: #239237. + Patch taken from 2.3 maintenance branch. + * threading.py: Remove calls to currentThread() in _Condition methods that + were side-effect. Side-effects were deemed unnecessary and were causing + problems at shutdown time when threads were catching exceptions at start + time and then triggering exceptions trying to call currentThread() after + gc'ed. Masked the initial exception which was deemed bad. + Closes: #195812. + * Properly support normalization of empty unicode strings. Closes: #239986. + Patch taken from 2.3 maintenance branch. + * README.maintainers: Add section where to find the documentation tools. + * Fix crash in pyexpat module (closes: #229281). + * For the Hurd, set the interpreters recursion limit to 930. + * Do not try to byte-compile the test files on installation; this + currently breaks the Hurd install. + + -- Matthias Klose Sat, 1 May 2004 07:50:46 +0200 + +python2.3 (2.3.3-6) unstable; urgency=low + + * Don't build the unversioned python{,-*} packages anymore. Now + built from the python-defaults package. + * Update to the proposed python-policy: byte-compile using -E. + * Remove python-elisp's dependency on emacs20 (closes: #232785). + * Don't build python-elisp from the python2.3 source anymore, + get it from python-mode.sf.net as a separate source package. + * python2.3-dev suggests libc-dev (closes: #231091). + * get LDSHARED and CCSHARED (like, CC, CXX, CPP, CFLAGS) from + the environment + * Set CXX in installed config/Makefile (closes: #230273). + + -- Matthias Klose Tue, 24 Feb 2004 07:07:51 +0100 + +python2.3 (2.3.3-5) unstable; urgency=low + + * Build-depend on libdb4.2-dev, instead of libdb4.1-dev. According + to the docs the file format is compatible. + + -- Matthias Klose Mon, 12 Jan 2004 10:37:45 +0100 + +python2.3 (2.3.3-4) unstable; urgency=low + + * Fix broken _bsddb module. setup.py picked up the wrong library. + + -- Matthias Klose Sun, 4 Jan 2004 11:30:00 +0100 + +python2.3 (2.3.3-3) unstable; urgency=low + + * Fix typo in patch (closes: #224797, #226064). + + -- Matthias Klose Sun, 4 Jan 2004 09:23:21 +0100 + +python2.3 (2.3.3-2) unstable; urgency=medium + + * Lib/email/Charset: use locale unaware function to lower case of locale + name (closes: #224797). + * Update python-mode to version from python-mode.sf.net. Fixes highlighting + problems (closes: #223520). + * Backport from mainline: Add IPV6_ socket options from RFCs 3493 and 3542. + + -- Matthias Klose Fri, 2 Jan 2004 14:03:26 +0100 + +python2.3 (2.3.3-1) unstable; urgency=low + + * New upstream release. + * Copy the templates, tools and scripts from the Doc dir in the source + to /usr/share/lib/python2.3/doc in the python2.3-dev package. Needed + for packages building documentation like python does (closes: #207337). + + -- Matthias Klose Fri, 19 Dec 2003 10:57:39 +0100 + +python2.3 (2.3.2.91-1) unstable; urgency=low + + * New upstream version (2.3.3 release candidate). + * Update python-mode.el (closes: #158811, #159630). + Closing unreproducible report (closes: #159628). + + -- Matthias Klose Sat, 6 Dec 2003 14:41:14 +0100 + +python2.3 (2.3.2-7) unstable; urgency=low + + * Put the conflict in the correct direction. python2.3 (2.3.2-6) doesn't + conflict with python (<= 2.3.2-5) but python (2.3.2-6) conflicts with + python2.3 (<= 2.3.2-5) (thanks to Brian May). Really closes #221791. + + -- Matthias Klose Fri, 21 Nov 2003 00:20:02 +0100 + +python2.3 (2.3.2-6) unstable; urgency=low + + * Add conflicts with older python{,2.3} packages to fix overwrite + errors (closes: #221791). + + -- Matthias Klose Thu, 20 Nov 2003 07:24:36 +0100 + +python2.3 (2.3.2-5) unstable; urgency=low + + * Updated to CVS release23-maint 20031119. + * Re-upgrade the dependency of python2.3 on python (>= 2.3) to + a dependency (closes: #221523). + + -- Matthias Klose Wed, 19 Nov 2003 00:30:27 +0100 + +python2.3 (2.3.2-4) unstable; urgency=low + + * Don't build-depend on latex2html (moved to non-free), but keep + the prebuilt docs in debian/patches (closes: #221347). + * Fix typos in the library reference (closes: #220510, #220954). + * Fix typo in python-elisp's autoloading code (closes: #220308). + * Update proposed python policy: private modules can be installed + into /usr/lib/ (arch dependent) and into /usr/share/ + (arch independent). + + -- Matthias Klose Tue, 18 Nov 2003 00:41:39 +0100 + +python2.3 (2.3.2-3) unstable; urgency=low + + * Downgrade the dependency of python2.3 on python (>= 2.3) to + a recommendation. + * Fix path to interpreter in binfmt file. + * Fix segfault in unicodedata module (closes: #218697). + * Adjust python-elisp autoload code (closes: #219821). + + -- Matthias Klose Sun, 9 Nov 2003 19:43:37 +0100 + +python2.3 (2.3.2-2) unstable; urgency=medium + + * Fix broken doc link (closes: #214217). + * Disable wrongly detected large file support for GNU/Hurd. + * Really fix the FTBFS for the binary-indep target (closes: #214303). + + -- Matthias Klose Mon, 6 Oct 2003 07:54:58 +0200 + +python2.3 (2.3.2-1) unstable; urgency=low + + * New upstream version. + * Fix a FTBFS for the binary-indep target. + + -- Matthias Klose Sat, 4 Oct 2003 10:20:15 +0200 + +python2.3 (2.3.1-3) unstable; urgency=low + + * Fix names of codec packages in recommends. + * On alpha compile using -mieee (see #212912). + + -- Matthias Klose Sun, 28 Sep 2003 10:48:12 +0200 + +python2.3 (2.3.1-2) unstable; urgency=low + + * Update python policy draft (closes: #128911, #163785). + * Re-add os.fsync function (closes: #212672). + * Let python2.3-doc conflict with older python2.3 versions (closes: #211882). + * Add recommends for pythonX.Y-japanese-codecs, pythonX.Y-iconvcodec, + pythonX.Y-cjkcodecs, pythonX.Y-korean-codecs (closes: #207161). + * Generate binfmt file (closes: #208005). + * Add IPPROTO_IPV6 option to the socketmodule (closes: #206569). + * Bugs reported against python2.2 and fixed in python2.3: + - Crashes in idle (closes: #186887, #200084). + + -- Matthias Klose Sat, 27 Sep 2003 11:21:47 +0200 + +python2.3 (2.3.1-1) unstable; urgency=low + + * New upstream version (bug fix release). + + -- Matthias Klose Wed, 24 Sep 2003 11:27:43 +0200 + +python2.3 (2.3-4) unstable; urgency=high + + * Disable check for utimes function, which is broken in glibc-2.3.2. + Packages using distutils had '1970/01/01-01:00:01' timestamps in files. + * Bugs fixed by making python2.3 the default python version: + - Canvas.scan_dragto() takes a 3rd optional parmeter "gain". + Closes: #158168. + - New command line parsing module (closes: #38628). + - compileall.py allows compiling single files (closes: #139971). + * Bugs reported for 2.2 and fixed in 2.3: + - Idle does save files with ASCII characters (closes: #179313). + - imaplib support for prefix-quoted strings (closes: #150485). + - posixpath includes getctime (closes: #173827). + - pydoc has support for keywords (closes: #186775). + * Bugs reported for 2.1 and fixed in 2.3: + - Fix handling of "#anchor" URLs in urlparse (closes: #147844). + - Fix readline if C stdin is not a tty, even if sys.stdin is. + Closes: #131810. + * Updated to CVS release23-maint 20030810 (fixing memory leaks in + array and socket modules). + * pydoc's usage output uses the basename of the script. + * Don't explicitely remove /etc/python2.3 on purge (closes: #202864). + * python conflicts with python-xmlbase (closes: #204773). + * Add dependency python (>= 2.3) to python2.3, so make sure the + unversioned names can be used. + + -- Matthias Klose Sun, 10 Aug 2003 09:27:52 +0200 + +python2.3 (2.3-3) unstable; urgency=medium + + * Fix shlibs file. + + -- Matthias Klose Fri, 8 Aug 2003 08:45:12 +0200 + +python2.3 (2.3-2) unstable; urgency=medium + + * Make python2.3 the default python version. + + -- Matthias Klose Tue, 5 Aug 2003 22:13:22 +0200 + +python2.3 (2.3-1) unstable; urgency=low + + * Python 2.3 final release. + + -- Matthias Klose Wed, 30 Jul 2003 08:12:28 +0200 + +python2.3 (2.2.107-1rc2) unstable; urgency=medium + + * Python 2.3 release candidate 2. + * Don't compress .txt files referenced by the html docs (closes: #200298). + * Include the email/_compat* files (closes: #200349). + + -- Matthias Klose Fri, 25 Jul 2003 07:08:09 +0200 + +python2.3 (2.2.106-2beta2) unstable; urgency=medium + + * Python 2.3 beta2 release, updated to CVS 20030704. + - Fixes AssertionError in httplib (closed: #192452). + - Fixes uncaught division by zero in difflib.py (closed: #199287). + * Detect presence of setgroups(2) at configure time (closes: #199839). + * Use default gcc on arm as well. + + -- Matthias Klose Sat, 5 Jul 2003 10:21:33 +0200 + +python2.3 (2.2.105-1beta2) unstable; urgency=low + + * Python 2.3 beta2 release. + - Includes merged idle fork. + - Fixed socket.setdefaulttimeout(). Closes: #189380. + - socket.ssl works with _socketobj. Closes: #196082. + * Do not link libtix to the _tkinter module. It's loaded via + 'package require tix' at runtime. python2.3-tkinter now + suggests tix8.1 instead. + * On arm, use gcc-3.2 to build. + * Add -fno-strict-aliasing rules to OPT to avoid warnings + "dereferencing type-punned pointer will break strict-aliasing rules", + when building with gcc-3.3. + + -- Matthias Klose Mon, 30 Jun 2003 00:19:32 +0200 + +python2.3 (2.2.104-1beta1.1) unstable; urgency=low + + * Non-maintainer upload with maintainer consent. + * debian/control (Build-Depends): s/libgdbmg1-dev/libgdbm-dev/. + + -- James Troup Wed, 4 Jun 2003 02:24:27 +0100 + +python2.3 (2.2.104-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030514. + - build the current documentation. + * Reenable Tix support. + + -- Matthias Klose Wed, 14 May 2003 07:38:57 +0200 + +python2.3 (2.2.103-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030506. + - updated due to build problems on mips/mipsel. + - keep the 2.3b1 documentation (doc build problems with cvs). + + -- Matthias Klose Wed, 7 May 2003 06:26:39 +0200 + +python2.3 (2.2.102-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release. + + -- Matthias Klose Sat, 3 May 2003 22:45:16 +0200 + +python2.3 (2.2.101-1exp1) unstable; urgency=medium + + * Python 2.3 alpha2 release, updated to CVS 20030321. + * Tkinter: Catch exceptions thrown for undefined substitutions in + events (needed for tk 8.4.2). + + -- Matthias Klose Fri, 21 Mar 2003 21:32:14 +0100 + +python2.3 (2.2.100-1exp1) unstable; urgency=low + + * Python 2.3 alpha2 release, updated to CVS 20030221. + + -- Matthias Klose Fri, 21 Feb 2003 19:37:17 +0100 + +python2.3 (2.2.99-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030123. + - should fix the testsuite (and package build) failure on alpha. + * Remove build dependency on libexpat1-dev. Merge the python2.3-xmlbase + package into python2.3 (closes: #177739). + + -- Matthias Klose Thu, 23 Jan 2003 22:48:12 +0100 + +python2.3 (2.2.98-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030117. + * Build using libdb4.1. + + -- Matthias Klose Sat, 18 Jan 2003 00:14:01 +0100 + +python2.3 (2.2.97-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030109. + * Build-Depend on g++ (>= 3:3.2). + * Python package maintainers: please wait uploading python dependent + packages until python2.2 and python2.1 are compiled using gcc-3.2. + + -- Matthias Klose Thu, 9 Jan 2003 23:56:42 +0100 + +python2.3 (2.2.96-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release (not exactly the tarball, but taken from + CVS 20030101). + - Includes support for linking with threaded tk8.4 (closes: #172714). + * Install and register whatsnew document (closes: #173859). + * Properly unregister info documentation. + + -- Matthias Klose Wed, 1 Jan 2003 17:38:54 +0100 + +python2.3 (2.2.95-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021212. + - data in unicodedate module is up to date (closes: #171061). + * Fix idle packaging (closes: #170394). + * Configure using unicode UCS-4 (closes: #171062). + This change breaks compatibility with binary modules, but what do you + expect from experimental packages ... Please recompile dependent packages. + * Don't strip binaries for now. + + -- Matthias Klose Thu, 12 Dec 2002 21:42:27 +0100 + +python2.3 (2.2.94-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021120. + * Remove outdated README.dbm. + * Depend on tk8.4. + * python-elisp: Install emacsen install file with mode 644 (closes: #167718). + + -- Matthias Klose Thu, 21 Nov 2002 01:04:51 +0100 + +python2.3 (2.2.93-1exp1) unstable; urgency=medium + + * Experimental packages from CVS 021015. + * Build a static library libpython2.3-pic.a. + * Enable large file support for the Hurd (closes: #164602). + + -- Matthias Klose Tue, 15 Oct 2002 21:06:27 +0200 + +python2.3 (2.2.92-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020922. + * Fix build error on ia64 (closes: #161234). + * Build depend on gcc-3.2-3.2.1-0pre2 to fix build error on arm. + + -- Matthias Klose Sun, 22 Sep 2002 18:30:28 +0200 + +python2.3 (2.2.91-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020906. + * idle-python2.3: Fix conflict (closes: #159267). + * Fix location of python-mode.el (closes: #159564, #159619). + * Use tix8.1. + * Apply fix for distutils/ccompiler problem (closes: #159288). + + -- Matthias Klose Sat, 7 Sep 2002 09:55:07 +0200 + +python2.3 (2.2.90-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020820. + * Don't build python2.3-elisp, but put the latest version into + python-elisp. + + -- Matthias Klose Thu, 22 Aug 2002 21:52:04 +0200 + +python2.2 (2.2.1-6) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-07-23. + * Enable IPv6 support (closes: #152543). + * Add python2.2-tk suggestion for python2.2 (pydoc -g). + * Fix from SF patch #527518: proxy config with user+pass authentication. + * Point pydoc to the correct location of the docs (closes: #147579). + * Remove '*.py[co]' files, when removing the python package, + not when purging (closes: #147130). + * Update to new py2texi.el version (Milan Zamazal). + + -- Matthias Klose Mon, 29 Jul 2002 23:11:32 +0200 + +python2.2 (2.2.1-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-05-03. + * Build the info docs (closes: #145653). + + -- Matthias Klose Fri, 3 May 2002 22:35:46 +0200 + +python2.2 (2.2.1-4) unstable; urgency=high + + * Fix indentation errors introduced in last upload (closes: #143809). + + -- Matthias Klose Sun, 21 Apr 2002 01:00:14 +0200 + +python2.2 (2.2.1-3) unstable; urgency=high + + * Add Build-Conflicts: tcl8.0-dev, tk8.0-dev, tcl8.2-dev, tk8.2-dev. + Closes: #143534 (build a working _tkinter module, on machines, where + 8.0's tk.h gets included). + * CVS updates of the release22-maint branch upto 2002-04-20. + + -- Matthias Klose Sat, 20 Apr 2002 09:22:37 +0200 + +python2.2 (2.2.1-2) unstable; urgency=low + + * Forgot to copy the dlmodule patch from the 2.1.3 package. Really + closes: #141681. + + -- Matthias Klose Sat, 13 Apr 2002 01:28:05 +0200 + +python2.2 (2.2.1-1) unstable; urgency=high + + * Final 2.2.1 release. + * According to report #131813, the python interpreter is much faster on some + architectures, when beeing linked statically with the python library (25%). + Gregor and me tested on i386, m68k and alpha, but we could not reproduce + such a speedup (generally between 5% and 10%). But we are linking the + python executable now statically ... + * Build info docs from the tex source, merge the python-doc-info + package into the python-doc package. + * Always build the dl module. Failure in case of + sizeof(int)!=sizeof(long)!=sizeof(void*) + is delayed until dl.open is called. Closes: #141681. + + -- Matthias Klose Thu, 11 Apr 2002 00:19:19 +0200 + +python2.2 (2.2.0.92-0) unstable; urgency=low + + * Package CVS sources, omit cvs-updates.dpatch (closes: #140977). + + -- Matthias Klose Wed, 3 Apr 2002 08:20:52 +0200 + +python2.2 (2.2-6) unstable; urgency=medium + + * Update to python-2.2.1 release candidate 2 (final release scheduled + for April 10). + * Enable dl module (closes: #138992). + * Build doc files with python binary from package (closes: #139657). + * Build _tkinter module with BLT and Tix support. + * python2.2-elisp: Conflict with python2-elisp (closes: #138970). + * string.split docs updated in python-2.2.1 (closes: #129272). + + -- Matthias Klose Mon, 1 Apr 2002 13:52:36 +0200 + +python2.2 (2.2-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 20020310 (aproaching + the first 2.2.1 release candidate). + * Stolen from HEAD: check argument of locale.nl_langinfo (closes: #137371). + + -- Matthias Klose Fri, 15 Mar 2002 01:05:59 +0100 + +python2.2 (2.2-4) unstable; urgency=medium + + * Include test/{__init__.py,README,pystone.py} in package (closes: #129013). + * Fix python-elisp conflict (closes: #129046). + * Don't compress stylesheets (closes: #133179). + * CVS updates of the release22-maint branch upto 20020310. + + -- Matthias Klose Sun, 10 Mar 2002 23:32:28 +0100 + +python2.2 (2.2-3) unstable; urgency=medium + + * Updates from the CVS python22-maint branch up to 20020107. + webbrowser.py: properly escape url's. + * The Hurd does not have large file support: disabled. + + -- Matthias Klose Mon, 7 Jan 2002 21:55:57 +0100 + +python2.2 (2.2-2) unstable; urgency=medium + + * CVS updates of the release22-maint branch upto 20011229. Fixes: + - Include TCP_CORK flag in plat-linux2 headers (fixes: #84340). + - Update CDROM.py module (fixes: #125785). + * Add missing chunk of the GNU/Hurd patch (therefore urgency medium). + * Send anonymous password when using anonftp (closes: #126814). + + -- Matthias Klose Sat, 29 Dec 2001 20:18:26 +0100 + +python2.2 (2.2-1) unstable; urgency=low + + * New upstream version: 2.2. + * Bugs fixed upstream: + - Docs for os.kill reference the signal module for constants. + - Documentation strings in the tutorial end with a period (closes: #94770). + - Tk: grid_location method moved from Grid to Misc (closes: #98338). + - mhlib.SubMessage.getbodytext takes decode parameter (closes: #31876). + - Strings in modules are locale aware (closes: #51444). + - Printable 8-bit characters in strings are correctly printed + (closes: #64354). + - Dictionary can be updated with abstract mapping object (closes: #46566). + * Make site.py a config files. + + -- Matthias Klose Sat, 22 Dec 2001 00:51:46 +0100 + +python2.2 (2.1.99c1-1) unstable; urgency=low + + * New upstream version: 2.2c1 (release candidate). + * Do not provide python2.2-base anymore. + * Install correct README.Debian for python2.2 package. Include hint + where to find Makefile.pre.in. + * Suggest installation of python-ssl. + * Remove idle config files on purge. + * Remove empty /usr/lib/python2.2 directory on purge. + + -- Matthias Klose Sat, 15 Dec 2001 17:56:27 +0100 + +python2.2 (2.1.99beta2-1) unstable; urgency=high + + * debian/rules: Reflect removal of regrtest package (closes: #122278). + Resulted in build failures on all architectures. + * Build -doc package from source. + + -- Matthias Klose Sat, 8 Dec 2001 00:38:41 +0100 + +python2.2 (2.1.99beta2-0.1) unstable; urgency=low + + * Non maintainer upload. + * New upstream version (this is 2.2beta2). + * Do not build the python-regrtest package anymore; keep the test framework + components test/regrtest.py and test/test_support.py in the python + package (closes: #119408). + + -- Gregor Hoffleit Tue, 27 Nov 2001 09:53:26 +0100 + +python2.2 (2.1.99beta1-4) unstable; urgency=low + + * Configure with --with-fpectl (closes: #118125). + * setup.py: Remove broken check for _curses_panel module (#116081). + * idle: Move config-* files to /etc and mark as conffiles (#106390). + * Move idle packages to section `devel'. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-3) unstable; urgency=low + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * README.Debian: point to draft of python-policy in the python package. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-2) unstable; urgency=medium + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * Rename package python2.2-base to python2.2. + + -- Matthias Klose Wed, 24 Oct 2001 23:00:50 +0200 + +python2.2 (2.1.99beta1-1) unstable; urgency=low + + * New upstream version (beta). Call the package version 2.1.99beta1-1. + * New maintainer until the final 2.2 release. + * Updated the debian patches. + + -- Matthias Klose Sat, 20 Oct 2001 18:56:26 +0200 + +python2.1 (2.1.1-1.2) unstable; urgency=low + + * Really remove the python alternative. + + -- Matthias Klose Sat, 20 Oct 2001 15:16:56 +0200 + +python2.1 (2.1.1-1.1) unstable; urgency=low + + * README FOR PACKAGE MAINTAINERS: It is planned to remove the python2-XXX + packages from unstable and move on to python2.1. + If you repackage/adapt your modules for python2.1, don't build + python2-XXX and python2.1-XXX packages from the same source package, + so that the python2-XXX package can be removed without influencing the + python2.1-XXX package. + + See the debian-python mailing list at http://lists.debian.org/devel.html + for details and the current discussion and a draft for a debian-python + policy (August to October 2001). + + * Remove alternative for /usr/bin/python. The python-base package now + provides the default python version. + + * Regenerate control file to fix build dependencies (closes: #116190). + * Remove alternative for /usr/bin/{python,pydoc}. + * Provide a libpython2.1.so symlink in /usr/lib/python2.1/config, + so that the shared library is found when -L/usr/lib/python2.1/config + is specified. + * Conflict with old package versions, where /usr/bin/python is a real + program (closes: #115943). + * python2.1-elisp conflicts with python-elisp (closes: #115895). + * We now have 2.1 (closes: #96851, #107849, #110243). + + -- Matthias Klose Fri, 19 Oct 2001 17:34:41 +0200 + +python2.1 (2.1.1-1) unstable; urgency=low + + * Incorporated Matthias' modifications. + + -- Gregor Hoffleit Thu, 11 Oct 2001 00:16:42 +0200 + +python2.1 (2.1.1-0.2) unstable; urgency=low + + * New upstream 2.1.1. + * GPL compatible licence (fixes #84080, #102949, #110643). + * Fixed upstream (closes: #99692, #111340). + * Build in separate build directory. + * Split Debian patches into debian/patches directory. + * Build dependencies: Add libgmp3-dev, libexpat1-dev, tighten + debhelper dependency. + * debian/rules: Updated a "bit". + * python-elisp: Remove custom dependency (closes: #87783), + fix emacs path (closes: #89712), remove emacs19 dependency (#82694). + * Mention distutils in python-dev package description (closes: #108170). + * Update README.Debian (closes: #85430). + * Run versioned python in postinsts (closes: #113349). + * debian/sample.{postinst,prerm}: Change to version independent scripts. + * Use '/usr/bin/env python2.1' as interpreter for all python scripts. + * Add libssl-dev to Build-Conflicts. + * python-elisp: Add support for emacs21 (closes: #98635). + * Do not compress .py files in doc directories. + * Don't link explicitely with libc. + + -- Matthias Klose Wed, 3 Oct 2001 09:53:08 +0200 + +python2.1 (2.1.1-0.1) unstable; urgency=low + + * New upstream version (CVS branch release21-maint, will become 2.1.1): + This CVS branch will be released as 2.1.1 under a GPL compatible + license. + + -- Gregor Hoffleit Wed, 27 Jun 2001 22:47:58 +0200 + +python2 (2.1-0.1) unstable; urgency=low + + * Fixed Makefile.pre.in. + * Fixed the postinst files in order to use 2.1 (instead of 2.0). + * Mention the immanent release of 2.0.1 and 2.1.1, with a GPL + compatible license. + + -- Gregor Hoffleit Sun, 17 Jun 2001 21:05:25 +0200 + +python2 (2.1-0) unstable; urgency=low + + * New upstream version. + * Experimental packages. + + -- Gregor Hoffleit Thu, 10 May 2001 00:20:04 +0200 + +python2 (2.0-7) unstable; urgency=low + + * Rebuilt with recent tcl8.3-dev/tk8.3-dev in order to fix a + dependency problem with python2-tk (closes: #87793, #92962). + * Change postinst to create and update /usr/local/lib/python2.0 and + site-python with permissions and owner as mandated by policy: + 2775 and root:staff (closes: #89047). + * Fix to compileall.py: A superfluous argument made compileall without + options fail (cf. #92990 for python). + * Move the distutils module into python2-dev. It needs Makefile.pre.in + in order to work (closes: #89900). + * Remove build-dependency on libgdbm2-dev (which isn't built anyway). + * Add a build-dependency on libdb2-dev (cf. #90220 for python). + + -- Gregor Hoffleit Sat, 14 Apr 2001 21:07:51 +0200 + +python2 (2.0-6) unstable; urgency=low + + * Remove python-zlib package; merge it into python-base. + * Mark that README.python2 is not yet updated. + + -- Gregor Hoffleit Wed, 21 Feb 2001 12:34:18 +0100 + +python2 (2.0-5) unstable; urgency=low + + * Recompile with tcl/tk8.3 (closes: #82088). + * Modifications to README.why-python2 (closes: #82116). + * Add menu hint to idle2 menu entry. + * idle2 is renamed idle-python2 and now build correctly (closes: #82218). + * Add build-dependency on autoconf (closes: #85339). + * Build bsddbmodule as shared module (Modules/Setup.config.in), + and link libpython2.so with -lm in Makefile (closes: #86027). + * various cleanups in debian/rules, e.g. removing dh_suidregister. + * Make pdb available as /usr/bin/pdb-python2 in python2-dev + (cf. #79870 in python-base). + * Remove libgmp3 from build-dependencies, since we currently can't + build the mpzmodule for Python2 due to license problems. + + -- Gregor Hoffleit Sun, 18 Feb 2001 00:12:17 +0100 + +python2 (2.0-4) unstable; urgency=low + + * control: make python2-elisp conflict with python-elisp (it doesn't + make sense to have both of them installed, does it ?) + * include build-depend on libxmltok1-dev. + * again, build with tcl/tk8.0. + + -- Gregor Hoffleit Wed, 10 Jan 2001 23:37:01 +0100 + +python2 (2.0-3) unstable; urgency=low + + * Modules/Setup.in: Added a missing \ that made _tkinter be built + incorrectly. + * rules: on the fly, change all '#!' python scripts to use python2. + + -- Gregor Hoffleit Wed, 13 Dec 2000 20:07:24 +0100 + +python2 (2.0-2) unstable; urgency=low + + * Aaargh. Remove conflicts/provides/replaces on python-base to make + parallel installation of python-base and python2-base possible. + * Install examples into /usr/share/doc/python2 (not python) and fix + symlink to python2.0 (thanks to Rick Younie for + pointing out this). + * Rename man page to python2.1. + + -- Gregor Hoffleit Wed, 13 Dec 2000 09:31:05 +0100 + +python2 (2.0-1) unstable; urgency=low + + * New upstream version. Initial release for python2. + + -- Gregor Hoffleit Mon, 11 Dec 2000 22:39:46 +0100 --- python2.7-2.7.2.orig/debian/pygettext.1 +++ python2.7-2.7.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". --- python2.7-2.7.2.orig/debian/patches/profile-pstats.diff +++ python2.7-2.7.2/debian/patches/profile-pstats.diff @@ -0,0 +1,1321 @@ +--- /dev/null ++++ b/Lib/profile.py +@@ -0,0 +1,610 @@ ++#! /usr/bin/env python ++# ++# Class for profiling python code. rev 1.0 6/2/94 ++# ++# Written by James Roskind ++# Based on prior profile module by Sjoerd Mullender... ++# which was hacked somewhat by: Guido van Rossum ++ ++"""Class for profiling Python code.""" ++ ++# Copyright Disney Enterprises, Inc. All Rights Reserved. ++# 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 ++# governing permissions and limitations under the License. ++ ++ ++import sys ++import os ++import time ++import marshal ++from optparse import OptionParser ++ ++__all__ = ["run", "runctx", "help", "Profile"] ++ ++# Sample timer for use with ++#i_count = 0 ++#def integer_timer(): ++# global i_count ++# i_count = i_count + 1 ++# return i_count ++#itimes = integer_timer # replace with C coded timer returning integers ++ ++#************************************************************************** ++# The following are the static member functions for the profiler class ++# Note that an instance of Profile() is *not* needed to call them. ++#************************************************************************** ++ ++def run(statement, filename=None, sort=-1): ++ """Run statement under profiler optionally saving results in filename ++ ++ This function takes a single argument that can be passed to the ++ "exec" statement, and an optional file name. In all cases this ++ routine attempts to "exec" its first argument and gather profiling ++ statistics from the execution. If no file name is present, then this ++ function automatically prints a simple profiling report, sorted by the ++ standard name string (file/line/function-name) that is presented in ++ each line. ++ """ ++ prof = Profile() ++ try: ++ prof = prof.run(statement) ++ except SystemExit: ++ pass ++ if filename is not None: ++ prof.dump_stats(filename) ++ else: ++ return prof.print_stats(sort) ++ ++def runctx(statement, globals, locals, filename=None, sort=-1): ++ """Run statement under profiler, supplying your own globals and locals, ++ optionally saving results in filename. ++ ++ statement and filename have the same semantics as profile.run ++ """ ++ prof = Profile() ++ try: ++ prof = prof.runctx(statement, globals, locals) ++ except SystemExit: ++ pass ++ ++ if filename is not None: ++ prof.dump_stats(filename) ++ else: ++ return prof.print_stats(sort) ++ ++# Backwards compatibility. ++def help(): ++ print "Documentation for the profile module can be found " ++ print "in the Python Library Reference, section 'The Python Profiler'." ++ ++if hasattr(os, "times"): ++ def _get_time_times(timer=os.times): ++ t = timer() ++ return t[0] + t[1] ++ ++# Using getrusage(3) is better than clock(3) if available: ++# on some systems (e.g. FreeBSD), getrusage has a higher resolution ++# Furthermore, on a POSIX system, returns microseconds, which ++# wrap around after 36min. ++_has_res = 0 ++try: ++ import resource ++ resgetrusage = lambda: resource.getrusage(resource.RUSAGE_SELF) ++ def _get_time_resource(timer=resgetrusage): ++ t = timer() ++ return t[0] + t[1] ++ _has_res = 1 ++except ImportError: ++ pass ++ ++class Profile: ++ """Profiler class. ++ ++ self.cur is always a tuple. Each such tuple corresponds to a stack ++ frame that is currently active (self.cur[-2]). The following are the ++ definitions of its members. We use this external "parallel stack" to ++ avoid contaminating the program that we are profiling. (old profiler ++ used to write into the frames local dictionary!!) Derived classes ++ can change the definition of some entries, as long as they leave ++ [-2:] intact (frame and previous tuple). In case an internal error is ++ detected, the -3 element is used as the function name. ++ ++ [ 0] = Time that needs to be charged to the parent frame's function. ++ It is used so that a function call will not have to access the ++ timing data for the parent frame. ++ [ 1] = Total time spent in this frame's function, excluding time in ++ subfunctions (this latter is tallied in cur[2]). ++ [ 2] = Total time spent in subfunctions, excluding time executing the ++ frame's function (this latter is tallied in cur[1]). ++ [-3] = Name of the function that corresponds to this frame. ++ [-2] = Actual frame that we correspond to (used to sync exception handling). ++ [-1] = Our parent 6-tuple (corresponds to frame.f_back). ++ ++ Timing data for each function is stored as a 5-tuple in the dictionary ++ self.timings[]. The index is always the name stored in self.cur[-3]. ++ The following are the definitions of the members: ++ ++ [0] = The number of times this function was called, not counting direct ++ or indirect recursion, ++ [1] = Number of times this function appears on the stack, minus one ++ [2] = Total time spent internal to this function ++ [3] = Cumulative time that this function was present on the stack. In ++ non-recursive functions, this is the total execution time from start ++ to finish of each invocation of a function, including time spent in ++ all subfunctions. ++ [4] = A dictionary indicating for each function name, the number of times ++ it was called by us. ++ """ ++ ++ bias = 0 # calibration constant ++ ++ def __init__(self, timer=None, bias=None): ++ self.timings = {} ++ self.cur = None ++ self.cmd = "" ++ self.c_func_name = "" ++ ++ if bias is None: ++ bias = self.bias ++ self.bias = bias # Materialize in local dict for lookup speed. ++ ++ if not timer: ++ if _has_res: ++ self.timer = resgetrusage ++ self.dispatcher = self.trace_dispatch ++ self.get_time = _get_time_resource ++ elif hasattr(time, 'clock'): ++ self.timer = self.get_time = time.clock ++ self.dispatcher = self.trace_dispatch_i ++ elif hasattr(os, 'times'): ++ self.timer = os.times ++ self.dispatcher = self.trace_dispatch ++ self.get_time = _get_time_times ++ else: ++ self.timer = self.get_time = time.time ++ self.dispatcher = self.trace_dispatch_i ++ else: ++ self.timer = timer ++ t = self.timer() # test out timer function ++ try: ++ length = len(t) ++ except TypeError: ++ self.get_time = timer ++ self.dispatcher = self.trace_dispatch_i ++ else: ++ if length == 2: ++ self.dispatcher = self.trace_dispatch ++ else: ++ self.dispatcher = self.trace_dispatch_l ++ # This get_time() implementation needs to be defined ++ # here to capture the passed-in timer in the parameter ++ # list (for performance). Note that we can't assume ++ # the timer() result contains two values in all ++ # cases. ++ def get_time_timer(timer=timer, sum=sum): ++ return sum(timer()) ++ self.get_time = get_time_timer ++ self.t = self.get_time() ++ self.simulate_call('profiler') ++ ++ # Heavily optimized dispatch routine for os.times() timer ++ ++ def trace_dispatch(self, frame, event, arg): ++ timer = self.timer ++ t = timer() ++ t = t[0] + t[1] - self.t - self.bias ++ ++ if event == "c_call": ++ self.c_func_name = arg.__name__ ++ ++ if self.dispatch[event](self, frame,t): ++ t = timer() ++ self.t = t[0] + t[1] ++ else: ++ r = timer() ++ self.t = r[0] + r[1] - t # put back unrecorded delta ++ ++ # Dispatch routine for best timer program (return = scalar, fastest if ++ # an integer but float works too -- and time.clock() relies on that). ++ ++ def trace_dispatch_i(self, frame, event, arg): ++ timer = self.timer ++ t = timer() - self.t - self.bias ++ ++ if event == "c_call": ++ self.c_func_name = arg.__name__ ++ ++ if self.dispatch[event](self, frame, t): ++ self.t = timer() ++ else: ++ self.t = timer() - t # put back unrecorded delta ++ ++ # Dispatch routine for macintosh (timer returns time in ticks of ++ # 1/60th second) ++ ++ def trace_dispatch_mac(self, frame, event, arg): ++ timer = self.timer ++ t = timer()/60.0 - self.t - self.bias ++ ++ if event == "c_call": ++ self.c_func_name = arg.__name__ ++ ++ if self.dispatch[event](self, frame, t): ++ self.t = timer()/60.0 ++ else: ++ self.t = timer()/60.0 - t # put back unrecorded delta ++ ++ # SLOW generic dispatch routine for timer returning lists of numbers ++ ++ def trace_dispatch_l(self, frame, event, arg): ++ get_time = self.get_time ++ t = get_time() - self.t - self.bias ++ ++ if event == "c_call": ++ self.c_func_name = arg.__name__ ++ ++ if self.dispatch[event](self, frame, t): ++ self.t = get_time() ++ else: ++ self.t = get_time() - t # put back unrecorded delta ++ ++ # In the event handlers, the first 3 elements of self.cur are unpacked ++ # into vrbls w/ 3-letter names. The last two characters are meant to be ++ # mnemonic: ++ # _pt self.cur[0] "parent time" time to be charged to parent frame ++ # _it self.cur[1] "internal time" time spent directly in the function ++ # _et self.cur[2] "external time" time spent in subfunctions ++ ++ def trace_dispatch_exception(self, frame, t): ++ rpt, rit, ret, rfn, rframe, rcur = self.cur ++ if (rframe is not frame) and rcur: ++ return self.trace_dispatch_return(rframe, t) ++ self.cur = rpt, rit+t, ret, rfn, rframe, rcur ++ return 1 ++ ++ ++ def trace_dispatch_call(self, frame, t): ++ if self.cur and frame.f_back is not self.cur[-2]: ++ rpt, rit, ret, rfn, rframe, rcur = self.cur ++ if not isinstance(rframe, Profile.fake_frame): ++ assert rframe.f_back is frame.f_back, ("Bad call", rfn, ++ rframe, rframe.f_back, ++ frame, frame.f_back) ++ self.trace_dispatch_return(rframe, 0) ++ assert (self.cur is None or \ ++ frame.f_back is self.cur[-2]), ("Bad call", ++ self.cur[-3]) ++ fcode = frame.f_code ++ fn = (fcode.co_filename, fcode.co_firstlineno, fcode.co_name) ++ self.cur = (t, 0, 0, fn, frame, self.cur) ++ timings = self.timings ++ if fn in timings: ++ cc, ns, tt, ct, callers = timings[fn] ++ timings[fn] = cc, ns + 1, tt, ct, callers ++ else: ++ timings[fn] = 0, 0, 0, 0, {} ++ return 1 ++ ++ def trace_dispatch_c_call (self, frame, t): ++ fn = ("", 0, self.c_func_name) ++ self.cur = (t, 0, 0, fn, frame, self.cur) ++ timings = self.timings ++ if fn in timings: ++ cc, ns, tt, ct, callers = timings[fn] ++ timings[fn] = cc, ns+1, tt, ct, callers ++ else: ++ timings[fn] = 0, 0, 0, 0, {} ++ return 1 ++ ++ def trace_dispatch_return(self, frame, t): ++ if frame is not self.cur[-2]: ++ assert frame is self.cur[-2].f_back, ("Bad return", self.cur[-3]) ++ self.trace_dispatch_return(self.cur[-2], 0) ++ ++ # Prefix "r" means part of the Returning or exiting frame. ++ # Prefix "p" means part of the Previous or Parent or older frame. ++ ++ rpt, rit, ret, rfn, frame, rcur = self.cur ++ rit = rit + t ++ frame_total = rit + ret ++ ++ ppt, pit, pet, pfn, pframe, pcur = rcur ++ self.cur = ppt, pit + rpt, pet + frame_total, pfn, pframe, pcur ++ ++ timings = self.timings ++ cc, ns, tt, ct, callers = timings[rfn] ++ if not ns: ++ # This is the only occurrence of the function on the stack. ++ # Else this is a (directly or indirectly) recursive call, and ++ # its cumulative time will get updated when the topmost call to ++ # it returns. ++ ct = ct + frame_total ++ cc = cc + 1 ++ ++ if pfn in callers: ++ callers[pfn] = callers[pfn] + 1 # hack: gather more ++ # stats such as the amount of time added to ct courtesy ++ # of this specific call, and the contribution to cc ++ # courtesy of this call. ++ else: ++ callers[pfn] = 1 ++ ++ timings[rfn] = cc, ns - 1, tt + rit, ct, callers ++ ++ return 1 ++ ++ ++ dispatch = { ++ "call": trace_dispatch_call, ++ "exception": trace_dispatch_exception, ++ "return": trace_dispatch_return, ++ "c_call": trace_dispatch_c_call, ++ "c_exception": trace_dispatch_return, # the C function returned ++ "c_return": trace_dispatch_return, ++ } ++ ++ ++ # The next few functions play with self.cmd. By carefully preloading ++ # our parallel stack, we can force the profiled result to include ++ # an arbitrary string as the name of the calling function. ++ # We use self.cmd as that string, and the resulting stats look ++ # very nice :-). ++ ++ def set_cmd(self, cmd): ++ if self.cur[-1]: return # already set ++ self.cmd = cmd ++ self.simulate_call(cmd) ++ ++ class fake_code: ++ def __init__(self, filename, line, name): ++ self.co_filename = filename ++ self.co_line = line ++ self.co_name = name ++ self.co_firstlineno = 0 ++ ++ def __repr__(self): ++ return repr((self.co_filename, self.co_line, self.co_name)) ++ ++ class fake_frame: ++ def __init__(self, code, prior): ++ self.f_code = code ++ self.f_back = prior ++ ++ def simulate_call(self, name): ++ code = self.fake_code('profile', 0, name) ++ if self.cur: ++ pframe = self.cur[-2] ++ else: ++ pframe = None ++ frame = self.fake_frame(code, pframe) ++ self.dispatch['call'](self, frame, 0) ++ ++ # collect stats from pending stack, including getting final ++ # timings for self.cmd frame. ++ ++ def simulate_cmd_complete(self): ++ get_time = self.get_time ++ t = get_time() - self.t ++ while self.cur[-1]: ++ # We *can* cause assertion errors here if ++ # dispatch_trace_return checks for a frame match! ++ self.dispatch['return'](self, self.cur[-2], t) ++ t = 0 ++ self.t = get_time() - t ++ ++ ++ def print_stats(self, sort=-1): ++ import pstats ++ pstats.Stats(self).strip_dirs().sort_stats(sort). \ ++ print_stats() ++ ++ def dump_stats(self, file): ++ f = open(file, 'wb') ++ self.create_stats() ++ marshal.dump(self.stats, f) ++ f.close() ++ ++ def create_stats(self): ++ self.simulate_cmd_complete() ++ self.snapshot_stats() ++ ++ def snapshot_stats(self): ++ self.stats = {} ++ for func, (cc, ns, tt, ct, callers) in self.timings.iteritems(): ++ callers = callers.copy() ++ nc = 0 ++ for callcnt in callers.itervalues(): ++ nc += callcnt ++ self.stats[func] = cc, nc, tt, ct, callers ++ ++ ++ # The following two methods can be called by clients to use ++ # a profiler to profile a statement, given as a string. ++ ++ def run(self, cmd): ++ import __main__ ++ dict = __main__.__dict__ ++ return self.runctx(cmd, dict, dict) ++ ++ def runctx(self, cmd, globals, locals): ++ self.set_cmd(cmd) ++ sys.setprofile(self.dispatcher) ++ try: ++ exec cmd in globals, locals ++ finally: ++ sys.setprofile(None) ++ return self ++ ++ # This method is more useful to profile a single function call. ++ def runcall(self, func, *args, **kw): ++ self.set_cmd(repr(func)) ++ sys.setprofile(self.dispatcher) ++ try: ++ return func(*args, **kw) ++ finally: ++ sys.setprofile(None) ++ ++ ++ #****************************************************************** ++ # The following calculates the overhead for using a profiler. The ++ # problem is that it takes a fair amount of time for the profiler ++ # to stop the stopwatch (from the time it receives an event). ++ # Similarly, there is a delay from the time that the profiler ++ # re-starts the stopwatch before the user's code really gets to ++ # continue. The following code tries to measure the difference on ++ # a per-event basis. ++ # ++ # Note that this difference is only significant if there are a lot of ++ # events, and relatively little user code per event. For example, ++ # code with small functions will typically benefit from having the ++ # profiler calibrated for the current platform. This *could* be ++ # done on the fly during init() time, but it is not worth the ++ # effort. Also note that if too large a value specified, then ++ # execution time on some functions will actually appear as a ++ # negative number. It is *normal* for some functions (with very ++ # low call counts) to have such negative stats, even if the ++ # calibration figure is "correct." ++ # ++ # One alternative to profile-time calibration adjustments (i.e., ++ # adding in the magic little delta during each event) is to track ++ # more carefully the number of events (and cumulatively, the number ++ # of events during sub functions) that are seen. If this were ++ # done, then the arithmetic could be done after the fact (i.e., at ++ # display time). Currently, we track only call/return events. ++ # These values can be deduced by examining the callees and callers ++ # vectors for each functions. Hence we *can* almost correct the ++ # internal time figure at print time (note that we currently don't ++ # track exception event processing counts). Unfortunately, there ++ # is currently no similar information for cumulative sub-function ++ # time. It would not be hard to "get all this info" at profiler ++ # time. Specifically, we would have to extend the tuples to keep ++ # counts of this in each frame, and then extend the defs of timing ++ # tuples to include the significant two figures. I'm a bit fearful ++ # that this additional feature will slow the heavily optimized ++ # event/time ratio (i.e., the profiler would run slower, fur a very ++ # low "value added" feature.) ++ #************************************************************** ++ ++ def calibrate(self, m, verbose=0): ++ if self.__class__ is not Profile: ++ raise TypeError("Subclasses must override .calibrate().") ++ ++ saved_bias = self.bias ++ self.bias = 0 ++ try: ++ return self._calibrate_inner(m, verbose) ++ finally: ++ self.bias = saved_bias ++ ++ def _calibrate_inner(self, m, verbose): ++ get_time = self.get_time ++ ++ # Set up a test case to be run with and without profiling. Include ++ # lots of calls, because we're trying to quantify stopwatch overhead. ++ # Do not raise any exceptions, though, because we want to know ++ # exactly how many profile events are generated (one call event, + ++ # one return event, per Python-level call). ++ ++ def f1(n): ++ for i in range(n): ++ x = 1 ++ ++ def f(m, f1=f1): ++ for i in range(m): ++ f1(100) ++ ++ f(m) # warm up the cache ++ ++ # elapsed_noprofile <- time f(m) takes without profiling. ++ t0 = get_time() ++ f(m) ++ t1 = get_time() ++ elapsed_noprofile = t1 - t0 ++ if verbose: ++ print "elapsed time without profiling =", elapsed_noprofile ++ ++ # elapsed_profile <- time f(m) takes with profiling. The difference ++ # is profiling overhead, only some of which the profiler subtracts ++ # out on its own. ++ p = Profile() ++ t0 = get_time() ++ p.runctx('f(m)', globals(), locals()) ++ t1 = get_time() ++ elapsed_profile = t1 - t0 ++ if verbose: ++ print "elapsed time with profiling =", elapsed_profile ++ ++ # reported_time <- "CPU seconds" the profiler charged to f and f1. ++ total_calls = 0.0 ++ reported_time = 0.0 ++ for (filename, line, funcname), (cc, ns, tt, ct, callers) in \ ++ p.timings.items(): ++ if funcname in ("f", "f1"): ++ total_calls += cc ++ reported_time += tt ++ ++ if verbose: ++ print "'CPU seconds' profiler reported =", reported_time ++ print "total # calls =", total_calls ++ if total_calls != m + 1: ++ raise ValueError("internal error: total calls = %d" % total_calls) ++ ++ # reported_time - elapsed_noprofile = overhead the profiler wasn't ++ # able to measure. Divide by twice the number of calls (since there ++ # are two profiler events per call in this test) to get the hidden ++ # overhead per event. ++ mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls ++ if verbose: ++ print "mean stopwatch overhead per profile event =", mean ++ return mean ++ ++#**************************************************************************** ++def Stats(*args): ++ print 'Report generating functions are in the "pstats" module\a' ++ ++def main(): ++ usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..." ++ parser = OptionParser(usage=usage) ++ parser.allow_interspersed_args = False ++ parser.add_option('-o', '--outfile', dest="outfile", ++ help="Save stats to ", default=None) ++ parser.add_option('-s', '--sort', dest="sort", ++ help="Sort order when printing to stdout, based on pstats.Stats class", ++ default=-1) ++ ++ if not sys.argv[1:]: ++ parser.print_usage() ++ sys.exit(2) ++ ++ (options, args) = parser.parse_args() ++ sys.argv[:] = args ++ ++ if len(args) > 0: ++ progname = args[0] ++ sys.path.insert(0, os.path.dirname(progname)) ++ with open(progname, 'rb') as fp: ++ code = compile(fp.read(), progname, 'exec') ++ globs = { ++ '__file__': progname, ++ '__name__': '__main__', ++ '__package__': None, ++ } ++ runctx(code, globs, None, options.outfile, options.sort) ++ else: ++ parser.print_usage() ++ return parser ++ ++# When invoked as main program, invoke the profiler on a script ++if __name__ == '__main__': ++ main() +--- /dev/null ++++ b/Lib/pstats.py +@@ -0,0 +1,705 @@ ++"""Class for printing reports on profiled python code.""" ++ ++# Class for printing reports on profiled python code. rev 1.0 4/1/94 ++# ++# Written by James Roskind ++# Based on prior profile module by Sjoerd Mullender... ++# which was hacked somewhat by: Guido van Rossum ++ ++"""Class for profiling Python code.""" ++ ++# Copyright Disney Enterprises, Inc. All Rights Reserved. ++# 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 ++# governing permissions and limitations under the License. ++ ++ ++import sys ++import os ++import time ++import marshal ++import re ++from functools import cmp_to_key ++ ++__all__ = ["Stats"] ++ ++class Stats: ++ """This class is used for creating reports from data generated by the ++ Profile class. It is a "friend" of that class, and imports data either ++ by direct access to members of Profile class, or by reading in a dictionary ++ that was emitted (via marshal) from the Profile class. ++ ++ The big change from the previous Profiler (in terms of raw functionality) ++ is that an "add()" method has been provided to combine Stats from ++ several distinct profile runs. Both the constructor and the add() ++ method now take arbitrarily many file names as arguments. ++ ++ All the print methods now take an argument that indicates how many lines ++ to print. If the arg is a floating point number between 0 and 1.0, then ++ it is taken as a decimal percentage of the available lines to be printed ++ (e.g., .1 means print 10% of all available lines). If it is an integer, ++ it is taken to mean the number of lines of data that you wish to have ++ printed. ++ ++ The sort_stats() method now processes some additional options (i.e., in ++ addition to the old -1, 0, 1, or 2). It takes an arbitrary number of ++ quoted strings to select the sort order. For example sort_stats('time', ++ 'name') sorts on the major key of 'internal function time', and on the ++ minor key of 'the name of the function'. Look at the two tables in ++ sort_stats() and get_sort_arg_defs(self) for more examples. ++ ++ All methods return self, so you can string together commands like: ++ Stats('foo', 'goo').strip_dirs().sort_stats('calls').\ ++ print_stats(5).print_callers(5) ++ """ ++ ++ def __init__(self, *args, **kwds): ++ # I can't figure out how to explictly specify a stream keyword arg ++ # with *args: ++ # def __init__(self, *args, stream=sys.stdout): ... ++ # so I use **kwds and sqauwk if something unexpected is passed in. ++ self.stream = sys.stdout ++ if "stream" in kwds: ++ self.stream = kwds["stream"] ++ del kwds["stream"] ++ if kwds: ++ keys = kwds.keys() ++ keys.sort() ++ extras = ", ".join(["%s=%s" % (k, kwds[k]) for k in keys]) ++ raise ValueError, "unrecognized keyword args: %s" % extras ++ if not len(args): ++ arg = None ++ else: ++ arg = args[0] ++ args = args[1:] ++ self.init(arg) ++ self.add(*args) ++ ++ def init(self, arg): ++ self.all_callees = None # calc only if needed ++ self.files = [] ++ self.fcn_list = None ++ self.total_tt = 0 ++ self.total_calls = 0 ++ self.prim_calls = 0 ++ self.max_name_len = 0 ++ self.top_level = {} ++ self.stats = {} ++ self.sort_arg_dict = {} ++ self.load_stats(arg) ++ trouble = 1 ++ try: ++ self.get_top_level_stats() ++ trouble = 0 ++ finally: ++ if trouble: ++ print >> self.stream, "Invalid timing data", ++ if self.files: print >> self.stream, self.files[-1], ++ print >> self.stream ++ ++ def load_stats(self, arg): ++ if not arg: self.stats = {} ++ elif isinstance(arg, basestring): ++ f = open(arg, 'rb') ++ self.stats = marshal.load(f) ++ f.close() ++ try: ++ file_stats = os.stat(arg) ++ arg = time.ctime(file_stats.st_mtime) + " " + arg ++ except: # in case this is not unix ++ pass ++ self.files = [ arg ] ++ elif hasattr(arg, 'create_stats'): ++ arg.create_stats() ++ self.stats = arg.stats ++ arg.stats = {} ++ if not self.stats: ++ raise TypeError, "Cannot create or construct a %r object from '%r''" % ( ++ self.__class__, arg) ++ return ++ ++ def get_top_level_stats(self): ++ for func, (cc, nc, tt, ct, callers) in self.stats.items(): ++ self.total_calls += nc ++ self.prim_calls += cc ++ self.total_tt += tt ++ if ("jprofile", 0, "profiler") in callers: ++ self.top_level[func] = None ++ if len(func_std_string(func)) > self.max_name_len: ++ self.max_name_len = len(func_std_string(func)) ++ ++ def add(self, *arg_list): ++ if not arg_list: return self ++ if len(arg_list) > 1: self.add(*arg_list[1:]) ++ other = arg_list[0] ++ if type(self) != type(other) or self.__class__ != other.__class__: ++ other = Stats(other) ++ self.files += other.files ++ self.total_calls += other.total_calls ++ self.prim_calls += other.prim_calls ++ self.total_tt += other.total_tt ++ for func in other.top_level: ++ self.top_level[func] = None ++ ++ if self.max_name_len < other.max_name_len: ++ self.max_name_len = other.max_name_len ++ ++ self.fcn_list = None ++ ++ for func, stat in other.stats.iteritems(): ++ if func in self.stats: ++ old_func_stat = self.stats[func] ++ else: ++ old_func_stat = (0, 0, 0, 0, {},) ++ self.stats[func] = add_func_stats(old_func_stat, stat) ++ return self ++ ++ def dump_stats(self, filename): ++ """Write the profile data to a file we know how to load back.""" ++ f = file(filename, 'wb') ++ try: ++ marshal.dump(self.stats, f) ++ finally: ++ f.close() ++ ++ # list the tuple indices and directions for sorting, ++ # along with some printable description ++ sort_arg_dict_default = { ++ "calls" : (((1,-1), ), "call count"), ++ "cumulative": (((3,-1), ), "cumulative time"), ++ "file" : (((4, 1), ), "file name"), ++ "line" : (((5, 1), ), "line number"), ++ "module" : (((4, 1), ), "file name"), ++ "name" : (((6, 1), ), "function name"), ++ "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"), ++ "pcalls" : (((0,-1), ), "call count"), ++ "stdname" : (((7, 1), ), "standard name"), ++ "time" : (((2,-1), ), "internal time"), ++ } ++ ++ def get_sort_arg_defs(self): ++ """Expand all abbreviations that are unique.""" ++ if not self.sort_arg_dict: ++ self.sort_arg_dict = dict = {} ++ bad_list = {} ++ for word, tup in self.sort_arg_dict_default.iteritems(): ++ fragment = word ++ while fragment: ++ if not fragment: ++ break ++ if fragment in dict: ++ bad_list[fragment] = 0 ++ break ++ dict[fragment] = tup ++ fragment = fragment[:-1] ++ for word in bad_list: ++ del dict[word] ++ return self.sort_arg_dict ++ ++ def sort_stats(self, *field): ++ if not field: ++ self.fcn_list = 0 ++ return self ++ if len(field) == 1 and isinstance(field[0], (int, long)): ++ # Be compatible with old profiler ++ field = [ {-1: "stdname", ++ 0: "calls", ++ 1: "time", ++ 2: "cumulative"}[field[0]] ] ++ ++ sort_arg_defs = self.get_sort_arg_defs() ++ sort_tuple = () ++ self.sort_type = "" ++ connector = "" ++ for word in field: ++ sort_tuple = sort_tuple + sort_arg_defs[word][0] ++ self.sort_type += connector + sort_arg_defs[word][1] ++ connector = ", " ++ ++ stats_list = [] ++ for func, (cc, nc, tt, ct, callers) in self.stats.iteritems(): ++ stats_list.append((cc, nc, tt, ct) + func + ++ (func_std_string(func), func)) ++ ++ stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare)) ++ ++ self.fcn_list = fcn_list = [] ++ for tuple in stats_list: ++ fcn_list.append(tuple[-1]) ++ return self ++ ++ def reverse_order(self): ++ if self.fcn_list: ++ self.fcn_list.reverse() ++ return self ++ ++ def strip_dirs(self): ++ oldstats = self.stats ++ self.stats = newstats = {} ++ max_name_len = 0 ++ for func, (cc, nc, tt, ct, callers) in oldstats.iteritems(): ++ newfunc = func_strip_path(func) ++ if len(func_std_string(newfunc)) > max_name_len: ++ max_name_len = len(func_std_string(newfunc)) ++ newcallers = {} ++ for func2, caller in callers.iteritems(): ++ newcallers[func_strip_path(func2)] = caller ++ ++ if newfunc in newstats: ++ newstats[newfunc] = add_func_stats( ++ newstats[newfunc], ++ (cc, nc, tt, ct, newcallers)) ++ else: ++ newstats[newfunc] = (cc, nc, tt, ct, newcallers) ++ old_top = self.top_level ++ self.top_level = new_top = {} ++ for func in old_top: ++ new_top[func_strip_path(func)] = None ++ ++ self.max_name_len = max_name_len ++ ++ self.fcn_list = None ++ self.all_callees = None ++ return self ++ ++ def calc_callees(self): ++ if self.all_callees: return ++ self.all_callees = all_callees = {} ++ for func, (cc, nc, tt, ct, callers) in self.stats.iteritems(): ++ if not func in all_callees: ++ all_callees[func] = {} ++ for func2, caller in callers.iteritems(): ++ if not func2 in all_callees: ++ all_callees[func2] = {} ++ all_callees[func2][func] = caller ++ return ++ ++ #****************************************************************** ++ # The following functions support actual printing of reports ++ #****************************************************************** ++ ++ # Optional "amount" is either a line count, or a percentage of lines. ++ ++ def eval_print_amount(self, sel, list, msg): ++ new_list = list ++ if isinstance(sel, basestring): ++ try: ++ rex = re.compile(sel) ++ except re.error: ++ msg += " \n" % sel ++ return new_list, msg ++ new_list = [] ++ for func in list: ++ if rex.search(func_std_string(func)): ++ new_list.append(func) ++ else: ++ count = len(list) ++ if isinstance(sel, float) and 0.0 <= sel < 1.0: ++ count = int(count * sel + .5) ++ new_list = list[:count] ++ elif isinstance(sel, (int, long)) and 0 <= sel < count: ++ count = sel ++ new_list = list[:count] ++ if len(list) != len(new_list): ++ msg += " List reduced from %r to %r due to restriction <%r>\n" % ( ++ len(list), len(new_list), sel) ++ ++ return new_list, msg ++ ++ def get_print_list(self, sel_list): ++ width = self.max_name_len ++ if self.fcn_list: ++ stat_list = self.fcn_list[:] ++ msg = " Ordered by: " + self.sort_type + '\n' ++ else: ++ stat_list = self.stats.keys() ++ msg = " Random listing order was used\n" ++ ++ for selection in sel_list: ++ stat_list, msg = self.eval_print_amount(selection, stat_list, msg) ++ ++ count = len(stat_list) ++ ++ if not stat_list: ++ return 0, stat_list ++ print >> self.stream, msg ++ if count < len(self.stats): ++ width = 0 ++ for func in stat_list: ++ if len(func_std_string(func)) > width: ++ width = len(func_std_string(func)) ++ return width+2, stat_list ++ ++ def print_stats(self, *amount): ++ for filename in self.files: ++ print >> self.stream, filename ++ if self.files: print >> self.stream ++ indent = ' ' * 8 ++ for func in self.top_level: ++ print >> self.stream, indent, func_get_function_name(func) ++ ++ print >> self.stream, indent, self.total_calls, "function calls", ++ if self.total_calls != self.prim_calls: ++ print >> self.stream, "(%d primitive calls)" % self.prim_calls, ++ print >> self.stream, "in %.3f seconds" % self.total_tt ++ print >> self.stream ++ width, list = self.get_print_list(amount) ++ if list: ++ self.print_title() ++ for func in list: ++ self.print_line(func) ++ print >> self.stream ++ print >> self.stream ++ return self ++ ++ def print_callees(self, *amount): ++ width, list = self.get_print_list(amount) ++ if list: ++ self.calc_callees() ++ ++ self.print_call_heading(width, "called...") ++ for func in list: ++ if func in self.all_callees: ++ self.print_call_line(width, func, self.all_callees[func]) ++ else: ++ self.print_call_line(width, func, {}) ++ print >> self.stream ++ print >> self.stream ++ return self ++ ++ def print_callers(self, *amount): ++ width, list = self.get_print_list(amount) ++ if list: ++ self.print_call_heading(width, "was called by...") ++ for func in list: ++ cc, nc, tt, ct, callers = self.stats[func] ++ self.print_call_line(width, func, callers, "<-") ++ print >> self.stream ++ print >> self.stream ++ return self ++ ++ def print_call_heading(self, name_size, column_title): ++ print >> self.stream, "Function ".ljust(name_size) + column_title ++ # print sub-header only if we have new-style callers ++ subheader = False ++ for cc, nc, tt, ct, callers in self.stats.itervalues(): ++ if callers: ++ value = callers.itervalues().next() ++ subheader = isinstance(value, tuple) ++ break ++ if subheader: ++ print >> self.stream, " "*name_size + " ncalls tottime cumtime" ++ ++ def print_call_line(self, name_size, source, call_dict, arrow="->"): ++ print >> self.stream, func_std_string(source).ljust(name_size) + arrow, ++ if not call_dict: ++ print >> self.stream ++ return ++ clist = call_dict.keys() ++ clist.sort() ++ indent = "" ++ for func in clist: ++ name = func_std_string(func) ++ value = call_dict[func] ++ if isinstance(value, tuple): ++ nc, cc, tt, ct = value ++ if nc != cc: ++ substats = '%d/%d' % (nc, cc) ++ else: ++ substats = '%d' % (nc,) ++ substats = '%s %s %s %s' % (substats.rjust(7+2*len(indent)), ++ f8(tt), f8(ct), name) ++ left_width = name_size + 1 ++ else: ++ substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3])) ++ left_width = name_size + 3 ++ print >> self.stream, indent*left_width + substats ++ indent = " " ++ ++ def print_title(self): ++ print >> self.stream, ' ncalls tottime percall cumtime percall', ++ print >> self.stream, 'filename:lineno(function)' ++ ++ def print_line(self, func): # hack : should print percentages ++ cc, nc, tt, ct, callers = self.stats[func] ++ c = str(nc) ++ if nc != cc: ++ c = c + '/' + str(cc) ++ print >> self.stream, c.rjust(9), ++ print >> self.stream, f8(tt), ++ if nc == 0: ++ print >> self.stream, ' '*8, ++ else: ++ print >> self.stream, f8(float(tt)/nc), ++ print >> self.stream, f8(ct), ++ if cc == 0: ++ print >> self.stream, ' '*8, ++ else: ++ print >> self.stream, f8(float(ct)/cc), ++ print >> self.stream, func_std_string(func) ++ ++class TupleComp: ++ """This class provides a generic function for comparing any two tuples. ++ Each instance records a list of tuple-indices (from most significant ++ to least significant), and sort direction (ascending or decending) for ++ each tuple-index. The compare functions can then be used as the function ++ argument to the system sort() function when a list of tuples need to be ++ sorted in the instances order.""" ++ ++ def __init__(self, comp_select_list): ++ self.comp_select_list = comp_select_list ++ ++ def compare (self, left, right): ++ for index, direction in self.comp_select_list: ++ l = left[index] ++ r = right[index] ++ if l < r: ++ return -direction ++ if l > r: ++ return direction ++ return 0 ++ ++#************************************************************************** ++# func_name is a triple (file:string, line:int, name:string) ++ ++def func_strip_path(func_name): ++ filename, line, name = func_name ++ return os.path.basename(filename), line, name ++ ++def func_get_function_name(func): ++ return func[2] ++ ++def func_std_string(func_name): # match what old profile produced ++ if func_name[:2] == ('~', 0): ++ # special case for built-in functions ++ name = func_name[2] ++ if name.startswith('<') and name.endswith('>'): ++ return '{%s}' % name[1:-1] ++ else: ++ return name ++ else: ++ return "%s:%d(%s)" % func_name ++ ++#************************************************************************** ++# The following functions combine statists for pairs functions. ++# The bulk of the processing involves correctly handling "call" lists, ++# such as callers and callees. ++#************************************************************************** ++ ++def add_func_stats(target, source): ++ """Add together all the stats for two profile entries.""" ++ cc, nc, tt, ct, callers = source ++ t_cc, t_nc, t_tt, t_ct, t_callers = target ++ return (cc+t_cc, nc+t_nc, tt+t_tt, ct+t_ct, ++ add_callers(t_callers, callers)) ++ ++def add_callers(target, source): ++ """Combine two caller lists in a single list.""" ++ new_callers = {} ++ for func, caller in target.iteritems(): ++ new_callers[func] = caller ++ for func, caller in source.iteritems(): ++ if func in new_callers: ++ if isinstance(caller, tuple): ++ # format used by cProfile ++ new_callers[func] = tuple([i[0] + i[1] for i in ++ zip(caller, new_callers[func])]) ++ else: ++ # format used by profile ++ new_callers[func] += caller ++ else: ++ new_callers[func] = caller ++ return new_callers ++ ++def count_calls(callers): ++ """Sum the caller statistics to get total number of calls received.""" ++ nc = 0 ++ for calls in callers.itervalues(): ++ nc += calls ++ return nc ++ ++#************************************************************************** ++# The following functions support printing of reports ++#************************************************************************** ++ ++def f8(x): ++ return "%8.3f" % x ++ ++#************************************************************************** ++# Statistics browser added by ESR, April 2001 ++#************************************************************************** ++ ++if __name__ == '__main__': ++ import cmd ++ try: ++ import readline ++ except ImportError: ++ pass ++ ++ class ProfileBrowser(cmd.Cmd): ++ def __init__(self, profile=None): ++ cmd.Cmd.__init__(self) ++ self.prompt = "% " ++ self.stats = None ++ self.stream = sys.stdout ++ if profile is not None: ++ self.do_read(profile) ++ ++ def generic(self, fn, line): ++ args = line.split() ++ processed = [] ++ for term in args: ++ try: ++ processed.append(int(term)) ++ continue ++ except ValueError: ++ pass ++ try: ++ frac = float(term) ++ if frac > 1 or frac < 0: ++ print >> self.stream, "Fraction argument must be in [0, 1]" ++ continue ++ processed.append(frac) ++ continue ++ except ValueError: ++ pass ++ processed.append(term) ++ if self.stats: ++ getattr(self.stats, fn)(*processed) ++ else: ++ print >> self.stream, "No statistics object is loaded." ++ return 0 ++ def generic_help(self): ++ print >> self.stream, "Arguments may be:" ++ print >> self.stream, "* An integer maximum number of entries to print." ++ print >> self.stream, "* A decimal fractional number between 0 and 1, controlling" ++ print >> self.stream, " what fraction of selected entries to print." ++ print >> self.stream, "* A regular expression; only entries with function names" ++ print >> self.stream, " that match it are printed." ++ ++ def do_add(self, line): ++ if self.stats: ++ self.stats.add(line) ++ else: ++ print >> self.stream, "No statistics object is loaded." ++ return 0 ++ def help_add(self): ++ print >> self.stream, "Add profile info from given file to current statistics object." ++ ++ def do_callees(self, line): ++ return self.generic('print_callees', line) ++ def help_callees(self): ++ print >> self.stream, "Print callees statistics from the current stat object." ++ self.generic_help() ++ ++ def do_callers(self, line): ++ return self.generic('print_callers', line) ++ def help_callers(self): ++ print >> self.stream, "Print callers statistics from the current stat object." ++ self.generic_help() ++ ++ def do_EOF(self, line): ++ print >> self.stream, "" ++ return 1 ++ def help_EOF(self): ++ print >> self.stream, "Leave the profile brower." ++ ++ def do_quit(self, line): ++ return 1 ++ def help_quit(self): ++ print >> self.stream, "Leave the profile brower." ++ ++ def do_read(self, line): ++ if line: ++ try: ++ self.stats = Stats(line) ++ except IOError, args: ++ print >> self.stream, args[1] ++ return ++ except Exception as err: ++ print >> self.stream, err.__class__.__name__ + ':', err ++ return ++ self.prompt = line + "% " ++ elif len(self.prompt) > 2: ++ line = self.prompt[:-2] ++ self.do_read(line) ++ else: ++ print >> self.stream, "No statistics object is current -- cannot reload." ++ return 0 ++ def help_read(self): ++ print >> self.stream, "Read in profile data from a specified file." ++ print >> self.stream, "Without argument, reload the current file." ++ ++ def do_reverse(self, line): ++ if self.stats: ++ self.stats.reverse_order() ++ else: ++ print >> self.stream, "No statistics object is loaded." ++ return 0 ++ def help_reverse(self): ++ print >> self.stream, "Reverse the sort order of the profiling report." ++ ++ def do_sort(self, line): ++ if not self.stats: ++ print >> self.stream, "No statistics object is loaded." ++ return ++ abbrevs = self.stats.get_sort_arg_defs() ++ if line and all((x in abbrevs) for x in line.split()): ++ self.stats.sort_stats(*line.split()) ++ else: ++ print >> self.stream, "Valid sort keys (unique prefixes are accepted):" ++ for (key, value) in Stats.sort_arg_dict_default.iteritems(): ++ print >> self.stream, "%s -- %s" % (key, value[1]) ++ return 0 ++ def help_sort(self): ++ print >> self.stream, "Sort profile data according to specified keys." ++ print >> self.stream, "(Typing `sort' without arguments lists valid keys.)" ++ def complete_sort(self, text, *args): ++ return [a for a in Stats.sort_arg_dict_default if a.startswith(text)] ++ ++ def do_stats(self, line): ++ return self.generic('print_stats', line) ++ def help_stats(self): ++ print >> self.stream, "Print statistics from the current stat object." ++ self.generic_help() ++ ++ def do_strip(self, line): ++ if self.stats: ++ self.stats.strip_dirs() ++ else: ++ print >> self.stream, "No statistics object is loaded." ++ def help_strip(self): ++ print >> self.stream, "Strip leading path information from filenames in the report." ++ ++ def help_help(self): ++ print >> self.stream, "Show help for a given command." ++ ++ def postcmd(self, stop, line): ++ if stop: ++ return stop ++ return None ++ ++ import sys ++ if len(sys.argv) > 1: ++ initprofile = sys.argv[1] ++ else: ++ initprofile = None ++ try: ++ browser = ProfileBrowser(initprofile) ++ print >> browser.stream, "Welcome to the profile statistics browser." ++ browser.cmdloop() ++ print >> browser.stream, "Goodbye." ++ except KeyboardInterrupt: ++ pass ++ ++# That's all, folks. --- python2.7-2.7.2.orig/debian/patches/disable-utimes.diff +++ python2.7-2.7.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 +@@ -2698,7 +2698,7 @@ + setsid setpgid setpgrp setuid setvbuf snprintf \ + sigaction siginterrupt sigrelse strftime \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ +- truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) ++ truncate uname unsetenv waitpid wait3 wait4 wcscoll _getpty) + + # For some functions, having a definition is not sufficient, since + # we want to take their address. --- python2.7-2.7.2.orig/debian/patches/link-system-expat.diff +++ python2.7-2.7.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 +@@ -180,7 +180,7 @@ + #itertools itertoolsmodule.c # Functions creating iterators for efficient looping + #strop stropmodule.c # String manipulations + #_functools _functoolsmodule.c # Tools for working with functions and callable objects +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #datetime datetimemodule.c # date/time type + #_bisect _bisectmodule.c # Bisection algorithms +@@ -471,7 +471,7 @@ + # + # More information on Expat can be found at www.libexpat.org. + # +-#pyexpat expat/xmlparse.c expat/xmlrole.c expat/xmltok.c pyexpat.c -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI ++#pyexpat pyexpat.c -lexpat + + + # Hye-Shik Chang's CJKCodecs --- python2.7-2.7.2.orig/debian/patches/site-locations.diff +++ python2.7-2.7.2/debian/patches/site-locations.diff @@ -0,0 +1,32 @@ +# DP: Set site-packages/dist-packages + +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -19,6 +19,12 @@ + resulting directories, if they exist, are appended to sys.path, and + also inspected for path configuration files. + ++For Debian and derivatives, this sys.path is augmented with directories ++for packages distributed within the distribution. Local addons go ++into /usr/local/lib/python/dist-packages, Debian addons ++install into /usr/{lib,share}/python/dist-packages. ++/usr/lib/python/site-packages is not used. ++ + A path configuration file is a file whose name has the form + .pth; its contents are additional directories (one per line) + to be added to sys.path. Non-existing directories (or +@@ -300,10 +306,12 @@ + if sys.platform in ('os2emx', 'riscos'): + sitepackages.append(os.path.join(prefix, "Lib", "site-packages")) + elif os.sep == '/': ++ sitepackages.append(os.path.join(prefix, "local/lib", ++ "python" + sys.version[:3], ++ "dist-packages")) + sitepackages.append(os.path.join(prefix, "lib", + "python" + sys.version[:3], +- "site-packages")) +- sitepackages.append(os.path.join(prefix, "lib", "site-python")) ++ "dist-packages")) + else: + sitepackages.append(prefix) + sitepackages.append(os.path.join(prefix, "lib", "site-packages")) --- python2.7-2.7.2.orig/debian/patches/statvfs-f_flag-constants.diff +++ python2.7-2.7.2/debian/patches/statvfs-f_flag-constants.diff @@ -0,0 +1,57 @@ +From 21fda4c78000d78cb1824fdf0373031d07f5325a Mon Sep 17 00:00:00 2001 +From: Peter Jones +Date: Wed, 6 Jan 2010 15:22:38 -0500 +Subject: [PATCH] Add flags for statvfs.f_flag to constant list. + +You really need these to figure out what statvfs is trying to say to +you, so add them here. +--- + Modules/posixmodule.c | 37 +++++++++++++++++++++++++++++++++++++ + 1 files changed, 37 insertions(+), 0 deletions(-) + +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -9301,6 +9301,43 @@ + if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1; + #endif /* EX_NOTFOUND */ + ++ /* These came from statvfs.h */ ++#ifdef ST_RDONLY ++ if (ins(d, "ST_RDONLY", (long)ST_RDONLY)) return -1; ++#endif /* ST_RDONLY */ ++#ifdef ST_NOSUID ++ if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1; ++#endif /* ST_NOSUID */ ++ ++ /* GNU extensions */ ++#ifdef ST_NODEV ++ if (ins(d, "ST_NODEV", (long)ST_NODEV)) return -1; ++#endif /* ST_NODEV */ ++#ifdef ST_NOEXEC ++ if (ins(d, "ST_NOEXEC", (long)ST_NOEXEC)) return -1; ++#endif /* ST_NOEXEC */ ++#ifdef ST_SYNCHRONOUS ++ if (ins(d, "ST_SYNCHRONOUS", (long)ST_SYNCHRONOUS)) return -1; ++#endif /* ST_SYNCHRONOUS */ ++#ifdef ST_MANDLOCK ++ if (ins(d, "ST_MANDLOCK", (long)ST_MANDLOCK)) return -1; ++#endif /* ST_MANDLOCK */ ++#ifdef ST_WRITE ++ if (ins(d, "ST_WRITE", (long)ST_WRITE)) return -1; ++#endif /* ST_WRITE */ ++#ifdef ST_APPEND ++ if (ins(d, "ST_APPEND", (long)ST_APPEND)) return -1; ++#endif /* ST_APPEND */ ++#ifdef ST_NOATIME ++ if (ins(d, "ST_NOATIME", (long)ST_NOATIME)) return -1; ++#endif /* ST_NOATIME */ ++#ifdef ST_NODIRATIME ++ if (ins(d, "ST_NODIRATIME", (long)ST_NODIRATIME)) return -1; ++#endif /* ST_NODIRATIME */ ++#ifdef ST_RELATIME ++ if (ins(d, "ST_RELATIME", (long)ST_RELATIME)) return -1; ++#endif /* ST_RELATIME */ ++ + #ifdef HAVE_SPAWNV + #if defined(PYOS_OS2) && defined(PYCC_GCC) + if (ins(d, "P_WAIT", (long)P_WAIT)) return -1; --- python2.7-2.7.2.orig/debian/patches/deb-locations.diff +++ python2.7-2.7.2/debian/patches/deb-locations.diff @@ -0,0 +1,63 @@ +# DP: adjust locations of directories to debian policy + +--- a/Demo/tkinter/guido/ManPage.py ++++ b/Demo/tkinter/guido/ManPage.py +@@ -189,8 +189,9 @@ + def test(): + import os + import sys +- # XXX This directory may be different on your system +- MANDIR = '/usr/local/man/mann' ++ # XXX This directory may be different on your system, ++ # it is here set for Debian GNU/Linux. ++ MANDIR = '/usr/share/man' + DEFAULTPAGE = 'Tcl' + formatted = 0 + if sys.argv[1:] and sys.argv[1] == '-f': +--- a/Demo/tkinter/guido/tkman.py ++++ b/Demo/tkinter/guido/tkman.py +@@ -9,8 +9,8 @@ + from Tkinter import * + from ManPage import ManPage + +-MANNDIRLIST = ['/depot/sundry/man/mann','/usr/local/man/mann'] +-MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3'] ++MANNDIRLIST = ['/depot/sundry/man/mann','/usr/share/man/mann'] ++MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/share/man/man3'] + + foundmanndir = 0 + for dir in MANNDIRLIST: +--- a/Misc/python.man ++++ b/Misc/python.man +@@ -323,7 +323,7 @@ + These are subject to difference depending on local installation + conventions; ${prefix} and ${exec_prefix} are installation-dependent + and should be interpreted as for GNU software; they may be the same. +-The default for both is \fI/usr/local\fP. ++On Debian GNU/{Hurd,Linux} the default for both is \fI/usr\fP. + .IP \fI${exec_prefix}/bin/python\fP + Recommended location of the interpreter. + .PP +--- a/Tools/faqwiz/faqconf.py ++++ b/Tools/faqwiz/faqconf.py +@@ -21,7 +21,7 @@ + OWNEREMAIL = "nobody@anywhere.org" # Email for feedback + HOMEURL = "http://www.python.org" # Related home page + HOMENAME = "Python home" # Name of related home page +-RCSBINDIR = "/usr/local/bin/" # Directory containing RCS commands ++RCSBINDIR = "/usr/bin/" # Directory containing RCS commands + # (must end in a slash) + + # Parameters you can normally leave alone +--- a/Tools/webchecker/webchecker.py ++++ b/Tools/webchecker/webchecker.py +@@ -19,7 +19,8 @@ + a directory listing is returned. Now, you can point webchecker to the + document tree in the local file system of your HTTP daemon, and have + most of it checked. In fact the default works this way if your local +-web tree is located at /usr/local/etc/httpd/htdpcs (the default for ++web tree is located at /var/www, which is the default for Debian ++GNU/Linux. Other systems use /usr/local/etc/httpd/htdocs (the default for + the NCSA HTTP daemon and probably others). + + Report printed: --- python2.7-2.7.2.orig/debian/patches/plat-linux2_sparc.diff +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/patches/disable-ssl-cert-tests.diff +++ python2.7-2.7.2/debian/patches/disable-ssl-cert-tests.diff @@ -0,0 +1,75 @@ +--- a/Lib/test/test_ssl.py ++++ b/Lib/test/test_ssl.py +@@ -231,59 +231,6 @@ + finally: + s.close() + +- # this should succeed because we specify the root cert +- s = ssl.wrap_socket(socket.socket(socket.AF_INET), +- cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT) +- try: +- s.connect(("svn.python.org", 443)) +- finally: +- s.close() +- +- def test_connect_ex(self): +- # Issue #11326: check connect_ex() implementation +- with test_support.transient_internet("svn.python.org"): +- s = ssl.wrap_socket(socket.socket(socket.AF_INET), +- cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT) +- try: +- self.assertEqual(0, s.connect_ex(("svn.python.org", 443))) +- self.assertTrue(s.getpeercert()) +- finally: +- s.close() +- +- def test_non_blocking_connect_ex(self): +- # Issue #11326: non-blocking connect_ex() should allow handshake +- # to proceed after the socket gets ready. +- with test_support.transient_internet("svn.python.org"): +- s = ssl.wrap_socket(socket.socket(socket.AF_INET), +- cert_reqs=ssl.CERT_REQUIRED, +- ca_certs=SVN_PYTHON_ORG_ROOT_CERT, +- do_handshake_on_connect=False) +- try: +- s.setblocking(False) +- rc = s.connect_ex(('svn.python.org', 443)) +- # EWOULDBLOCK under Windows, EINPROGRESS elsewhere +- self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK)) +- # Wait for connect to finish +- select.select([], [s], [], 5.0) +- # Non-blocking handshake +- while True: +- try: +- s.do_handshake() +- break +- except ssl.SSLError as err: +- if err.args[0] == ssl.SSL_ERROR_WANT_READ: +- select.select([s], [], [], 5.0) +- elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: +- select.select([], [s], [], 5.0) +- else: +- raise +- # SSL established +- self.assertTrue(s.getpeercert()) +- finally: +- s.close() +- + @unittest.skipIf(os.name == "nt", "Can't use a socket as a file under Windows") + def test_makefile_close(self): + # Issue #5238: creating a file-like object with makefile() shouldn't +@@ -343,12 +290,6 @@ + else: + self.fail("Got server certificate %s for svn.python.org!" % pem) + +- pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT) +- if not pem: +- self.fail("No server certificate on svn.python.org:443!") +- if test_support.verbose: +- sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem) +- + def test_algorithms(self): + # Issue #8484: all algorithms should be available when verifying a + # certificate. --- python2.7-2.7.2.orig/debian/patches/bdist-wininst-notfound.diff +++ python2.7-2.7.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 +@@ -360,7 +360,10 @@ + sfix = '' + + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) +- f = open(filename, "rb") ++ try: ++ f = open(filename, "rb") ++ except IOError, msg: ++ raise DistutilsFileError, str(msg) + ', please install the python%s-dev package' % sys.version[:3] + try: + return f.read() + finally: --- python2.7-2.7.2.orig/debian/patches/arm-float.dpatch +++ python2.7-2.7.2/debian/patches/arm-float.dpatch @@ -0,0 +1,119 @@ +#! /bin/sh -e + +# DP: Support mixed-endian IEEE floating point, as found in the ARM old-ABI. + +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 + +--- Objects/floatobject.c.orig 2006-05-25 10:53:30.000000000 -0500 ++++ Objects/floatobject.c 2007-07-27 06:43:15.000000000 -0500 +@@ -982,7 +982,7 @@ + /* this is for the benefit of the pack/unpack routines below */ + + typedef enum { +- unknown_format, ieee_big_endian_format, ieee_little_endian_format ++ unknown_format, ieee_big_endian_format, ieee_little_endian_format, ieee_mixed_endian_format + } float_format_type; + + static float_format_type double_format, float_format; +@@ -1021,6 +1021,8 @@ + return PyString_FromString("IEEE, little-endian"); + case ieee_big_endian_format: + return PyString_FromString("IEEE, big-endian"); ++ case ieee_mixed_endian_format: ++ return PyString_FromString("IEEE, mixed-endian"); + default: + Py_FatalError("insane float_format or double_format"); + return NULL; +@@ -1073,11 +1075,14 @@ + else if (strcmp(format, "IEEE, big-endian") == 0) { + f = ieee_big_endian_format; + } ++ else if (strcmp(format, "IEEE, mixed-endian") == 0) { ++ f = ieee_mixed_endian_format; ++ } + else { + PyErr_SetString(PyExc_ValueError, + "__setformat__() argument 2 must be " +- "'unknown', 'IEEE, little-endian' or " +- "'IEEE, big-endian'"); ++ "'unknown', 'IEEE, little-endian', " ++ "'IEEE, big-endian' or 'IEEE, mixed-endian'"); + return NULL; + + } +@@ -1230,6 +1235,8 @@ + detected_double_format = ieee_big_endian_format; + else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) + detected_double_format = ieee_little_endian_format; ++ else if (memcmp(&x, "\x01\xff\x3f\x43\x05\x04\x03\x02", 8) == 0) ++ detected_double_format = ieee_mixed_endian_format; + else + detected_double_format = unknown_format; + } +@@ -1565,8 +1572,19 @@ + p += 7; + incr = -1; + } ++ else if (double_format == ieee_mixed_endian_format) { ++ if (le) ++ p += 4; ++ else { ++ p += 3; ++ incr = -1; ++ } ++ } + + for (i = 0; i < 8; i++) { ++ if (double_format == ieee_mixed_endian_format && i == 4) ++ p += -8 * incr; ++ + *p = *s++; + p += incr; + } +@@ -1739,6 +1757,27 @@ + } + memcpy(&x, buf, 8); + } ++ else if (double_format == ieee_mixed_endian_format) { ++ char buf[8]; ++ char *d; ++ int i, incr = 1; ++ ++ if (le) ++ d = &buf[4]; ++ else ++ d = &buf[3]; ++ ++ for (i = 0; i < 4; i++) { ++ *d = *p++; ++ d += incr; ++ } ++ d += -8 * incr; ++ for (i = 0; i < 4; i++) { ++ *d = *p++; ++ d += incr; ++ } ++ memcpy(&x, buf, 8); ++ } + else { + memcpy(&x, p, 8); + } --- python2.7-2.7.2.orig/debian/patches/doc-faq.dpatch +++ python2.7-2.7.2/debian/patches/doc-faq.dpatch @@ -0,0 +1,54 @@ +#! /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 + #cd ${dir}gcc && autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + #rm ${dir}gcc/configure + ;; + *) + 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 @@ + + + ++ ++ ++   ++

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

--- python2.7-2.7.2.orig/debian/patches/site-builddir.diff +++ python2.7-2.7.2/debian/patches/site-builddir.diff @@ -0,0 +1,32 @@ +--- site.py~ 2010-06-29 00:20:33.000000000 +0200 ++++ site.py 2010-06-29 00:26:17.440243273 +0200 +@@ -115,19 +115,6 @@ + sys.path[:] = L + return known_paths + +-# XXX This should not be part of site.py, since it is needed even when +-# using the -S option for Python. See http://www.python.org/sf/586680 +-def addbuilddir(): +- """Append ./build/lib. in case we're running in the build dir +- (especially for Guido :-)""" +- from sysconfig import get_platform +- s = "build/lib.%s-%.3s" % (get_platform(), sys.version) +- if hasattr(sys, 'gettotalrefcount'): +- s += '-pydebug' +- s = os.path.join(os.path.dirname(sys.path.pop()), s) +- sys.path.append(s) +- +- + def _init_pathinfo(): + """Return a set containing all existing directory entries from sys.path""" + d = set() +@@ -538,9 +525,6 @@ + + abs__file__() + known_paths = removeduppaths() +- if (os.name == "posix" and sys.path and +- os.path.basename(sys.path[-1]) == "Modules"): +- addbuilddir() + if ENABLE_USER_SITE is None: + ENABLE_USER_SITE = check_enableusersite() + known_paths = addusersitepackages(known_paths) --- python2.7-2.7.2.orig/debian/patches/hotshot-import.diff +++ python2.7-2.7.2/debian/patches/hotshot-import.diff @@ -0,0 +1,17 @@ +# DP: hotshot: Check for the availability of the profile and pstats modules. + +--- a/Lib/hotshot/stats.py ++++ b/Lib/hotshot/stats.py +@@ -1,7 +1,10 @@ + """Statistics analyzer for HotShot.""" + +-import profile +-import pstats ++try: ++ import profile ++ import pstats ++except ImportError, e: ++ raise ImportError, str(e) + '; please install the python-profiler package' + + import hotshot.log + --- python2.7-2.7.2.orig/debian/patches/link-whole-archive.diff +++ python2.7-2.7.2/debian/patches/link-whole-archive.diff @@ -0,0 +1,13 @@ +# DP: Link libpython with --whole-archive. + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -406,7 +406,7 @@ + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) + $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ +- $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) ++ -Wl,--whole-archive $(BLDLIBRARY) -Wl,--no-whole-archive $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + + platform: $(BUILDPYTHON) + $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from sysconfig import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform --- python2.7-2.7.2.orig/debian/patches/plat-linux2_mips.diff +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/patches/setup-modules.dpatch +++ python2.7-2.7.2/debian/patches/setup-modules.dpatch @@ -0,0 +1,75 @@ +#! /bin/sh -e + +# DP: Modules/Setup.dist: patches to build some extensions statically + +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 + +--- Modules/_elementtree.c~ 2008-11-27 10:01:33.000000000 +0100 ++++ Modules/_elementtree.c 2008-11-27 10:03:30.000000000 +0100 +@@ -1837,7 +1837,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 { +--- Modules/Setup.dist~ 2008-11-27 10:59:37.000000000 +0100 ++++ Modules/Setup.dist 2008-11-27 11:00:26.000000000 +0100 +@@ -165,7 +165,7 @@ + #itertools itertoolsmodule.c # Functions creating iterators for efficient looping + #atexit atexitmodule.c # Register functions to be run at interpreter-shutdown + #_functools _functoolsmodule.c # Tools for working with functions and callable objects +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #datetime datetimemodule.c # date/time type + #_bisect _bisectmodule.c # Bisection algorithms +@@ -257,6 +257,7 @@ + #_sha256 sha256module.c + #_sha512 sha512module.c + ++#_hashlib _hashopenssl.c -lssl -lcrypto + + # SGI IRIX specific modules -- off by default. + +@@ -341,6 +341,7 @@ + #DBLIB=$(DB)/lib + #_bsddb _bsddb.c -I$(DBINC) -L$(DBLIB) -ldb-$(DBLIBVER) + ++#_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 + + # Helper module for various ascii-encoders + #binascii binascii.c +@@ -382,7 +382,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 + --- python2.7-2.7.2.orig/debian/patches/platform-lsbrelease.diff +++ python2.7-2.7.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 +@@ -288,6 +288,10 @@ + id = l[1] + return '', version, id + ++_distributor_id_file_re = re.compile("(?:DISTRIB_ID\s*=)\s*(.*)", re.I) ++_release_file_re = re.compile("(?:DISTRIB_RELEASE\s*=)\s*(.*)", re.I) ++_codename_file_re = re.compile("(?:DISTRIB_CODENAME\s*=)\s*(.*)", re.I) ++ + def linux_distribution(distname='', version='', id='', + + supported_dists=_supported_dists, +@@ -312,6 +316,25 @@ + args given as parameters. + + """ ++ # check for the 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: --- python2.7-2.7.2.orig/debian/patches/issue670664.diff +++ python2.7-2.7.2/debian/patches/issue670664.diff @@ -0,0 +1,54 @@ +# DP: Proposed patch for issue #670664. + +--- a/Lib/HTMLParser.py ++++ b/Lib/HTMLParser.py +@@ -96,6 +96,7 @@ + self.rawdata = '' + self.lasttag = '???' + self.interesting = interesting_normal ++ self.cdata_tag = None + markupbase.ParserBase.reset(self) + + def feed(self, data): +@@ -120,11 +121,13 @@ + """Return full source of start tag: '<...>'.""" + return self.__starttag_text + +- def set_cdata_mode(self): ++ def set_cdata_mode(self, tag): + self.interesting = interesting_cdata ++ self.cdata_tag = tag.lower() + + def clear_cdata_mode(self): + self.interesting = interesting_normal ++ self.cdata_tag = None + + # Internal -- handle data as far as reasonable. May leave state + # and data to be processed by a subsequent call. If 'end' is +@@ -270,7 +273,7 @@ + else: + self.handle_starttag(tag, attrs) + if tag in self.CDATA_CONTENT_ELEMENTS: +- self.set_cdata_mode() ++ self.set_cdata_mode(tag) + return endpos + + # Internal -- check to see if we have a complete starttag; return end +@@ -314,10 +317,16 @@ + j = match.end() + match = endtagfind.match(rawdata, i) # + if not match: ++ if self.cdata_tag is not None: return j + self.error("bad end tag: %r" % (rawdata[i:j],)) +- tag = match.group(1) ++ tag = match.group(1).strip() ++ ++ if self.cdata_tag is not None: ++ if tag.lower() != self.cdata_tag: return j ++ + self.handle_endtag(tag.lower()) + self.clear_cdata_mode() ++ + return j + + # Overridable -- finish processing of start+end tag: --- python2.7-2.7.2.orig/debian/patches/subprocess-eintr-safety.dpatch +++ python2.7-2.7.2/debian/patches/subprocess-eintr-safety.dpatch @@ -0,0 +1,81 @@ +#! /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 + #cd ${dir}gcc && autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + #rm ${dir}gcc/configure + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/test/test_subprocess.py 2007-03-14 19:16:36.000000000 +0100 ++++ Lib/test/test_subprocess.py 2007-03-14 19:18:57.000000000 +0100 +@@ -580,6 +578,34 @@ class ProcessTestCase(unittest.TestCase) + os.remove(fname) + self.assertEqual(rc, 47) + ++ def test_eintr(self): ++ # retries on EINTR for an argv ++ ++ # send ourselves a signal that causes EINTR ++ prev_handler = signal.signal(signal.SIGALRM, lambda x,y: 1) ++ signal.alarm(1) ++ time.sleep(0.5) ++ ++ rc = subprocess.Popen(['sleep', '1']) ++ self.assertEqual(rc.wait(), 0) ++ ++ signal.signal(signal.SIGALRM, prev_handler) ++ ++ def test_eintr_out(self): ++ # retries on EINTR for a shell call and pipelining ++ ++ # send ourselves a signal that causes EINTR ++ prev_handler = signal.signal(signal.SIGALRM, lambda x,y: 1) ++ signal.alarm(1) ++ time.sleep(0.5) ++ ++ rc = subprocess.Popen("sleep 1; echo hello", ++ shell=True, stdout=subprocess.PIPE) ++ out = rc.communicate()[0] ++ self.assertEqual(rc.returncode, 0) ++ self.assertEqual(out, "hello\n") ++ ++ signal.signal(signal.SIGALRM, prev_handler) + + # + # Windows tests +--- Lib/subprocess.py~ 2008-07-15 15:41:24.000000000 +0200 ++++ Lib/subprocess.py 2008-07-15 15:42:49.000000000 +0200 +@@ -657,13 +657,13 @@ + stderr = None + if self.stdin: + if input: +- self.stdin.write(input) ++ self._fo_write_no_intr(self.stdin, input) + self.stdin.close() + elif self.stdout: +- stdout = self.stdout.read() ++ stdout = self._fo_read_no_intr(self.stdout) + self.stdout.close() + elif self.stderr: +- stderr = self.stderr.read() ++ stderr = self._fo_read_no_intr(self.stderr) + self.stderr.close() + self.wait() + return (stdout, stderr) --- python2.7-2.7.2.orig/debian/patches/setup-modules-ssl.diff +++ python2.7-2.7.2/debian/patches/setup-modules-ssl.diff @@ -0,0 +1,24 @@ +# DP: Modules/Setup.dist: patch to build _hashlib and _ssl extensions statically + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -211,10 +211,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). +@@ -257,6 +254,7 @@ + #_sha256 sha256module.c + #_sha512 sha512module.c + ++#_hashlib _hashopenssl.c -lssl -lcrypto + + # SGI IRIX specific modules -- off by default. + --- python2.7-2.7.2.orig/debian/patches/distutils-link.diff +++ python2.7-2.7.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,7 +213,12 @@ + objects, output_dir = self._fix_object_args(objects, output_dir) + libraries, library_dirs, runtime_library_dirs = \ + self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) +- ++ # filter out standard library paths, which are not explicitely needed ++ # for linking ++ library_dirs = [dir for dir in library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] ++ runtime_library_dirs = [dir for dir in runtime_library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, + libraries) + if type(output_dir) not in (StringType, NoneType): --- python2.7-2.7.2.orig/debian/patches/plat-gnukfreebsd.diff +++ python2.7-2.7.2/debian/patches/plat-gnukfreebsd.diff @@ -0,0 +1,2478 @@ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/IN.py +@@ -0,0 +1,809 @@ ++# Generated by h2py from /usr/include/netinet/in.h ++_NETINET_IN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from stdint.h ++_STDINT_H = 1 ++ ++# Included from bits/wchar.h ++_BITS_WCHAR_H = 1 ++__WCHAR_MAX = (2147483647) ++__WCHAR_MIN = (-__WCHAR_MAX - 1) ++def __INT64_C(c): return c ## L ++ ++def __UINT64_C(c): return c ## UL ++ ++def __INT64_C(c): return c ## LL ++ ++def __UINT64_C(c): return c ## ULL ++ ++INT8_MIN = (-128) ++INT16_MIN = (-32767-1) ++INT32_MIN = (-2147483647-1) ++INT64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT8_MAX = (127) ++INT16_MAX = (32767) ++INT32_MAX = (2147483647) ++INT64_MAX = (__INT64_C(9223372036854775807)) ++UINT8_MAX = (255) ++UINT16_MAX = (65535) ++UINT64_MAX = (__UINT64_C(18446744073709551615)) ++INT_LEAST8_MIN = (-128) ++INT_LEAST16_MIN = (-32767-1) ++INT_LEAST32_MIN = (-2147483647-1) ++INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_LEAST8_MAX = (127) ++INT_LEAST16_MAX = (32767) ++INT_LEAST32_MAX = (2147483647) ++INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_LEAST8_MAX = (255) ++UINT_LEAST16_MAX = (65535) ++UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) ++INT_FAST8_MIN = (-128) ++INT_FAST16_MIN = (-9223372036854775807L-1) ++INT_FAST32_MIN = (-9223372036854775807L-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807L) ++INT_FAST32_MAX = (9223372036854775807L) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807L-1) ++INTPTR_MAX = (9223372036854775807L) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807L-1) ++PTRDIFF_MAX = (9223372036854775807L) ++PTRDIFF_MIN = (-2147483647-1) ++PTRDIFF_MAX = (2147483647) ++SIG_ATOMIC_MIN = (-2147483647-1) ++SIG_ATOMIC_MAX = (2147483647) ++WCHAR_MIN = __WCHAR_MIN ++WCHAR_MAX = __WCHAR_MAX ++def INT8_C(c): return c ++ ++def INT16_C(c): return c ++ ++def INT32_C(c): return c ++ ++def INT64_C(c): return c ## L ++ ++def INT64_C(c): return c ## LL ++ ++def UINT8_C(c): return c ++ ++def UINT16_C(c): return c ++ ++def UINT32_C(c): return c ## U ++ ++def UINT64_C(c): return c ## UL ++ ++def UINT64_C(c): return c ## ULL ++ ++def INTMAX_C(c): return c ## L ++ ++def UINTMAX_C(c): return c ## UL ++ ++def INTMAX_C(c): return c ## LL ++ ++def UINTMAX_C(c): return c ## ULL ++ ++ ++# Included from sys/socket.h ++_SYS_SOCKET_H = 1 ++ ++# Included from sys/uio.h ++_SYS_UIO_H = 1 ++from TYPES import * ++ ++# Included from bits/uio.h ++_BITS_UIO_H = 1 ++from TYPES import * ++UIO_MAXIOV = 1024 ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++ ++# Included from bits/socket.h ++__BITS_SOCKET_H = 1 ++ ++# Included from limits.h ++_LIBC_LIMITS_H_ = 1 ++MB_LEN_MAX = 16 ++_LIMITS_H = 1 ++CHAR_BIT = 8 ++SCHAR_MIN = (-128) ++SCHAR_MAX = 127 ++UCHAR_MAX = 255 ++CHAR_MIN = 0 ++CHAR_MAX = UCHAR_MAX ++CHAR_MIN = SCHAR_MIN ++CHAR_MAX = SCHAR_MAX ++SHRT_MIN = (-32768) ++SHRT_MAX = 32767 ++USHRT_MAX = 65535 ++INT_MAX = 2147483647 ++LONG_MAX = 9223372036854775807L ++LONG_MAX = 2147483647L ++LONG_MIN = (-LONG_MAX - 1L) ++ ++# Included from bits/posix1_lim.h ++_BITS_POSIX1_LIM_H = 1 ++_POSIX_AIO_LISTIO_MAX = 2 ++_POSIX_AIO_MAX = 1 ++_POSIX_ARG_MAX = 4096 ++_POSIX_CHILD_MAX = 25 ++_POSIX_CHILD_MAX = 6 ++_POSIX_DELAYTIMER_MAX = 32 ++_POSIX_HOST_NAME_MAX = 255 ++_POSIX_LINK_MAX = 8 ++_POSIX_LOGIN_NAME_MAX = 9 ++_POSIX_MAX_CANON = 255 ++_POSIX_MAX_INPUT = 255 ++_POSIX_MQ_OPEN_MAX = 8 ++_POSIX_MQ_PRIO_MAX = 32 ++_POSIX_NAME_MAX = 14 ++_POSIX_NGROUPS_MAX = 8 ++_POSIX_NGROUPS_MAX = 0 ++_POSIX_OPEN_MAX = 20 ++_POSIX_OPEN_MAX = 16 ++_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX ++_POSIX_PATH_MAX = 256 ++_POSIX_PIPE_BUF = 512 ++_POSIX_RE_DUP_MAX = 255 ++_POSIX_RTSIG_MAX = 8 ++_POSIX_SEM_NSEMS_MAX = 256 ++_POSIX_SEM_VALUE_MAX = 32767 ++_POSIX_SIGQUEUE_MAX = 32 ++_POSIX_SSIZE_MAX = 32767 ++_POSIX_STREAM_MAX = 8 ++_POSIX_SYMLINK_MAX = 255 ++_POSIX_SYMLOOP_MAX = 8 ++_POSIX_TIMER_MAX = 32 ++_POSIX_TTY_NAME_MAX = 9 ++_POSIX_TZNAME_MAX = 6 ++_POSIX_QLIMIT = 1 ++_POSIX_HIWAT = _POSIX_PIPE_BUF ++_POSIX_UIO_MAXIOV = 16 ++_POSIX_CLOCKRES_MIN = 20000000 ++ ++# Included from bits/local_lim.h ++ ++# Included from sys/syslimits.h ++ARG_MAX = 262144 ++CHILD_MAX = 40 ++LINK_MAX = 32767 ++MAX_CANON = 255 ++MAX_INPUT = 255 ++NAME_MAX = 255 ++NGROUPS_MAX = 1023 ++OPEN_MAX = 64 ++PATH_MAX = 1024 ++PIPE_BUF = 512 ++IOV_MAX = 1024 ++_POSIX_THREAD_KEYS_MAX = 128 ++PTHREAD_KEYS_MAX = 1024 ++_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4 ++PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS ++_POSIX_THREAD_THREADS_MAX = 64 ++PTHREAD_THREADS_MAX = 1024 ++AIO_PRIO_DELTA_MAX = 20 ++PTHREAD_STACK_MIN = 16384 ++TIMER_MAX = 256 ++DELAYTIMER_MAX = 2147483647 ++SSIZE_MAX = LONG_MAX ++NGROUPS_MAX = 8 ++ ++# Included from bits/posix2_lim.h ++_BITS_POSIX2_LIM_H = 1 ++_POSIX2_BC_BASE_MAX = 99 ++_POSIX2_BC_DIM_MAX = 2048 ++_POSIX2_BC_SCALE_MAX = 99 ++_POSIX2_BC_STRING_MAX = 1000 ++_POSIX2_COLL_WEIGHTS_MAX = 2 ++_POSIX2_EXPR_NEST_MAX = 32 ++_POSIX2_LINE_MAX = 2048 ++_POSIX2_RE_DUP_MAX = 255 ++_POSIX2_CHARCLASS_NAME_MAX = 14 ++BC_BASE_MAX = _POSIX2_BC_BASE_MAX ++BC_DIM_MAX = _POSIX2_BC_DIM_MAX ++BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX ++BC_STRING_MAX = _POSIX2_BC_STRING_MAX ++COLL_WEIGHTS_MAX = 255 ++EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX ++LINE_MAX = _POSIX2_LINE_MAX ++CHARCLASS_NAME_MAX = 2048 ++RE_DUP_MAX = (0x7fff) ++ ++# Included from bits/xopen_lim.h ++_XOPEN_LIM_H = 1 ++ ++# Included from bits/stdio_lim.h ++L_tmpnam = 20 ++TMP_MAX = 238328 ++FILENAME_MAX = 1024 ++L_ctermid = 9 ++L_cuserid = 9 ++FOPEN_MAX = 64 ++IOV_MAX = 1024 ++_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV ++NL_ARGMAX = _POSIX_ARG_MAX ++NL_LANGMAX = _POSIX2_LINE_MAX ++NL_MSGMAX = INT_MAX ++NL_NMAX = INT_MAX ++NL_SETMAX = INT_MAX ++NL_TEXTMAX = INT_MAX ++NZERO = 20 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 32 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 64 ++LONG_BIT = 32 ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++PF_UNSPEC = 0 ++PF_LOCAL = 1 ++PF_UNIX = PF_LOCAL ++PF_FILE = PF_LOCAL ++PF_INET = 2 ++PF_IMPLINK = 3 ++PF_PUP = 4 ++PF_CHAOS = 5 ++PF_NS = 6 ++PF_ISO = 7 ++PF_OSI = PF_ISO ++PF_ECMA = 8 ++PF_DATAKIT = 9 ++PF_CCITT = 10 ++PF_SNA = 11 ++PF_DECnet = 12 ++PF_DLI = 13 ++PF_LAT = 14 ++PF_HYLINK = 15 ++PF_APPLETALK = 16 ++PF_ROUTE = 17 ++PF_LINK = 18 ++PF_XTP = 19 ++PF_COIP = 20 ++PF_CNT = 21 ++PF_RTIP = 22 ++PF_IPX = 23 ++PF_SIP = 24 ++PF_PIP = 25 ++PF_ISDN = 26 ++PF_KEY = 27 ++PF_INET6 = 28 ++PF_NATM = 29 ++PF_ATM = 30 ++PF_HDRCMPLT = 31 ++PF_NETGRAPH = 32 ++PF_MAX = 33 ++AF_UNSPEC = PF_UNSPEC ++AF_LOCAL = PF_LOCAL ++AF_UNIX = PF_UNIX ++AF_FILE = PF_FILE ++AF_INET = PF_INET ++AF_IMPLINK = PF_IMPLINK ++AF_PUP = PF_PUP ++AF_CHAOS = PF_CHAOS ++AF_NS = PF_NS ++AF_ISO = PF_ISO ++AF_OSI = PF_OSI ++AF_ECMA = PF_ECMA ++AF_DATAKIT = PF_DATAKIT ++AF_CCITT = PF_CCITT ++AF_SNA = PF_SNA ++AF_DECnet = PF_DECnet ++AF_DLI = PF_DLI ++AF_LAT = PF_LAT ++AF_HYLINK = PF_HYLINK ++AF_APPLETALK = PF_APPLETALK ++AF_ROUTE = PF_ROUTE ++AF_LINK = PF_LINK ++pseudo_AF_XTP = PF_XTP ++AF_COIP = PF_COIP ++AF_CNT = PF_CNT ++pseudo_AF_RTIP = PF_RTIP ++AF_IPX = PF_IPX ++AF_SIP = PF_SIP ++pseudo_AF_PIP = PF_PIP ++AF_ISDN = PF_ISDN ++AF_E164 = AF_ISDN ++pseudo_AF_KEY = PF_KEY ++AF_INET6 = PF_INET6 ++AF_NATM = PF_NATM ++AF_ATM = PF_ATM ++pseudo_AF_HDRCMPLT = PF_HDRCMPLT ++AF_NETGRAPH = PF_NETGRAPH ++AF_MAX = PF_MAX ++SOMAXCONN = 128 ++ ++# Included from bits/sockaddr.h ++_BITS_SOCKADDR_H = 1 ++def __SOCKADDR_COMMON(sa_prefix): return \ ++ ++_HAVE_SA_LEN = 1 ++_SS_SIZE = 128 ++def CMSG_FIRSTHDR(mhdr): return \ ++ ++CMGROUP_MAX = 16 ++SOL_SOCKET = 0xffff ++LOCAL_PEERCRED = 0x001 ++LOCAL_CREDS = 0x002 ++LOCAL_CONNWAIT = 0x004 ++ ++# Included from bits/socket2.h ++def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) ++ ++IN_CLASSA_NET = (-16777216) ++IN_CLASSA_NSHIFT = 24 ++IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET) ++IN_CLASSA_MAX = 128 ++def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) ++ ++IN_CLASSB_NET = (-65536) ++IN_CLASSB_NSHIFT = 16 ++IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET) ++IN_CLASSB_MAX = 65536 ++def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) ++ ++IN_CLASSC_NET = (-256) ++IN_CLASSC_NSHIFT = 8 ++IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) ++def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912)) ++ ++def IN_MULTICAST(a): return IN_CLASSD(a) ++ ++def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) ++ ++def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456)) ++ ++IN_LOOPBACKNET = 127 ++INET_ADDRSTRLEN = 16 ++INET6_ADDRSTRLEN = 46 ++ ++# Included from bits/in.h ++IMPLINK_IP = 155 ++IMPLINK_LOWEXPER = 156 ++IMPLINK_HIGHEXPER = 158 ++IPPROTO_DIVERT = 258 ++SOL_IP = 0 ++IP_OPTIONS = 1 ++IP_HDRINCL = 2 ++IP_TOS = 3 ++IP_TTL = 4 ++IP_RECVOPTS = 5 ++IP_RECVRETOPTS = 6 ++IP_RECVDSTADDR = 7 ++IP_SENDSRCADDR = IP_RECVDSTADDR ++IP_RETOPTS = 8 ++IP_MULTICAST_IF = 9 ++IP_MULTICAST_TTL = 10 ++IP_MULTICAST_LOOP = 11 ++IP_ADD_MEMBERSHIP = 12 ++IP_DROP_MEMBERSHIP = 13 ++IP_MULTICAST_VIF = 14 ++IP_RSVP_ON = 15 ++IP_RSVP_OFF = 16 ++IP_RSVP_VIF_ON = 17 ++IP_RSVP_VIF_OFF = 18 ++IP_PORTRANGE = 19 ++IP_RECVIF = 20 ++IP_IPSEC_POLICY = 21 ++IP_FAITH = 22 ++IP_ONESBCAST = 23 ++IP_NONLOCALOK = 24 ++IP_FW_TABLE_ADD = 40 ++IP_FW_TABLE_DEL = 41 ++IP_FW_TABLE_FLUSH = 42 ++IP_FW_TABLE_GETSIZE = 43 ++IP_FW_TABLE_LIST = 44 ++IP_FW_ADD = 50 ++IP_FW_DEL = 51 ++IP_FW_FLUSH = 52 ++IP_FW_ZERO = 53 ++IP_FW_GET = 54 ++IP_FW_RESETLOG = 55 ++IP_FW_NAT_CFG = 56 ++IP_FW_NAT_DEL = 57 ++IP_FW_NAT_GET_CONFIG = 58 ++IP_FW_NAT_GET_LOG = 59 ++IP_DUMMYNET_CONFIGURE = 60 ++IP_DUMMYNET_DEL = 61 ++IP_DUMMYNET_FLUSH = 62 ++IP_DUMMYNET_GET = 64 ++IP_RECVTTL = 65 ++IP_MINTTL = 66 ++IP_DONTFRAG = 67 ++IP_ADD_SOURCE_MEMBERSHIP = 70 ++IP_DROP_SOURCE_MEMBERSHIP = 71 ++IP_BLOCK_SOURCE = 72 ++IP_UNBLOCK_SOURCE = 73 ++IP_MSFILTER = 74 ++MCAST_JOIN_GROUP = 80 ++MCAST_LEAVE_GROUP = 81 ++MCAST_JOIN_SOURCE_GROUP = 82 ++MCAST_LEAVE_SOURCE_GROUP = 83 ++MCAST_BLOCK_SOURCE = 84 ++MCAST_UNBLOCK_SOURCE = 85 ++IP_DEFAULT_MULTICAST_TTL = 1 ++IP_DEFAULT_MULTICAST_LOOP = 1 ++IP_MIN_MEMBERSHIPS = 31 ++IP_MAX_MEMBERSHIPS = 4095 ++IP_MAX_SOURCE_FILTER = 1024 ++MCAST_UNDEFINED = 0 ++MCAST_INCLUDE = 1 ++MCAST_EXCLUDE = 2 ++IP_PORTRANGE_DEFAULT = 0 ++IP_PORTRANGE_HIGH = 1 ++IP_PORTRANGE_LOW = 2 ++IPCTL_FORWARDING = 1 ++IPCTL_SENDREDIRECTS = 2 ++IPCTL_DEFTTL = 3 ++IPCTL_DEFMTU = 4 ++IPCTL_RTEXPIRE = 5 ++IPCTL_RTMINEXPIRE = 6 ++IPCTL_RTMAXCACHE = 7 ++IPCTL_SOURCEROUTE = 8 ++IPCTL_DIRECTEDBROADCAST = 9 ++IPCTL_INTRQMAXLEN = 10 ++IPCTL_INTRQDROPS = 11 ++IPCTL_STATS = 12 ++IPCTL_ACCEPTSOURCEROUTE = 13 ++IPCTL_FASTFORWARDING = 14 ++IPCTL_KEEPFAITH = 15 ++IPCTL_GIF_TTL = 16 ++IPCTL_MAXID = 17 ++IPV6_SOCKOPT_RESERVED1 = 3 ++IPV6_UNICAST_HOPS = 4 ++IPV6_MULTICAST_IF = 9 ++IPV6_MULTICAST_HOPS = 10 ++IPV6_MULTICAST_LOOP = 11 ++IPV6_JOIN_GROUP = 12 ++IPV6_LEAVE_GROUP = 13 ++IPV6_PORTRANGE = 14 ++ICMP6_FILTER = 18 ++IPV6_CHECKSUM = 26 ++IPV6_V6ONLY = 27 ++IPV6_IPSEC_POLICY = 28 ++IPV6_FAITH = 29 ++IPV6_FW_ADD = 30 ++IPV6_FW_DEL = 31 ++IPV6_FW_FLUSH = 32 ++IPV6_FW_ZERO = 33 ++IPV6_FW_GET = 34 ++IPV6_RTHDRDSTOPTS = 35 ++IPV6_RECVPKTINFO = 36 ++IPV6_RECVHOPLIMIT = 37 ++IPV6_RECVRTHDR = 38 ++IPV6_RECVHOPOPTS = 39 ++IPV6_RECVDSTOPTS = 40 ++IPV6_USE_MIN_MTU = 42 ++IPV6_RECVPATHMTU = 43 ++IPV6_PATHMTU = 44 ++IPV6_PKTINFO = 46 ++IPV6_HOPLIMIT = 47 ++IPV6_NEXTHOP = 48 ++IPV6_HOPOPTS = 49 ++IPV6_DSTOPTS = 50 ++IPV6_RTHDR = 51 ++IPV6_RECVTCLASS = 57 ++IPV6_AUTOFLOWLABEL = 59 ++IPV6_TCLASS = 61 ++IPV6_DONTFRAG = 62 ++IPV6_PREFER_TEMPADDR = 63 ++IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP ++IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP ++IPV6_RXHOPOPTS = IPV6_HOPOPTS ++IPV6_RXDSTOPTS = IPV6_DSTOPTS ++SOL_IPV6 = 41 ++SOL_ICMPV6 = 58 ++IPV6_DEFAULT_MULTICAST_HOPS = 1 ++IPV6_DEFAULT_MULTICAST_LOOP = 1 ++IPV6_PORTRANGE_DEFAULT = 0 ++IPV6_PORTRANGE_HIGH = 1 ++IPV6_PORTRANGE_LOW = 2 ++IPV6_RTHDR_LOOSE = 0 ++IPV6_RTHDR_STRICT = 1 ++IPV6_RTHDR_TYPE_0 = 0 ++IPV6CTL_FORWARDING = 1 ++IPV6CTL_SENDREDIRECTS = 2 ++IPV6CTL_DEFHLIM = 3 ++IPV6CTL_FORWSRCRT = 5 ++IPV6CTL_STATS = 6 ++IPV6CTL_MRTSTATS = 7 ++IPV6CTL_MRTPROTO = 8 ++IPV6CTL_MAXFRAGPACKETS = 9 ++IPV6CTL_SOURCECHECK = 10 ++IPV6CTL_SOURCECHECK_LOGINT = 11 ++IPV6CTL_ACCEPT_RTADV = 12 ++IPV6CTL_KEEPFAITH = 13 ++IPV6CTL_LOG_INTERVAL = 14 ++IPV6CTL_HDRNESTLIMIT = 15 ++IPV6CTL_DAD_COUNT = 16 ++IPV6CTL_AUTO_FLOWLABEL = 17 ++IPV6CTL_DEFMCASTHLIM = 18 ++IPV6CTL_GIF_HLIM = 19 ++IPV6CTL_KAME_VERSION = 20 ++IPV6CTL_USE_DEPRECATED = 21 ++IPV6CTL_RR_PRUNE = 22 ++IPV6CTL_V6ONLY = 24 ++IPV6CTL_RTEXPIRE = 25 ++IPV6CTL_RTMINEXPIRE = 26 ++IPV6CTL_RTMAXCACHE = 27 ++IPV6CTL_USETEMPADDR = 32 ++IPV6CTL_TEMPPLTIME = 33 ++IPV6CTL_TEMPVLTIME = 34 ++IPV6CTL_AUTO_LINKLOCAL = 35 ++IPV6CTL_RIP6STATS = 36 ++IPV6CTL_PREFER_TEMPADDR = 37 ++IPV6CTL_ADDRCTLPOLICY = 38 ++IPV6CTL_USE_DEFAULTZONE = 39 ++IPV6CTL_MAXFRAGS = 41 ++IPV6CTL_MCAST_PMTU = 44 ++IPV6CTL_STEALTH = 45 ++ICMPV6CTL_ND6_ONLINKNSRFC4861 = 47 ++IPV6CTL_MAXID = 48 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++def ntohl(x): return (x) ++ ++def ntohs(x): return (x) ++ ++def htonl(x): return (x) ++ ++def htons(x): return (x) ++ ++def ntohl(x): return __bswap_32 (x) ++ ++def ntohs(x): return __bswap_16 (x) ++ ++def htonl(x): return __bswap_32 (x) ++ ++def htons(x): return __bswap_16 (x) ++ ++def IN6_IS_ADDR_UNSPECIFIED(a): return \ ++ ++def IN6_IS_ADDR_LOOPBACK(a): return \ ++ ++def IN6_IS_ADDR_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_V4MAPPED(a): return \ ++ ++def IN6_IS_ADDR_V4COMPAT(a): return \ ++ ++def IN6_IS_ADDR_MC_NODELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_GLOBAL(a): return \ ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/TYPES.py +@@ -0,0 +1,303 @@ ++# Generated by h2py from /usr/include/sys/types.h ++_SYS_TYPES_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++ ++# Included from time.h ++_TIME_H = 1 ++ ++# Included from bits/time.h ++_BITS_TIME_H = 1 ++CLOCKS_PER_SEC = 1000000l ++CLK_TCK = 128 ++CLOCK_REALTIME = 0 ++CLOCK_PROCESS_CPUTIME_ID = 2 ++CLOCK_THREAD_CPUTIME_ID = 3 ++CLOCK_MONOTONIC = 4 ++CLOCK_VIRTUAL = 1 ++CLOCK_PROF = 2 ++CLOCK_UPTIME = 5 ++CLOCK_UPTIME_PRECISE = 7 ++CLOCK_UPTIME_FAST = 8 ++CLOCK_REALTIME_PRECISE = 9 ++CLOCK_REALTIME_FAST = 10 ++CLOCK_MONOTONIC_PRECISE = 11 ++CLOCK_MONOTONIC_FAST = 12 ++CLOCK_SECOND = 13 ++TIMER_RELTIME = 0 ++TIMER_ABSTIME = 1 ++_STRUCT_TIMEVAL = 1 ++CLK_TCK = CLOCKS_PER_SEC ++__clock_t_defined = 1 ++__time_t_defined = 1 ++__clockid_t_defined = 1 ++__timer_t_defined = 1 ++__timespec_defined = 1 ++ ++# Included from xlocale.h ++_XLOCALE_H = 1 ++def __isleap(year): return \ ++ ++__BIT_TYPES_DEFINED__ = 1 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++ ++# Included from sys/select.h ++_SYS_SELECT_H = 1 ++ ++# Included from bits/select.h ++def __FD_ZERO(fdsp): return \ ++ ++def __FD_ZERO(set): return \ ++ ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++def __FDELT(d): return ((d) / __NFDBITS) ++ ++FD_SETSIZE = __FD_SETSIZE ++def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) ++ ++ ++# Included from sys/sysmacros.h ++_SYS_SYSMACROS_H = 1 ++def minor(dev): return ((int)((dev) & (-65281))) ++ ++def gnu_dev_major(dev): return major (dev) ++ ++def gnu_dev_minor(dev): return minor (dev) ++ ++ ++# Included from bits/pthreadtypes.h ++_BITS_PTHREADTYPES_H = 1 ++ ++# Included from bits/sched.h ++SCHED_OTHER = 2 ++SCHED_FIFO = 1 ++SCHED_RR = 3 ++CSIGNAL = 0x000000ff ++CLONE_VM = 0x00000100 ++CLONE_FS = 0x00000200 ++CLONE_FILES = 0x00000400 ++CLONE_SIGHAND = 0x00000800 ++CLONE_PTRACE = 0x00002000 ++CLONE_VFORK = 0x00004000 ++CLONE_SYSVSEM = 0x00040000 ++__defined_schedparam = 1 ++__CPU_SETSIZE = 128 ++def __CPUELT(cpu): return ((cpu) / __NCPUBITS) ++ ++def __CPU_ALLOC_SIZE(count): return \ ++ ++def __CPU_ALLOC(count): return __sched_cpualloc (count) ++ ++def __CPU_FREE(cpuset): return __sched_cpufree (cpuset) ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd7/DLFCN.py +@@ -0,0 +1,118 @@ ++# Generated by h2py from /usr/include/dlfcn.h ++_DLFCN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/dlfcn.h ++RTLD_LAZY = 0x00001 ++RTLD_NOW = 0x00002 ++RTLD_BINDING_MASK = 0x3 ++RTLD_NOLOAD = 0x00004 ++RTLD_DEEPBIND = 0x00008 ++RTLD_GLOBAL = 0x00100 ++RTLD_LOCAL = 0 ++RTLD_NODELETE = 0x01000 ++LM_ID_BASE = 0 ++LM_ID_NEWLM = -1 +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/IN.py +@@ -0,0 +1,809 @@ ++# Generated by h2py from /usr/include/netinet/in.h ++_NETINET_IN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from stdint.h ++_STDINT_H = 1 ++ ++# Included from bits/wchar.h ++_BITS_WCHAR_H = 1 ++__WCHAR_MAX = (2147483647) ++__WCHAR_MIN = (-__WCHAR_MAX - 1) ++def __INT64_C(c): return c ## L ++ ++def __UINT64_C(c): return c ## UL ++ ++def __INT64_C(c): return c ## LL ++ ++def __UINT64_C(c): return c ## ULL ++ ++INT8_MIN = (-128) ++INT16_MIN = (-32767-1) ++INT32_MIN = (-2147483647-1) ++INT64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT8_MAX = (127) ++INT16_MAX = (32767) ++INT32_MAX = (2147483647) ++INT64_MAX = (__INT64_C(9223372036854775807)) ++UINT8_MAX = (255) ++UINT16_MAX = (65535) ++UINT64_MAX = (__UINT64_C(18446744073709551615)) ++INT_LEAST8_MIN = (-128) ++INT_LEAST16_MIN = (-32767-1) ++INT_LEAST32_MIN = (-2147483647-1) ++INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_LEAST8_MAX = (127) ++INT_LEAST16_MAX = (32767) ++INT_LEAST32_MAX = (2147483647) ++INT_LEAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_LEAST8_MAX = (255) ++UINT_LEAST16_MAX = (65535) ++UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615)) ++INT_FAST8_MIN = (-128) ++INT_FAST16_MIN = (-9223372036854775807L-1) ++INT_FAST32_MIN = (-9223372036854775807L-1) ++INT_FAST16_MIN = (-2147483647-1) ++INT_FAST32_MIN = (-2147483647-1) ++INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1) ++INT_FAST8_MAX = (127) ++INT_FAST16_MAX = (9223372036854775807L) ++INT_FAST32_MAX = (9223372036854775807L) ++INT_FAST16_MAX = (2147483647) ++INT_FAST32_MAX = (2147483647) ++INT_FAST64_MAX = (__INT64_C(9223372036854775807)) ++UINT_FAST8_MAX = (255) ++UINT_FAST64_MAX = (__UINT64_C(18446744073709551615)) ++INTPTR_MIN = (-9223372036854775807L-1) ++INTPTR_MAX = (9223372036854775807L) ++INTPTR_MIN = (-2147483647-1) ++INTPTR_MAX = (2147483647) ++INTMAX_MIN = (-__INT64_C(9223372036854775807)-1) ++INTMAX_MAX = (__INT64_C(9223372036854775807)) ++UINTMAX_MAX = (__UINT64_C(18446744073709551615)) ++PTRDIFF_MIN = (-9223372036854775807L-1) ++PTRDIFF_MAX = (9223372036854775807L) ++PTRDIFF_MIN = (-2147483647-1) ++PTRDIFF_MAX = (2147483647) ++SIG_ATOMIC_MIN = (-2147483647-1) ++SIG_ATOMIC_MAX = (2147483647) ++WCHAR_MIN = __WCHAR_MIN ++WCHAR_MAX = __WCHAR_MAX ++def INT8_C(c): return c ++ ++def INT16_C(c): return c ++ ++def INT32_C(c): return c ++ ++def INT64_C(c): return c ## L ++ ++def INT64_C(c): return c ## LL ++ ++def UINT8_C(c): return c ++ ++def UINT16_C(c): return c ++ ++def UINT32_C(c): return c ## U ++ ++def UINT64_C(c): return c ## UL ++ ++def UINT64_C(c): return c ## ULL ++ ++def INTMAX_C(c): return c ## L ++ ++def UINTMAX_C(c): return c ## UL ++ ++def INTMAX_C(c): return c ## LL ++ ++def UINTMAX_C(c): return c ## ULL ++ ++ ++# Included from sys/socket.h ++_SYS_SOCKET_H = 1 ++ ++# Included from sys/uio.h ++_SYS_UIO_H = 1 ++from TYPES import * ++ ++# Included from bits/uio.h ++_BITS_UIO_H = 1 ++from TYPES import * ++UIO_MAXIOV = 1024 ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++ ++# Included from bits/socket.h ++__BITS_SOCKET_H = 1 ++ ++# Included from limits.h ++_LIBC_LIMITS_H_ = 1 ++MB_LEN_MAX = 16 ++_LIMITS_H = 1 ++CHAR_BIT = 8 ++SCHAR_MIN = (-128) ++SCHAR_MAX = 127 ++UCHAR_MAX = 255 ++CHAR_MIN = 0 ++CHAR_MAX = UCHAR_MAX ++CHAR_MIN = SCHAR_MIN ++CHAR_MAX = SCHAR_MAX ++SHRT_MIN = (-32768) ++SHRT_MAX = 32767 ++USHRT_MAX = 65535 ++INT_MAX = 2147483647 ++LONG_MAX = 9223372036854775807L ++LONG_MAX = 2147483647L ++LONG_MIN = (-LONG_MAX - 1L) ++ ++# Included from bits/posix1_lim.h ++_BITS_POSIX1_LIM_H = 1 ++_POSIX_AIO_LISTIO_MAX = 2 ++_POSIX_AIO_MAX = 1 ++_POSIX_ARG_MAX = 4096 ++_POSIX_CHILD_MAX = 25 ++_POSIX_CHILD_MAX = 6 ++_POSIX_DELAYTIMER_MAX = 32 ++_POSIX_HOST_NAME_MAX = 255 ++_POSIX_LINK_MAX = 8 ++_POSIX_LOGIN_NAME_MAX = 9 ++_POSIX_MAX_CANON = 255 ++_POSIX_MAX_INPUT = 255 ++_POSIX_MQ_OPEN_MAX = 8 ++_POSIX_MQ_PRIO_MAX = 32 ++_POSIX_NAME_MAX = 14 ++_POSIX_NGROUPS_MAX = 8 ++_POSIX_NGROUPS_MAX = 0 ++_POSIX_OPEN_MAX = 20 ++_POSIX_OPEN_MAX = 16 ++_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX ++_POSIX_PATH_MAX = 256 ++_POSIX_PIPE_BUF = 512 ++_POSIX_RE_DUP_MAX = 255 ++_POSIX_RTSIG_MAX = 8 ++_POSIX_SEM_NSEMS_MAX = 256 ++_POSIX_SEM_VALUE_MAX = 32767 ++_POSIX_SIGQUEUE_MAX = 32 ++_POSIX_SSIZE_MAX = 32767 ++_POSIX_STREAM_MAX = 8 ++_POSIX_SYMLINK_MAX = 255 ++_POSIX_SYMLOOP_MAX = 8 ++_POSIX_TIMER_MAX = 32 ++_POSIX_TTY_NAME_MAX = 9 ++_POSIX_TZNAME_MAX = 6 ++_POSIX_QLIMIT = 1 ++_POSIX_HIWAT = _POSIX_PIPE_BUF ++_POSIX_UIO_MAXIOV = 16 ++_POSIX_CLOCKRES_MIN = 20000000 ++ ++# Included from bits/local_lim.h ++ ++# Included from sys/syslimits.h ++ARG_MAX = 262144 ++CHILD_MAX = 40 ++LINK_MAX = 32767 ++MAX_CANON = 255 ++MAX_INPUT = 255 ++NAME_MAX = 255 ++NGROUPS_MAX = 1023 ++OPEN_MAX = 64 ++PATH_MAX = 1024 ++PIPE_BUF = 512 ++IOV_MAX = 1024 ++_POSIX_THREAD_KEYS_MAX = 128 ++PTHREAD_KEYS_MAX = 1024 ++_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4 ++PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS ++_POSIX_THREAD_THREADS_MAX = 64 ++PTHREAD_THREADS_MAX = 1024 ++AIO_PRIO_DELTA_MAX = 20 ++PTHREAD_STACK_MIN = 16384 ++TIMER_MAX = 256 ++DELAYTIMER_MAX = 2147483647 ++SSIZE_MAX = LONG_MAX ++NGROUPS_MAX = 8 ++ ++# Included from bits/posix2_lim.h ++_BITS_POSIX2_LIM_H = 1 ++_POSIX2_BC_BASE_MAX = 99 ++_POSIX2_BC_DIM_MAX = 2048 ++_POSIX2_BC_SCALE_MAX = 99 ++_POSIX2_BC_STRING_MAX = 1000 ++_POSIX2_COLL_WEIGHTS_MAX = 2 ++_POSIX2_EXPR_NEST_MAX = 32 ++_POSIX2_LINE_MAX = 2048 ++_POSIX2_RE_DUP_MAX = 255 ++_POSIX2_CHARCLASS_NAME_MAX = 14 ++BC_BASE_MAX = _POSIX2_BC_BASE_MAX ++BC_DIM_MAX = _POSIX2_BC_DIM_MAX ++BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX ++BC_STRING_MAX = _POSIX2_BC_STRING_MAX ++COLL_WEIGHTS_MAX = 255 ++EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX ++LINE_MAX = _POSIX2_LINE_MAX ++CHARCLASS_NAME_MAX = 2048 ++RE_DUP_MAX = (0x7fff) ++ ++# Included from bits/xopen_lim.h ++_XOPEN_LIM_H = 1 ++ ++# Included from bits/stdio_lim.h ++L_tmpnam = 20 ++TMP_MAX = 238328 ++FILENAME_MAX = 1024 ++L_ctermid = 9 ++L_cuserid = 9 ++FOPEN_MAX = 64 ++IOV_MAX = 1024 ++_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV ++NL_ARGMAX = _POSIX_ARG_MAX ++NL_LANGMAX = _POSIX2_LINE_MAX ++NL_MSGMAX = INT_MAX ++NL_NMAX = INT_MAX ++NL_SETMAX = INT_MAX ++NL_TEXTMAX = INT_MAX ++NZERO = 20 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 16 ++WORD_BIT = 32 ++WORD_BIT = 64 ++WORD_BIT = 32 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 32 ++LONG_BIT = 64 ++LONG_BIT = 64 ++LONG_BIT = 32 ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++PF_UNSPEC = 0 ++PF_LOCAL = 1 ++PF_UNIX = PF_LOCAL ++PF_FILE = PF_LOCAL ++PF_INET = 2 ++PF_IMPLINK = 3 ++PF_PUP = 4 ++PF_CHAOS = 5 ++PF_NS = 6 ++PF_ISO = 7 ++PF_OSI = PF_ISO ++PF_ECMA = 8 ++PF_DATAKIT = 9 ++PF_CCITT = 10 ++PF_SNA = 11 ++PF_DECnet = 12 ++PF_DLI = 13 ++PF_LAT = 14 ++PF_HYLINK = 15 ++PF_APPLETALK = 16 ++PF_ROUTE = 17 ++PF_LINK = 18 ++PF_XTP = 19 ++PF_COIP = 20 ++PF_CNT = 21 ++PF_RTIP = 22 ++PF_IPX = 23 ++PF_SIP = 24 ++PF_PIP = 25 ++PF_ISDN = 26 ++PF_KEY = 27 ++PF_INET6 = 28 ++PF_NATM = 29 ++PF_ATM = 30 ++PF_HDRCMPLT = 31 ++PF_NETGRAPH = 32 ++PF_MAX = 33 ++AF_UNSPEC = PF_UNSPEC ++AF_LOCAL = PF_LOCAL ++AF_UNIX = PF_UNIX ++AF_FILE = PF_FILE ++AF_INET = PF_INET ++AF_IMPLINK = PF_IMPLINK ++AF_PUP = PF_PUP ++AF_CHAOS = PF_CHAOS ++AF_NS = PF_NS ++AF_ISO = PF_ISO ++AF_OSI = PF_OSI ++AF_ECMA = PF_ECMA ++AF_DATAKIT = PF_DATAKIT ++AF_CCITT = PF_CCITT ++AF_SNA = PF_SNA ++AF_DECnet = PF_DECnet ++AF_DLI = PF_DLI ++AF_LAT = PF_LAT ++AF_HYLINK = PF_HYLINK ++AF_APPLETALK = PF_APPLETALK ++AF_ROUTE = PF_ROUTE ++AF_LINK = PF_LINK ++pseudo_AF_XTP = PF_XTP ++AF_COIP = PF_COIP ++AF_CNT = PF_CNT ++pseudo_AF_RTIP = PF_RTIP ++AF_IPX = PF_IPX ++AF_SIP = PF_SIP ++pseudo_AF_PIP = PF_PIP ++AF_ISDN = PF_ISDN ++AF_E164 = AF_ISDN ++pseudo_AF_KEY = PF_KEY ++AF_INET6 = PF_INET6 ++AF_NATM = PF_NATM ++AF_ATM = PF_ATM ++pseudo_AF_HDRCMPLT = PF_HDRCMPLT ++AF_NETGRAPH = PF_NETGRAPH ++AF_MAX = PF_MAX ++SOMAXCONN = 128 ++ ++# Included from bits/sockaddr.h ++_BITS_SOCKADDR_H = 1 ++def __SOCKADDR_COMMON(sa_prefix): return \ ++ ++_HAVE_SA_LEN = 1 ++_SS_SIZE = 128 ++def CMSG_FIRSTHDR(mhdr): return \ ++ ++CMGROUP_MAX = 16 ++SOL_SOCKET = 0xffff ++LOCAL_PEERCRED = 0x001 ++LOCAL_CREDS = 0x002 ++LOCAL_CONNWAIT = 0x004 ++ ++# Included from bits/socket2.h ++def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0) ++ ++IN_CLASSA_NET = (-16777216) ++IN_CLASSA_NSHIFT = 24 ++IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET) ++IN_CLASSA_MAX = 128 ++def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648)) ++ ++IN_CLASSB_NET = (-65536) ++IN_CLASSB_NSHIFT = 16 ++IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET) ++IN_CLASSB_MAX = 65536 ++def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824)) ++ ++IN_CLASSC_NET = (-256) ++IN_CLASSC_NSHIFT = 8 ++IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET) ++def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912)) ++ ++def IN_MULTICAST(a): return IN_CLASSD(a) ++ ++def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912)) ++ ++def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456)) ++ ++IN_LOOPBACKNET = 127 ++INET_ADDRSTRLEN = 16 ++INET6_ADDRSTRLEN = 46 ++ ++# Included from bits/in.h ++IMPLINK_IP = 155 ++IMPLINK_LOWEXPER = 156 ++IMPLINK_HIGHEXPER = 158 ++IPPROTO_DIVERT = 258 ++SOL_IP = 0 ++IP_OPTIONS = 1 ++IP_HDRINCL = 2 ++IP_TOS = 3 ++IP_TTL = 4 ++IP_RECVOPTS = 5 ++IP_RECVRETOPTS = 6 ++IP_RECVDSTADDR = 7 ++IP_SENDSRCADDR = IP_RECVDSTADDR ++IP_RETOPTS = 8 ++IP_MULTICAST_IF = 9 ++IP_MULTICAST_TTL = 10 ++IP_MULTICAST_LOOP = 11 ++IP_ADD_MEMBERSHIP = 12 ++IP_DROP_MEMBERSHIP = 13 ++IP_MULTICAST_VIF = 14 ++IP_RSVP_ON = 15 ++IP_RSVP_OFF = 16 ++IP_RSVP_VIF_ON = 17 ++IP_RSVP_VIF_OFF = 18 ++IP_PORTRANGE = 19 ++IP_RECVIF = 20 ++IP_IPSEC_POLICY = 21 ++IP_FAITH = 22 ++IP_ONESBCAST = 23 ++IP_NONLOCALOK = 24 ++IP_FW_TABLE_ADD = 40 ++IP_FW_TABLE_DEL = 41 ++IP_FW_TABLE_FLUSH = 42 ++IP_FW_TABLE_GETSIZE = 43 ++IP_FW_TABLE_LIST = 44 ++IP_FW_ADD = 50 ++IP_FW_DEL = 51 ++IP_FW_FLUSH = 52 ++IP_FW_ZERO = 53 ++IP_FW_GET = 54 ++IP_FW_RESETLOG = 55 ++IP_FW_NAT_CFG = 56 ++IP_FW_NAT_DEL = 57 ++IP_FW_NAT_GET_CONFIG = 58 ++IP_FW_NAT_GET_LOG = 59 ++IP_DUMMYNET_CONFIGURE = 60 ++IP_DUMMYNET_DEL = 61 ++IP_DUMMYNET_FLUSH = 62 ++IP_DUMMYNET_GET = 64 ++IP_RECVTTL = 65 ++IP_MINTTL = 66 ++IP_DONTFRAG = 67 ++IP_ADD_SOURCE_MEMBERSHIP = 70 ++IP_DROP_SOURCE_MEMBERSHIP = 71 ++IP_BLOCK_SOURCE = 72 ++IP_UNBLOCK_SOURCE = 73 ++IP_MSFILTER = 74 ++MCAST_JOIN_GROUP = 80 ++MCAST_LEAVE_GROUP = 81 ++MCAST_JOIN_SOURCE_GROUP = 82 ++MCAST_LEAVE_SOURCE_GROUP = 83 ++MCAST_BLOCK_SOURCE = 84 ++MCAST_UNBLOCK_SOURCE = 85 ++IP_DEFAULT_MULTICAST_TTL = 1 ++IP_DEFAULT_MULTICAST_LOOP = 1 ++IP_MIN_MEMBERSHIPS = 31 ++IP_MAX_MEMBERSHIPS = 4095 ++IP_MAX_SOURCE_FILTER = 1024 ++MCAST_UNDEFINED = 0 ++MCAST_INCLUDE = 1 ++MCAST_EXCLUDE = 2 ++IP_PORTRANGE_DEFAULT = 0 ++IP_PORTRANGE_HIGH = 1 ++IP_PORTRANGE_LOW = 2 ++IPCTL_FORWARDING = 1 ++IPCTL_SENDREDIRECTS = 2 ++IPCTL_DEFTTL = 3 ++IPCTL_DEFMTU = 4 ++IPCTL_RTEXPIRE = 5 ++IPCTL_RTMINEXPIRE = 6 ++IPCTL_RTMAXCACHE = 7 ++IPCTL_SOURCEROUTE = 8 ++IPCTL_DIRECTEDBROADCAST = 9 ++IPCTL_INTRQMAXLEN = 10 ++IPCTL_INTRQDROPS = 11 ++IPCTL_STATS = 12 ++IPCTL_ACCEPTSOURCEROUTE = 13 ++IPCTL_FASTFORWARDING = 14 ++IPCTL_KEEPFAITH = 15 ++IPCTL_GIF_TTL = 16 ++IPCTL_MAXID = 17 ++IPV6_SOCKOPT_RESERVED1 = 3 ++IPV6_UNICAST_HOPS = 4 ++IPV6_MULTICAST_IF = 9 ++IPV6_MULTICAST_HOPS = 10 ++IPV6_MULTICAST_LOOP = 11 ++IPV6_JOIN_GROUP = 12 ++IPV6_LEAVE_GROUP = 13 ++IPV6_PORTRANGE = 14 ++ICMP6_FILTER = 18 ++IPV6_CHECKSUM = 26 ++IPV6_V6ONLY = 27 ++IPV6_IPSEC_POLICY = 28 ++IPV6_FAITH = 29 ++IPV6_FW_ADD = 30 ++IPV6_FW_DEL = 31 ++IPV6_FW_FLUSH = 32 ++IPV6_FW_ZERO = 33 ++IPV6_FW_GET = 34 ++IPV6_RTHDRDSTOPTS = 35 ++IPV6_RECVPKTINFO = 36 ++IPV6_RECVHOPLIMIT = 37 ++IPV6_RECVRTHDR = 38 ++IPV6_RECVHOPOPTS = 39 ++IPV6_RECVDSTOPTS = 40 ++IPV6_USE_MIN_MTU = 42 ++IPV6_RECVPATHMTU = 43 ++IPV6_PATHMTU = 44 ++IPV6_PKTINFO = 46 ++IPV6_HOPLIMIT = 47 ++IPV6_NEXTHOP = 48 ++IPV6_HOPOPTS = 49 ++IPV6_DSTOPTS = 50 ++IPV6_RTHDR = 51 ++IPV6_RECVTCLASS = 57 ++IPV6_AUTOFLOWLABEL = 59 ++IPV6_TCLASS = 61 ++IPV6_DONTFRAG = 62 ++IPV6_PREFER_TEMPADDR = 63 ++IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP ++IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP ++IPV6_RXHOPOPTS = IPV6_HOPOPTS ++IPV6_RXDSTOPTS = IPV6_DSTOPTS ++SOL_IPV6 = 41 ++SOL_ICMPV6 = 58 ++IPV6_DEFAULT_MULTICAST_HOPS = 1 ++IPV6_DEFAULT_MULTICAST_LOOP = 1 ++IPV6_PORTRANGE_DEFAULT = 0 ++IPV6_PORTRANGE_HIGH = 1 ++IPV6_PORTRANGE_LOW = 2 ++IPV6_RTHDR_LOOSE = 0 ++IPV6_RTHDR_STRICT = 1 ++IPV6_RTHDR_TYPE_0 = 0 ++IPV6CTL_FORWARDING = 1 ++IPV6CTL_SENDREDIRECTS = 2 ++IPV6CTL_DEFHLIM = 3 ++IPV6CTL_FORWSRCRT = 5 ++IPV6CTL_STATS = 6 ++IPV6CTL_MRTSTATS = 7 ++IPV6CTL_MRTPROTO = 8 ++IPV6CTL_MAXFRAGPACKETS = 9 ++IPV6CTL_SOURCECHECK = 10 ++IPV6CTL_SOURCECHECK_LOGINT = 11 ++IPV6CTL_ACCEPT_RTADV = 12 ++IPV6CTL_KEEPFAITH = 13 ++IPV6CTL_LOG_INTERVAL = 14 ++IPV6CTL_HDRNESTLIMIT = 15 ++IPV6CTL_DAD_COUNT = 16 ++IPV6CTL_AUTO_FLOWLABEL = 17 ++IPV6CTL_DEFMCASTHLIM = 18 ++IPV6CTL_GIF_HLIM = 19 ++IPV6CTL_KAME_VERSION = 20 ++IPV6CTL_USE_DEPRECATED = 21 ++IPV6CTL_RR_PRUNE = 22 ++IPV6CTL_V6ONLY = 24 ++IPV6CTL_RTEXPIRE = 25 ++IPV6CTL_RTMINEXPIRE = 26 ++IPV6CTL_RTMAXCACHE = 27 ++IPV6CTL_USETEMPADDR = 32 ++IPV6CTL_TEMPPLTIME = 33 ++IPV6CTL_TEMPVLTIME = 34 ++IPV6CTL_AUTO_LINKLOCAL = 35 ++IPV6CTL_RIP6STATS = 36 ++IPV6CTL_PREFER_TEMPADDR = 37 ++IPV6CTL_ADDRCTLPOLICY = 38 ++IPV6CTL_USE_DEFAULTZONE = 39 ++IPV6CTL_MAXFRAGS = 41 ++IPV6CTL_MCAST_PMTU = 44 ++IPV6CTL_STEALTH = 45 ++ICMPV6CTL_ND6_ONLINKNSRFC4861 = 47 ++IPV6CTL_MAXID = 48 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++def ntohl(x): return (x) ++ ++def ntohs(x): return (x) ++ ++def htonl(x): return (x) ++ ++def htons(x): return (x) ++ ++def ntohl(x): return __bswap_32 (x) ++ ++def ntohs(x): return __bswap_16 (x) ++ ++def htonl(x): return __bswap_32 (x) ++ ++def htons(x): return __bswap_16 (x) ++ ++def IN6_IS_ADDR_UNSPECIFIED(a): return \ ++ ++def IN6_IS_ADDR_LOOPBACK(a): return \ ++ ++def IN6_IS_ADDR_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_V4MAPPED(a): return \ ++ ++def IN6_IS_ADDR_V4COMPAT(a): return \ ++ ++def IN6_IS_ADDR_MC_NODELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_SITELOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ ++ ++def IN6_IS_ADDR_MC_GLOBAL(a): return \ ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/TYPES.py +@@ -0,0 +1,303 @@ ++# Generated by h2py from /usr/include/sys/types.h ++_SYS_TYPES_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/types.h ++_BITS_TYPES_H = 1 ++__S32_TYPE = int ++__SWORD_TYPE = int ++__SLONG32_TYPE = int ++ ++# Included from bits/typesizes.h ++_BITS_TYPESIZES_H = 1 ++__PID_T_TYPE = __S32_TYPE ++__CLOCK_T_TYPE = __S32_TYPE ++__SWBLK_T_TYPE = __S32_TYPE ++__CLOCKID_T_TYPE = __S32_TYPE ++__TIMER_T_TYPE = __S32_TYPE ++__SSIZE_T_TYPE = __SWORD_TYPE ++__FD_SETSIZE = 1024 ++ ++# Included from time.h ++_TIME_H = 1 ++ ++# Included from bits/time.h ++_BITS_TIME_H = 1 ++CLOCKS_PER_SEC = 1000000l ++CLK_TCK = 128 ++CLOCK_REALTIME = 0 ++CLOCK_PROCESS_CPUTIME_ID = 2 ++CLOCK_THREAD_CPUTIME_ID = 3 ++CLOCK_MONOTONIC = 4 ++CLOCK_VIRTUAL = 1 ++CLOCK_PROF = 2 ++CLOCK_UPTIME = 5 ++CLOCK_UPTIME_PRECISE = 7 ++CLOCK_UPTIME_FAST = 8 ++CLOCK_REALTIME_PRECISE = 9 ++CLOCK_REALTIME_FAST = 10 ++CLOCK_MONOTONIC_PRECISE = 11 ++CLOCK_MONOTONIC_FAST = 12 ++CLOCK_SECOND = 13 ++TIMER_RELTIME = 0 ++TIMER_ABSTIME = 1 ++_STRUCT_TIMEVAL = 1 ++CLK_TCK = CLOCKS_PER_SEC ++__clock_t_defined = 1 ++__time_t_defined = 1 ++__clockid_t_defined = 1 ++__timer_t_defined = 1 ++__timespec_defined = 1 ++ ++# Included from xlocale.h ++_XLOCALE_H = 1 ++def __isleap(year): return \ ++ ++__BIT_TYPES_DEFINED__ = 1 ++ ++# Included from endian.h ++_ENDIAN_H = 1 ++__LITTLE_ENDIAN = 1234 ++__BIG_ENDIAN = 4321 ++__PDP_ENDIAN = 3412 ++ ++# Included from bits/endian.h ++__BYTE_ORDER = __LITTLE_ENDIAN ++__FLOAT_WORD_ORDER = __BYTE_ORDER ++LITTLE_ENDIAN = __LITTLE_ENDIAN ++BIG_ENDIAN = __BIG_ENDIAN ++PDP_ENDIAN = __PDP_ENDIAN ++BYTE_ORDER = __BYTE_ORDER ++ ++# Included from bits/byteswap.h ++_BITS_BYTESWAP_H = 1 ++def __bswap_constant_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_16(x): return \ ++ ++def __bswap_constant_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_32(x): return \ ++ ++def __bswap_constant_64(x): return \ ++ ++def __bswap_64(x): return \ ++ ++def htobe16(x): return __bswap_16 (x) ++ ++def htole16(x): return (x) ++ ++def be16toh(x): return __bswap_16 (x) ++ ++def le16toh(x): return (x) ++ ++def htobe32(x): return __bswap_32 (x) ++ ++def htole32(x): return (x) ++ ++def be32toh(x): return __bswap_32 (x) ++ ++def le32toh(x): return (x) ++ ++def htobe64(x): return __bswap_64 (x) ++ ++def htole64(x): return (x) ++ ++def be64toh(x): return __bswap_64 (x) ++ ++def le64toh(x): return (x) ++ ++def htobe16(x): return (x) ++ ++def htole16(x): return __bswap_16 (x) ++ ++def be16toh(x): return (x) ++ ++def le16toh(x): return __bswap_16 (x) ++ ++def htobe32(x): return (x) ++ ++def htole32(x): return __bswap_32 (x) ++ ++def be32toh(x): return (x) ++ ++def le32toh(x): return __bswap_32 (x) ++ ++def htobe64(x): return (x) ++ ++def htole64(x): return __bswap_64 (x) ++ ++def be64toh(x): return (x) ++ ++def le64toh(x): return __bswap_64 (x) ++ ++ ++# Included from sys/select.h ++_SYS_SELECT_H = 1 ++ ++# Included from bits/select.h ++def __FD_ZERO(fdsp): return \ ++ ++def __FD_ZERO(set): return \ ++ ++ ++# Included from bits/sigset.h ++_SIGSET_H_types = 1 ++_SIGSET_H_fns = 1 ++def __sigword(sig): return (((sig) - 1) >> 5) ++ ++def __sigemptyset(set): return \ ++ ++def __sigfillset(set): return \ ++ ++def __sigisemptyset(set): return \ ++ ++def __FDELT(d): return ((d) / __NFDBITS) ++ ++FD_SETSIZE = __FD_SETSIZE ++def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp) ++ ++ ++# Included from sys/sysmacros.h ++_SYS_SYSMACROS_H = 1 ++def minor(dev): return ((int)((dev) & (-65281))) ++ ++def gnu_dev_major(dev): return major (dev) ++ ++def gnu_dev_minor(dev): return minor (dev) ++ ++ ++# Included from bits/pthreadtypes.h ++_BITS_PTHREADTYPES_H = 1 ++ ++# Included from bits/sched.h ++SCHED_OTHER = 2 ++SCHED_FIFO = 1 ++SCHED_RR = 3 ++CSIGNAL = 0x000000ff ++CLONE_VM = 0x00000100 ++CLONE_FS = 0x00000200 ++CLONE_FILES = 0x00000400 ++CLONE_SIGHAND = 0x00000800 ++CLONE_PTRACE = 0x00002000 ++CLONE_VFORK = 0x00004000 ++CLONE_SYSVSEM = 0x00040000 ++__defined_schedparam = 1 ++__CPU_SETSIZE = 128 ++def __CPUELT(cpu): return ((cpu) / __NCPUBITS) ++ ++def __CPU_ALLOC_SIZE(count): return \ ++ ++def __CPU_ALLOC(count): return __sched_cpualloc (count) ++ ++def __CPU_FREE(cpuset): return __sched_cpufree (cpuset) ++ +--- /dev/null ++++ b/Lib/plat-gnukfreebsd8/DLFCN.py +@@ -0,0 +1,118 @@ ++# Generated by h2py from /usr/include/dlfcn.h ++_DLFCN_H = 1 ++ ++# Included from features.h ++_FEATURES_H = 1 ++__USE_ANSI = 1 ++__FAVOR_BSD = 1 ++_ISOC99_SOURCE = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 200809L ++_XOPEN_SOURCE = 700 ++_XOPEN_SOURCE_EXTENDED = 1 ++_LARGEFILE64_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++_ATFILE_SOURCE = 1 ++_BSD_SOURCE = 1 ++_SVID_SOURCE = 1 ++__USE_ISOC99 = 1 ++__USE_ISOC95 = 1 ++_POSIX_SOURCE = 1 ++_POSIX_C_SOURCE = 2 ++_POSIX_C_SOURCE = 199506L ++_POSIX_C_SOURCE = 200112L ++_POSIX_C_SOURCE = 200809L ++__USE_POSIX_IMPLICITLY = 1 ++__USE_POSIX = 1 ++__USE_POSIX2 = 1 ++__USE_POSIX199309 = 1 ++__USE_POSIX199506 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN2K8 = 1 ++_ATFILE_SOURCE = 1 ++__USE_XOPEN = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_UNIX98 = 1 ++_LARGEFILE_SOURCE = 1 ++__USE_XOPEN2K8 = 1 ++__USE_XOPEN2K = 1 ++__USE_ISOC99 = 1 ++__USE_XOPEN_EXTENDED = 1 ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_FILE_OFFSET64 = 1 ++__USE_MISC = 1 ++__USE_BSD = 1 ++__USE_SVID = 1 ++__USE_ATFILE = 1 ++__USE_GNU = 1 ++__USE_REENTRANT = 1 ++__USE_FORTIFY_LEVEL = 2 ++__USE_FORTIFY_LEVEL = 1 ++__USE_FORTIFY_LEVEL = 0 ++ ++# Included from bits/predefs.h ++__STDC_IEC_559__ = 1 ++__STDC_IEC_559_COMPLEX__ = 1 ++__STDC_ISO_10646__ = 200009L ++__GNU_LIBRARY__ = 6 ++__GLIBC__ = 2 ++__GLIBC_MINOR__ = 11 ++__GLIBC_HAVE_LONG_LONG = 1 ++ ++# Included from sys/cdefs.h ++_SYS_CDEFS_H = 1 ++def __NTH(fct): return fct ++ ++def __NTH(fct): return fct ++ ++def __P(args): return args ++ ++def __PMT(args): return args ++ ++def __STRING(x): return #x ++ ++def __bos(ptr): return __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) ++ ++def __bos0(ptr): return __builtin_object_size (ptr, 0) ++ ++def __warnattr(msg): return __attribute__((__warning__ (msg))) ++ ++__flexarr = [] ++__flexarr = [0] ++__flexarr = [] ++__flexarr = [1] ++def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname) ++ ++def __attribute__(xyz): return ++ ++def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x))) ++ ++def __attribute_format_arg__(x): return ++ ++ ++# Included from bits/wordsize.h ++__WORDSIZE = 32 ++__LDBL_COMPAT = 1 ++def __LDBL_REDIR_DECL(name): return \ ++ ++__USE_LARGEFILE = 1 ++__USE_LARGEFILE64 = 1 ++__USE_EXTERN_INLINES = 1 ++__USE_EXTERN_INLINES_IN_LIBC = 1 ++ ++# Included from gnu/stubs.h ++ ++# Included from bits/dlfcn.h ++RTLD_LAZY = 0x00001 ++RTLD_NOW = 0x00002 ++RTLD_BINDING_MASK = 0x3 ++RTLD_NOLOAD = 0x00004 ++RTLD_DEEPBIND = 0x00008 ++RTLD_GLOBAL = 0x00100 ++RTLD_LOCAL = 0 ++RTLD_NODELETE = 0x01000 ++LM_ID_BASE = 0 ++LM_ID_NEWLM = -1 --- python2.7-2.7.2.orig/debian/patches/ctypes-arm.diff +++ python2.7-2.7.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') + --- python2.7-2.7.2.orig/debian/patches/apport-support.dpatch +++ python2.7-2.7.2/debian/patches/apport-support.dpatch @@ -0,0 +1,42 @@ +#! /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 + #cd ${dir}gcc && autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + #rm ${dir}gcc/configure + ;; + *) + 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() + --- python2.7-2.7.2.orig/debian/patches/no-zip-on-sys.path.diff +++ python2.7-2.7.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 +@@ -380,7 +380,9 @@ + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + char argv0_path[MAXPATHLEN+1]; ++#ifdef WITH_ZIP_PATH + char zip_path[MAXPATHLEN+1]; ++#endif + int pfound, efound; /* 1 if found; -1 if found build directory */ + char *buf; + size_t bufsz; +@@ -520,6 +522,7 @@ + else + reduce(prefix); + ++#ifdef WITH_ZIP_PATH + strncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ +@@ -532,6 +535,7 @@ + bufsz = strlen(zip_path); /* Replace "00" with version */ + zip_path[bufsz - 6] = VERSION[0]; + zip_path[bufsz - 5] = VERSION[2]; ++#endif + + if (!(efound = search_for_exec_prefix(argv0_path, home))) { + if (!Py_FrozenFlag) +@@ -571,7 +575,9 @@ + defpath = delim + 1; + } + ++#ifdef WITH_ZIP_PATH + bufsz += strlen(zip_path) + 1; ++#endif + bufsz += strlen(exec_prefix) + 1; + + /* This is the only malloc call in this file */ +@@ -592,9 +598,11 @@ + else + buf[0] = '\0'; + ++#ifdef WITH_ZIP_PATH + /* Next is the default zip path */ + strcat(buf, zip_path); + strcat(buf, delimiter); ++#endif + + /* Next goes merge of compile-time $PYTHONPATH with + * dynamically located prefix. --- python2.7-2.7.2.orig/debian/patches/doc-nodownload.diff +++ python2.7-2.7.2/debian/patches/doc-nodownload.diff @@ -0,0 +1,13 @@ +# DP: Don't try to download documentation tools + +--- a/Doc/Makefile ++++ b/Doc/Makefile +@@ -57,7 +57,7 @@ + + update: clean checkout + +-build: checkout ++build: + mkdir -p build/$(BUILDER) build/doctrees + $(PYTHON) tools/sphinx-build.py $(ALLSPHINXOPTS) + @echo --- python2.7-2.7.2.orig/debian/patches/cthreads.diff +++ python2.7-2.7.2/debian/patches/cthreads.diff @@ -0,0 +1,39 @@ +# DP: Remove cthreads detection + +--- a/configure.in ++++ b/configure.in +@@ -2154,7 +2154,6 @@ + + # Templates for things AC_DEFINEd more than once. + # For a single AC_DEFINE, no template is needed. +-AH_TEMPLATE(C_THREADS,[Define if you have the Mach cthreads package]) + AH_TEMPLATE(_REENTRANT, + [Define to force use of thread-safe errno, h_errno, and other functions]) + AH_TEMPLATE(WITH_THREAD, +@@ -2236,17 +2235,6 @@ + AC_MSG_RESULT($unistd_defines_pthreads) + + AC_DEFINE(_REENTRANT) +- AC_CHECK_HEADER(cthreads.h, [AC_DEFINE(WITH_THREAD) +- AC_DEFINE(C_THREADS) +- AC_DEFINE(HURD_C_THREADS, 1, +- [Define if you are using Mach cthreads directly under /include]) +- LIBS="$LIBS -lthreads" +- THREADOBJ="Python/thread.o"],[ +- AC_CHECK_HEADER(mach/cthreads.h, [AC_DEFINE(WITH_THREAD) +- AC_DEFINE(C_THREADS) +- AC_DEFINE(MACH_C_THREADS, 1, +- [Define if you are using Mach cthreads under mach /]) +- THREADOBJ="Python/thread.o"],[ + AC_MSG_CHECKING(for --with-pth) + AC_ARG_WITH([pth], + AS_HELP_STRING([--with-pth], [use GNU pth threading libraries]), +@@ -2301,7 +2289,7 @@ + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o"],[ + USE_THREAD_MODULE="#"]) +- ])])])])])])])])])]) ++ ])])])])])])])]) + + AC_CHECK_LIB(mpc, usconfig, [AC_DEFINE(WITH_THREAD) + LIBS="$LIBS -lmpc" --- python2.7-2.7.2.orig/debian/patches/profiled-build.diff +++ python2.7-2.7.2/debian/patches/profiled-build.diff @@ -0,0 +1,27 @@ +# DP: Fix profiled build; don't use Python/thread.gc*, gcc complains + +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -388,18 +388,18 @@ + $(MAKE) build_all_use_profile + + build_all_generate_profile: +- $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" ++ $(MAKE) all PY_CFLAGS="$(PY_CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" + + run_profile_task: +- ./$(BUILDPYTHON) $(PROFILE_TASK) ++ -./$(BUILDPYTHON) $(PROFILE_TASK) + + build_all_use_profile: +- $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" ++ $(MAKE) all PY_CFLAGS="$(PY_CFLAGS) -fprofile-use -fprofile-correction" + + coverage: + @echo "Building with support for coverage checking:" + $(MAKE) clean +- $(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov" ++ $(MAKE) all PY_CFLAGS="$(PY_CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov" + + + # Build the interpreter --- python2.7-2.7.2.orig/debian/patches/link-opt.diff +++ python2.7-2.7.2/debian/patches/link-opt.diff @@ -0,0 +1,24 @@ +# DP: Call the linker with -O1 -Bsymbolic-functions + +--- a/configure.in ++++ b/configure.in +@@ -1866,8 +1866,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";; +@@ -1969,7 +1969,7 @@ + LINKFORSHARED="-Wl,-E -Wl,+s";; + # LINKFORSHARED="-Wl,-E -Wl,+s -Wl,+b\$(BINLIBDEST)/lib-dynload";; + BSD/OS/4*) LINKFORSHARED="-Xlinker -export-dynamic";; +- Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic";; ++ Linux*|GNU*) LINKFORSHARED="-Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions";; + # -u libsys_s pulls in all symbols in libsys + Darwin/*) + # -u _PyMac_Error is needed to pull in the mac toolbox glue, --- python2.7-2.7.2.orig/debian/patches/disable-sem-check.diff +++ python2.7-2.7.2/debian/patches/disable-sem-check.diff @@ -0,0 +1,28 @@ +# DP: Assume working semaphores on Linux, don't rely on running kernel for the check. + +--- a/configure.in ++++ b/configure.in +@@ -3645,6 +3645,11 @@ + [ac_cv_posix_semaphores_enabled=no], + [ac_cv_posix_semaphores_enabled=yes]) + ) ++case $ac_sys_system in ++ Linux*) ++ # assume enabled, see https://launchpad.net/bugs/630511 ++ ac_cv_posix_semaphores_enabled=yes ++esac + AC_MSG_RESULT($ac_cv_posix_semaphores_enabled) + if test $ac_cv_posix_semaphores_enabled = no + then +@@ -3681,6 +3686,11 @@ + [ac_cv_broken_sem_getvalue=yes], + [ac_cv_broken_sem_getvalue=yes]) + ) ++case $ac_sys_system in ++ Linux*) ++ # assume enabled, see https://launchpad.net/bugs/630511 ++ ac_cv_broken_sem_getvalue=no ++esac + AC_MSG_RESULT($ac_cv_broken_sem_getvalue) + if test $ac_cv_broken_sem_getvalue = yes + then --- python2.7-2.7.2.orig/debian/patches/no-large-file-support.diff +++ python2.7-2.7.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 +@@ -1434,6 +1434,9 @@ + use_lfs=no + fi + ++# Don't use largefile support anyway. ++use_lfs=no ++ + if test "$use_lfs" = "yes"; then + # Two defines needed to enable largefile support on various platforms + # These may affect some typedefs --- python2.7-2.7.2.orig/debian/patches/pydebug-path.dpatch +++ python2.7-2.7.2/debian/patches/pydebug-path.dpatch @@ -0,0 +1,100 @@ +#! /bin/sh -e + +# DP: When built with --with-pydebug, add a debug directory +# DP: /lib-dynload/debug to sys.path just before +# DP: /lib-dynload und install the extension modules +# DP: of the debug build in this directory. + +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 + +--- Modules/getpath.c.orig 2005-01-18 00:56:31.571961744 +0100 ++++ Modules/getpath.c 2005-01-18 01:02:23.811413208 +0100 +@@ -112,9 +112,14 @@ + #endif + + #ifndef PYTHONPATH ++#ifdef Py_DEBUG ++#define PYTHONPATH PREFIX "/lib/python" VERSION ":" \ ++ EXEC_PREFIX "/lib/python" VERSION "/lib-dynload/debug" ++#else + #define PYTHONPATH PREFIX "/lib/python" VERSION ":" \ + EXEC_PREFIX "/lib/python" VERSION "/lib-dynload" + #endif ++#endif + + #ifndef LANDMARK + #define LANDMARK "os.py" +@@ -323,6 +328,9 @@ + strncpy(exec_prefix, home, MAXPATHLEN); + joinpath(exec_prefix, lib_python); + joinpath(exec_prefix, "lib-dynload"); ++#ifdef Py_DEBUG ++ joinpath(exec_prefix, "debug"); ++#endif + return 1; + } + +@@ -340,6 +348,9 @@ + n = strlen(exec_prefix); + joinpath(exec_prefix, lib_python); + joinpath(exec_prefix, "lib-dynload"); ++#ifdef Py_DEBUG ++ joinpath(exec_prefix, "debug"); ++#endif + if (isdir(exec_prefix)) + return 1; + exec_prefix[n] = '\0'; +@@ -350,6 +361,9 @@ + strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN); + joinpath(exec_prefix, lib_python); + joinpath(exec_prefix, "lib-dynload"); ++#ifdef Py_DEBUG ++ joinpath(exec_prefix, "debug"); ++#endif + if (isdir(exec_prefix)) + return 1; + +@@ -654,6 +654,9 @@ + reduce(exec_prefix); + reduce(exec_prefix); + reduce(exec_prefix); ++#ifdef Py_DEBUG ++ reduce(exec_prefix); ++#endif + if (!exec_prefix[0]) + strcpy(exec_prefix, separator); + } +--- Lib/site.py~ 2004-12-04 00:39:05.000000000 +0100 ++++ Lib/site.py 2005-01-18 01:33:36.589707632 +0100 +@@ -188,6 +188,12 @@ + "python" + sys.version[:3], + "site-packages"), + os.path.join(prefix, "lib", "site-python")] ++ try: ++ # sys.getobjects only available in --with-pydebug build ++ sys.getobjects ++ sitedirs.insert(0, os.path.join(sitedirs[0], 'debug')) ++ except AttributeError: ++ pass + else: + sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")] + if sys.platform == 'darwin': --- python2.7-2.7.2.orig/debian/patches/test-sundry.diff +++ python2.7-2.7.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 +@@ -62,7 +62,11 @@ + import os2emxpath + import pdb + import posixfile +- import pstats ++ try: ++ import pstats # separated out into the python-profiler package ++ except ImportError: ++ if test_support.verbose: ++ print "skipping profile and pstats" + import py_compile + import rexec + import sched --- python2.7-2.7.2.orig/debian/patches/linecache.diff +++ python2.7-2.7.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 +@@ -108,6 +108,11 @@ + if os.path.isabs(filename): + return [] + ++ # Take care to handle packages ++ if basename == '__init__.py': ++ # filename referes to a package ++ basename = filename ++ + for dirname in sys.path: + # When using imputil, sys.path may contain things other than + # strings; ignore them when it happens. --- python2.7-2.7.2.orig/debian/patches/tkinter-import.diff +++ python2.7-2.7.2/debian/patches/tkinter-import.diff @@ -0,0 +1,16 @@ +# DP: suggest installation of python-tk package on failing _tkinter import + +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -36,7 +36,10 @@ + if sys.platform == "win32": + # Attempt to configure Tcl/Tk without requiring PATH + import FixTk +-import _tkinter # If this fails your Python may not be configured for Tk ++try: ++ import _tkinter ++except ImportError, msg: ++ raise ImportError, str(msg) + ', please install the python-tk package' + tkinter = _tkinter # b/w compat for export + TclError = _tkinter.TclError + from types import * --- python2.7-2.7.2.orig/debian/patches/debug-build.diff +++ python2.7-2.7.2/debian/patches/debug-build.diff @@ -0,0 +1,228 @@ +# DP: Change the interpreter to build and install python extensions +# DP: built with the python-dbg interpreter with a different name into +# DP: the same path (by appending `_d' to the extension name). + +--- a/Lib/distutils/command/build.py ++++ b/Lib/distutils/command/build.py +@@ -91,7 +91,8 @@ + # 'lib.' under the base build directory. We only use one of + # them for a given distribution, though -- + if self.build_purelib is None: +- self.build_purelib = os.path.join(self.build_base, 'lib') ++ self.build_purelib = os.path.join(self.build_base, ++ 'lib' + plat_specifier) + if self.build_platlib is None: + self.build_platlib = os.path.join(self.build_base, + 'lib' + plat_specifier) +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -85,7 +85,7 @@ + # Include is located in the srcdir + inc_dir = os.path.join(srcdir, "Include") + return inc_dir +- return os.path.join(prefix, "include", "python" + get_python_version()) ++ return os.path.join(prefix, "include", "python" + get_python_version())+(sys.pydebug and "_d" or "") + elif os.name == "nt": + return os.path.join(prefix, "include") + elif os.name == "os2": +@@ -216,7 +216,7 @@ + if python_build: + return os.path.join(os.path.dirname(sys.executable), "Makefile") + lib_dir = get_python_lib(plat_specific=1, standard_lib=1) +- return os.path.join(lib_dir, "config", "Makefile") ++ return os.path.join(lib_dir, "config"+(sys.pydebug and "_d" or ""), "Makefile") + + + def parse_config_h(fp, g=None): +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -299,7 +299,7 @@ + def _get_makefile_filename(): + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile") ++ return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") + + + def _init_posix(vars): +@@ -384,7 +384,7 @@ + else: + inc_dir = _PROJECT_BASE + else: +- inc_dir = get_path('platinclude').replace("/usr/local","/usr",1) ++ inc_dir = get_path('platinclude').replace("/usr/local","/usr",1)+(sys.pydebug and "_d" or "") + return os.path.join(inc_dir, 'pyconfig.h') + + def get_scheme_names(): +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -108,8 +108,8 @@ + # Detailed destination directories + BINLIBDEST= $(LIBDIR)/python$(VERSION) + LIBDEST= $(SCRIPTDIR)/python$(VERSION) +-INCLUDEPY= $(INCLUDEDIR)/python$(VERSION) +-CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION) ++INCLUDEPY= $(INCLUDEDIR)/python$(VERSION)$(DEBUG_EXT) ++CONFINCLUDEPY= $(CONFINCLUDEDIR)/python$(VERSION)$(DEBUG_EXT) + LIBP= $(LIBDIR)/python$(VERSION) + + # Symbols used for using shared libraries +@@ -123,6 +123,8 @@ + EXE= @EXEEXT@ + BUILDEXE= @BUILDEXEEXT@ + ++DEBUG_EXT= @DEBUG_EXT@ ++ + # Short name and location for Mac OS X Python framework + UNIVERSALSDK=@UNIVERSALSDK@ + PYTHONFRAMEWORK= @PYTHONFRAMEWORK@ +@@ -429,7 +431,7 @@ + $(AR) $(ARFLAGS) $@ $(MODOBJS) + $(RANLIB) $@ + +-libpython$(VERSION).so: $(LIBRARY_OBJS) ++libpython$(VERSION)$(DEBUG_EXT).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ + $(BLDSHARED) $(PY_LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ +@@ -990,8 +992,8 @@ + $(INSTALL_DATA) pyconfig.h $(DESTDIR)$(CONFINCLUDEPY)/pyconfig.h + + # Install the library and miscellaneous stuff needed for extending/embedding +-# This goes into $(exec_prefix) +-LIBPL= $(LIBP)/config ++# This goes into $(exec_prefix)$(DEBUG_EXT) ++LIBPL= $(LIBP)/config$(DEBUG_EXT) + + # pkgconfig directory + LIBPC= $(LIBDIR)/pkgconfig +--- a/Misc/python-config.in ++++ b/Misc/python-config.in +@@ -45,7 +45,7 @@ + + elif opt in ('--libs', '--ldflags'): + libs = getvar('LIBS').split() + getvar('SYSLIBS').split() +- libs.append('-lpython'+pyver) ++ libs.append('-lpython' + pyver + (sys.pydebug and "_d" or "")) + # add the prefix/lib/pythonX.Y/config dir, but only if there is no + # shared library in prefix/lib/. + if opt == '--ldflags': +--- a/Python/dynload_shlib.c ++++ b/Python/dynload_shlib.c +@@ -46,6 +46,10 @@ + {"module.exe", "rb", C_EXTENSION}, + {"MODULE.EXE", "rb", C_EXTENSION}, + #else ++#ifdef Py_DEBUG ++ {"_d.so", "rb", C_EXTENSION}, ++ {"module_d.so", "rb", C_EXTENSION}, ++#endif + {".so", "rb", C_EXTENSION}, + {"module.so", "rb", C_EXTENSION}, + #endif +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -1504,6 +1504,12 @@ + PyString_FromString("legacy")); + #endif + ++#ifdef Py_DEBUG ++ PyDict_SetItemString(sysdict, "pydebug", Py_True); ++#else ++ PyDict_SetItemString(sysdict, "pydebug", Py_False); ++#endif ++ + #undef SET_SYS_FROM_STRING + if (PyErr_Occurred()) + return NULL; +--- a/configure.in ++++ b/configure.in +@@ -634,7 +634,7 @@ + AC_MSG_CHECKING(LIBRARY) + if test -z "$LIBRARY" + then +- LIBRARY='libpython$(VERSION).a' ++ LIBRARY='libpython$(VERSION)$(DEBUG_EXT).a' + fi + AC_MSG_RESULT($LIBRARY) + +@@ -779,8 +779,8 @@ + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; + Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*) +- LDLIBRARY='libpython$(VERSION).so' +- BLDLIBRARY='-L. -lpython$(VERSION)' ++ LDLIBRARY='libpython$(VERSION)$(DEBUG_EXT).so' ++ BLDLIBRARY='-L. -lpython$(VERSION)$(DEBUG_EXT)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + case $ac_sys_system in + FreeBSD*) +@@ -904,6 +904,12 @@ + fi], + [AC_MSG_RESULT(no)]) + ++if test "$Py_DEBUG" = 'true' ++then ++ DEBUG_EXT=_d ++fi ++AC_SUBST(DEBUG_EXT) ++ + # XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be + # merged with this chunk of code? + +@@ -1759,7 +1765,7 @@ + esac + ;; + CYGWIN*) SO=.dll;; +- *) SO=.so;; ++ *) SO=$DEBUG_EXT.so;; + esac + else + # this might also be a termcap variable, see #610332 +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -287,8 +287,8 @@ + finally: + os.chdir(old_wd) + self.assertTrue(os.path.exists(so_file)) +- self.assertEqual(os.path.splitext(so_file)[-1], +- sysconfig.get_config_var('SO')) ++ so_ext = sysconfig.get_config_var('SO') ++ self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext) + so_dir = os.path.dirname(so_file) + self.assertEqual(so_dir, other_tmp_dir) + cmd.compiler = None +@@ -296,8 +296,7 @@ + cmd.run() + so_file = cmd.get_outputs()[0] + self.assertTrue(os.path.exists(so_file)) +- self.assertEqual(os.path.splitext(so_file)[-1], +- sysconfig.get_config_var('SO')) ++ self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext) + so_dir = os.path.dirname(so_file) + self.assertEqual(so_dir, cmd.build_lib) + +--- a/Lib/distutils/tests/test_build.py ++++ b/Lib/distutils/tests/test_build.py +@@ -20,10 +20,6 @@ + # if not specified, plat_name gets the current platform + self.assertEqual(cmd.plat_name, get_platform()) + +- # build_purelib is build + lib +- wanted = os.path.join(cmd.build_base, 'lib') +- self.assertEqual(cmd.build_purelib, wanted) +- + # build_platlib is 'build/lib.platform-x.x[-pydebug]' + # examples: + # build/lib.macosx-10.3-i386-2.7 +@@ -34,6 +30,10 @@ + wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) + self.assertEqual(cmd.build_platlib, wanted) + ++ # build_purelib is build + lib ++ wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) ++ self.assertEqual(cmd.build_purelib, wanted) ++ + # by default, build_lib = build_purelib + self.assertEqual(cmd.build_lib, cmd.build_purelib) + --- python2.7-2.7.2.orig/debian/patches/distutils-sysconfig.diff +++ python2.7-2.7.2/debian/patches/distutils-sysconfig.diff @@ -0,0 +1,33 @@ +# DP: Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, +# DP: CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -153,8 +153,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, opt, extra_cflags, basecflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ + get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', ++ 'OPT', 'EXTRA_CFLAGS', 'BASECFLAGS', + 'CCSHARED', 'LDSHARED', 'SO', 'AR', + 'ARFLAGS') + +@@ -200,8 +201,13 @@ + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ if 'BASECFLAGS' in os.environ: ++ basecflags = os.environ['BASECFLAGS'] ++ if 'OPT' in os.environ: ++ opt = os.environ['OPT'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, extra_cflags) if x) + if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] --- python2.7-2.7.2.orig/debian/patches/distutils-install-layout.diff +++ python2.7-2.7.2/debian/patches/distutils-install-layout.diff @@ -0,0 +1,350 @@ +# DP: distutils: Add an option --install-layout=deb, which +# DP: - installs into $prefix/dist-packages instead of $prefix/site-packages. +# DP: - doesn't encode the python version into the egg name. + +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -240,6 +240,8 @@ + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Platform | Standard installation location | Default value | Notes | + +=================+=====================================================+==================================================+=======+ ++| Debian/Ubuntu | :file:`{prefix}/lib/python{X.Y}/dist-packages` | :file:`/usr/local/lib/python{X.Y}/dist-packages` | \(0) | +++-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Unix (pure) | :file:`{prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | + +-----------------+-----------------------------------------------------+--------------------------------------------------+-------+ + | Unix (non-pure) | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1) | +@@ -249,6 +251,14 @@ + + Notes: + ++(0) ++ Starting with Python-2.6 Debian/Ubuntu uses for the Python which comes within ++ the Linux distribution a non-default name for the installation directory. This ++ is to avoid overwriting of the python modules which come with the distribution, ++ which unfortunately is the upstream behaviour of the installation tools. The ++ non-default name in :file:`/usr/local` is used not to overwrite a local python ++ installation (defaulting to :file:`/usr/local`). ++ + (1) + Most Linux distributions include Python as a standard part of the system, so + :file:`{prefix}` and :file:`{exec-prefix}` are usually both :file:`/usr` on +@@ -433,6 +443,15 @@ + + /usr/bin/python setup.py install --prefix=/usr/local + ++Starting with Python-2.6 Debian/Ubuntu does use ++:file:`/usr/lib/python{X.Y}/dist-packages` and ++:file:`/usr/local/lib/python{X.Y}/dist-packages` for the installation ++of python modules included in the Linux distribution. To overwrite ++the name of the site directory, explicitely use the :option:`--prefix` ++option, however make sure that the installation path is included in ++``sys.path``. For packaging of python modules for Debian/Ubuntu, use ++the new ``setup.py install`` option :option:`--install-layout=deb`. ++ + Another possibility is a network filesystem where the name used to write to a + remote directory is different from the name used to read it: for example, the + Python interpreter accessed as :file:`/usr/local/bin/python` might search for +@@ -684,6 +703,17 @@ + import them, this directory must be added to ``sys.path``. There are several + different ways to add the directory. + ++On Debian/Ubuntu, starting with Python-2.6 the convention for system ++installed packages is to put then in the ++:file:`/usr/lib/python{X.Y}/dist-packages/` directory, and for locally ++installed packages is to put them in the ++:file:`/usr/lib/python{X.Y}/dist-packages/` directory. To share the ++locally installed packages for the system provided Python with the ++locally installed packages of a local python installation, make ++:file:`/usr/lib/python{X.Y}/dist-packages/` a symbolic link to the ++:file:`{...}/site-packages/` directory of your local python ++installation. ++ + The most convenient way is to add a path configuration file to a directory + that's already on Python's path, usually to the :file:`.../site-packages/` + directory. Path configuration files have an extension of :file:`.pth`, and each +--- a/Lib/distutils/command/install.py ++++ b/Lib/distutils/command/install.py +@@ -47,6 +47,20 @@ + 'scripts': '$base/bin', + 'data' : '$base', + }, ++ 'unix_local': { ++ 'purelib': '$base/local/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/local/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/local/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/local/bin', ++ 'data' : '$base/local', ++ }, ++ 'deb_system': { ++ 'purelib': '$base/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/bin', ++ 'data' : '$base', ++ }, + 'unix_home': { + 'purelib': '$base/lib/python', + 'platlib': '$base/lib/python', +@@ -154,6 +168,9 @@ + + ('record=', None, + "filename in which to record list of installed files"), ++ ++ ('install-layout=', None, ++ "installation layout to choose (known values: deb, unix)"), + ] + + boolean_options = ['compile', 'force', 'skip-build', 'user'] +@@ -168,6 +185,7 @@ + self.exec_prefix = None + self.home = None + self.user = 0 ++ self.prefix_option = None + + # These select only the installation base; it's up to the user to + # specify the installation scheme (currently, that means supplying +@@ -189,6 +207,9 @@ + self.install_userbase = USER_BASE + self.install_usersite = USER_SITE + ++ # enable custom installation, known values: deb ++ self.install_layout = None ++ + self.compile = None + self.optimize = None + +@@ -421,6 +442,7 @@ + self.install_base = self.install_platbase = self.home + self.select_scheme("unix_home") + else: ++ self.prefix_option = self.prefix + if self.prefix is None: + if self.exec_prefix is not None: + raise DistutilsOptionError, \ +@@ -435,7 +457,23 @@ + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix +- self.select_scheme("unix_prefix") ++ if self.install_layout: ++ if self.install_layout.lower() in ['deb']: ++ self.select_scheme("deb_system") ++ elif self.install_layout.lower() in ['posix', 'unix']: ++ self.select_scheme("unix_prefix") ++ else: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif (self.prefix_option and os.path.normpath(self.prefix) != '/usr/local') \ ++ or 'PYTHONUSERBASE' in os.environ \ ++ or 'real_prefix' in sys.__dict__: ++ self.select_scheme("unix_prefix") ++ else: ++ if os.path.normpath(self.prefix) == '/usr/local': ++ self.select_scheme("deb_system") ++ else: ++ self.select_scheme("unix_local") + + # finalize_unix () + +--- a/Lib/distutils/command/install_egg_info.py ++++ b/Lib/distutils/command/install_egg_info.py +@@ -14,18 +14,37 @@ + description = "Install package's PKG-INFO metadata as an .egg-info file" + user_options = [ + ('install-dir=', 'd', "directory to install to"), ++ ('install-layout', None, "custom installation layout"), + ] + + def initialize_options(self): + self.install_dir = None ++ self.install_layout = None ++ self.prefix_option = None + + def finalize_options(self): + self.set_undefined_options('install_lib',('install_dir','install_dir')) +- basename = "%s-%s-py%s.egg-info" % ( +- to_filename(safe_name(self.distribution.get_name())), +- to_filename(safe_version(self.distribution.get_version())), +- sys.version[:3] +- ) ++ self.set_undefined_options('install',('install_layout','install_layout')) ++ self.set_undefined_options('install',('prefix_option','prefix_option')) ++ if self.install_layout: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) ++ if not self.install_layout.lower() in ['deb']: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif self.prefix_option or 'real_prefix' in sys.__dict__: ++ basename = "%s-%s-py%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())), ++ sys.version[:3] ++ ) ++ else: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -110,6 +110,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 + +@@ -118,6 +119,8 @@ + "lib", "python" + get_python_version()) + if standard_lib: + return libpython ++ elif is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__: ++ return os.path.join(libpython, "dist-packages") + else: + return os.path.join(libpython, "site-packages") + +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -285,6 +285,13 @@ + + if ENABLE_USER_SITE and os.path.isdir(user_site): + addsitedir(user_site, known_paths) ++ if ENABLE_USER_SITE: ++ for dist_libdir in ("local/lib", "lib"): ++ user_site = os.path.join(USER_BASE, dist_libdir, ++ "python" + sys.version[:3], ++ "dist-packages") ++ if os.path.isdir(user_site): ++ addsitedir(user_site, known_paths) + return known_paths + + def getsitepackages(): +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -16,6 +16,26 @@ + 'scripts': '{base}/bin', + 'data': '{base}', + }, ++ 'posix_local': { ++ 'stdlib': '{base}/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/lib/python{py_version_short}', ++ 'purelib': '{base}/local/lib/python{py_version_short}/dist-packages', ++ 'platlib': '{platbase}/local/lib/python{py_version_short}/dist-packages', ++ 'include': '{base}/local/include/python{py_version_short}', ++ 'platinclude': '{platbase}/local/include/python{py_version_short}', ++ 'scripts': '{base}/local/bin', ++ 'data': '{base}/local', ++ }, ++ 'deb_system': { ++ 'stdlib': '{base}/lib/python{py_version_short}', ++ 'platstdlib': '{platbase}/lib/python{py_version_short}', ++ 'purelib': '{base}/lib/python{py_version_short}/dist-packages', ++ 'platlib': '{platbase}/lib/python{py_version_short}/dist-packages', ++ 'include': '{base}/include/python{py_version_short}', ++ 'platinclude': '{platbase}/include/python{py_version_short}', ++ 'scripts': '{base}/bin', ++ 'data': '{base}', ++ }, + 'posix_home': { + 'stdlib': '{base}/lib/python', + 'platstdlib': '{base}/lib/python', +@@ -125,7 +145,7 @@ + _PYTHON_BUILD = is_python_build() + + if _PYTHON_BUILD: +- for scheme in ('posix_prefix', 'posix_home'): ++ for scheme in ('posix_prefix', 'posix_local', 'deb_system', 'posix_home'): + _INSTALL_SCHEMES[scheme]['include'] = '{projectbase}/Include' + _INSTALL_SCHEMES[scheme]['platinclude'] = '{srcdir}' + +@@ -159,8 +179,11 @@ + + def _get_default_scheme(): + if os.name == 'posix': +- # the default scheme for posix is posix_prefix +- return 'posix_prefix' ++ # the default scheme for posix on Debian/Ubuntu is posix_local ++ # FIXME: return dist-packages/posix_prefix only for ++ # is_default_prefix and 'PYTHONUSERBASE' not in os.environ and 'real_prefix' not in sys.__dict__ ++ # is_default_prefix = not prefix or os.path.normpath(prefix) in ('/usr', '/usr/local') ++ return 'posix_local' + return os.name + + def _getuserbase(): +@@ -276,7 +299,7 @@ + def _get_makefile_filename(): + if _PYTHON_BUILD: + return os.path.join(_PROJECT_BASE, "Makefile") +- return os.path.join(get_path('platstdlib'), "config", "Makefile") ++ return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile") + + + def _init_posix(vars): +@@ -361,7 +384,7 @@ + else: + inc_dir = _PROJECT_BASE + else: +- inc_dir = get_path('platinclude') ++ inc_dir = get_path('platinclude').replace("/usr/local","/usr",1) + return os.path.join(inc_dir, 'pyconfig.h') + + def get_scheme_names(): +--- a/Lib/test/test_site.py ++++ b/Lib/test/test_site.py +@@ -230,10 +230,13 @@ + self.assertEqual(dirs[0], wanted) + elif os.sep == '/': + self.assertEqual(len(dirs), 2) +- wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3], +- 'site-packages') ++ wanted = os.path.join('xoxo', 'local', 'lib', ++ 'python' + sys.version[:3], ++ 'dist-packages') + self.assertEqual(dirs[0], wanted) +- wanted = os.path.join('xoxo', 'lib', 'site-python') ++ wanted = os.path.join('xoxo', 'lib', ++ 'python' + sys.version[:3], ++ 'dist-packages') + self.assertEqual(dirs[1], wanted) + else: + self.assertEqual(len(dirs), 2) +--- a/Lib/test/test_sysconfig.py ++++ b/Lib/test/test_sysconfig.py +@@ -230,8 +230,8 @@ + self.assertTrue(os.path.isfile(config_h), config_h) + + def test_get_scheme_names(self): +- wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', +- 'posix_home', 'posix_prefix', 'posix_user') ++ wanted = ('deb_system', 'nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user', ++ 'posix_home', 'posix_local', 'posix_prefix', 'posix_user') + self.assertEqual(get_scheme_names(), wanted) + + def test_symlink(self): +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -196,7 +196,7 @@ + + found = [os.path.basename(line) for line in content.splitlines()] + expected = ['hello', +- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ 'UNKNOWN-0.0.0.egg-info'] + self.assertEqual(found, expected) + + def test_record_extensions(self): +@@ -227,7 +227,7 @@ + + found = [os.path.basename(line) for line in content.splitlines()] + expected = [_make_ext_name('xx'), +- 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ 'UNKNOWN-0.0.0.egg-info'] + self.assertEqual(found, expected) + + def test_debug_mode(self): --- python2.7-2.7.2.orig/debian/patches/ncursesw-incdir.diff +++ python2.7-2.7.2/debian/patches/ncursesw-incdir.diff @@ -0,0 +1,66 @@ +# DP: use the correct include directory when linking with ncursesw. + +--- a/setup.py ++++ b/setup.py +@@ -1251,13 +1251,17 @@ + # Curses support, requiring the System V version of curses, often + # provided by the ncurses library. + panel_library = 'panel' ++ curses_incs = None + if curses_library.startswith('ncurses'): + if curses_library == 'ncursesw': + # Bug 1464056: If _curses.so links with ncursesw, + # _curses_panel.so must link with panelw. + panel_library = 'panelw' + curses_libs = [curses_library] ++ curses_incs = find_file('curses.h', inc_dirs, ++ [os.path.join(d, 'ncursesw') for d in inc_dirs]) + exts.append( Extension('_curses', ['_cursesmodule.c'], ++ include_dirs = curses_incs, + libraries = curses_libs) ) + elif curses_library == 'curses' and platform != 'darwin': + # OSX has an old Berkeley curses, not good enough for +@@ -1278,6 +1282,7 @@ + if (module_enabled(exts, '_curses') and + self.compiler.find_library_file(lib_dirs, panel_library)): + exts.append( Extension('_curses_panel', ['_curses_panel.c'], ++ include_dirs = curses_incs, + libraries = [panel_library] + curses_libs) ) + else: + missing.append('_curses_panel') +--- a/configure.in ++++ b/configure.in +@@ -1374,6 +1374,8 @@ + + # checks for header files + AC_HEADER_STDC ++ac_save_cppflags="$CPPFLAGS" ++CPPFLAGS="$CPPFLAGS -I/usr/include/ncursesw" + AC_CHECK_HEADERS(asm/types.h conio.h curses.h direct.h dlfcn.h errno.h \ + fcntl.h grp.h \ + ieeefp.h io.h langinfo.h libintl.h ncurses.h poll.h process.h pthread.h \ +@@ -1395,6 +1397,7 @@ + #include + #endif + ]) ++CPPFLAGS=$ac_save_cppflags + + # On Linux, netlink.h requires asm/types.h + AC_CHECK_HEADERS(linux/netlink.h,,,[ +@@ -4123,6 +4126,8 @@ + [Define if you have struct stat.st_mtimensec]) + fi + ++ac_save_cppflags="$CPPFLAGS" ++CPPFLAGS="$CPPFLAGS -I/usr/include/ncursesw" + # On HP/UX 11.0, mvwdelch is a block with a return statement + AC_MSG_CHECKING(whether mvwdelch is an expression) + AC_CACHE_VAL(ac_cv_mvwdelch_is_expression, +@@ -4177,6 +4182,7 @@ + AC_MSG_RESULT(yes)], + [AC_MSG_RESULT(no)] + ) ++CPPFLAGS=$ac_save_cppflags + + AC_MSG_CHECKING(for /dev/ptmx) + --- python2.7-2.7.2.orig/debian/patches/libre.diff +++ python2.7-2.7.2/debian/patches/libre.diff @@ -0,0 +1,9 @@ +--- Doc/lib/libre.tex~ 2003-07-25 09:29:22.000000000 +0200 ++++ Doc/lib/libre.tex 2003-07-25 09:30:58.000000000 +0200 +@@ -919,5 +919,5 @@ + Starting with Python 2.3, simple uses of the \regexp{*?} pattern are + special-cased to avoid recursion. Thus, the above regular expression + can avoid recursion by being recast as +-\regexp{Begin [a-zA-Z0-9_ ]*?end}. As a further benefit, such regular ++`Begin [a-zA-Z0-9_ ]*?end'. As a further benefit, such regular + expressions will run faster than their recursive equivalents. --- python2.7-2.7.2.orig/debian/patches/lto-link-flags.diff +++ python2.7-2.7.2/debian/patches/lto-link-flags.diff @@ -0,0 +1,22 @@ +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -114,8 +114,8 @@ + + # Symbols used for using shared libraries + SO= @SO@ +-LDSHARED= @LDSHARED@ $(LDFLAGS) +-BLDSHARED= @BLDSHARED@ $(LDFLAGS) ++LDSHARED= @LDSHARED@ $(PY_LDFLAGS) ++BLDSHARED= @BLDSHARED@ $(PY_LDFLAGS) $(PY_CFLAGS) + LDCXXSHARED= @LDCXXSHARED@ + DESTSHARED= $(BINLIBDEST)/lib-dynload + +@@ -404,7 +404,7 @@ + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +- $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ ++ $(LINKCC) $(PY_LDFLAGS) $(PY_CFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ + -Wl,--whole-archive $(BLDLIBRARY) -Wl,--no-whole-archive $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + --- python2.7-2.7.2.orig/debian/patches/multiprocessing-typos.diff +++ python2.7-2.7.2/debian/patches/multiprocessing-typos.diff @@ -0,0 +1,24 @@ +# DP: Fix typos in the multiprocessing module. + +--- a/Modules/_multiprocessing/multiprocessing.c ++++ b/Modules/_multiprocessing/multiprocessing.c +@@ -63,7 +63,7 @@ + break; + default: + PyErr_Format(PyExc_RuntimeError, +- "unkown error number %d", num); ++ "unknown error number %d", num); + } + return NULL; + } +--- a/Lib/multiprocessing/synchronize.py ++++ b/Lib/multiprocessing/synchronize.py +@@ -226,7 +226,7 @@ + num_waiters = (self._sleeping_count._semlock._get_value() - + self._woken_count._semlock._get_value()) + except Exception: +- num_waiters = 'unkown' ++ num_waiters = 'unknown' + return '' % (self._lock, num_waiters) + + def wait(self, timeout=None): --- python2.7-2.7.2.orig/debian/patches/plat-linux2_hppa.diff +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/patches/hg-updates.diff +++ python2.7-2.7.2/debian/patches/hg-updates.diff @@ -0,0 +1,48769 @@ +# DP: hg updates of the 2.7 release branch (until 2012-02-16). + +# hg diff -r v2.7.2 | filterdiff --exclude=Lib/pstats.py --exclude=Lib/profile.py --exclude=.*ignore --exclude=.hg* --remove-timestamps + +diff -r 8527427914a2 Demo/threads/sync.py +--- a/Demo/threads/sync.py ++++ b/Demo/threads/sync.py +@@ -265,7 +265,7 @@ + # intervening. If there are other threads waiting to write, they + # are allowed to proceed only if the current thread calls + # .read_out; threads waiting to read are only allowed to proceed +-# if there are are no threads waiting to write. (This is a ++# if there are no threads waiting to write. (This is a + # weakness of the interface!) + + import thread +diff -r 8527427914a2 Demo/tix/tixwidgets.py +--- a/Demo/tix/tixwidgets.py ++++ b/Demo/tix/tixwidgets.py +@@ -659,7 +659,7 @@ + I have implemented a new image type called "compound". It allows you + to glue together a bunch of bitmaps, images and text strings together + to form a bigger image. Then you can use this image with widgets that +-support the -image option. For example, you can display a text string string ++support the -image option. For example, you can display a text string + together with a bitmap, at the same time, inside a TK button widget. + """) + list.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) +diff -r 8527427914a2 Demo/turtle/about_turtle.txt +--- a/Demo/turtle/about_turtle.txt ++++ b/Demo/turtle/about_turtle.txt +@@ -7,10 +7,10 @@ + kids. It was part of the original Logo programming language developed + by Wally Feurzig and Seymour Papert in 1966. + +-Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it ++Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it + the command turtle.forward(15), and it moves (on-screen!) 15 pixels in + the direction it is facing, drawing a line as it moves. Give it the +-command turtle.left(25), and it rotates in-place 25 degrees clockwise. ++command turtle.right(25), and it rotates in-place 25 degrees clockwise. + + By combining together these and similar commands, intricate shapes and + pictures can easily be drawn. +diff -r 8527427914a2 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 +@@ -77,6 +78,7 @@ + * Travis B. Hartwell + * Tim Hatch + * Janko Hauser ++ * Ben Hayden + * Thomas Heller + * Bernhard Herzog + * Magnus L. Hetland +@@ -103,6 +105,7 @@ + * Robert Kern + * Jim Kerr + * Jan Kim ++ * Kamil Kisiel + * Greg Kochanski + * Guido Kollerie + * Peter A. Koren +@@ -139,7 +142,8 @@ + * Ross Moore + * Sjoerd Mullender + * Dale Nagata +- * Michal Nowikowski ++ * Michal Nowikowski ++ * Steffen Daode Nurpmeso + * Ng Pheng Siong + * Koray Oner + * Tomas Oppelstrup +@@ -180,6 +184,7 @@ + * Joakim Sernbrant + * Justin Sheehy + * Charlie Shepherd ++ * Yue Shuaijie + * Michael Simcich + * Ionel Simionescu + * Michael Sloan +@@ -197,6 +202,7 @@ + * Kalle Svensson + * Jim Tittsler + * David Turner ++ * Sandro Tosi + * Ville Vainio + * Martijn Vries + * Charles G. Waldman +@@ -214,6 +220,7 @@ + * Collin Winter + * Blake Winton + * Dan Wolfe ++ * Adam Woodbeck + * Steven Work + * Thomas Wouters + * Ka-Ping Yee +diff -r 8527427914a2 Doc/Makefile +--- a/Doc/Makefile ++++ b/Doc/Makefile +@@ -40,7 +40,7 @@ + checkout: + @if [ ! -d tools/sphinx ]; then \ + echo "Checking out Sphinx..."; \ +- svn checkout $(SVNROOT)/external/Sphinx-0.6.7/sphinx tools/sphinx; \ ++ svn checkout $(SVNROOT)/external/Sphinx-1.0.7/sphinx tools/sphinx; \ + fi + @if [ ! -d tools/docutils ]; then \ + echo "Checking out Docutils..."; \ +diff -r 8527427914a2 Doc/README.txt +--- a/Doc/README.txt ++++ b/Doc/README.txt +@@ -127,7 +127,7 @@ + as long as you don't change or remove the copyright notice: + + ---------------------------------------------------------------------- +-Copyright (c) 2000-2008 Python Software Foundation. ++Copyright (c) 2000-2012 Python Software Foundation. + All rights reserved. + + Copyright (c) 2000 BeOpen.com. +diff -r 8527427914a2 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 8527427914a2 Doc/c-api/abstract.rst +--- a/Doc/c-api/abstract.rst ++++ b/Doc/c-api/abstract.rst +@@ -13,7 +13,7 @@ + will raise a Python exception. + + It is not possible to use these functions on objects that are not properly +-initialized, such as a list object that has been created by :cfunc:`PyList_New`, ++initialized, such as a list object that has been created by :c:func:`PyList_New`, + but whose items have not been set to some non-\ ``NULL`` value yet. + + .. toctree:: +diff -r 8527427914a2 Doc/c-api/allocation.rst +--- a/Doc/c-api/allocation.rst ++++ b/Doc/c-api/allocation.rst +@@ -6,20 +6,20 @@ + ============================== + + +-.. cfunction:: PyObject* _PyObject_New(PyTypeObject *type) ++.. c:function:: PyObject* _PyObject_New(PyTypeObject *type) + + +-.. cfunction:: PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size) ++.. c:function:: PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size) + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: void _PyObject_Del(PyObject *op) ++.. c:function:: void _PyObject_Del(PyObject *op) + + +-.. cfunction:: PyObject* PyObject_Init(PyObject *op, PyTypeObject *type) ++.. c:function:: PyObject* PyObject_Init(PyObject *op, PyTypeObject *type) + + Initialize a newly-allocated object *op* with its type and initial + reference. Returns the initialized object. If *type* indicates that the +@@ -28,17 +28,17 @@ + affected. + + +-.. cfunction:: PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size) ++.. c:function:: PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size) + +- This does everything :cfunc:`PyObject_Init` does, and also initializes the ++ This does everything :c:func:`PyObject_Init` does, and also initializes the + length information for a variable-size object. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: TYPE* PyObject_New(TYPE, PyTypeObject *type) ++.. c:function:: TYPE* PyObject_New(TYPE, PyTypeObject *type) + + Allocate a new Python object using the C structure type *TYPE* and the + Python type object *type*. Fields not defined by the Python object header +@@ -47,7 +47,7 @@ + the type object. + + +-.. cfunction:: TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) ++.. c:function:: TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) + + Allocate a new Python object using the C structure type *TYPE* and the + Python type object *type*. Fields not defined by the Python object header +@@ -59,20 +59,20 @@ + improving the memory management efficiency. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: void PyObject_Del(PyObject *op) ++.. c:function:: void PyObject_Del(PyObject *op) + +- Releases memory allocated to an object using :cfunc:`PyObject_New` or +- :cfunc:`PyObject_NewVar`. This is normally called from the ++ Releases memory allocated to an object using :c:func:`PyObject_New` or ++ :c:func:`PyObject_NewVar`. This is normally called from the + :attr:`tp_dealloc` handler specified in the object's type. The fields of + the object should not be accessed after this call as the memory is no + longer a valid Python object. + + +-.. cfunction:: PyObject* Py_InitModule(char *name, PyMethodDef *methods) ++.. c:function:: PyObject* Py_InitModule(char *name, PyMethodDef *methods) + + Create a new module object based on a name and table of functions, + returning the new module object. +@@ -82,7 +82,7 @@ + *methods* argument. + + +-.. cfunction:: PyObject* Py_InitModule3(char *name, PyMethodDef *methods, char *doc) ++.. c:function:: PyObject* Py_InitModule3(char *name, PyMethodDef *methods, char *doc) + + Create a new module object based on a name and table of functions, + returning the new module object. If *doc* is non-*NULL*, it will be used +@@ -93,7 +93,7 @@ + *methods* argument. + + +-.. cfunction:: PyObject* Py_InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver) ++.. c:function:: PyObject* Py_InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver) + + Create a new module object based on a name and table of functions, + returning the new module object. If *doc* is non-*NULL*, it will be used +@@ -107,7 +107,7 @@ + .. note:: + + Most uses of this function should probably be using the +- :cfunc:`Py_InitModule3` instead; only use this if you are sure you need ++ :c:func:`Py_InitModule3` instead; only use this if you are sure you need + it. + + .. versionchanged:: 2.3 +@@ -115,7 +115,7 @@ + *methods* argument. + + +-.. cvar:: PyObject _Py_NoneStruct ++.. c:var:: PyObject _Py_NoneStruct + + Object which is visible in Python as ``None``. This should only be + accessed using the ``Py_None`` macro, which evaluates to a pointer to this +diff -r 8527427914a2 Doc/c-api/arg.rst +--- a/Doc/c-api/arg.rst ++++ b/Doc/c-api/arg.rst +@@ -9,8 +9,8 @@ + methods. Additional information and examples are available in + :ref:`extending-index`. + +-The first three of these functions described, :cfunc:`PyArg_ParseTuple`, +-:cfunc:`PyArg_ParseTupleAndKeywords`, and :cfunc:`PyArg_Parse`, all use ++The first three of these functions described, :c:func:`PyArg_ParseTuple`, ++:c:func:`PyArg_ParseTupleAndKeywords`, and :c:func:`PyArg_Parse`, all use + *format strings* which are used to tell the function about the expected + arguments. The format strings use the same syntax for each of these + functions. +@@ -24,6 +24,11 @@ + that matches the format unit; and the entry in [square] brackets is the type + of the C variable(s) whose address should be passed. + ++These formats allow to access an object as a contiguous chunk of memory. ++You don't have to provide raw storage for the returned unicode or bytes ++area. Also, you won't have to release any memory yourself, except with the ++``es``, ``es#``, ``et`` and ``et#`` formats. ++ + ``s`` (string or Unicode) [const char \*] + Convert a Python string or Unicode object to a C pointer to a character + string. You must not provide storage for the string itself; a pointer to +@@ -33,7 +38,7 @@ + raised. Unicode objects are converted to C strings using the default + encoding. If this conversion fails, a :exc:`UnicodeError` is raised. + +-``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int (or :ctype:`Py_ssize_t`, see below)] ++``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int (or :c:type:`Py_ssize_t`, see below)] + This variant on ``s`` stores into two C variables, the first one a pointer + to a character string, the second one its length. In this case the Python + string may contain embedded null bytes. Unicode objects pass back a +@@ -42,8 +47,8 @@ + a reference to the raw internal data representation. + + Starting with Python 2.5 the type of the length argument can be controlled +- by defining the macro :cmacro:`PY_SSIZE_T_CLEAN` before including +- :file:`Python.h`. If the macro is defined, length is a :ctype:`Py_ssize_t` ++ by defining the macro :c:macro:`PY_SSIZE_T_CLEAN` before including ++ :file:`Python.h`. If the macro is defined, length is a :c:type:`Py_ssize_t` + rather than an int. + + ``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer] +@@ -71,14 +76,14 @@ + Convert a Python Unicode object to a C pointer to a NUL-terminated buffer + of 16-bit Unicode (UTF-16) data. As with ``s``, there is no need to + provide storage for the Unicode data buffer; a pointer to the existing +- Unicode data is stored into the :ctype:`Py_UNICODE` pointer variable whose ++ Unicode data is stored into the :c:type:`Py_UNICODE` pointer variable whose + address you pass. + + ``u#`` (Unicode) [Py_UNICODE \*, int] + This variant on ``u`` stores into two C variables, the first one a pointer + to a Unicode data buffer, the second one its length. Non-Unicode objects + are handled by interpreting their read-buffer pointer as pointer to a +- :ctype:`Py_UNICODE` array. ++ :c:type:`Py_UNICODE` array. + + ``es`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer] + This variant on ``s`` is used for encoding Unicode and objects convertible +@@ -86,18 +91,18 @@ + embedded NUL bytes. + + This format requires two arguments. The first is only used as input, and +- must be a :ctype:`const char\*` which points to the name of an encoding as ++ must be a :c:type:`const char\*` which points to the name of an encoding as + a NUL-terminated string, or *NULL*, in which case the default encoding is + used. An exception is raised if the named encoding is not known to Python. +- The second argument must be a :ctype:`char\*\*`; the value of the pointer ++ The second argument must be a :c:type:`char\*\*`; the value of the pointer + it references will be set to a buffer with the contents of the argument + text. The text will be encoded in the encoding specified by the first + argument. + +- :cfunc:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy ++ :c:func:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy + the encoded data into this buffer and adjust *\*buffer* to reference the + newly allocated storage. The caller is responsible for calling +- :cfunc:`PyMem_Free` to free the allocated buffer after use. ++ :c:func:`PyMem_Free` to free the allocated buffer after use. + + ``et`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer] + Same as ``es`` except that 8-bit string objects are passed through without +@@ -110,10 +115,10 @@ + allows input data which contains NUL characters. + + It requires three arguments. The first is only used as input, and must be +- a :ctype:`const char\*` which points to the name of an encoding as a ++ a :c:type:`const char\*` which points to the name of an encoding as a + NUL-terminated string, or *NULL*, in which case the default encoding is + used. An exception is raised if the named encoding is not known to Python. +- The second argument must be a :ctype:`char\*\*`; the value of the pointer ++ The second argument must be a :c:type:`char\*\*`; the value of the pointer + it references will be set to a buffer with the contents of the argument + text. The text will be encoded in the encoding specified by the first + argument. The third argument must be a pointer to an integer; the +@@ -124,11 +129,11 @@ + If *\*buffer* points a *NULL* pointer, the function will allocate a buffer + of the needed size, copy the encoded data into this buffer and set + *\*buffer* to reference the newly allocated storage. The caller is +- responsible for calling :cfunc:`PyMem_Free` to free the allocated buffer ++ responsible for calling :c:func:`PyMem_Free` to free the allocated buffer + after usage. + + If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer), +- :cfunc:`PyArg_ParseTuple` will use this location as the buffer and ++ :c:func:`PyArg_ParseTuple` will use this location as the buffer and + interpret the initial value of *\*buffer_length* as the buffer size. It + will then copy the encoded data into the buffer and NUL-terminate it. If + the buffer is not large enough, a :exc:`ValueError` will be set. +@@ -143,71 +148,71 @@ + + ``b`` (integer) [unsigned char] + Convert a nonnegative Python integer to an unsigned tiny int, stored in a C +- :ctype:`unsigned char`. ++ :c:type:`unsigned char`. + + ``B`` (integer) [unsigned char] + Convert a Python integer to a tiny int without overflow checking, stored in +- a C :ctype:`unsigned char`. ++ a C :c:type:`unsigned char`. + + .. versionadded:: 2.3 + + ``h`` (integer) [short int] +- Convert a Python integer to a C :ctype:`short int`. ++ Convert a Python integer to a C :c:type:`short int`. + + ``H`` (integer) [unsigned short int] +- Convert a Python integer to a C :ctype:`unsigned short int`, without ++ Convert a Python integer to a C :c:type:`unsigned short int`, without + overflow checking. + + .. versionadded:: 2.3 + + ``i`` (integer) [int] +- Convert a Python integer to a plain C :ctype:`int`. ++ Convert a Python integer to a plain C :c:type:`int`. + + ``I`` (integer) [unsigned int] +- Convert a Python integer to a C :ctype:`unsigned int`, without overflow ++ Convert a Python integer to a C :c:type:`unsigned int`, without overflow + checking. + + .. versionadded:: 2.3 + + ``l`` (integer) [long int] +- Convert a Python integer to a C :ctype:`long int`. ++ Convert a Python integer to a C :c:type:`long int`. + + ``k`` (integer) [unsigned long] +- Convert a Python integer or long integer to a C :ctype:`unsigned long` ++ Convert a Python integer or long integer to a C :c:type:`unsigned long` + without overflow checking. + + .. versionadded:: 2.3 + + ``L`` (integer) [PY_LONG_LONG] +- Convert a Python integer to a C :ctype:`long long`. This format is only +- available on platforms that support :ctype:`long long` (or :ctype:`_int64` ++ Convert a Python integer to a C :c:type:`long long`. This format is only ++ available on platforms that support :c:type:`long long` (or :c:type:`_int64` + on Windows). + + ``K`` (integer) [unsigned PY_LONG_LONG] +- Convert a Python integer or long integer to a C :ctype:`unsigned long long` ++ Convert a Python integer or long integer to a C :c:type:`unsigned long long` + without overflow checking. This format is only available on platforms that +- support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on ++ support :c:type:`unsigned long long` (or :c:type:`unsigned _int64` on + Windows). + + .. versionadded:: 2.3 + + ``n`` (integer) [Py_ssize_t] +- Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`. ++ Convert a Python integer or long integer to a C :c:type:`Py_ssize_t`. + + .. versionadded:: 2.5 + + ``c`` (string of length 1) [char] + Convert a Python character, represented as a string of length 1, to a C +- :ctype:`char`. ++ :c:type:`char`. + + ``f`` (float) [float] +- Convert a Python floating point number to a C :ctype:`float`. ++ Convert a Python floating point number to a C :c:type:`float`. + + ``d`` (float) [double] +- Convert a Python floating point number to a C :ctype:`double`. ++ Convert a Python floating point number to a C :c:type:`double`. + + ``D`` (complex) [Py_complex] +- Convert a Python complex number to a C :ctype:`Py_complex` structure. ++ Convert a Python complex number to a C :c:type:`Py_complex` structure. + + ``O`` (object) [PyObject \*] + Store a Python object (without any conversion) in a C object pointer. The +@@ -217,20 +222,20 @@ + ``O!`` (object) [*typeobject*, PyObject \*] + Store a Python object in a C object pointer. This is similar to ``O``, but + takes two C arguments: the first is the address of a Python type object, +- the second is the address of the C variable (of type :ctype:`PyObject\*`) ++ the second is the address of the C variable (of type :c:type:`PyObject\*`) + into which the object pointer is stored. If the Python object does not + have the required type, :exc:`TypeError` is raised. + + ``O&`` (object) [*converter*, *anything*] + Convert a Python object to a C variable through a *converter* function. + This takes two arguments: the first is a function, the second is the +- address of a C variable (of arbitrary type), converted to :ctype:`void \*`. ++ address of a C variable (of arbitrary type), converted to :c:type:`void \*`. + The *converter* function in turn is called as follows:: + + status = converter(object, address); + + where *object* is the Python object to be converted and *address* is the +- :ctype:`void\*` argument that was passed to the :cfunc:`PyArg_Parse\*` ++ :c:type:`void\*` argument that was passed to the :c:func:`PyArg_Parse\*` + function. The returned *status* should be ``1`` for a successful + conversion and ``0`` if the conversion has failed. When the conversion + fails, the *converter* function should raise an exception and leave the +@@ -239,17 +244,17 @@ + ``S`` (string) [PyStringObject \*] + Like ``O`` but requires that the Python object is a string object. Raises + :exc:`TypeError` if the object is not a string object. The C variable may +- also be declared as :ctype:`PyObject\*`. ++ also be declared as :c:type:`PyObject\*`. + + ``U`` (Unicode string) [PyUnicodeObject \*] + Like ``O`` but requires that the Python object is a Unicode object. Raises + :exc:`TypeError` if the object is not a Unicode object. The C variable may +- also be declared as :ctype:`PyObject\*`. ++ also be declared as :c:type:`PyObject\*`. + + ``t#`` (read-only character buffer) [char \*, int] + Like ``s#``, but accepts any object which implements the read-only buffer +- interface. The :ctype:`char\*` variable is set to point to the first byte +- of the buffer, and the :ctype:`int` is set to the length of the buffer. ++ interface. The :c:type:`char\*` variable is set to point to the first byte ++ of the buffer, and the :c:type:`int` is set to the length of the buffer. + Only single-segment buffer objects are accepted; :exc:`TypeError` is raised + for all others. + +@@ -261,8 +266,8 @@ + + ``w#`` (read-write character buffer) [char \*, Py_ssize_t] + Like ``s#``, but accepts any object which implements the read-write buffer +- interface. The :ctype:`char \*` variable is set to point to the first byte +- of the buffer, and the :ctype:`Py_ssize_t` is set to the length of the ++ interface. The :c:type:`char \*` variable is set to point to the first byte ++ of the buffer, and the :c:type:`Py_ssize_t` is set to the length of the + buffer. Only single-segment buffer objects are accepted; :exc:`TypeError` + is raised for all others. + +@@ -297,13 +302,13 @@ + Indicates that the remaining arguments in the Python argument list are + optional. The C variables corresponding to optional arguments should be + initialized to their default value --- when an optional argument is not +- specified, :cfunc:`PyArg_ParseTuple` does not touch the contents of the ++ specified, :c:func:`PyArg_ParseTuple` does not touch the contents of the + corresponding C variable(s). + + ``:`` + The list of format units ends here; the string after the colon is used as + the function name in error messages (the "associated value" of the +- exception that :cfunc:`PyArg_ParseTuple` raises). ++ exception that :c:func:`PyArg_ParseTuple` raises). + + ``;`` + The list of format units ends here; the string after the semicolon is used +@@ -320,40 +325,40 @@ + should match what is specified for the corresponding format unit in that case. + + For the conversion to succeed, the *arg* object must match the format and the +-format must be exhausted. On success, the :cfunc:`PyArg_Parse\*` functions ++format must be exhausted. On success, the :c:func:`PyArg_Parse\*` functions + return true, otherwise they return false and raise an appropriate exception. +-When the :cfunc:`PyArg_Parse\*` functions fail due to conversion failure in ++When the :c:func:`PyArg_Parse\*` functions fail due to conversion failure in + one of the format units, the variables at the addresses corresponding to that + and the following format units are left untouched. + + +-.. cfunction:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) ++.. c:function:: int PyArg_ParseTuple(PyObject *args, const char *format, ...) + + Parse the parameters of a function that takes only positional parameters + into local variables. Returns true on success; on failure, it returns + false and raises the appropriate exception. + + +-.. cfunction:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs) ++.. c:function:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs) + +- Identical to :cfunc:`PyArg_ParseTuple`, except that it accepts a va_list ++ Identical to :c:func:`PyArg_ParseTuple`, except that it accepts a va_list + rather than a variable number of arguments. + + +-.. cfunction:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...) ++.. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...) + + Parse the parameters of a function that takes both positional and keyword + parameters into local variables. Returns true on success; on failure, it + returns false and raises the appropriate exception. + + +-.. cfunction:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs) ++.. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs) + +- Identical to :cfunc:`PyArg_ParseTupleAndKeywords`, except that it accepts a ++ Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a + va_list rather than a variable number of arguments. + + +-.. cfunction:: int PyArg_Parse(PyObject *args, const char *format, ...) ++.. c:function:: int PyArg_Parse(PyObject *args, const char *format, ...) + + Function used to deconstruct the argument lists of "old-style" functions + --- these are functions which use the :const:`METH_OLDARGS` parameter +@@ -364,7 +369,7 @@ + purpose. + + +-.. cfunction:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) ++.. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...) + + A simpler form of parameter retrieval which does not use a format string to + specify the types of the arguments. Functions which use this method to +@@ -373,7 +378,7 @@ + should be passed as *args*; it must actually be a tuple. The length of the + tuple must be at least *min* and no more than *max*; *min* and *max* may be + equal. Additional arguments must be passed to the function, each of which +- should be a pointer to a :ctype:`PyObject\*` variable; these will be filled ++ should be a pointer to a :c:type:`PyObject\*` variable; these will be filled + in with the values from *args*; they will contain borrowed references. The + variables which correspond to optional parameters not given by *args* will + not be filled in; these should be initialized by the caller. This function +@@ -396,26 +401,26 @@ + return result; + } + +- The call to :cfunc:`PyArg_UnpackTuple` in this example is entirely +- equivalent to this call to :cfunc:`PyArg_ParseTuple`:: ++ The call to :c:func:`PyArg_UnpackTuple` in this example is entirely ++ equivalent to this call to :c:func:`PyArg_ParseTuple`:: + + PyArg_ParseTuple(args, "O|O:ref", &object, &callback) + + .. versionadded:: 2.2 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *min* and *max*. This might ++ This function used an :c:type:`int` type for *min* and *max*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* Py_BuildValue(const char *format, ...) ++.. c:function:: PyObject* Py_BuildValue(const char *format, ...) + + Create a new value based on a format string similar to those accepted by +- the :cfunc:`PyArg_Parse\*` family of functions and a sequence of values. ++ the :c:func:`PyArg_Parse\*` family of functions and a sequence of values. + Returns the value or *NULL* in the case of an error; an exception will be + raised if *NULL* is returned. + +- :cfunc:`Py_BuildValue` does not always build a tuple. It builds a tuple ++ :c:func:`Py_BuildValue` does not always build a tuple. It builds a tuple + only if its format string contains two or more format units. If the format + string is empty, it returns ``None``; if it contains exactly one format + unit, it returns whatever object is described by that format unit. To +@@ -425,10 +430,10 @@ + When memory buffers are passed as parameters to supply data to build + objects, as for the ``s`` and ``s#`` formats, the required data is copied. + Buffers provided by the caller are never referenced by the objects created +- by :cfunc:`Py_BuildValue`. In other words, if your code invokes +- :cfunc:`malloc` and passes the allocated memory to :cfunc:`Py_BuildValue`, +- your code is responsible for calling :cfunc:`free` for that memory once +- :cfunc:`Py_BuildValue` returns. ++ by :c:func:`Py_BuildValue`. In other words, if your code invokes ++ :c:func:`malloc` and passes the allocated memory to :c:func:`Py_BuildValue`, ++ your code is responsible for calling :c:func:`free` for that memory once ++ :c:func:`Py_BuildValue` returns. + + In the following description, the quoted form is the format unit; the entry + in (round) parentheses is the Python object type that the format unit will +@@ -464,62 +469,62 @@ + length is ignored and ``None`` is returned. + + ``i`` (integer) [int] +- Convert a plain C :ctype:`int` to a Python integer object. ++ Convert a plain C :c:type:`int` to a Python integer object. + + ``b`` (integer) [char] +- Convert a plain C :ctype:`char` to a Python integer object. ++ Convert a plain C :c:type:`char` to a Python integer object. + + ``h`` (integer) [short int] +- Convert a plain C :ctype:`short int` to a Python integer object. ++ Convert a plain C :c:type:`short int` to a Python integer object. + + ``l`` (integer) [long int] +- Convert a C :ctype:`long int` to a Python integer object. ++ Convert a C :c:type:`long int` to a Python integer object. + + ``B`` (integer) [unsigned char] +- Convert a C :ctype:`unsigned char` to a Python integer object. ++ Convert a C :c:type:`unsigned char` to a Python integer object. + + ``H`` (integer) [unsigned short int] +- Convert a C :ctype:`unsigned short int` to a Python integer object. ++ Convert a C :c:type:`unsigned short int` to a Python integer object. + + ``I`` (integer/long) [unsigned int] +- Convert a C :ctype:`unsigned int` to a Python integer object or a Python ++ Convert a C :c:type:`unsigned int` to a Python integer object or a Python + long integer object, if it is larger than ``sys.maxint``. + + ``k`` (integer/long) [unsigned long] +- Convert a C :ctype:`unsigned long` to a Python integer object or a ++ Convert a C :c:type:`unsigned long` to a Python integer object or a + Python long integer object, if it is larger than ``sys.maxint``. + + ``L`` (long) [PY_LONG_LONG] +- Convert a C :ctype:`long long` to a Python long integer object. Only +- available on platforms that support :ctype:`long long`. ++ Convert a C :c:type:`long long` to a Python long integer object. Only ++ available on platforms that support :c:type:`long long`. + + ``K`` (long) [unsigned PY_LONG_LONG] +- Convert a C :ctype:`unsigned long long` to a Python long integer object. +- Only available on platforms that support :ctype:`unsigned long long`. ++ Convert a C :c:type:`unsigned long long` to a Python long integer object. ++ Only available on platforms that support :c:type:`unsigned long long`. + + ``n`` (int) [Py_ssize_t] +- Convert a C :ctype:`Py_ssize_t` to a Python integer or long integer. ++ Convert a C :c:type:`Py_ssize_t` to a Python integer or long integer. + + .. versionadded:: 2.5 + + ``c`` (string of length 1) [char] +- Convert a C :ctype:`int` representing a character to a Python string of ++ Convert a C :c:type:`int` representing a character to a Python string of + length 1. + + ``d`` (float) [double] +- Convert a C :ctype:`double` to a Python floating point number. ++ Convert a C :c:type:`double` to a Python floating point number. + + ``f`` (float) [float] + Same as ``d``. + + ``D`` (complex) [Py_complex \*] +- Convert a C :ctype:`Py_complex` structure to a Python complex number. ++ Convert a C :c:type:`Py_complex` structure to a Python complex number. + + ``O`` (object) [PyObject \*] + Pass a Python object untouched (except for its reference count, which is + incremented by one). If the object passed in is a *NULL* pointer, it is + assumed that this was caused because the call producing the argument +- found an error and set an exception. Therefore, :cfunc:`Py_BuildValue` ++ found an error and set an exception. Therefore, :c:func:`Py_BuildValue` + will return *NULL* but won't raise an exception. If no exception has + been raised yet, :exc:`SystemError` is set. + +@@ -534,7 +539,7 @@ + ``O&`` (object) [*converter*, *anything*] + Convert *anything* to a Python object through a *converter* function. + The function is called with *anything* (which should be compatible with +- :ctype:`void \*`) as its argument and should return a "new" Python ++ :c:type:`void \*`) as its argument and should return a "new" Python + object, or *NULL* if an error occurred. + + ``(items)`` (tuple) [*matching-items*] +@@ -553,7 +558,7 @@ + If there is an error in the format string, the :exc:`SystemError` exception + is set and *NULL* returned. + +-.. cfunction:: PyObject* Py_VaBuildValue(const char *format, va_list vargs) ++.. c:function:: PyObject* Py_VaBuildValue(const char *format, va_list vargs) + +- Identical to :cfunc:`Py_BuildValue`, except that it accepts a va_list ++ Identical to :c:func:`Py_BuildValue`, except that it accepts a va_list + rather than a variable number of arguments. +diff -r 8527427914a2 Doc/c-api/bool.rst +--- a/Doc/c-api/bool.rst ++++ b/Doc/c-api/bool.rst +@@ -11,26 +11,26 @@ + are available, however. + + +-.. cfunction:: int PyBool_Check(PyObject *o) ++.. c:function:: int PyBool_Check(PyObject *o) + +- Return true if *o* is of type :cdata:`PyBool_Type`. ++ Return true if *o* is of type :c:data:`PyBool_Type`. + + .. versionadded:: 2.3 + + +-.. cvar:: PyObject* Py_False ++.. c:var:: PyObject* Py_False + + The Python ``False`` object. This object has no methods. It needs to be + treated just like any other object with respect to reference counts. + + +-.. cvar:: PyObject* Py_True ++.. c:var:: PyObject* Py_True + + The Python ``True`` object. This object has no methods. It needs to be treated + just like any other object with respect to reference counts. + + +-.. cmacro:: Py_RETURN_FALSE ++.. c:macro:: Py_RETURN_FALSE + + Return :const:`Py_False` from a function, properly incrementing its reference + count. +@@ -38,7 +38,7 @@ + .. versionadded:: 2.4 + + +-.. cmacro:: Py_RETURN_TRUE ++.. c:macro:: Py_RETURN_TRUE + + Return :const:`Py_True` from a function, properly incrementing its reference + count. +@@ -46,7 +46,7 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyBool_FromLong(long v) ++.. c:function:: PyObject* PyBool_FromLong(long v) + + Return a new reference to :const:`Py_True` or :const:`Py_False` depending on the + truth value of *v*. +diff -r 8527427914a2 Doc/c-api/buffer.rst +--- a/Doc/c-api/buffer.rst ++++ b/Doc/c-api/buffer.rst +@@ -27,7 +27,7 @@ + An example user of the buffer interface is the file object's :meth:`write` + method. Any object that can export a series of bytes through the buffer + interface can be written to a file. There are a number of format codes to +-:cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface, ++:c:func:`PyArg_ParseTuple` that operate against an object's buffer interface, + returning data from the target object. + + Starting from version 1.6, Python has been providing Python-level buffer +@@ -47,49 +47,49 @@ + ============================== + + +-.. ctype:: Py_buffer ++.. c:type:: Py_buffer + +- .. cmember:: void *buf ++ .. c:member:: void *buf + + A pointer to the start of the memory for the object. + +- .. cmember:: Py_ssize_t len ++ .. c:member:: Py_ssize_t len + :noindex: + + The total length of the memory in bytes. + +- .. cmember:: int readonly ++ .. c:member:: int readonly + + An indicator of whether the buffer is read only. + +- .. cmember:: const char *format ++ .. c:member:: const char *format + :noindex: + + A *NULL* terminated string in :mod:`struct` module style syntax giving + the contents of the elements available through the buffer. If this is + *NULL*, ``"B"`` (unsigned bytes) is assumed. + +- .. cmember:: int ndim ++ .. c:member:: int ndim + + The number of dimensions the memory represents as a multi-dimensional +- array. If it is 0, :cdata:`strides` and :cdata:`suboffsets` must be ++ array. If it is 0, :c:data:`strides` and :c:data:`suboffsets` must be + *NULL*. + +- .. cmember:: Py_ssize_t *shape ++ .. c:member:: Py_ssize_t *shape + +- An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the ++ An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the + shape of the memory as a multi-dimensional array. Note that + ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to +- :cdata:`len`. ++ :c:data:`len`. + +- .. cmember:: Py_ssize_t *strides ++ .. c:member:: Py_ssize_t *strides + +- An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the ++ An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the + number of bytes to skip to get to a new element in each dimension. + +- .. cmember:: Py_ssize_t *suboffsets ++ .. c:member:: Py_ssize_t *suboffsets + +- An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim`. If these ++ An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim`. If these + suboffset numbers are greater than or equal to 0, then the value stored + along the indicated dimension is a pointer and the suboffset value + dictates how many bytes to add to the pointer after de-referencing. A +@@ -114,16 +114,16 @@ + } + + +- .. cmember:: Py_ssize_t itemsize ++ .. c:member:: Py_ssize_t itemsize + + This is a storage for the itemsize (in bytes) of each element of the + shared memory. It is technically un-necessary as it can be obtained +- using :cfunc:`PyBuffer_SizeFromFormat`, however an exporter may know ++ using :c:func:`PyBuffer_SizeFromFormat`, however an exporter may know + this information without parsing the format string and it is necessary + to know the itemsize for proper interpretation of striding. Therefore, + storing it is more convenient and faster. + +- .. cmember:: void *internal ++ .. c:member:: void *internal + + This is for use internally by the exporting object. For example, this + might be re-cast as an integer by the exporter and used to store flags +@@ -136,14 +136,14 @@ + ======================== + + +-.. cfunction:: int PyObject_CheckBuffer(PyObject *obj) ++.. c:function:: int PyObject_CheckBuffer(PyObject *obj) + + Return 1 if *obj* supports the buffer interface otherwise 0. + + +-.. cfunction:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) ++.. c:function:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) + +- Export *obj* into a :ctype:`Py_buffer`, *view*. These arguments must ++ Export *obj* into a :c:type:`Py_buffer`, *view*. These arguments must + never be *NULL*. The *flags* argument is a bit field indicating what + kind of buffer the caller is prepared to deal with and therefore what + kind of buffer the exporter is allowed to return. The buffer interface +@@ -156,131 +156,131 @@ + just not possible. These errors should be a :exc:`BufferError` unless + there is another error that is actually causing the problem. The + exporter can use flags information to simplify how much of the +- :cdata:`Py_buffer` structure is filled in with non-default values and/or ++ :c:data:`Py_buffer` structure is filled in with non-default values and/or + raise an error if the object can't support a simpler view of its memory. + + 0 is returned on success and -1 on error. + + The following table gives possible values to the *flags* arguments. + +- +------------------------------+---------------------------------------------------+ +- | Flag | Description | +- +==============================+===================================================+ +- | :cmacro:`PyBUF_SIMPLE` | This is the default flag state. The returned | +- | | buffer may or may not have writable memory. The | +- | | format of the data will be assumed to be unsigned | +- | | bytes. This is a "stand-alone" flag constant. It | +- | | never needs to be '|'d to the others. The exporter| +- | | will raise an error if it cannot provide such a | +- | | contiguous buffer of bytes. | +- | | | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is | +- | | not writable, then raise an error. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_STRIDES` | This implies :cmacro:`PyBUF_ND`. The returned | +- | | buffer must provide strides information (i.e. the | +- | | strides cannot be NULL). This would be used when | +- | | the consumer can handle strided, discontiguous | +- | | arrays. Handling strides automatically assumes | +- | | you can handle shape. The exporter can raise an | +- | | error if a strided representation of the data is | +- | | not possible (i.e. without the suboffsets). | +- | | | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_ND` | The returned buffer must provide shape | +- | | information. The memory will be assumed C-style | +- | | contiguous (last dimension varies the | +- | | fastest). The exporter may raise an error if it | +- | | cannot provide this kind of contiguous buffer. If | +- | | this is not given then shape will be *NULL*. | +- | | | +- | | | +- | | | +- +------------------------------+---------------------------------------------------+ +- |:cmacro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned | +- |:cmacro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last | +- |:cmacro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous | +- | | (first dimension varies the fastest) or either | +- | | one. All of these flags imply | +- | | :cmacro:`PyBUF_STRIDES` and guarantee that the | +- | | strides buffer info structure will be filled in | +- | | correctly. | +- | | | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_INDIRECT` | This flag indicates the returned buffer must have | +- | | suboffsets information (which can be NULL if no | +- | | suboffsets are needed). This can be used when | +- | | the consumer can handle indirect array | +- | | referencing implied by these suboffsets. This | +- | | implies :cmacro:`PyBUF_STRIDES`. | +- | | | +- | | | +- | | | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_FORMAT` | The returned buffer must have true format | +- | | information if this flag is provided. This would | +- | | be used when the consumer is going to be checking | +- | | for what 'kind' of data is actually stored. An | +- | | exporter should always be able to provide this | +- | | information if requested. If format is not | +- | | explicitly requested then the format must be | +- | | returned as *NULL* (which means ``'B'``, or | +- | | unsigned bytes) | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | | +- | | PyBUF_WRITABLE)``. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. | +- | | | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | | +- | | PyBUF_FORMAT | PyBUF_WRITABLE)``. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | | +- | | PyBUF_FORMAT)``. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | | +- | | PyBUF_FORMAT | PyBUF_WRITABLE)``. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | | +- | | PyBUF_FORMAT)``. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | | +- | | PyBUF_WRITABLE)``. | +- +------------------------------+---------------------------------------------------+ +- | :cmacro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. | +- | | | +- +------------------------------+---------------------------------------------------+ ++ +-------------------------------+---------------------------------------------------+ ++ | Flag | Description | ++ +===============================+===================================================+ ++ | :c:macro:`PyBUF_SIMPLE` | This is the default flag state. The returned | ++ | | buffer may or may not have writable memory. The | ++ | | format of the data will be assumed to be unsigned | ++ | | bytes. This is a "stand-alone" flag constant. It | ++ | | never needs to be '|'d to the others. The exporter| ++ | | will raise an error if it cannot provide such a | ++ | | contiguous buffer of bytes. | ++ | | | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is | ++ | | not writable, then raise an error. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_STRIDES` | This implies :c:macro:`PyBUF_ND`. The returned | ++ | | buffer must provide strides information (i.e. the | ++ | | strides cannot be NULL). This would be used when | ++ | | the consumer can handle strided, discontiguous | ++ | | arrays. Handling strides automatically assumes | ++ | | you can handle shape. The exporter can raise an | ++ | | error if a strided representation of the data is | ++ | | not possible (i.e. without the suboffsets). | ++ | | | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_ND` | The returned buffer must provide shape | ++ | | information. The memory will be assumed C-style | ++ | | contiguous (last dimension varies the | ++ | | fastest). The exporter may raise an error if it | ++ | | cannot provide this kind of contiguous buffer. If | ++ | | this is not given then shape will be *NULL*. | ++ | | | ++ | | | ++ | | | ++ +-------------------------------+---------------------------------------------------+ ++ |:c:macro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned | ++ |:c:macro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last | ++ |:c:macro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous | ++ | | (first dimension varies the fastest) or either | ++ | | one. All of these flags imply | ++ | | :c:macro:`PyBUF_STRIDES` and guarantee that the | ++ | | strides buffer info structure will be filled in | ++ | | correctly. | ++ | | | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_INDIRECT` | This flag indicates the returned buffer must have | ++ | | suboffsets information (which can be NULL if no | ++ | | suboffsets are needed). This can be used when | ++ | | the consumer can handle indirect array | ++ | | referencing implied by these suboffsets. This | ++ | | implies :c:macro:`PyBUF_STRIDES`. | ++ | | | ++ | | | ++ | | | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_FORMAT` | The returned buffer must have true format | ++ | | information if this flag is provided. This would | ++ | | be used when the consumer is going to be checking | ++ | | for what 'kind' of data is actually stored. An | ++ | | exporter should always be able to provide this | ++ | | information if requested. If format is not | ++ | | explicitly requested then the format must be | ++ | | returned as *NULL* (which means ``'B'``, or | ++ | | unsigned bytes) | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | | ++ | | PyBUF_WRITABLE)``. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. | ++ | | | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | | ++ | | PyBUF_FORMAT | PyBUF_WRITABLE)``. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | | ++ | | PyBUF_FORMAT)``. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | | ++ | | PyBUF_FORMAT | PyBUF_WRITABLE)``. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | | ++ | | PyBUF_FORMAT)``. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | | ++ | | PyBUF_WRITABLE)``. | ++ +-------------------------------+---------------------------------------------------+ ++ | :c:macro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. | ++ | | | ++ +-------------------------------+---------------------------------------------------+ + + +-.. cfunction:: void PyBuffer_Release(Py_buffer *view) ++.. c:function:: void PyBuffer_Release(Py_buffer *view) + + Release the buffer *view*. This should be called when the buffer + is no longer being used as it may free memory from it. + + +-.. cfunction:: Py_ssize_t PyBuffer_SizeFromFormat(const char *) ++.. c:function:: Py_ssize_t PyBuffer_SizeFromFormat(const char *) + +- Return the implied :cdata:`~Py_buffer.itemsize` from the struct-stype +- :cdata:`~Py_buffer.format`. ++ Return the implied :c:data:`~Py_buffer.itemsize` from the struct-stype ++ :c:data:`~Py_buffer.format`. + + +-.. cfunction:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran) ++.. c:function:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran) + + Return 1 if the memory defined by the *view* is C-style (*fortran* is + ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one + (*fortran* is ``'A'``). Return 0 otherwise. + + +-.. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran) ++.. c:function:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran) + + Fill the *strides* array with byte-strides of a contiguous (C-style if + *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'``) array of the + given shape with the given number of bytes per element. + + +-.. cfunction:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags) ++.. c:function:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags) + + Fill in a buffer-info structure, *view*, correctly for an exporter that can + only share a contiguous chunk of memory of "unsigned bytes" of the given +@@ -295,13 +295,13 @@ + A :class:`memoryview` object exposes the new C level buffer interface as a + Python object which can then be passed around like any other object. + +-.. cfunction:: PyObject *PyMemoryView_FromObject(PyObject *obj) ++.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj) + + Create a memoryview object from an object that defines the new buffer + interface. + + +-.. cfunction:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view) ++.. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view) + + Create a memoryview object wrapping the given buffer-info structure *view*. + The memoryview object then owns the buffer, which means you shouldn't +@@ -309,7 +309,7 @@ + memoryview object. + + +-.. cfunction:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) ++.. c:function:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) + + Create a memoryview object to a contiguous chunk of memory (in either + 'C' or 'F'ortran *order*) from an object that defines the buffer +@@ -318,13 +318,13 @@ + new bytes object. + + +-.. cfunction:: int PyMemoryView_Check(PyObject *obj) ++.. c:function:: int PyMemoryView_Check(PyObject *obj) + + Return true if the object *obj* is a memoryview object. It is not + currently allowed to create subclasses of :class:`memoryview`. + + +-.. cfunction:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *obj) ++.. c:function:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *obj) + + Return a pointer to the buffer-info structure wrapped by the given + object. The object **must** be a memoryview instance; this macro doesn't +@@ -337,7 +337,7 @@ + .. index:: single: PyBufferProcs + + More information on the old buffer interface is provided in the section +-:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`. ++:ref:`buffer-structs`, under the description for :c:type:`PyBufferProcs`. + + A "buffer object" is defined in the :file:`bufferobject.h` header (included by + :file:`Python.h`). These objects look very similar to string objects at the +@@ -356,36 +356,36 @@ + native, in-memory format. + + +-.. ctype:: PyBufferObject ++.. c:type:: PyBufferObject + +- This subtype of :ctype:`PyObject` represents a buffer object. ++ This subtype of :c:type:`PyObject` represents a buffer object. + + +-.. cvar:: PyTypeObject PyBuffer_Type ++.. c:var:: PyTypeObject PyBuffer_Type + + .. index:: single: BufferType (in module types) + +- The instance of :ctype:`PyTypeObject` which represents the Python buffer type; ++ The instance of :c:type:`PyTypeObject` which represents the Python buffer type; + it is the same object as ``buffer`` and ``types.BufferType`` in the Python + layer. . + + +-.. cvar:: int Py_END_OF_BUFFER ++.. c:var:: int Py_END_OF_BUFFER + + This constant may be passed as the *size* parameter to +- :cfunc:`PyBuffer_FromObject` or :cfunc:`PyBuffer_FromReadWriteObject`. It +- indicates that the new :ctype:`PyBufferObject` should refer to *base* ++ :c:func:`PyBuffer_FromObject` or :c:func:`PyBuffer_FromReadWriteObject`. It ++ indicates that the new :c:type:`PyBufferObject` should refer to *base* + object from the specified *offset* to the end of its exported buffer. + Using this enables the caller to avoid querying the *base* object for its + length. + + +-.. cfunction:: int PyBuffer_Check(PyObject *p) ++.. c:function:: int PyBuffer_Check(PyObject *p) + +- Return true if the argument has type :cdata:`PyBuffer_Type`. ++ Return true if the argument has type :c:data:`PyBuffer_Type`. + + +-.. cfunction:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size) ++.. c:function:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size) + + Return a new read-only buffer object. This raises :exc:`TypeError` if + *base* doesn't support the read-only buffer protocol or doesn't provide +@@ -397,24 +397,24 @@ + length of the *base* object's exported buffer data. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *offset* and *size*. This ++ This function used an :c:type:`int` type for *offset* and *size*. This + might require changes in your code for properly supporting 64-bit + systems. + + +-.. cfunction:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size) ++.. c:function:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size) + + Return a new writable buffer object. Parameters and exceptions are similar +- to those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not ++ to those for :c:func:`PyBuffer_FromObject`. If the *base* object does not + export the writeable buffer protocol, then :exc:`TypeError` is raised. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *offset* and *size*. This ++ This function used an :c:type:`int` type for *offset* and *size*. This + might require changes in your code for properly supporting 64-bit + systems. + + +-.. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size) ++.. c:function:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size) + + Return a new read-only buffer object that reads from a specified location + in memory, with a specified size. The caller is responsible for ensuring +@@ -424,27 +424,27 @@ + *size* parameter; :exc:`ValueError` will be raised in that case. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size) ++.. c:function:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size) + +- Similar to :cfunc:`PyBuffer_FromMemory`, but the returned buffer is ++ Similar to :c:func:`PyBuffer_FromMemory`, but the returned buffer is + writable. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyBuffer_New(Py_ssize_t size) ++.. c:function:: PyObject* PyBuffer_New(Py_ssize_t size) + + Return a new writable buffer object that maintains its own memory buffer of + *size* bytes. :exc:`ValueError` is returned if *size* is not zero or + positive. Note that the memory buffer (as returned by +- :cfunc:`PyObject_AsWriteBuffer`) is not specifically aligned. ++ :c:func:`PyObject_AsWriteBuffer`) is not specifically aligned. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. +diff -r 8527427914a2 Doc/c-api/bytearray.rst +--- a/Doc/c-api/bytearray.rst ++++ b/Doc/c-api/bytearray.rst +@@ -10,26 +10,26 @@ + .. versionadded:: 2.6 + + +-.. ctype:: PyByteArrayObject ++.. c:type:: PyByteArrayObject + +- This subtype of :ctype:`PyObject` represents a Python bytearray object. ++ This subtype of :c:type:`PyObject` represents a Python bytearray object. + + +-.. cvar:: PyTypeObject PyByteArray_Type ++.. c:var:: PyTypeObject PyByteArray_Type + +- This instance of :ctype:`PyTypeObject` represents the Python bytearray type; ++ This instance of :c:type:`PyTypeObject` represents the Python bytearray type; + it is the same object as ``bytearray`` in the Python layer. + + Type check macros + ^^^^^^^^^^^^^^^^^ + +-.. cfunction:: int PyByteArray_Check(PyObject *o) ++.. c:function:: int PyByteArray_Check(PyObject *o) + + Return true if the object *o* is a bytearray object or an instance of a + subtype of the bytearray type. + + +-.. cfunction:: int PyByteArray_CheckExact(PyObject *o) ++.. c:function:: int PyByteArray_CheckExact(PyObject *o) + + Return true if the object *o* is a bytearray object, but not an instance of a + subtype of the bytearray type. +@@ -38,7 +38,7 @@ + Direct API functions + ^^^^^^^^^^^^^^^^^^^^ + +-.. cfunction:: PyObject* PyByteArray_FromObject(PyObject *o) ++.. c:function:: PyObject* PyByteArray_FromObject(PyObject *o) + + Return a new bytearray object from any object, *o*, that implements the + buffer protocol. +@@ -46,29 +46,29 @@ + .. XXX expand about the buffer protocol, at least somewhere + + +-.. cfunction:: PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len) ++.. c:function:: PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len) + + Create a new bytearray object from *string* and its length, *len*. On + failure, *NULL* is returned. + + +-.. cfunction:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b) ++.. c:function:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b) + + Concat bytearrays *a* and *b* and return a new bytearray with the result. + + +-.. cfunction:: Py_ssize_t PyByteArray_Size(PyObject *bytearray) ++.. c:function:: Py_ssize_t PyByteArray_Size(PyObject *bytearray) + + Return the size of *bytearray* after checking for a *NULL* pointer. + + +-.. cfunction:: char* PyByteArray_AsString(PyObject *bytearray) ++.. c:function:: char* PyByteArray_AsString(PyObject *bytearray) + + Return the contents of *bytearray* as a char array after checking for a + *NULL* pointer. + + +-.. cfunction:: int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len) ++.. c:function:: int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len) + + Resize the internal buffer of *bytearray* to *len*. + +@@ -77,11 +77,11 @@ + + These macros trade safety for speed and they don't check pointers. + +-.. cfunction:: char* PyByteArray_AS_STRING(PyObject *bytearray) ++.. c:function:: char* PyByteArray_AS_STRING(PyObject *bytearray) + +- Macro version of :cfunc:`PyByteArray_AsString`. ++ Macro version of :c:func:`PyByteArray_AsString`. + + +-.. cfunction:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray) ++.. c:function:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray) + +- Macro version of :cfunc:`PyByteArray_Size`. ++ Macro version of :c:func:`PyByteArray_Size`. +diff -r 8527427914a2 Doc/c-api/capsule.rst +--- a/Doc/c-api/capsule.rst ++++ b/Doc/c-api/capsule.rst +@@ -10,33 +10,33 @@ + Refer to :ref:`using-capsules` for more information on using these objects. + + +-.. ctype:: PyCapsule ++.. c:type:: PyCapsule + +- This subtype of :ctype:`PyObject` represents an opaque value, useful for C +- extension modules who need to pass an opaque value (as a :ctype:`void\*` ++ This subtype of :c:type:`PyObject` represents an opaque value, useful for C ++ extension modules who need to pass an opaque value (as a :c:type:`void\*` + pointer) through Python code to other C code. It is often used to make a C + function pointer defined in one module available to other modules, so the + regular import mechanism can be used to access C APIs defined in dynamically + loaded modules. + +-.. ctype:: PyCapsule_Destructor ++.. c:type:: PyCapsule_Destructor + + The type of a destructor callback for a capsule. Defined as:: + + typedef void (*PyCapsule_Destructor)(PyObject *); + +- See :cfunc:`PyCapsule_New` for the semantics of PyCapsule_Destructor ++ See :c:func:`PyCapsule_New` for the semantics of PyCapsule_Destructor + callbacks. + + +-.. cfunction:: int PyCapsule_CheckExact(PyObject *p) ++.. c:function:: int PyCapsule_CheckExact(PyObject *p) + +- Return true if its argument is a :ctype:`PyCapsule`. ++ Return true if its argument is a :c:type:`PyCapsule`. + + +-.. cfunction:: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) ++.. c:function:: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) + +- Create a :ctype:`PyCapsule` encapsulating the *pointer*. The *pointer* ++ Create a :c:type:`PyCapsule` encapsulating the *pointer*. The *pointer* + argument may not be *NULL*. + + On failure, set an exception and return *NULL*. +@@ -50,91 +50,91 @@ + + If this capsule will be stored as an attribute of a module, the *name* should + be specified as ``modulename.attributename``. This will enable other modules +- to import the capsule using :cfunc:`PyCapsule_Import`. ++ to import the capsule using :c:func:`PyCapsule_Import`. + + +-.. cfunction:: void* PyCapsule_GetPointer(PyObject *capsule, const char *name) ++.. c:function:: void* PyCapsule_GetPointer(PyObject *capsule, const char *name) + + Retrieve the *pointer* stored in the capsule. On failure, set an exception + and return *NULL*. + + The *name* parameter must compare exactly to the name stored in the capsule. + If the name stored in the capsule is *NULL*, the *name* passed in must also +- be *NULL*. Python uses the C function :cfunc:`strcmp` to compare capsule ++ be *NULL*. Python uses the C function :c:func:`strcmp` to compare capsule + names. + + +-.. cfunction:: PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule) ++.. c:function:: PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule) + + Return the current destructor stored in the capsule. On failure, set an + exception and return *NULL*. + + It is legal for a capsule to have a *NULL* destructor. This makes a *NULL* +- return code somewhat ambiguous; use :cfunc:`PyCapsule_IsValid` or +- :cfunc:`PyErr_Occurred` to disambiguate. ++ return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or ++ :c:func:`PyErr_Occurred` to disambiguate. + + +-.. cfunction:: void* PyCapsule_GetContext(PyObject *capsule) ++.. c:function:: void* PyCapsule_GetContext(PyObject *capsule) + + Return the current context stored in the capsule. On failure, set an + exception and return *NULL*. + + It is legal for a capsule to have a *NULL* context. This makes a *NULL* +- return code somewhat ambiguous; use :cfunc:`PyCapsule_IsValid` or +- :cfunc:`PyErr_Occurred` to disambiguate. ++ return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or ++ :c:func:`PyErr_Occurred` to disambiguate. + + +-.. cfunction:: const char* PyCapsule_GetName(PyObject *capsule) ++.. c:function:: const char* PyCapsule_GetName(PyObject *capsule) + + Return the current name stored in the capsule. On failure, set an exception + and return *NULL*. + + It is legal for a capsule to have a *NULL* name. This makes a *NULL* return +- code somewhat ambiguous; use :cfunc:`PyCapsule_IsValid` or +- :cfunc:`PyErr_Occurred` to disambiguate. ++ code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or ++ :c:func:`PyErr_Occurred` to disambiguate. + + +-.. cfunction:: void* PyCapsule_Import(const char *name, int no_block) ++.. c:function:: void* PyCapsule_Import(const char *name, int no_block) + + Import a pointer to a C object from a capsule attribute in a module. The + *name* parameter should specify the full name to the attribute, as in + ``module.attribute``. The *name* stored in the capsule must match this + string exactly. If *no_block* is true, import the module without blocking +- (using :cfunc:`PyImport_ImportModuleNoBlock`). If *no_block* is false, +- import the module conventionally (using :cfunc:`PyImport_ImportModule`). ++ (using :c:func:`PyImport_ImportModuleNoBlock`). If *no_block* is false, ++ import the module conventionally (using :c:func:`PyImport_ImportModule`). + + Return the capsule's internal *pointer* on success. On failure, set an +- exception and return *NULL*. However, if :cfunc:`PyCapsule_Import` failed to ++ exception and return *NULL*. However, if :c:func:`PyCapsule_Import` failed to + import the module, and *no_block* was true, no exception is set. + +-.. cfunction:: int PyCapsule_IsValid(PyObject *capsule, const char *name) ++.. c:function:: int PyCapsule_IsValid(PyObject *capsule, const char *name) + + Determines whether or not *capsule* is a valid capsule. A valid capsule is +- non-*NULL*, passes :cfunc:`PyCapsule_CheckExact`, has a non-*NULL* pointer ++ non-*NULL*, passes :c:func:`PyCapsule_CheckExact`, has a non-*NULL* pointer + stored in it, and its internal name matches the *name* parameter. (See +- :cfunc:`PyCapsule_GetPointer` for information on how capsule names are ++ :c:func:`PyCapsule_GetPointer` for information on how capsule names are + compared.) + +- In other words, if :cfunc:`PyCapsule_IsValid` returns a true value, calls to +- any of the accessors (any function starting with :cfunc:`PyCapsule_Get`) are ++ In other words, if :c:func:`PyCapsule_IsValid` returns a true value, calls to ++ any of the accessors (any function starting with :c:func:`PyCapsule_Get`) are + guaranteed to succeed. + + Return a nonzero value if the object is valid and matches the name passed in. + Return 0 otherwise. This function will not fail. + +-.. cfunction:: int PyCapsule_SetContext(PyObject *capsule, void *context) ++.. c:function:: int PyCapsule_SetContext(PyObject *capsule, void *context) + + Set the context pointer inside *capsule* to *context*. + + Return 0 on success. Return nonzero and set an exception on failure. + +-.. cfunction:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor) ++.. c:function:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor) + + Set the destructor inside *capsule* to *destructor*. + + Return 0 on success. Return nonzero and set an exception on failure. + +-.. cfunction:: int PyCapsule_SetName(PyObject *capsule, const char *name) ++.. c:function:: int PyCapsule_SetName(PyObject *capsule, const char *name) + + Set the name inside *capsule* to *name*. If non-*NULL*, the name must + outlive the capsule. If the previous *name* stored in the capsule was not +@@ -142,7 +142,7 @@ + + Return 0 on success. Return nonzero and set an exception on failure. + +-.. cfunction:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer) ++.. c:function:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer) + + Set the void pointer inside *capsule* to *pointer*. The pointer may not be + *NULL*. +diff -r 8527427914a2 Doc/c-api/cell.rst +--- a/Doc/c-api/cell.rst ++++ b/Doc/c-api/cell.rst +@@ -15,39 +15,39 @@ + Cell objects are not likely to be useful elsewhere. + + +-.. ctype:: PyCellObject ++.. c:type:: PyCellObject + + The C structure used for cell objects. + + +-.. cvar:: PyTypeObject PyCell_Type ++.. c:var:: PyTypeObject PyCell_Type + + The type object corresponding to cell objects. + + +-.. cfunction:: int PyCell_Check(ob) ++.. c:function:: int PyCell_Check(ob) + + Return true if *ob* is a cell object; *ob* must not be *NULL*. + + +-.. cfunction:: PyObject* PyCell_New(PyObject *ob) ++.. c:function:: PyObject* PyCell_New(PyObject *ob) + + Create and return a new cell object containing the value *ob*. The parameter may + be *NULL*. + + +-.. cfunction:: PyObject* PyCell_Get(PyObject *cell) ++.. c:function:: PyObject* PyCell_Get(PyObject *cell) + + Return the contents of the cell *cell*. + + +-.. cfunction:: PyObject* PyCell_GET(PyObject *cell) ++.. c:function:: PyObject* PyCell_GET(PyObject *cell) + + Return the contents of the cell *cell*, but without checking that *cell* is + non-*NULL* and a cell object. + + +-.. cfunction:: int PyCell_Set(PyObject *cell, PyObject *value) ++.. c:function:: int PyCell_Set(PyObject *cell, PyObject *value) + + Set the contents of the cell object *cell* to *value*. This releases the + reference to any current content of the cell. *value* may be *NULL*. *cell* +@@ -55,7 +55,7 @@ + success, ``0`` will be returned. + + +-.. cfunction:: void PyCell_SET(PyObject *cell, PyObject *value) ++.. c:function:: void PyCell_SET(PyObject *cell, PyObject *value) + + Sets the value of the cell object *cell* to *value*. No reference counts are + adjusted, and no checks are made for safety; *cell* must be non-*NULL* and must +diff -r 8527427914a2 Doc/c-api/class.rst +--- a/Doc/c-api/class.rst ++++ b/Doc/c-api/class.rst +@@ -12,12 +12,12 @@ + will want to work with type objects (section :ref:`typeobjects`). + + +-.. ctype:: PyClassObject ++.. c:type:: PyClassObject + + The C structure of the objects used to describe built-in classes. + + +-.. cvar:: PyObject* PyClass_Type ++.. c:var:: PyObject* PyClass_Type + + .. index:: single: ClassType (in module types) + +@@ -25,13 +25,13 @@ + ``types.ClassType`` in the Python layer. + + +-.. cfunction:: int PyClass_Check(PyObject *o) ++.. c:function:: int PyClass_Check(PyObject *o) + + Return true if the object *o* is a class object, including instances of types + derived from the standard class object. Return false in all other cases. + + +-.. cfunction:: int PyClass_IsSubclass(PyObject *klass, PyObject *base) ++.. c:function:: int PyClass_IsSubclass(PyObject *klass, PyObject *base) + + Return true if *klass* is a subclass of *base*. Return false in all other cases. + +@@ -41,23 +41,23 @@ + There are very few functions specific to instance objects. + + +-.. cvar:: PyTypeObject PyInstance_Type ++.. c:var:: PyTypeObject PyInstance_Type + + Type object for class instances. + + +-.. cfunction:: int PyInstance_Check(PyObject *obj) ++.. c:function:: int PyInstance_Check(PyObject *obj) + + Return true if *obj* is an instance. + + +-.. cfunction:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw) ++.. c:function:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw) + + Create a new instance of a specific class. The parameters *arg* and *kw* are + used as the positional and keyword parameters to the object's constructor. + + +-.. cfunction:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict) ++.. c:function:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict) + + Create a new instance of a specific class without calling its constructor. + *class* is the class of new object. The *dict* parameter will be used as the +diff -r 8527427914a2 Doc/c-api/cobject.rst +--- a/Doc/c-api/cobject.rst ++++ b/Doc/c-api/cobject.rst +@@ -13,47 +13,47 @@ + The CObject API is deprecated as of Python 2.7. Please switch to the new + :ref:`capsules` API. + +-.. ctype:: PyCObject ++.. c:type:: PyCObject + +- This subtype of :ctype:`PyObject` represents an opaque value, useful for C +- extension modules who need to pass an opaque value (as a :ctype:`void\*` ++ This subtype of :c:type:`PyObject` represents an opaque value, useful for C ++ extension modules who need to pass an opaque value (as a :c:type:`void\*` + pointer) through Python code to other C code. It is often used to make a C + function pointer defined in one module available to other modules, so the + regular import mechanism can be used to access C APIs defined in dynamically + loaded modules. + + +-.. cfunction:: int PyCObject_Check(PyObject *p) ++.. c:function:: int PyCObject_Check(PyObject *p) + +- Return true if its argument is a :ctype:`PyCObject`. ++ Return true if its argument is a :c:type:`PyCObject`. + + +-.. cfunction:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *)) ++.. c:function:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *)) + +- Create a :ctype:`PyCObject` from the ``void *`` *cobj*. The *destr* function ++ Create a :c:type:`PyCObject` from the ``void *`` *cobj*. The *destr* function + will be called when the object is reclaimed, unless it is *NULL*. + + +-.. cfunction:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *)) ++.. c:function:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *)) + +- Create a :ctype:`PyCObject` from the :ctype:`void \*` *cobj*. The *destr* ++ Create a :c:type:`PyCObject` from the :c:type:`void \*` *cobj*. The *destr* + function will be called when the object is reclaimed. The *desc* argument can + be used to pass extra callback data for the destructor function. + + +-.. cfunction:: void* PyCObject_AsVoidPtr(PyObject* self) ++.. c:function:: void* PyCObject_AsVoidPtr(PyObject* self) + +- Return the object :ctype:`void \*` that the :ctype:`PyCObject` *self* was ++ Return the object :c:type:`void \*` that the :c:type:`PyCObject` *self* was + created with. + + +-.. cfunction:: void* PyCObject_GetDesc(PyObject* self) ++.. c:function:: void* PyCObject_GetDesc(PyObject* self) + +- Return the description :ctype:`void \*` that the :ctype:`PyCObject` *self* was ++ Return the description :c:type:`void \*` that the :c:type:`PyCObject` *self* was + created with. + + +-.. cfunction:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj) ++.. c:function:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj) + +- Set the void pointer inside *self* to *cobj*. The :ctype:`PyCObject` must not ++ Set the void pointer inside *self* to *cobj*. The :c:type:`PyCObject` must not + have an associated destructor. Return true on success, false on failure. +diff -r 8527427914a2 Doc/c-api/code.rst +--- a/Doc/c-api/code.rst ++++ b/Doc/c-api/code.rst +@@ -15,35 +15,35 @@ + Each one represents a chunk of executable code that hasn't yet been + bound into a function. + +-.. ctype:: PyCodeObject ++.. c:type:: PyCodeObject + + The C structure of the objects used to describe code objects. The + fields of this type are subject to change at any time. + + +-.. cvar:: PyTypeObject PyCode_Type ++.. c:var:: PyTypeObject PyCode_Type + +- This is an instance of :ctype:`PyTypeObject` representing the Python ++ This is an instance of :c:type:`PyTypeObject` representing the Python + :class:`code` type. + + +-.. cfunction:: int PyCode_Check(PyObject *co) ++.. c:function:: int PyCode_Check(PyObject *co) + + Return true if *co* is a :class:`code` object + +-.. cfunction:: int PyCode_GetNumFree(PyObject *co) ++.. c:function:: int PyCode_GetNumFree(PyObject *co) + + Return the number of free variables in *co*. + +-.. cfunction:: PyCodeObject *PyCode_New(int argcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab) ++.. c:function:: PyCodeObject *PyCode_New(int argcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab) + + Return a new code object. If you need a dummy code object to +- create a frame, use :cfunc:`PyCode_NewEmpty` instead. Calling +- :cfunc:`PyCode_New` directly can bind you to a precise Python ++ create a frame, use :c:func:`PyCode_NewEmpty` instead. Calling ++ :c:func:`PyCode_New` directly can bind you to a precise Python + version since the definition of the bytecode changes often. + + +-.. cfunction:: int PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) ++.. c:function:: int PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) + + Return a new empty code object with the specified filename, + function name, and first line number. It is illegal to +diff -r 8527427914a2 Doc/c-api/codec.rst +--- a/Doc/c-api/codec.rst ++++ b/Doc/c-api/codec.rst +@@ -3,19 +3,19 @@ + Codec registry and support functions + ==================================== + +-.. cfunction:: int PyCodec_Register(PyObject *search_function) ++.. c:function:: int PyCodec_Register(PyObject *search_function) + + Register a new codec search function. + + As side effect, this tries to load the :mod:`encodings` package, if not yet + done, to make sure that it is always first in the list of search functions. + +-.. cfunction:: int PyCodec_KnownEncoding(const char *encoding) ++.. c:function:: int PyCodec_KnownEncoding(const char *encoding) + + Return ``1`` or ``0`` depending on whether there is a registered codec for + the given *encoding*. + +-.. cfunction:: PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors) + + Generic codec based encoding API. + +@@ -24,7 +24,7 @@ + be *NULL* to use the default method defined for the codec. Raises a + :exc:`LookupError` if no encoder can be found. + +-.. cfunction:: PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors) + + Generic codec based decoding API. + +@@ -42,27 +42,27 @@ + effectively case-insensitive. If no codec is found, a :exc:`KeyError` is set + and *NULL* returned. + +-.. cfunction:: PyObject* PyCodec_Encoder(const char *encoding) ++.. c:function:: PyObject* PyCodec_Encoder(const char *encoding) + + Get an encoder function for the given *encoding*. + +-.. cfunction:: PyObject* PyCodec_Decoder(const char *encoding) ++.. c:function:: PyObject* PyCodec_Decoder(const char *encoding) + + Get a decoder function for the given *encoding*. + +-.. cfunction:: PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors) ++.. c:function:: PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors) + + Get an :class:`IncrementalEncoder` object for the given *encoding*. + +-.. cfunction:: PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors) ++.. c:function:: PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors) + + Get an :class:`IncrementalDecoder` object for the given *encoding*. + +-.. cfunction:: PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors) ++.. c:function:: PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors) + + Get a :class:`StreamReader` factory function for the given *encoding*. + +-.. cfunction:: PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors) ++.. c:function:: PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors) + + Get a :class:`StreamWriter` factory function for the given *encoding*. + +@@ -70,7 +70,7 @@ + Registry API for Unicode encoding error handlers + ------------------------------------------------ + +-.. cfunction:: int PyCodec_RegisterError(const char *name, PyObject *error) ++.. c:function:: int PyCodec_RegisterError(const char *name, PyObject *error) + + Register the error handling callback function *error* under the given *name*. + This callback function will be called by a codec when it encounters +@@ -89,29 +89,29 @@ + + Return ``0`` on success, ``-1`` on error. + +-.. cfunction:: PyObject* PyCodec_LookupError(const char *name) ++.. c:function:: PyObject* PyCodec_LookupError(const char *name) + + Lookup the error handling callback function registered under *name*. As a + special case *NULL* can be passed, in which case the error handling callback + for "strict" will be returned. + +-.. cfunction:: PyObject* PyCodec_StrictErrors(PyObject *exc) ++.. c:function:: PyObject* PyCodec_StrictErrors(PyObject *exc) + + Raise *exc* as an exception. + +-.. cfunction:: PyObject* PyCodec_IgnoreErrors(PyObject *exc) ++.. c:function:: PyObject* PyCodec_IgnoreErrors(PyObject *exc) + + Ignore the unicode error, skipping the faulty input. + +-.. cfunction:: PyObject* PyCodec_ReplaceErrors(PyObject *exc) ++.. c:function:: PyObject* PyCodec_ReplaceErrors(PyObject *exc) + + Replace the unicode encode error with ``?`` or ``U+FFFD``. + +-.. cfunction:: PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc) ++.. c:function:: PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc) + + Replace the unicode encode error with XML character references. + +-.. cfunction:: PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc) ++.. c:function:: PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc) + + Replace the unicode encode error with backslash escapes (``\x``, ``\u`` and + ``\U``). +diff -r 8527427914a2 Doc/c-api/complex.rst +--- a/Doc/c-api/complex.rst ++++ b/Doc/c-api/complex.rst +@@ -21,7 +21,7 @@ + pointers. This is consistent throughout the API. + + +-.. ctype:: Py_complex ++.. c:type:: Py_complex + + The C structure which corresponds to the value portion of a Python complex + number object. Most of the functions for dealing with complex number objects +@@ -34,97 +34,104 @@ + } Py_complex; + + +-.. cfunction:: Py_complex _Py_c_sum(Py_complex left, Py_complex right) ++.. c:function:: Py_complex _Py_c_sum(Py_complex left, Py_complex right) + +- Return the sum of two complex numbers, using the C :ctype:`Py_complex` ++ Return the sum of two complex numbers, using the C :c:type:`Py_complex` + representation. + + +-.. cfunction:: Py_complex _Py_c_diff(Py_complex left, Py_complex right) ++.. c:function:: Py_complex _Py_c_diff(Py_complex left, Py_complex right) + + Return the difference between two complex numbers, using the C +- :ctype:`Py_complex` representation. ++ :c:type:`Py_complex` representation. + + +-.. cfunction:: Py_complex _Py_c_neg(Py_complex complex) ++.. c:function:: Py_complex _Py_c_neg(Py_complex complex) + + Return the negation of the complex number *complex*, using the C +- :ctype:`Py_complex` representation. ++ :c:type:`Py_complex` representation. + + +-.. cfunction:: Py_complex _Py_c_prod(Py_complex left, Py_complex right) ++.. c:function:: Py_complex _Py_c_prod(Py_complex left, Py_complex right) + +- Return the product of two complex numbers, using the C :ctype:`Py_complex` ++ Return the product of two complex numbers, using the C :c:type:`Py_complex` + representation. + + +-.. cfunction:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor) ++.. c:function:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor) + +- Return the quotient of two complex numbers, using the C :ctype:`Py_complex` ++ 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`. + +-.. cfunction:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp) + +- Return the exponentiation of *num* by *exp*, using the C :ctype:`Py_complex` ++.. 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 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + +-.. ctype:: PyComplexObject ++.. c:type:: PyComplexObject + +- This subtype of :ctype:`PyObject` represents a Python complex number object. ++ This subtype of :c:type:`PyObject` represents a Python complex number object. + + +-.. cvar:: PyTypeObject PyComplex_Type ++.. c:var:: PyTypeObject PyComplex_Type + +- This instance of :ctype:`PyTypeObject` represents the Python complex number ++ This instance of :c:type:`PyTypeObject` represents the Python complex number + type. It is the same object as ``complex`` and ``types.ComplexType``. + + +-.. cfunction:: int PyComplex_Check(PyObject *p) ++.. c:function:: int PyComplex_Check(PyObject *p) + +- Return true if its argument is a :ctype:`PyComplexObject` or a subtype of +- :ctype:`PyComplexObject`. ++ Return true if its argument is a :c:type:`PyComplexObject` or a subtype of ++ :c:type:`PyComplexObject`. + + .. versionchanged:: 2.2 + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyComplex_CheckExact(PyObject *p) ++.. c:function:: int PyComplex_CheckExact(PyObject *p) + +- Return true if its argument is a :ctype:`PyComplexObject`, but not a subtype of +- :ctype:`PyComplexObject`. ++ Return true if its argument is a :c:type:`PyComplexObject`, but not a subtype of ++ :c:type:`PyComplexObject`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyComplex_FromCComplex(Py_complex v) ++.. c:function:: PyObject* PyComplex_FromCComplex(Py_complex v) + +- Create a new Python complex number object from a C :ctype:`Py_complex` value. ++ Create a new Python complex number object from a C :c:type:`Py_complex` value. + + +-.. cfunction:: PyObject* PyComplex_FromDoubles(double real, double imag) ++.. c:function:: PyObject* PyComplex_FromDoubles(double real, double imag) + +- Return a new :ctype:`PyComplexObject` object from *real* and *imag*. ++ Return a new :c:type:`PyComplexObject` object from *real* and *imag*. + + +-.. cfunction:: double PyComplex_RealAsDouble(PyObject *op) ++.. c:function:: double PyComplex_RealAsDouble(PyObject *op) + +- Return the real part of *op* as a C :ctype:`double`. ++ Return the real part of *op* as a C :c:type:`double`. + + +-.. cfunction:: double PyComplex_ImagAsDouble(PyObject *op) ++.. c:function:: double PyComplex_ImagAsDouble(PyObject *op) + +- Return the imaginary part of *op* as a C :ctype:`double`. ++ Return the imaginary part of *op* as a C :c:type:`double`. + + +-.. cfunction:: Py_complex PyComplex_AsCComplex(PyObject *op) ++.. c:function:: Py_complex PyComplex_AsCComplex(PyObject *op) + +- Return the :ctype:`Py_complex` value of the complex number *op*. ++ Return the :c:type:`Py_complex` value of the complex number *op*. ++ Upon failure, this method returns ``-1.0`` as a real value. + + .. versionchanged:: 2.6 + If *op* is not a Python complex number object but has a :meth:`__complex__` +diff -r 8527427914a2 Doc/c-api/concrete.rst +--- a/Doc/c-api/concrete.rst ++++ b/Doc/c-api/concrete.rst +@@ -11,7 +11,7 @@ + Passing them an object of the wrong type is not a good idea; if you receive an + object from a Python program and you are not sure that it has the right type, + you must perform a type check first; for example, to check that an object is a +-dictionary, use :cfunc:`PyDict_Check`. The chapter is structured like the ++dictionary, use :c:func:`PyDict_Check`. The chapter is structured like the + "family tree" of Python object types. + + .. warning:: +diff -r 8527427914a2 Doc/c-api/conversion.rst +--- a/Doc/c-api/conversion.rst ++++ b/Doc/c-api/conversion.rst +@@ -8,20 +8,20 @@ + Functions for number conversion and formatted string output. + + +-.. cfunction:: int PyOS_snprintf(char *str, size_t size, const char *format, ...) ++.. c:function:: int PyOS_snprintf(char *str, size_t size, const char *format, ...) + + Output not more than *size* bytes to *str* according to the format string + *format* and the extra arguments. See the Unix man page :manpage:`snprintf(2)`. + + +-.. cfunction:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) ++.. c:function:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) + + Output not more than *size* bytes to *str* according to the format string + *format* and the variable argument list *va*. Unix man page + :manpage:`vsnprintf(2)`. + +-:cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` wrap the Standard C library +-functions :cfunc:`snprintf` and :cfunc:`vsnprintf`. Their purpose is to ++:c:func:`PyOS_snprintf` and :c:func:`PyOS_vsnprintf` wrap the Standard C library ++functions :c:func:`snprintf` and :c:func:`vsnprintf`. Their purpose is to + guarantee consistent behavior in corner cases, which the Standard C functions do + not. + +@@ -30,7 +30,7 @@ + Both functions require that ``str != NULL``, ``size > 0`` and ``format != + NULL``. + +-If the platform doesn't have :cfunc:`vsnprintf` and the buffer size needed to ++If the platform doesn't have :c:func:`vsnprintf` and the buffer size needed to + avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a + *Py_FatalError*. + +@@ -51,9 +51,9 @@ + The following functions provide locale-independent string to number conversions. + + +-.. cfunction:: double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) ++.. c:function:: double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) + +- Convert a string ``s`` to a :ctype:`double`, raising a Python ++ Convert a string ``s`` to a :c:type:`double`, raising a Python + exception on failure. The set of accepted strings corresponds to + the set of strings accepted by Python's :func:`float` constructor, + except that ``s`` must not have leading or trailing whitespace. +@@ -85,13 +85,13 @@ + .. versionadded:: 2.7 + + +-.. cfunction:: double PyOS_ascii_strtod(const char *nptr, char **endptr) ++.. c:function:: double PyOS_ascii_strtod(const char *nptr, char **endptr) + +- Convert a string to a :ctype:`double`. This function behaves like the Standard C +- function :cfunc:`strtod` does in the C locale. It does this without changing the ++ Convert a string to a :c:type:`double`. This function behaves like the Standard C ++ function :c:func:`strtod` does in the C locale. It does this without changing the + current locale, since that would not be thread-safe. + +- :cfunc:`PyOS_ascii_strtod` should typically be used for reading configuration ++ :c:func:`PyOS_ascii_strtod` should typically be used for reading configuration + files or other non-user input that should be locale independent. + + See the Unix man page :manpage:`strtod(2)` for details. +@@ -99,14 +99,14 @@ + .. versionadded:: 2.4 + + .. deprecated:: 2.7 +- Use :cfunc:`PyOS_string_to_double` instead. ++ Use :c:func:`PyOS_string_to_double` instead. + + + +-.. cfunction:: char* PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d) ++.. c:function:: char* PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d) + +- Convert a :ctype:`double` to a string using the ``'.'`` as the decimal +- separator. *format* is a :cfunc:`printf`\ -style format string specifying the ++ Convert a :c:type:`double` to a string using the ``'.'`` as the decimal ++ separator. *format* is a :c:func:`printf`\ -style format string specifying the + number format. Allowed conversion characters are ``'e'``, ``'E'``, ``'f'``, + ``'F'``, ``'g'`` and ``'G'``. + +@@ -119,9 +119,9 @@ + instead. + + +-.. cfunction:: char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype) ++.. c:function:: char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype) + +- Convert a :ctype:`double` *val* to a string using supplied ++ Convert a :c:type:`double` *val* to a string using supplied + *format_code*, *precision*, and *flags*. + + *format_code* must be one of ``'e'``, ``'E'``, ``'f'``, ``'F'``, +@@ -139,7 +139,7 @@ + like an integer. + + * *Py_DTSF_ALT* means to apply "alternate" formatting rules. See the +- documentation for the :cfunc:`PyOS_snprintf` ``'#'`` specifier for ++ documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for + details. + + If *ptype* is non-NULL, then the value it points to will be set to one of +@@ -148,34 +148,34 @@ + + The return value is a pointer to *buffer* with the converted string or + *NULL* if the conversion failed. The caller is responsible for freeing the +- returned string by calling :cfunc:`PyMem_Free`. ++ returned string by calling :c:func:`PyMem_Free`. + + .. versionadded:: 2.7 + + +-.. cfunction:: double PyOS_ascii_atof(const char *nptr) ++.. c:function:: double PyOS_ascii_atof(const char *nptr) + +- Convert a string to a :ctype:`double` in a locale-independent way. ++ Convert a string to a :c:type:`double` in a locale-independent way. + + See the Unix man page :manpage:`atof(2)` for details. + + .. versionadded:: 2.4 + + .. deprecated:: 3.1 +- Use :cfunc:`PyOS_string_to_double` instead. ++ Use :c:func:`PyOS_string_to_double` instead. + + +-.. cfunction:: char* PyOS_stricmp(char *s1, char *s2) ++.. c:function:: char* PyOS_stricmp(char *s1, char *s2) + + Case insensitive comparison of strings. The function works almost +- identically to :cfunc:`strcmp` except that it ignores the case. ++ identically to :c:func:`strcmp` except that it ignores the case. + + .. versionadded:: 2.6 + + +-.. cfunction:: char* PyOS_strnicmp(char *s1, char *s2, Py_ssize_t size) ++.. c:function:: char* PyOS_strnicmp(char *s1, char *s2, Py_ssize_t size) + + Case insensitive comparison of strings. The function works almost +- identically to :cfunc:`strncmp` except that it ignores the case. ++ identically to :c:func:`strncmp` except that it ignores the case. + + .. versionadded:: 2.6 +diff -r 8527427914a2 Doc/c-api/datetime.rst +--- a/Doc/c-api/datetime.rst ++++ b/Doc/c-api/datetime.rst +@@ -8,89 +8,89 @@ + Various date and time objects are supplied by the :mod:`datetime` module. + Before using any of these functions, the header file :file:`datetime.h` must be + included in your source (note that this is not included by :file:`Python.h`), +-and the macro :cmacro:`PyDateTime_IMPORT` must be invoked, usually as part of ++and the macro :c:macro:`PyDateTime_IMPORT` must be invoked, usually as part of + the module initialisation function. The macro puts a pointer to a C structure +-into a static variable, :cdata:`PyDateTimeAPI`, that is used by the following ++into a static variable, :c:data:`PyDateTimeAPI`, that is used by the following + macros. + + Type-check macros: + + +-.. cfunction:: int PyDate_Check(PyObject *ob) ++.. c:function:: int PyDate_Check(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_DateType` or a subtype of +- :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*. ++ Return true if *ob* is of type :c:data:`PyDateTime_DateType` or a subtype of ++ :c:data:`PyDateTime_DateType`. *ob* must not be *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDate_CheckExact(PyObject *ob) ++.. c:function:: int PyDate_CheckExact(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_DateType`. *ob* must not be ++ Return true if *ob* is of type :c:data:`PyDateTime_DateType`. *ob* must not be + *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_Check(PyObject *ob) ++.. c:function:: int PyDateTime_Check(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType` or a subtype of +- :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. ++ Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType` or a subtype of ++ :c:data:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_CheckExact(PyObject *ob) ++.. c:function:: int PyDateTime_CheckExact(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType`. *ob* must not ++ Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType`. *ob* must not + be *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyTime_Check(PyObject *ob) ++.. c:function:: int PyTime_Check(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_TimeType` or a subtype of +- :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*. ++ Return true if *ob* is of type :c:data:`PyDateTime_TimeType` or a subtype of ++ :c:data:`PyDateTime_TimeType`. *ob* must not be *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyTime_CheckExact(PyObject *ob) ++.. c:function:: int PyTime_CheckExact(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_TimeType`. *ob* must not be ++ Return true if *ob* is of type :c:data:`PyDateTime_TimeType`. *ob* must not be + *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDelta_Check(PyObject *ob) ++.. c:function:: int PyDelta_Check(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_DeltaType` or a subtype of +- :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*. ++ Return true if *ob* is of type :c:data:`PyDateTime_DeltaType` or a subtype of ++ :c:data:`PyDateTime_DeltaType`. *ob* must not be *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDelta_CheckExact(PyObject *ob) ++.. c:function:: int PyDelta_CheckExact(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_DeltaType`. *ob* must not be ++ Return true if *ob* is of type :c:data:`PyDateTime_DeltaType`. *ob* must not be + *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyTZInfo_Check(PyObject *ob) ++.. c:function:: int PyTZInfo_Check(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType` or a subtype of +- :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. ++ Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType` or a subtype of ++ :c:data:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyTZInfo_CheckExact(PyObject *ob) ++.. c:function:: int PyTZInfo_CheckExact(PyObject *ob) + +- Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType`. *ob* must not be ++ Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType`. *ob* must not be + *NULL*. + + .. versionadded:: 2.4 +@@ -98,14 +98,14 @@ + Macros to create objects: + + +-.. cfunction:: PyObject* PyDate_FromDate(int year, int month, int day) ++.. c:function:: PyObject* PyDate_FromDate(int year, int month, int day) + + Return a ``datetime.date`` object with the specified year, month and day. + + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond) ++.. c:function:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond) + + Return a ``datetime.datetime`` object with the specified year, month, day, hour, + minute, second and microsecond. +@@ -113,7 +113,7 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond) ++.. c:function:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond) + + Return a ``datetime.time`` object with the specified hour, minute, second and + microsecond. +@@ -121,7 +121,7 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds) ++.. c:function:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds) + + Return a ``datetime.timedelta`` object representing the given number of days, + seconds and microseconds. Normalization is performed so that the resulting +@@ -131,90 +131,90 @@ + .. versionadded:: 2.4 + + Macros to extract fields from date objects. The argument must be an instance of +-:cdata:`PyDateTime_Date`, including subclasses (such as +-:cdata:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is ++:c:data:`PyDateTime_Date`, including subclasses (such as ++:c:data:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is + not checked: + + +-.. cfunction:: int PyDateTime_GET_YEAR(PyDateTime_Date *o) ++.. c:function:: int PyDateTime_GET_YEAR(PyDateTime_Date *o) + + Return the year, as a positive int. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_GET_MONTH(PyDateTime_Date *o) ++.. c:function:: int PyDateTime_GET_MONTH(PyDateTime_Date *o) + + Return the month, as an int from 1 through 12. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_GET_DAY(PyDateTime_Date *o) ++.. c:function:: int PyDateTime_GET_DAY(PyDateTime_Date *o) + + Return the day, as an int from 1 through 31. + + .. versionadded:: 2.4 + + Macros to extract fields from datetime objects. The argument must be an +-instance of :cdata:`PyDateTime_DateTime`, including subclasses. The argument ++instance of :c:data:`PyDateTime_DateTime`, including subclasses. The argument + must not be *NULL*, and the type is not checked: + + +-.. cfunction:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o) ++.. c:function:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o) + + Return the hour, as an int from 0 through 23. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o) ++.. c:function:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o) + + Return the minute, as an int from 0 through 59. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o) ++.. c:function:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o) + + Return the second, as an int from 0 through 59. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o) ++.. c:function:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o) + + Return the microsecond, as an int from 0 through 999999. + + .. versionadded:: 2.4 + + Macros to extract fields from time objects. The argument must be an instance of +-:cdata:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*, ++:c:data:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*, + and the type is not checked: + + +-.. cfunction:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o) ++.. c:function:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o) + + Return the hour, as an int from 0 through 23. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o) ++.. c:function:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o) + + Return the minute, as an int from 0 through 59. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o) ++.. c:function:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o) + + Return the second, as an int from 0 through 59. + + .. versionadded:: 2.4 + + +-.. cfunction:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o) ++.. c:function:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o) + + Return the microsecond, as an int from 0 through 999999. + +@@ -223,7 +223,7 @@ + Macros for the convenience of modules implementing the DB API: + + +-.. cfunction:: PyObject* PyDateTime_FromTimestamp(PyObject *args) ++.. c:function:: PyObject* PyDateTime_FromTimestamp(PyObject *args) + + Create and return a new ``datetime.datetime`` object given an argument tuple + suitable for passing to ``datetime.datetime.fromtimestamp()``. +@@ -231,7 +231,7 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyDate_FromTimestamp(PyObject *args) ++.. c:function:: PyObject* PyDate_FromTimestamp(PyObject *args) + + Create and return a new ``datetime.date`` object given an argument tuple + suitable for passing to ``datetime.date.fromtimestamp()``. +diff -r 8527427914a2 Doc/c-api/descriptor.rst +--- a/Doc/c-api/descriptor.rst ++++ b/Doc/c-api/descriptor.rst +@@ -9,39 +9,39 @@ + found in the dictionary of type objects. + + +-.. cvar:: PyTypeObject PyProperty_Type ++.. c:var:: PyTypeObject PyProperty_Type + + The type object for the built-in descriptor types. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset) ++.. c:function:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset) + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth) ++.. c:function:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth) + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth) ++.. c:function:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth) + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped) ++.. c:function:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped) + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) ++.. c:function:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) + + .. versionadded:: 2.3 + + +-.. cfunction:: int PyDescr_IsData(PyObject *descr) ++.. c:function:: int PyDescr_IsData(PyObject *descr) + + Return true if the descriptor objects *descr* describes a data attribute, or + false if it describes a method. *descr* must be a descriptor object; there is +@@ -50,6 +50,6 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *) ++.. c:function:: PyObject* PyWrapper_New(PyObject *, PyObject *) + + .. versionadded:: 2.2 +diff -r 8527427914a2 Doc/c-api/dict.rst +--- a/Doc/c-api/dict.rst ++++ b/Doc/c-api/dict.rst +@@ -8,23 +8,23 @@ + .. index:: object: dictionary + + +-.. ctype:: PyDictObject ++.. c:type:: PyDictObject + +- This subtype of :ctype:`PyObject` represents a Python dictionary object. ++ This subtype of :c:type:`PyObject` represents a Python dictionary object. + + +-.. cvar:: PyTypeObject PyDict_Type ++.. c:var:: PyTypeObject PyDict_Type + + .. index:: + single: DictType (in module types) + single: DictionaryType (in module types) + +- This instance of :ctype:`PyTypeObject` represents the Python dictionary ++ This instance of :c:type:`PyTypeObject` represents the Python dictionary + type. This is exposed to Python programs as ``dict`` and + ``types.DictType``. + + +-.. cfunction:: int PyDict_Check(PyObject *p) ++.. c:function:: int PyDict_Check(PyObject *p) + + Return true if *p* is a dict object or an instance of a subtype of the dict + type. +@@ -33,7 +33,7 @@ + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyDict_CheckExact(PyObject *p) ++.. c:function:: int PyDict_CheckExact(PyObject *p) + + Return true if *p* is a dict object, but not an instance of a subtype of + the dict type. +@@ -41,12 +41,12 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyDict_New() ++.. c:function:: PyObject* PyDict_New() + + Return a new empty dictionary, or *NULL* on failure. + + +-.. cfunction:: PyObject* PyDictProxy_New(PyObject *dict) ++.. c:function:: PyObject* PyDictProxy_New(PyObject *dict) + + Return a proxy object for a mapping which enforces read-only behavior. + This is normally used to create a proxy to prevent modification of the +@@ -55,12 +55,12 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: void PyDict_Clear(PyObject *p) ++.. c:function:: void PyDict_Clear(PyObject *p) + + Empty an existing dictionary of all key-value pairs. + + +-.. cfunction:: int PyDict_Contains(PyObject *p, PyObject *key) ++.. c:function:: int PyDict_Contains(PyObject *p, PyObject *key) + + Determine if dictionary *p* contains *key*. If an item in *p* is matches + *key*, return ``1``, otherwise return ``0``. On error, return ``-1``. +@@ -69,74 +69,74 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PyDict_Copy(PyObject *p) ++.. c:function:: PyObject* PyDict_Copy(PyObject *p) + + Return a new dictionary that contains the same key-value pairs as *p*. + + .. versionadded:: 1.6 + + +-.. cfunction:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val) ++.. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val) + + Insert *value* into the dictionary *p* with a key of *key*. *key* must be + :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return + ``0`` on success or ``-1`` on failure. + + +-.. cfunction:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val) ++.. c:function:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val) + + .. index:: single: PyString_FromString() + + Insert *value* into the dictionary *p* using *key* as a key. *key* should +- be a :ctype:`char\*`. The key object is created using ++ be a :c:type:`char\*`. The key object is created using + ``PyString_FromString(key)``. Return ``0`` on success or ``-1`` on + failure. + + +-.. cfunction:: int PyDict_DelItem(PyObject *p, PyObject *key) ++.. c:function:: int PyDict_DelItem(PyObject *p, PyObject *key) + + Remove the entry in dictionary *p* with key *key*. *key* must be hashable; + if it isn't, :exc:`TypeError` is raised. Return ``0`` on success or ``-1`` + on failure. + + +-.. cfunction:: int PyDict_DelItemString(PyObject *p, char *key) ++.. c:function:: int PyDict_DelItemString(PyObject *p, char *key) + + Remove the entry in dictionary *p* which has a key specified by the string + *key*. Return ``0`` on success or ``-1`` on failure. + + +-.. cfunction:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key) ++.. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key) + + Return the object from dictionary *p* which has a key *key*. Return *NULL* + if the key *key* is not present, but *without* setting an exception. + + +-.. cfunction:: PyObject* PyDict_GetItemString(PyObject *p, const char *key) ++.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key) + +- This is the same as :cfunc:`PyDict_GetItem`, but *key* is specified as a +- :ctype:`char\*`, rather than a :ctype:`PyObject\*`. ++ This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a ++ :c:type:`char\*`, rather than a :c:type:`PyObject\*`. + + +-.. cfunction:: PyObject* PyDict_Items(PyObject *p) ++.. c:function:: PyObject* PyDict_Items(PyObject *p) + +- Return a :ctype:`PyListObject` containing all the items from the ++ Return a :c:type:`PyListObject` containing all the items from the + dictionary, as in the dictionary method :meth:`dict.items`. + + +-.. cfunction:: PyObject* PyDict_Keys(PyObject *p) ++.. c:function:: PyObject* PyDict_Keys(PyObject *p) + +- Return a :ctype:`PyListObject` containing all the keys from the dictionary, ++ Return a :c:type:`PyListObject` containing all the keys from the dictionary, + as in the dictionary method :meth:`dict.keys`. + + +-.. cfunction:: PyObject* PyDict_Values(PyObject *p) ++.. c:function:: PyObject* PyDict_Values(PyObject *p) + +- Return a :ctype:`PyListObject` containing all the values from the ++ Return a :c:type:`PyListObject` containing all the values from the + dictionary *p*, as in the dictionary method :meth:`dict.values`. + + +-.. cfunction:: Py_ssize_t PyDict_Size(PyObject *p) ++.. c:function:: Py_ssize_t PyDict_Size(PyObject *p) + + .. index:: builtin: len + +@@ -144,18 +144,18 @@ + ``len(p)`` on a dictionary. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) ++.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) + + Iterate over all key-value pairs in the dictionary *p*. The +- :ctype:`Py_ssize_t` referred to by *ppos* must be initialized to ``0`` ++ :c:type:`Py_ssize_t` referred to by *ppos* must be initialized to ``0`` + prior to the first call to this function to start the iteration; the + function returns true for each pair in the dictionary, and false once all + pairs have been reported. The parameters *pkey* and *pvalue* should either +- point to :ctype:`PyObject\*` variables that will be filled in with each key ++ point to :c:type:`PyObject\*` variables that will be filled in with each key + and value, respectively, or may be *NULL*. Any references returned through + them are borrowed. *ppos* should not be altered during iteration. Its + value represents offsets within the internal dictionary structure, and +@@ -192,15 +192,15 @@ + } + + .. versionchanged:: 2.5 +- This function used an :ctype:`int *` type for *ppos*. This might require ++ This function used an :c:type:`int *` type for *ppos*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyDict_Merge(PyObject *a, PyObject *b, int override) ++.. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override) + + Iterate over mapping object *b* adding key-value pairs to dictionary *a*. +- *b* may be a dictionary, or any object supporting :cfunc:`PyMapping_Keys` +- and :cfunc:`PyObject_GetItem`. If *override* is true, existing pairs in *a* ++ *b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys` ++ and :c:func:`PyObject_GetItem`. If *override* is true, existing pairs in *a* + will be replaced if a matching key is found in *b*, otherwise pairs will + only be added if there is not a matching key in *a*. Return ``0`` on + success or ``-1`` if an exception was raised. +@@ -208,7 +208,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: int PyDict_Update(PyObject *a, PyObject *b) ++.. c:function:: int PyDict_Update(PyObject *a, PyObject *b) + + This is the same as ``PyDict_Merge(a, b, 1)`` in C, or ``a.update(b)`` in + Python. Return ``0`` on success or ``-1`` if an exception was raised. +@@ -216,7 +216,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override) ++.. c:function:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override) + + Update or merge into dictionary *a*, from the key-value pairs in *seq2*. + *seq2* must be an iterable object producing iterable objects of length 2, +diff -r 8527427914a2 Doc/c-api/exceptions.rst +--- a/Doc/c-api/exceptions.rst ++++ b/Doc/c-api/exceptions.rst +@@ -9,12 +9,12 @@ + + The functions described in this chapter will let you handle and raise Python + exceptions. It is important to understand some of the basics of Python +-exception handling. It works somewhat like the Unix :cdata:`errno` variable: ++exception handling. It works somewhat like the Unix :c:data:`errno` variable: + there is a global indicator (per thread) of the last error that occurred. Most + functions don't clear this on success, but will set it to indicate the cause of + the error on failure. Most functions also return an error indicator, usually + *NULL* if they are supposed to return a pointer, or ``-1`` if they return an +-integer (exception: the :cfunc:`PyArg_\*` functions return ``1`` for success and ++integer (exception: the :c:func:`PyArg_\*` functions return ``1`` for success and + ``0`` for failure). + + When a function must fail because some function it called failed, it generally +@@ -41,7 +41,7 @@ + Either alphabetical or some kind of structure. + + +-.. cfunction:: void PyErr_PrintEx(int set_sys_last_vars) ++.. c:function:: void PyErr_PrintEx(int set_sys_last_vars) + + Print a standard traceback to ``sys.stderr`` and clear the error indicator. + Call this function only when the error indicator is set. (Otherwise it will +@@ -52,35 +52,35 @@ + type, value and traceback of the printed exception, respectively. + + +-.. cfunction:: void PyErr_Print() ++.. c:function:: void PyErr_Print() + + Alias for ``PyErr_PrintEx(1)``. + + +-.. cfunction:: PyObject* PyErr_Occurred() ++.. c:function:: PyObject* PyErr_Occurred() + + Test whether the error indicator is set. If set, return the exception *type* +- (the first argument to the last call to one of the :cfunc:`PyErr_Set\*` +- functions or to :cfunc:`PyErr_Restore`). If not set, return *NULL*. You do not +- own a reference to the return value, so you do not need to :cfunc:`Py_DECREF` ++ (the first argument to the last call to one of the :c:func:`PyErr_Set\*` ++ functions or to :c:func:`PyErr_Restore`). If not set, return *NULL*. You do not ++ own a reference to the return value, so you do not need to :c:func:`Py_DECREF` + it. + + .. note:: + + Do not compare the return value to a specific exception; use +- :cfunc:`PyErr_ExceptionMatches` instead, shown below. (The comparison could ++ :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could + easily fail since the exception may be an instance instead of a class, in the + case of a class exception, or it may the a subclass of the expected exception.) + + +-.. cfunction:: int PyErr_ExceptionMatches(PyObject *exc) ++.. c:function:: int PyErr_ExceptionMatches(PyObject *exc) + + Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This + should only be called when an exception is actually set; a memory access + violation will occur if no exception has been raised. + + +-.. cfunction:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) ++.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) + + Return true if the *given* exception matches the exception in *exc*. If + *exc* is a class object, this also returns true when *given* is an instance +@@ -88,22 +88,22 @@ + recursively in subtuples) are searched for a match. + + +-.. cfunction:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb) ++.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb) + +- Under certain circumstances, the values returned by :cfunc:`PyErr_Fetch` below ++ Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below + can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is + not an instance of the same class. This function can be used to instantiate + the class in that case. If the values are already normalized, nothing happens. + The delayed normalization is implemented to improve performance. + + +-.. cfunction:: void PyErr_Clear() ++.. c:function:: void PyErr_Clear() + + Clear the error indicator. If the error indicator is not set, there is no + effect. + + +-.. cfunction:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) ++.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) + + Retrieve the error indicator into three variables whose addresses are passed. + If the error indicator is not set, set all three variables to *NULL*. If it is +@@ -116,7 +116,7 @@ + by code that needs to save and restore the error indicator temporarily. + + +-.. cfunction:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) ++.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) + + Set the error indicator from the three objects. If the error indicator is + already set, it is cleared first. If the objects are *NULL*, the error +@@ -131,111 +131,111 @@ + .. note:: + + This function is normally only used by code that needs to save and restore the +- error indicator temporarily; use :cfunc:`PyErr_Fetch` to save the current ++ error indicator temporarily; use :c:func:`PyErr_Fetch` to save the current + exception state. + + +-.. cfunction:: void PyErr_SetString(PyObject *type, const char *message) ++.. c:function:: void PyErr_SetString(PyObject *type, const char *message) + + This is the most common way to set the error indicator. The first argument + specifies the exception type; it is normally one of the standard exceptions, +- e.g. :cdata:`PyExc_RuntimeError`. You need not increment its reference count. ++ e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count. + The second argument is an error message; it is converted to a string object. + + +-.. cfunction:: void PyErr_SetObject(PyObject *type, PyObject *value) ++.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value) + +- This function is similar to :cfunc:`PyErr_SetString` but lets you specify an ++ This function is similar to :c:func:`PyErr_SetString` but lets you specify an + arbitrary Python object for the "value" of the exception. + + +-.. cfunction:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...) ++.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...) + + This function sets the error indicator and returns *NULL*. *exception* + should be a Python exception class. The *format* and subsequent + parameters help format the error message; they have the same meaning and +- values as in :cfunc:`PyString_FromFormat`. ++ values as in :c:func:`PyString_FromFormat`. + + +-.. cfunction:: void PyErr_SetNone(PyObject *type) ++.. c:function:: void PyErr_SetNone(PyObject *type) + + This is a shorthand for ``PyErr_SetObject(type, Py_None)``. + + +-.. cfunction:: int PyErr_BadArgument() ++.. c:function:: int PyErr_BadArgument() + + This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where + *message* indicates that a built-in operation was invoked with an illegal + argument. It is mostly for internal use. + + +-.. cfunction:: PyObject* PyErr_NoMemory() ++.. c:function:: PyObject* PyErr_NoMemory() + + This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL* + so an object allocation function can write ``return PyErr_NoMemory();`` when it + runs out of memory. + + +-.. cfunction:: PyObject* PyErr_SetFromErrno(PyObject *type) ++.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type) + + .. index:: single: strerror() + + This is a convenience function to raise an exception when a C library function +- has returned an error and set the C variable :cdata:`errno`. It constructs a +- tuple object whose first item is the integer :cdata:`errno` value and whose +- second item is the corresponding error message (gotten from :cfunc:`strerror`), ++ has returned an error and set the C variable :c:data:`errno`. It constructs a ++ tuple object whose first item is the integer :c:data:`errno` value and whose ++ second item is the corresponding error message (gotten from :c:func:`strerror`), + and then calls ``PyErr_SetObject(type, object)``. On Unix, when the +- :cdata:`errno` value is :const:`EINTR`, indicating an interrupted system call, +- this calls :cfunc:`PyErr_CheckSignals`, and if that set the error indicator, ++ :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call, ++ this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator, + leaves it set to that. The function always returns *NULL*, so a wrapper + function around a system call can write ``return PyErr_SetFromErrno(type);`` + when the system call returns an error. + + +-.. cfunction:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) ++.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) + +- Similar to :cfunc:`PyErr_SetFromErrno`, with the additional behavior that if ++ Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if + *filename* is not *NULL*, it is passed to the constructor of *type* as a third + parameter. In the case of exceptions such as :exc:`IOError` and :exc:`OSError`, + this is used to define the :attr:`filename` attribute of the exception instance. + + +-.. cfunction:: PyObject* PyErr_SetFromWindowsErr(int ierr) ++.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr) + + This is a convenience function to raise :exc:`WindowsError`. If called with +- *ierr* of :cdata:`0`, the error code returned by a call to :cfunc:`GetLastError` +- is used instead. It calls the Win32 function :cfunc:`FormatMessage` to retrieve +- the Windows description of error code given by *ierr* or :cfunc:`GetLastError`, ++ *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError` ++ is used instead. It calls the Win32 function :c:func:`FormatMessage` to retrieve ++ the Windows description of error code given by *ierr* or :c:func:`GetLastError`, + then it constructs a tuple object whose first item is the *ierr* value and whose + second item is the corresponding error message (gotten from +- :cfunc:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError, ++ :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError, + object)``. This function always returns *NULL*. Availability: Windows. + + +-.. cfunction:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr) ++.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr) + +- Similar to :cfunc:`PyErr_SetFromWindowsErr`, with an additional parameter ++ Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter + specifying the exception type to be raised. Availability: Windows. + + .. versionadded:: 2.3 + + +-.. cfunction:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) ++.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) + +- Similar to :cfunc:`PyErr_SetFromWindowsErr`, with the additional behavior that ++ Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior that + if *filename* is not *NULL*, it is passed to the constructor of + :exc:`WindowsError` as a third parameter. Availability: Windows. + + +-.. cfunction:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, char *filename) ++.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, char *filename) + +- Similar to :cfunc:`PyErr_SetFromWindowsErrWithFilename`, with an additional ++ Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional + parameter specifying the exception type to be raised. Availability: Windows. + + .. versionadded:: 2.3 + + +-.. cfunction:: void PyErr_BadInternalCall() ++.. c:function:: void PyErr_BadInternalCall() + + This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``, + where *message* indicates that an internal operation (e.g. a Python/C API +@@ -243,13 +243,13 @@ + use. + + +-.. cfunction:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel) ++.. c:function:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel) + + Issue a warning message. The *category* argument is a warning category (see + below) or *NULL*; the *message* argument is a message string. *stacklevel* is a + positive number giving a number of stack frames; the warning will be issued from + the currently executing line of code in that stack frame. A *stacklevel* of 1 +- is the function calling :cfunc:`PyErr_WarnEx`, 2 is the function above that, ++ is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, + and so forth. + + This function normally prints a warning message to *sys.stderr*; however, it is +@@ -261,36 +261,36 @@ + is raised. (It is not possible to determine whether a warning message is + actually printed, nor what the reason is for the exception; this is + intentional.) If an exception is raised, the caller should do its normal +- exception handling (for example, :cfunc:`Py_DECREF` owned references and return ++ exception handling (for example, :c:func:`Py_DECREF` owned references and return + an error value). + +- Warning categories must be subclasses of :cdata:`Warning`; the default warning +- category is :cdata:`RuntimeWarning`. The standard Python warning categories are ++ Warning categories must be subclasses of :c:data:`Warning`; the default warning ++ category is :c:data:`RuntimeWarning`. The standard Python warning categories are + available as global variables whose names are ``PyExc_`` followed by the Python +- exception name. These have the type :ctype:`PyObject\*`; they are all class +- objects. Their names are :cdata:`PyExc_Warning`, :cdata:`PyExc_UserWarning`, +- :cdata:`PyExc_UnicodeWarning`, :cdata:`PyExc_DeprecationWarning`, +- :cdata:`PyExc_SyntaxWarning`, :cdata:`PyExc_RuntimeWarning`, and +- :cdata:`PyExc_FutureWarning`. :cdata:`PyExc_Warning` is a subclass of +- :cdata:`PyExc_Exception`; the other warning categories are subclasses of +- :cdata:`PyExc_Warning`. ++ exception name. These have the type :c:type:`PyObject\*`; they are all class ++ objects. Their names are :c:data:`PyExc_Warning`, :c:data:`PyExc_UserWarning`, ++ :c:data:`PyExc_UnicodeWarning`, :c:data:`PyExc_DeprecationWarning`, ++ :c:data:`PyExc_SyntaxWarning`, :c:data:`PyExc_RuntimeWarning`, and ++ :c:data:`PyExc_FutureWarning`. :c:data:`PyExc_Warning` is a subclass of ++ :c:data:`PyExc_Exception`; the other warning categories are subclasses of ++ :c:data:`PyExc_Warning`. + + For information about warning control, see the documentation for the + :mod:`warnings` module and the :option:`-W` option in the command line + documentation. There is no C API for warning control. + + +-.. cfunction:: int PyErr_Warn(PyObject *category, char *message) ++.. c:function:: int PyErr_Warn(PyObject *category, char *message) + + Issue a warning message. The *category* argument is a warning category (see + below) or *NULL*; the *message* argument is a message string. The warning will +- appear to be issued from the function calling :cfunc:`PyErr_Warn`, equivalent to +- calling :cfunc:`PyErr_WarnEx` with a *stacklevel* of 1. ++ appear to be issued from the function calling :c:func:`PyErr_Warn`, equivalent to ++ calling :c:func:`PyErr_WarnEx` with a *stacklevel* of 1. + +- Deprecated; use :cfunc:`PyErr_WarnEx` instead. ++ Deprecated; use :c:func:`PyErr_WarnEx` instead. + + +-.. cfunction:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry) ++.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry) + + Issue a warning message with explicit control over all warning attributes. This + is a straightforward wrapper around the Python function +@@ -299,15 +299,15 @@ + described there. + + +-.. cfunction:: int PyErr_WarnPy3k(char *message, int stacklevel) ++.. c:function:: int PyErr_WarnPy3k(char *message, int stacklevel) + + Issue a :exc:`DeprecationWarning` with the given *message* and *stacklevel* +- if the :cdata:`Py_Py3kWarningFlag` flag is enabled. ++ if the :c:data:`Py_Py3kWarningFlag` flag is enabled. + + .. versionadded:: 2.6 + + +-.. cfunction:: int PyErr_CheckSignals() ++.. c:function:: int PyErr_CheckSignals() + + .. index:: + module: signal +@@ -324,21 +324,21 @@ + cleared if it was previously set. + + +-.. cfunction:: void PyErr_SetInterrupt() ++.. c:function:: void PyErr_SetInterrupt() + + .. index:: + single: SIGINT + single: KeyboardInterrupt (built-in exception) + + This function simulates the effect of a :const:`SIGINT` signal arriving --- the +- next time :cfunc:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will ++ next time :c:func:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will + be raised. It may be called without holding the interpreter lock. + + .. % XXX This was described as obsolete, but is used in + .. % thread.interrupt_main() (used from IDLE), so it's still needed. + + +-.. cfunction:: int PySignal_SetWakeupFd(int fd) ++.. c:function:: int PySignal_SetWakeupFd(int fd) + + This utility function specifies a file descriptor to which a ``'\0'`` byte will + be written whenever a signal is received. It returns the previous such file +@@ -350,13 +350,13 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict) ++.. c:function:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict) + +- This utility function creates and returns a new exception object. The *name* ++ This utility function creates and returns a new exception class. The *name* + argument must be the name of the new exception, a C string of the form +- ``module.class``. The *base* and *dict* arguments are normally *NULL*. This +- creates a class object derived from :exc:`Exception` (accessible in C as +- :cdata:`PyExc_Exception`). ++ ``module.classname``. The *base* and *dict* arguments are normally *NULL*. ++ This creates a class object derived from :exc:`Exception` (accessible in C as ++ :c:data:`PyExc_Exception`). + + The :attr:`__module__` attribute of the new class is set to the first part (up + to the last dot) of the *name* argument, and the class name is set to the last +@@ -365,16 +365,16 @@ + argument can be used to specify a dictionary of class variables and methods. + + +-.. cfunction:: PyObject* PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict) ++.. c:function:: PyObject* PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict) + +- Same as :cfunc:`PyErr_NewException`, except that the new exception class can ++ Same as :c:func:`PyErr_NewException`, except that the new exception class can + easily be given a docstring: If *doc* is non-*NULL*, it will be used as the + docstring for the exception class. + + .. versionadded:: 2.7 + + +-.. cfunction:: void PyErr_WriteUnraisable(PyObject *obj) ++.. c:function:: void PyErr_WriteUnraisable(PyObject *obj) + + This utility function prints a warning message to ``sys.stderr`` when an + exception has been set but it is impossible for the interpreter to actually +@@ -393,33 +393,33 @@ + + The following functions are used to create and modify Unicode exceptions from C. + +-.. cfunction:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) ++.. c:function:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) + + Create a :class:`UnicodeDecodeError` object with the attributes *encoding*, + *object*, *length*, *start*, *end* and *reason*. + +-.. cfunction:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) ++.. c:function:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) + + Create a :class:`UnicodeEncodeError` object with the attributes *encoding*, + *object*, *length*, *start*, *end* and *reason*. + +-.. cfunction:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) ++.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) + + Create a :class:`UnicodeTranslateError` object with the attributes *object*, + *length*, *start*, *end* and *reason*. + +-.. cfunction:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc) ++.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc) + PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc) + + Return the *encoding* attribute of the given exception object. + +-.. cfunction:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc) ++.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc) + PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc) + PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc) + + Return the *object* attribute of the given exception object. + +-.. cfunction:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) ++.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) + int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) + int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) + +@@ -427,14 +427,14 @@ + *\*start*. *start* must not be *NULL*. Return ``0`` on success, ``-1`` on + failure. + +-.. cfunction:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start) ++.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start) + int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start) + int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start) + + Set the *start* attribute of the given exception object to *start*. Return + ``0`` on success, ``-1`` on failure. + +-.. cfunction:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end) ++.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end) + int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end) + int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end) + +@@ -442,20 +442,20 @@ + *\*end*. *end* must not be *NULL*. Return ``0`` on success, ``-1`` on + failure. + +-.. cfunction:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end) ++.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end) + int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end) + int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end) + + Set the *end* attribute of the given exception object to *end*. Return ``0`` + on success, ``-1`` on failure. + +-.. cfunction:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc) ++.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc) + PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc) + PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc) + + Return the *reason* attribute of the given exception object. + +-.. cfunction:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason) ++.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason) + int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason) + int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason) + +@@ -471,12 +471,12 @@ + recursive code does not necessarily invoke Python code (which tracks its + recursion depth automatically). + +-.. cfunction:: int Py_EnterRecursiveCall(char *where) ++.. c:function:: int Py_EnterRecursiveCall(char *where) + + Marks a point where a recursive C-level call is about to be performed. + +- If :const:`USE_STACKCHECK` is defined, this function checks if the the OS +- stack overflowed using :cfunc:`PyOS_CheckStack`. In this is the case, it ++ If :const:`USE_STACKCHECK` is defined, this function checks if the OS ++ stack overflowed using :c:func:`PyOS_CheckStack`. In this is the case, it + sets a :exc:`MemoryError` and returns a nonzero value. + + The function then checks if the recursion limit is reached. If this is the +@@ -487,10 +487,10 @@ + concatenated to the :exc:`RuntimeError` message caused by the recursion depth + limit. + +-.. cfunction:: void Py_LeaveRecursiveCall() ++.. c:function:: void Py_LeaveRecursiveCall() + +- Ends a :cfunc:`Py_EnterRecursiveCall`. Must be called once for each +- *successful* invocation of :cfunc:`Py_EnterRecursiveCall`. ++ Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each ++ *successful* invocation of :c:func:`Py_EnterRecursiveCall`. + + + .. _standardexceptions: +@@ -500,70 +500,70 @@ + + All standard Python exceptions are available as global variables whose names are + ``PyExc_`` followed by the Python exception name. These have the type +-:ctype:`PyObject\*`; they are all class objects. For completeness, here are all ++:c:type:`PyObject\*`; they are all class objects. For completeness, here are all + the variables: + +-+------------------------------------+----------------------------+----------+ +-| C Name | Python Name | Notes | +-+====================================+============================+==========+ +-| :cdata:`PyExc_BaseException` | :exc:`BaseException` | (1), (4) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_Exception` | :exc:`Exception` | \(1) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_StandardError` | :exc:`StandardError` | \(1) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_LookupError` | :exc:`LookupError` | \(1) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_AssertionError` | :exc:`AssertionError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_AttributeError` | :exc:`AttributeError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_EOFError` | :exc:`EOFError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_EnvironmentError` | :exc:`EnvironmentError` | \(1) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_IOError` | :exc:`IOError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_ImportError` | :exc:`ImportError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_IndexError` | :exc:`IndexError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_KeyError` | :exc:`KeyError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_MemoryError` | :exc:`MemoryError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_NameError` | :exc:`NameError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_OSError` | :exc:`OSError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_OverflowError` | :exc:`OverflowError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_RuntimeError` | :exc:`RuntimeError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_SyntaxError` | :exc:`SyntaxError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_SystemError` | :exc:`SystemError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_SystemExit` | :exc:`SystemExit` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_TypeError` | :exc:`TypeError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_ValueError` | :exc:`ValueError` | | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_WindowsError` | :exc:`WindowsError` | \(3) | +-+------------------------------------+----------------------------+----------+ +-| :cdata:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | | +-+------------------------------------+----------------------------+----------+ +++-------------------------------------+----------------------------+----------+ ++| C Name | Python Name | Notes | +++=====================================+============================+==========+ ++| :c:data:`PyExc_BaseException` | :exc:`BaseException` | (1), (4) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_StandardError` | :exc:`StandardError` | \(1) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_LookupError` | :exc:`LookupError` | \(1) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_EOFError` | :exc:`EOFError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_EnvironmentError` | :exc:`EnvironmentError` | \(1) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_IOError` | :exc:`IOError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_ImportError` | :exc:`ImportError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_IndexError` | :exc:`IndexError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_KeyError` | :exc:`KeyError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_NameError` | :exc:`NameError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_OSError` | :exc:`OSError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_SystemError` | :exc:`SystemError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_TypeError` | :exc:`TypeError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_ValueError` | :exc:`ValueError` | | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_WindowsError` | :exc:`WindowsError` | \(3) | +++-------------------------------------+----------------------------+----------+ ++| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | | +++-------------------------------------+----------------------------+----------+ + + .. index:: + single: PyExc_BaseException +diff -r 8527427914a2 Doc/c-api/file.rst +--- a/Doc/c-api/file.rst ++++ b/Doc/c-api/file.rst +@@ -7,78 +7,79 @@ + + .. index:: object: file + +-Python's built-in file objects are implemented entirely on the :ctype:`FILE\*` ++Python's built-in file objects are implemented entirely on the :c:type:`FILE\*` + support from the C standard library. This is an implementation detail and may + change in future releases of Python. + + +-.. ctype:: PyFileObject ++.. c:type:: PyFileObject + +- This subtype of :ctype:`PyObject` represents a Python file object. ++ This subtype of :c:type:`PyObject` represents a Python file object. + + +-.. cvar:: PyTypeObject PyFile_Type ++.. c:var:: PyTypeObject PyFile_Type + + .. index:: single: FileType (in module types) + +- This instance of :ctype:`PyTypeObject` represents the Python file type. This is ++ This instance of :c:type:`PyTypeObject` represents the Python file type. This is + exposed to Python programs as ``file`` and ``types.FileType``. + + +-.. cfunction:: int PyFile_Check(PyObject *p) ++.. c:function:: int PyFile_Check(PyObject *p) + +- Return true if its argument is a :ctype:`PyFileObject` or a subtype of +- :ctype:`PyFileObject`. ++ Return true if its argument is a :c:type:`PyFileObject` or a subtype of ++ :c:type:`PyFileObject`. + + .. versionchanged:: 2.2 + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyFile_CheckExact(PyObject *p) ++.. c:function:: int PyFile_CheckExact(PyObject *p) + +- Return true if its argument is a :ctype:`PyFileObject`, but not a subtype of +- :ctype:`PyFileObject`. ++ Return true if its argument is a :c:type:`PyFileObject`, but not a subtype of ++ :c:type:`PyFileObject`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyFile_FromString(char *filename, char *mode) ++.. c:function:: PyObject* PyFile_FromString(char *filename, char *mode) + + .. index:: single: fopen() + + On success, return a new file object that is opened on the file given by + *filename*, with a file mode given by *mode*, where *mode* has the same +- semantics as the standard C routine :cfunc:`fopen`. On failure, return *NULL*. ++ semantics as the standard C routine :c:func:`fopen`. On failure, return *NULL*. + + +-.. cfunction:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*)) ++.. c:function:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*)) + +- Create a new :ctype:`PyFileObject` from the already-open standard C file ++ Create a new :c:type:`PyFileObject` from the already-open standard C file + pointer, *fp*. The function *close* will be called when the file should be +- closed. Return *NULL* on failure. ++ closed. Return *NULL* and close the file using *close* on failure. ++ *close* is optional and can be set to *NULL*. + + +-.. cfunction:: FILE* PyFile_AsFile(PyObject \*p) ++.. c:function:: FILE* PyFile_AsFile(PyObject \*p) + +- Return the file object associated with *p* as a :ctype:`FILE\*`. ++ Return the file object associated with *p* as a :c:type:`FILE\*`. + +- If the caller will ever use the returned :ctype:`FILE\*` object while +- the :term:`GIL` is released it must also call the :cfunc:`PyFile_IncUseCount` and +- :cfunc:`PyFile_DecUseCount` functions described below as appropriate. ++ If the caller will ever use the returned :c:type:`FILE\*` object while ++ the :term:`GIL` is released it must also call the :c:func:`PyFile_IncUseCount` and ++ :c:func:`PyFile_DecUseCount` functions described below as appropriate. + + +-.. cfunction:: void PyFile_IncUseCount(PyFileObject \*p) ++.. c:function:: void PyFile_IncUseCount(PyFileObject \*p) + + Increments the PyFileObject's internal use count to indicate +- that the underlying :ctype:`FILE\*` is being used. ++ that the underlying :c:type:`FILE\*` is being used. + This prevents Python from calling f_close() on it from another thread. +- Callers of this must call :cfunc:`PyFile_DecUseCount` when they are +- finished with the :ctype:`FILE\*`. Otherwise the file object will ++ Callers of this must call :c:func:`PyFile_DecUseCount` when they are ++ finished with the :c:type:`FILE\*`. Otherwise the file object will + never be closed by Python. + + The :term:`GIL` must be held while calling this function. + +- The suggested use is to call this after :cfunc:`PyFile_AsFile` and before ++ The suggested use is to call this after :c:func:`PyFile_AsFile` and before + you release the GIL:: + + FILE *fp = PyFile_AsFile(p); +@@ -93,11 +94,11 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: void PyFile_DecUseCount(PyFileObject \*p) ++.. c:function:: void PyFile_DecUseCount(PyFileObject \*p) + + Decrements the PyFileObject's internal unlocked_count member to +- indicate that the caller is done with its own use of the :ctype:`FILE\*`. +- This may only be called to undo a prior call to :cfunc:`PyFile_IncUseCount`. ++ indicate that the caller is done with its own use of the :c:type:`FILE\*`. ++ This may only be called to undo a prior call to :c:func:`PyFile_IncUseCount`. + + The :term:`GIL` must be held while calling this function (see the example + above). +@@ -105,7 +106,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyFile_GetLine(PyObject *p, int n) ++.. c:function:: PyObject* PyFile_GetLine(PyObject *p, int n) + + .. index:: single: EOFError (built-in exception) + +@@ -119,20 +120,20 @@ + raised if the end of the file is reached immediately. + + +-.. cfunction:: PyObject* PyFile_Name(PyObject *p) ++.. c:function:: PyObject* PyFile_Name(PyObject *p) + + Return the name of the file specified by *p* as a string object. + + +-.. cfunction:: void PyFile_SetBufSize(PyFileObject *p, int n) ++.. c:function:: void PyFile_SetBufSize(PyFileObject *p, int n) + + .. index:: single: setvbuf() + +- Available on systems with :cfunc:`setvbuf` only. This should only be called ++ Available on systems with :c:func:`setvbuf` only. This should only be called + immediately after file object creation. + + +-.. cfunction:: int PyFile_SetEncoding(PyFileObject *p, const char *enc) ++.. c:function:: int PyFile_SetEncoding(PyFileObject *p, const char *enc) + + Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0 + on failure. +@@ -140,7 +141,7 @@ + .. versionadded:: 2.3 + + +-.. cfunction:: int PyFile_SetEncodingAndErrors(PyFileObject *p, const char *enc, *errors) ++.. c:function:: int PyFile_SetEncodingAndErrors(PyFileObject *p, const char *enc, *errors) + + Set the file's encoding for Unicode output to *enc*, and its error + mode to *err*. Return 1 on success and 0 on failure. +@@ -148,7 +149,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag) ++.. c:function:: int PyFile_SoftSpace(PyObject *p, int newflag) + + .. index:: single: softspace (file attribute) + +@@ -162,7 +163,7 @@ + but doing so should not be needed. + + +-.. cfunction:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags) ++.. c:function:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags) + + .. index:: single: Py_PRINT_RAW + +@@ -172,7 +173,7 @@ + appropriate exception will be set. + + +-.. cfunction:: int PyFile_WriteString(const char *s, PyObject *p) ++.. c:function:: int PyFile_WriteString(const char *s, PyObject *p) + + Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on + failure; the appropriate exception will be set. +diff -r 8527427914a2 Doc/c-api/float.rst +--- a/Doc/c-api/float.rst ++++ b/Doc/c-api/float.rst +@@ -8,62 +8,64 @@ + .. index:: object: floating point + + +-.. ctype:: PyFloatObject ++.. c:type:: PyFloatObject + +- This subtype of :ctype:`PyObject` represents a Python floating point object. ++ This subtype of :c:type:`PyObject` represents a Python floating point object. + + +-.. cvar:: PyTypeObject PyFloat_Type ++.. c:var:: PyTypeObject PyFloat_Type + + .. index:: single: FloatType (in modules types) + +- This instance of :ctype:`PyTypeObject` represents the Python floating point ++ This instance of :c:type:`PyTypeObject` represents the Python floating point + type. This is the same object as ``float`` and ``types.FloatType``. + + +-.. cfunction:: int PyFloat_Check(PyObject *p) ++.. c:function:: int PyFloat_Check(PyObject *p) + +- Return true if its argument is a :ctype:`PyFloatObject` or a subtype of +- :ctype:`PyFloatObject`. ++ Return true if its argument is a :c:type:`PyFloatObject` or a subtype of ++ :c:type:`PyFloatObject`. + + .. versionchanged:: 2.2 + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyFloat_CheckExact(PyObject *p) ++.. c:function:: int PyFloat_CheckExact(PyObject *p) + +- Return true if its argument is a :ctype:`PyFloatObject`, but not a subtype of +- :ctype:`PyFloatObject`. ++ Return true if its argument is a :c:type:`PyFloatObject`, but not a subtype of ++ :c:type:`PyFloatObject`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyFloat_FromString(PyObject *str, char **pend) ++.. c:function:: PyObject* PyFloat_FromString(PyObject *str, char **pend) + +- Create a :ctype:`PyFloatObject` object based on the string value in *str*, or ++ Create a :c:type:`PyFloatObject` object based on the string value in *str*, or + *NULL* on failure. The *pend* argument is ignored. It remains only for + backward compatibility. + + +-.. cfunction:: PyObject* PyFloat_FromDouble(double v) ++.. c:function:: PyObject* PyFloat_FromDouble(double v) + +- Create a :ctype:`PyFloatObject` object from *v*, or *NULL* on failure. ++ Create a :c:type:`PyFloatObject` object from *v*, or *NULL* on failure. + + +-.. cfunction:: double PyFloat_AsDouble(PyObject *pyfloat) ++.. c:function:: double PyFloat_AsDouble(PyObject *pyfloat) + +- Return a C :ctype:`double` representation of the contents of *pyfloat*. If ++ 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. + + +-.. cfunction:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) ++.. c:function:: double PyFloat_AS_DOUBLE(PyObject *pyfloat) + +- Return a C :ctype:`double` representation of the contents of *pyfloat*, but ++ Return a C :c:type:`double` representation of the contents of *pyfloat*, but + without error checking. + + +-.. cfunction:: PyObject* PyFloat_GetInfo(void) ++.. c:function:: PyObject* PyFloat_GetInfo(void) + + Return a structseq instance which contains information about the + precision, minimum and maximum values of a float. It's a thin wrapper +@@ -72,21 +74,21 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: double PyFloat_GetMax() ++.. c:function:: double PyFloat_GetMax() + +- Return the maximum representable finite float *DBL_MAX* as C :ctype:`double`. ++ Return the maximum representable finite float *DBL_MAX* as C :c:type:`double`. + + .. versionadded:: 2.6 + + +-.. cfunction:: double PyFloat_GetMin() ++.. c:function:: double PyFloat_GetMin() + +- Return the minimum normalized positive float *DBL_MIN* as C :ctype:`double`. ++ Return the minimum normalized positive float *DBL_MIN* as C :c:type:`double`. + + .. versionadded:: 2.6 + + +-.. cfunction:: int PyFloat_ClearFreeList() ++.. c:function:: int PyFloat_ClearFreeList() + + Clear the float free list. Return the number of items that could not + be freed. +@@ -94,7 +96,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: void PyFloat_AsString(char *buf, PyFloatObject *v) ++.. c:function:: void PyFloat_AsString(char *buf, PyFloatObject *v) + + Convert the argument *v* to a string, using the same rules as + :func:`str`. The length of *buf* should be at least 100. +@@ -106,7 +108,7 @@ + Use :func:`PyObject_Str` or :func:`PyOS_double_to_string` instead. + + +-.. cfunction:: void PyFloat_AsReprString(char *buf, PyFloatObject *v) ++.. c:function:: void PyFloat_AsReprString(char *buf, PyFloatObject *v) + + Same as PyFloat_AsString, except uses the same rules as + :func:`repr`. The length of *buf* should be at least 100. +diff -r 8527427914a2 Doc/c-api/function.rst +--- a/Doc/c-api/function.rst ++++ b/Doc/c-api/function.rst +@@ -10,26 +10,26 @@ + There are a few functions specific to Python functions. + + +-.. ctype:: PyFunctionObject ++.. c:type:: PyFunctionObject + + The C structure used for functions. + + +-.. cvar:: PyTypeObject PyFunction_Type ++.. c:var:: PyTypeObject PyFunction_Type + + .. index:: single: MethodType (in module types) + +- This is an instance of :ctype:`PyTypeObject` and represents the Python function ++ This is an instance of :c:type:`PyTypeObject` and represents the Python function + type. It is exposed to Python programmers as ``types.FunctionType``. + + +-.. cfunction:: int PyFunction_Check(PyObject *o) ++.. c:function:: int PyFunction_Check(PyObject *o) + +- Return true if *o* is a function object (has type :cdata:`PyFunction_Type`). ++ Return true if *o* is a function object (has type :c:data:`PyFunction_Type`). + The parameter must not be *NULL*. + + +-.. cfunction:: PyObject* PyFunction_New(PyObject *code, PyObject *globals) ++.. c:function:: PyObject* PyFunction_New(PyObject *code, PyObject *globals) + + Return a new function object associated with the code object *code*. *globals* + must be a dictionary with the global variables accessible to the function. +@@ -38,30 +38,30 @@ + object, the argument defaults and closure are set to *NULL*. + + +-.. cfunction:: PyObject* PyFunction_GetCode(PyObject *op) ++.. c:function:: PyObject* PyFunction_GetCode(PyObject *op) + + Return the code object associated with the function object *op*. + + +-.. cfunction:: PyObject* PyFunction_GetGlobals(PyObject *op) ++.. c:function:: PyObject* PyFunction_GetGlobals(PyObject *op) + + Return the globals dictionary associated with the function object *op*. + + +-.. cfunction:: PyObject* PyFunction_GetModule(PyObject *op) ++.. c:function:: PyObject* PyFunction_GetModule(PyObject *op) + + Return the *__module__* attribute of the function object *op*. This is normally + a string containing the module name, but can be set to any other object by + Python code. + + +-.. cfunction:: PyObject* PyFunction_GetDefaults(PyObject *op) ++.. c:function:: PyObject* PyFunction_GetDefaults(PyObject *op) + + Return the argument default values of the function object *op*. This can be a + tuple of arguments or *NULL*. + + +-.. cfunction:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) ++.. c:function:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) + + Set the argument default values for the function object *op*. *defaults* must be + *Py_None* or a tuple. +@@ -69,13 +69,13 @@ + Raises :exc:`SystemError` and returns ``-1`` on failure. + + +-.. cfunction:: PyObject* PyFunction_GetClosure(PyObject *op) ++.. c:function:: PyObject* PyFunction_GetClosure(PyObject *op) + + Return the closure associated with the function object *op*. This can be *NULL* + or a tuple of cell objects. + + +-.. cfunction:: int PyFunction_SetClosure(PyObject *op, PyObject *closure) ++.. c:function:: int PyFunction_SetClosure(PyObject *op, PyObject *closure) + + Set the closure associated with the function object *op*. *closure* must be + *Py_None* or a tuple of cell objects. +diff -r 8527427914a2 Doc/c-api/gcsupport.rst +--- a/Doc/c-api/gcsupport.rst ++++ b/Doc/c-api/gcsupport.rst +@@ -30,40 +30,40 @@ + + Constructors for container types must conform to two rules: + +-#. The memory for the object must be allocated using :cfunc:`PyObject_GC_New` +- or :cfunc:`PyObject_GC_NewVar`. ++#. The memory for the object must be allocated using :c:func:`PyObject_GC_New` ++ or :c:func:`PyObject_GC_NewVar`. + + #. Once all the fields which may contain references to other containers are +- initialized, it must call :cfunc:`PyObject_GC_Track`. ++ initialized, it must call :c:func:`PyObject_GC_Track`. + + +-.. cfunction:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type) ++.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type) + +- Analogous to :cfunc:`PyObject_New` but for container objects with the ++ Analogous to :c:func:`PyObject_New` but for container objects with the + :const:`Py_TPFLAGS_HAVE_GC` flag set. + + +-.. cfunction:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) ++.. c:function:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size) + +- Analogous to :cfunc:`PyObject_NewVar` but for container objects with the ++ Analogous to :c:func:`PyObject_NewVar` but for container objects with the + :const:`Py_TPFLAGS_HAVE_GC` flag set. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) ++.. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize) + +- Resize an object allocated by :cfunc:`PyObject_NewVar`. Returns the ++ Resize an object allocated by :c:func:`PyObject_NewVar`. Returns the + resized object or *NULL* on failure. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *newsize*. This might ++ This function used an :c:type:`int` type for *newsize*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: void PyObject_GC_Track(PyObject *op) ++.. c:function:: void PyObject_GC_Track(PyObject *op) + + Adds the object *op* to the set of container objects tracked by the + collector. The collector can run at unexpected times so objects must be +@@ -72,44 +72,44 @@ + end of the constructor. + + +-.. cfunction:: void _PyObject_GC_TRACK(PyObject *op) ++.. c:function:: void _PyObject_GC_TRACK(PyObject *op) + +- A macro version of :cfunc:`PyObject_GC_Track`. It should not be used for ++ A macro version of :c:func:`PyObject_GC_Track`. It should not be used for + extension modules. + + Similarly, the deallocator for the object must conform to a similar pair of + rules: + + #. Before fields which refer to other containers are invalidated, +- :cfunc:`PyObject_GC_UnTrack` must be called. ++ :c:func:`PyObject_GC_UnTrack` must be called. + +-#. The object's memory must be deallocated using :cfunc:`PyObject_GC_Del`. ++#. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`. + + +-.. cfunction:: void PyObject_GC_Del(void *op) ++.. c:function:: void PyObject_GC_Del(void *op) + +- Releases memory allocated to an object using :cfunc:`PyObject_GC_New` or +- :cfunc:`PyObject_GC_NewVar`. ++ Releases memory allocated to an object using :c:func:`PyObject_GC_New` or ++ :c:func:`PyObject_GC_NewVar`. + + +-.. cfunction:: void PyObject_GC_UnTrack(void *op) ++.. c:function:: void PyObject_GC_UnTrack(void *op) + + Remove the object *op* from the set of container objects tracked by the +- collector. Note that :cfunc:`PyObject_GC_Track` can be called again on ++ collector. Note that :c:func:`PyObject_GC_Track` can be called again on + this object to add it back to the set of tracked objects. The deallocator + (:attr:`tp_dealloc` handler) should call this for the object before any of + the fields used by the :attr:`tp_traverse` handler become invalid. + + +-.. cfunction:: void _PyObject_GC_UNTRACK(PyObject *op) ++.. c:function:: void _PyObject_GC_UNTRACK(PyObject *op) + +- A macro version of :cfunc:`PyObject_GC_UnTrack`. It should not be used for ++ A macro version of :c:func:`PyObject_GC_UnTrack`. It should not be used for + extension modules. + + The :attr:`tp_traverse` handler accepts a function parameter of this type: + + +-.. ctype:: int (*visitproc)(PyObject *object, void *arg) ++.. c:type:: int (*visitproc)(PyObject *object, void *arg) + + Type of the visitor function passed to the :attr:`tp_traverse` handler. + The function should be called with an object to traverse as *object* and +@@ -121,7 +121,7 @@ + The :attr:`tp_traverse` handler must have the following type: + + +-.. ctype:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg) ++.. c:type:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg) + + Traversal function for a container object. Implementations must call the + *visit* function for each object directly contained by *self*, with the +@@ -130,12 +130,12 @@ + object argument. If *visit* returns a non-zero value that value should be + returned immediately. + +-To simplify writing :attr:`tp_traverse` handlers, a :cfunc:`Py_VISIT` macro is ++To simplify writing :attr:`tp_traverse` handlers, a :c:func:`Py_VISIT` macro is + provided. In order to use this macro, the :attr:`tp_traverse` implementation + must name its arguments exactly *visit* and *arg*: + + +-.. cfunction:: void Py_VISIT(PyObject *o) ++.. c:function:: void Py_VISIT(PyObject *o) + + Call the *visit* callback, with arguments *o* and *arg*. If *visit* returns + a non-zero value, then return it. Using this macro, :attr:`tp_traverse` +@@ -151,15 +151,15 @@ + + .. versionadded:: 2.4 + +-The :attr:`tp_clear` handler must be of the :ctype:`inquiry` type, or *NULL* ++The :attr:`tp_clear` handler must be of the :c:type:`inquiry` type, or *NULL* + if the object is immutable. + + +-.. ctype:: int (*inquiry)(PyObject *self) ++.. c:type:: int (*inquiry)(PyObject *self) + + Drop references that may have created reference cycles. Immutable objects + do not have to define this method since they can never directly create + reference cycles. Note that the object must still be valid after calling +- this method (don't just call :cfunc:`Py_DECREF` on a reference). The ++ this method (don't just call :c:func:`Py_DECREF` on a reference). The + collector will call this method if it detects that this object is involved + in a reference cycle. +diff -r 8527427914a2 Doc/c-api/gen.rst +--- a/Doc/c-api/gen.rst ++++ b/Doc/c-api/gen.rst +@@ -7,31 +7,31 @@ + + Generator objects are what Python uses to implement generator iterators. They + are normally created by iterating over a function that yields values, rather +-than explicitly calling :cfunc:`PyGen_New`. ++than explicitly calling :c:func:`PyGen_New`. + + +-.. ctype:: PyGenObject ++.. c:type:: PyGenObject + + The C structure used for generator objects. + + +-.. cvar:: PyTypeObject PyGen_Type ++.. c:var:: PyTypeObject PyGen_Type + + The type object corresponding to generator objects + + +-.. cfunction:: int PyGen_Check(ob) ++.. c:function:: int PyGen_Check(ob) + + Return true if *ob* is a generator object; *ob* must not be *NULL*. + + +-.. cfunction:: int PyGen_CheckExact(ob) ++.. c:function:: int PyGen_CheckExact(ob) + + Return true if *ob*'s type is *PyGen_Type* is a generator object; *ob* must not + be *NULL*. + + +-.. cfunction:: PyObject* PyGen_New(PyFrameObject *frame) ++.. c:function:: PyObject* PyGen_New(PyFrameObject *frame) + + Create and return a new generator object based on the *frame* object. A + reference to *frame* is stolen by this function. The parameter must not be +diff -r 8527427914a2 Doc/c-api/import.rst +--- a/Doc/c-api/import.rst ++++ b/Doc/c-api/import.rst +@@ -6,14 +6,14 @@ + ================= + + +-.. cfunction:: PyObject* PyImport_ImportModule(const char *name) ++.. c:function:: PyObject* PyImport_ImportModule(const char *name) + + .. index:: + single: package variable; __all__ + single: __all__ (package variable) + single: modules (in module sys) + +- This is a simplified interface to :cfunc:`PyImport_ImportModuleEx` below, ++ This is a simplified interface to :c:func:`PyImport_ImportModuleEx` below, + leaving the *globals* and *locals* arguments set to *NULL* and *level* set + to 0. When the *name* + argument contains a dot (when it specifies a submodule of a package), the +@@ -34,20 +34,20 @@ + Always uses absolute imports. + + +-.. cfunction:: PyObject* PyImport_ImportModuleNoBlock(const char *name) ++.. c:function:: PyObject* PyImport_ImportModuleNoBlock(const char *name) + +- This version of :cfunc:`PyImport_ImportModule` does not block. It's intended ++ This version of :c:func:`PyImport_ImportModule` does not block. It's intended + to be used in C functions that import other modules to execute a function. + The import may block if another thread holds the import lock. The function +- :cfunc:`PyImport_ImportModuleNoBlock` never blocks. It first tries to fetch +- the module from sys.modules and falls back to :cfunc:`PyImport_ImportModule` ++ :c:func:`PyImport_ImportModuleNoBlock` never blocks. It first tries to fetch ++ the module from sys.modules and falls back to :c:func:`PyImport_ImportModule` + unless the lock is held, in which case the function will raise an + :exc:`ImportError`. + + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) ++.. c:function:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) + + .. index:: builtin: __import__ + +@@ -65,11 +65,11 @@ + Failing imports remove incomplete module objects. + + .. versionchanged:: 2.6 +- The function is an alias for :cfunc:`PyImport_ImportModuleLevel` with ++ The function is an alias for :c:func:`PyImport_ImportModuleLevel` with + -1 as level, meaning relative import. + + +-.. cfunction:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) ++.. c:function:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level) + + Import a module. This is best described by referring to the built-in Python + function :func:`__import__`, as the standard :func:`__import__` function calls +@@ -83,7 +83,7 @@ + .. versionadded:: 2.5 + + +-.. cfunction:: PyObject* PyImport_Import(PyObject *name) ++.. c:function:: PyObject* PyImport_Import(PyObject *name) + + .. index:: + module: rexec +@@ -98,7 +98,7 @@ + Always uses absolute imports. + + +-.. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m) ++.. c:function:: PyObject* PyImport_ReloadModule(PyObject *m) + + .. index:: builtin: reload + +@@ -108,7 +108,7 @@ + with an exception set on failure (the module still exists in this case). + + +-.. cfunction:: PyObject* PyImport_AddModule(const char *name) ++.. c:function:: PyObject* PyImport_AddModule(const char *name) + + Return the module object corresponding to a module name. The *name* argument + may be of the form ``package.module``. First check the modules dictionary if +@@ -118,12 +118,12 @@ + .. note:: + + This function does not load or import the module; if the module wasn't already +- loaded, you will get an empty module object. Use :cfunc:`PyImport_ImportModule` ++ loaded, you will get an empty module object. Use :c:func:`PyImport_ImportModule` + or one of its variants to import a module. Package structures implied by a + dotted name for *name* are not created if not already present. + + +-.. cfunction:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co) ++.. c:function:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co) + + .. index:: builtin: compile + +@@ -133,16 +133,16 @@ + or *NULL* with an exception set if an error occurred. Before Python 2.4, the + module could still be created in error cases. Starting with Python 2.4, *name* + is removed from :attr:`sys.modules` in error cases, and even if *name* was already +- in :attr:`sys.modules` on entry to :cfunc:`PyImport_ExecCodeModule`. Leaving ++ in :attr:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`. Leaving + incompletely initialized modules in :attr:`sys.modules` is dangerous, as imports of + such modules have no way to know that the module object is an unknown (and + probably damaged with respect to the module author's intents) state. + + The module's :attr:`__file__` attribute will be set to the code object's +- :cmember:`co_filename`. ++ :c:member:`co_filename`. + + This function will reload the module if it was already imported. See +- :cfunc:`PyImport_ReloadModule` for the intended way to reload a module. ++ :c:func:`PyImport_ReloadModule` for the intended way to reload a module. + + If *name* points to a dotted name of the form ``package.module``, any package + structures not already created will still not be created. +@@ -151,26 +151,26 @@ + *name* is removed from :attr:`sys.modules` in error cases. + + +-.. cfunction:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) ++.. c:function:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname) + +- Like :cfunc:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of ++ Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of + the module object is set to *pathname* if it is non-``NULL``. + + +-.. cfunction:: long PyImport_GetMagicNumber() ++.. c:function:: long PyImport_GetMagicNumber() + + Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and + :file:`.pyo` files). The magic number should be present in the first four bytes + of the bytecode file, in little-endian byte order. + + +-.. cfunction:: PyObject* PyImport_GetModuleDict() ++.. c:function:: PyObject* PyImport_GetModuleDict() + + Return the dictionary used for the module administration (a.k.a. + ``sys.modules``). Note that this is a per-interpreter variable. + + +-.. cfunction:: PyObject* PyImport_GetImporter(PyObject *path) ++.. c:function:: PyObject* PyImport_GetImporter(PyObject *path) + + Return an importer object for a :data:`sys.path`/:attr:`pkg.__path__` item + *path*, possibly by fetching it from the :data:`sys.path_importer_cache` +@@ -183,41 +183,41 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: void _PyImport_Init() ++.. c:function:: void _PyImport_Init() + + Initialize the import mechanism. For internal use only. + + +-.. cfunction:: void PyImport_Cleanup() ++.. c:function:: void PyImport_Cleanup() + + Empty the module table. For internal use only. + + +-.. cfunction:: void _PyImport_Fini() ++.. c:function:: void _PyImport_Fini() + + Finalize the import mechanism. For internal use only. + + +-.. cfunction:: PyObject* _PyImport_FindExtension(char *, char *) ++.. c:function:: PyObject* _PyImport_FindExtension(char *, char *) + + For internal use only. + + +-.. cfunction:: PyObject* _PyImport_FixupExtension(char *, char *) ++.. c:function:: PyObject* _PyImport_FixupExtension(char *, char *) + + For internal use only. + + +-.. cfunction:: int PyImport_ImportFrozenModule(char *name) ++.. c:function:: int PyImport_ImportFrozenModule(char *name) + + Load a frozen module named *name*. Return ``1`` for success, ``0`` if the + module is not found, and ``-1`` with an exception set if the initialization + failed. To access the imported module on a successful load, use +- :cfunc:`PyImport_ImportModule`. (Note the misnomer --- this function would ++ :c:func:`PyImport_ImportModule`. (Note the misnomer --- this function would + reload the module if it was already imported.) + + +-.. ctype:: struct _frozen ++.. c:type:: struct _frozen + + .. index:: single: freeze utility + +@@ -233,30 +233,30 @@ + }; + + +-.. cvar:: struct _frozen* PyImport_FrozenModules ++.. c:var:: struct _frozen* PyImport_FrozenModules + +- This pointer is initialized to point to an array of :ctype:`struct _frozen` ++ This pointer is initialized to point to an array of :c:type:`struct _frozen` + records, terminated by one whose members are all *NULL* or zero. When a frozen + module is imported, it is searched in this table. Third-party code could play + tricks with this to provide a dynamically created collection of frozen modules. + + +-.. cfunction:: int PyImport_AppendInittab(const char *name, void (*initfunc)(void)) ++.. c:function:: int PyImport_AppendInittab(const char *name, void (*initfunc)(void)) + + Add a single module to the existing table of built-in modules. This is a +- convenience wrapper around :cfunc:`PyImport_ExtendInittab`, returning ``-1`` if ++ convenience wrapper around :c:func:`PyImport_ExtendInittab`, returning ``-1`` if + the table could not be extended. The new module can be imported by the name + *name*, and uses the function *initfunc* as the initialization function called + on the first attempted import. This should be called before +- :cfunc:`Py_Initialize`. ++ :c:func:`Py_Initialize`. + + +-.. ctype:: struct _inittab ++.. c:type:: struct _inittab + + Structure describing a single entry in the list of built-in modules. Each of + these structures gives the name and initialization function for a module built + into the interpreter. Programs which embed Python may use an array of these +- structures in conjunction with :cfunc:`PyImport_ExtendInittab` to provide ++ structures in conjunction with :c:func:`PyImport_ExtendInittab` to provide + additional built-in modules. The structure is defined in + :file:`Include/import.h` as:: + +@@ -266,11 +266,11 @@ + }; + + +-.. cfunction:: int PyImport_ExtendInittab(struct _inittab *newtab) ++.. c:function:: int PyImport_ExtendInittab(struct _inittab *newtab) + + Add a collection of modules to the table of built-in modules. The *newtab* + array must end with a sentinel entry which contains *NULL* for the :attr:`name` + field; failure to provide the sentinel value can result in a memory fault. + Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to + extend the internal table. In the event of failure, no modules are added to the +- internal table. This should be called before :cfunc:`Py_Initialize`. ++ internal table. This should be called before :c:func:`Py_Initialize`. +diff -r 8527427914a2 Doc/c-api/init.rst +--- a/Doc/c-api/init.rst ++++ b/Doc/c-api/init.rst +@@ -12,7 +12,7 @@ + =========================================== + + +-.. cfunction:: void Py_Initialize() ++.. c:function:: void Py_Initialize() + + .. index:: + single: Py_SetProgramName() +@@ -31,40 +31,40 @@ + + Initialize the Python interpreter. In an application embedding Python, this + should be called before using any other Python/C API functions; with the +- exception of :cfunc:`Py_SetProgramName`, :cfunc:`PyEval_InitThreads`, +- :cfunc:`PyEval_ReleaseLock`, and :cfunc:`PyEval_AcquireLock`. This initializes ++ exception of :c:func:`Py_SetProgramName`, :c:func:`Py_SetPythonHome`, :c:func:`PyEval_InitThreads`, ++ :c:func:`PyEval_ReleaseLock`, and :c:func:`PyEval_AcquireLock`. This initializes + the table of loaded modules (``sys.modules``), and creates the fundamental + modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`. It also initializes + the module search path (``sys.path``). It does not set ``sys.argv``; use +- :cfunc:`PySys_SetArgvEx` for that. This is a no-op when called for a second time +- (without calling :cfunc:`Py_Finalize` first). There is no return value; it is a ++ :c:func:`PySys_SetArgvEx` for that. This is a no-op when called for a second time ++ (without calling :c:func:`Py_Finalize` first). There is no return value; it is a + fatal error if the initialization fails. + + +-.. cfunction:: void Py_InitializeEx(int initsigs) ++.. c:function:: void Py_InitializeEx(int initsigs) + +- This function works like :cfunc:`Py_Initialize` if *initsigs* is 1. If ++ This function works like :c:func:`Py_Initialize` if *initsigs* is 1. If + *initsigs* is 0, it skips initialization registration of signal handlers, which + might be useful when Python is embedded. + + .. versionadded:: 2.4 + + +-.. cfunction:: int Py_IsInitialized() ++.. c:function:: int Py_IsInitialized() + + Return true (nonzero) when the Python interpreter has been initialized, false +- (zero) if not. After :cfunc:`Py_Finalize` is called, this returns false until +- :cfunc:`Py_Initialize` is called again. ++ (zero) if not. After :c:func:`Py_Finalize` is called, this returns false until ++ :c:func:`Py_Initialize` is called again. + + +-.. cfunction:: void Py_Finalize() ++.. c:function:: void Py_Finalize() + +- Undo all initializations made by :cfunc:`Py_Initialize` and subsequent use of ++ Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of + Python/C API functions, and destroy all sub-interpreters (see +- :cfunc:`Py_NewInterpreter` below) that were created and not yet destroyed since +- the last call to :cfunc:`Py_Initialize`. Ideally, this frees all memory ++ :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since ++ the last call to :c:func:`Py_Initialize`. Ideally, this frees all memory + allocated by the Python interpreter. This is a no-op when called for a second +- time (without calling :cfunc:`Py_Initialize` again first). There is no return ++ time (without calling :c:func:`Py_Initialize` again first). There is no return + value; errors during finalization are ignored. + + This function is provided for a number of reasons. An embedding application +@@ -83,25 +83,25 @@ + please report it). Memory tied up in circular references between objects is not + freed. Some memory allocated by extension modules may not be freed. Some + extensions may not work properly if their initialization routine is called more +- than once; this can happen if an application calls :cfunc:`Py_Initialize` and +- :cfunc:`Py_Finalize` more than once. ++ than once; this can happen if an application calls :c:func:`Py_Initialize` and ++ :c:func:`Py_Finalize` more than once. + + + Process-wide parameters + ======================= + + +-.. cfunction:: void Py_SetProgramName(char *name) ++.. c:function:: void Py_SetProgramName(char *name) + + .. index:: + single: Py_Initialize() + single: main() + single: Py_GetPath() + +- This function should be called before :cfunc:`Py_Initialize` is called for ++ This function should be called before :c:func:`Py_Initialize` is called for + the first time, if it is called at all. It tells the interpreter the value +- of the ``argv[0]`` argument to the :cfunc:`main` function of the program. +- This is used by :cfunc:`Py_GetPath` and some other functions below to find ++ of the ``argv[0]`` argument to the :c:func:`main` function of the program. ++ This is used by :c:func:`Py_GetPath` and some other functions below to find + the Python run-time libraries relative to the interpreter executable. The + default value is ``'python'``. The argument should point to a + zero-terminated character string in static storage whose contents will not +@@ -109,37 +109,37 @@ + interpreter will change the contents of this storage. + + +-.. cfunction:: char* Py_GetProgramName() ++.. c:function:: char* Py_GetProgramName() + + .. index:: single: Py_SetProgramName() + +- Return the program name set with :cfunc:`Py_SetProgramName`, or the default. ++ Return the program name set with :c:func:`Py_SetProgramName`, or the default. + The returned string points into static storage; the caller should not modify its + value. + + +-.. cfunction:: char* Py_GetPrefix() ++.. c:function:: char* Py_GetPrefix() + + Return the *prefix* for installed platform-independent files. This is derived + through a number of complicated rules from the program name set with +- :cfunc:`Py_SetProgramName` and some environment variables; for example, if the ++ :c:func:`Py_SetProgramName` and some environment variables; for example, if the + program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The + returned string points into static storage; the caller should not modify its + value. This corresponds to the :makevar:`prefix` variable in the top-level +- :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure` ++ :file:`Makefile` and the ``--prefix`` argument to the :program:`configure` + script at build time. The value is available to Python code as ``sys.prefix``. + It is only useful on Unix. See also the next function. + + +-.. cfunction:: char* Py_GetExecPrefix() ++.. c:function:: char* Py_GetExecPrefix() + + Return the *exec-prefix* for installed platform-*dependent* files. This is + derived through a number of complicated rules from the program name set with +- :cfunc:`Py_SetProgramName` and some environment variables; for example, if the ++ :c:func:`Py_SetProgramName` and some environment variables; for example, if the + program name is ``'/usr/local/bin/python'``, the exec-prefix is + ``'/usr/local'``. The returned string points into static storage; the caller + should not modify its value. This corresponds to the :makevar:`exec_prefix` +- variable in the top-level :file:`Makefile` and the :option:`--exec-prefix` ++ variable in the top-level :file:`Makefile` and the ``--exec-prefix`` + argument to the :program:`configure` script at build time. The value is + available to Python code as ``sys.exec_prefix``. It is only useful on Unix. + +@@ -166,7 +166,7 @@ + platform. + + +-.. cfunction:: char* Py_GetProgramFullPath() ++.. c:function:: char* Py_GetProgramFullPath() + + .. index:: + single: Py_SetProgramName() +@@ -174,19 +174,19 @@ + + Return the full program name of the Python executable; this is computed as a + side-effect of deriving the default module search path from the program name +- (set by :cfunc:`Py_SetProgramName` above). The returned string points into ++ (set by :c:func:`Py_SetProgramName` above). The returned string points into + static storage; the caller should not modify its value. The value is available + to Python code as ``sys.executable``. + + +-.. cfunction:: char* Py_GetPath() ++.. c:function:: char* Py_GetPath() + + .. index:: + triple: module; search; path + single: path (in module sys) + + Return the default module search path; this is computed from the program name +- (set by :cfunc:`Py_SetProgramName` above) and some environment variables. ++ (set by :c:func:`Py_SetProgramName` above) and some environment variables. + The returned string consists of a series of directory names separated by a + platform dependent delimiter character. The delimiter character is ``':'`` + on Unix and Mac OS X, ``';'`` on Windows. The returned string points into +@@ -198,7 +198,7 @@ + .. XXX should give the exact rules + + +-.. cfunction:: const char* Py_GetVersion() ++.. c:function:: const char* Py_GetVersion() + + Return the version of this Python interpreter. This is a string that looks + something like :: +@@ -213,7 +213,7 @@ + modify its value. The value is available to Python code as ``sys.version``. + + +-.. cfunction:: const char* Py_GetPlatform() ++.. c:function:: const char* Py_GetPlatform() + + .. index:: single: platform (in module sys) + +@@ -226,7 +226,7 @@ + to Python code as ``sys.platform``. + + +-.. cfunction:: const char* Py_GetCopyright() ++.. c:function:: const char* Py_GetCopyright() + + Return the official copyright string for the current Python version, for example + +@@ -238,7 +238,7 @@ + value. The value is available to Python code as ``sys.copyright``. + + +-.. cfunction:: const char* Py_GetCompiler() ++.. c:function:: const char* Py_GetCompiler() + + Return an indication of the compiler used to build the current Python version, + in square brackets, for example:: +@@ -252,7 +252,7 @@ + ``sys.version``. + + +-.. cfunction:: const char* Py_GetBuildInfo() ++.. c:function:: const char* Py_GetBuildInfo() + + Return information about the sequence number and build date and time of the + current Python interpreter instance, for example :: +@@ -266,7 +266,7 @@ + ``sys.version``. + + +-.. cfunction:: void PySys_SetArgvEx(int argc, char **argv, int updatepath) ++.. c:function:: void PySys_SetArgvEx(int argc, char **argv, int updatepath) + + .. index:: + single: main() +@@ -274,12 +274,12 @@ + single: argv (in module sys) + + Set :data:`sys.argv` based on *argc* and *argv*. These parameters are +- similar to those passed to the program's :cfunc:`main` function with the ++ similar to those passed to the program's :c:func:`main` function with the + difference that the first entry should refer to the script file to be + executed rather than the executable hosting the Python interpreter. If there + isn't a script that will be run, the first entry in *argv* can be an empty + string. If this function fails to initialize :data:`sys.argv`, a fatal +- condition is signalled using :cfunc:`Py_FatalError`. ++ condition is signalled using :c:func:`Py_FatalError`. + + If *updatepath* is zero, this is all the function does. If *updatepath* + is non-zero, the function also modifies :data:`sys.path` according to the +@@ -301,7 +301,7 @@ + + On versions before 2.6.6, you can achieve the same effect by manually + popping the first :data:`sys.path` element after having called +- :cfunc:`PySys_SetArgv`, for example using:: ++ :c:func:`PySys_SetArgv`, for example using:: + + PyRun_SimpleString("import sys; sys.path.pop(0)\n"); + +@@ -311,12 +311,12 @@ + check w/ Guido. + + +-.. cfunction:: void PySys_SetArgv(int argc, char **argv) ++.. c:function:: void PySys_SetArgv(int argc, char **argv) + +- This function works like :cfunc:`PySys_SetArgvEx` with *updatepath* set to 1. ++ This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set to 1. + + +-.. cfunction:: void Py_SetPythonHome(char *home) ++.. c:function:: void Py_SetPythonHome(char *home) + + Set the default "home" directory, that is, the location of the standard + Python libraries. See :envvar:`PYTHONHOME` for the meaning of the +@@ -328,10 +328,10 @@ + this storage. + + +-.. cfunction:: char* Py_GetPythonHome() ++.. c:function:: char* Py_GetPythonHome() + + Return the default "home", that is, the value set by a previous call to +- :cfunc:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME` ++ :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME` + environment variable if it is set. + + +@@ -368,9 +368,9 @@ + single: PyThreadState + + The Python interpreter keeps some thread-specific bookkeeping information +-inside a data structure called :ctype:`PyThreadState`. There's also one +-global variable pointing to the current :ctype:`PyThreadState`: it can +-be retrieved using :cfunc:`PyThreadState_Get`. ++inside a data structure called :c:type:`PyThreadState`. There's also one ++global variable pointing to the current :c:type:`PyThreadState`: it can ++be retrieved using :c:func:`PyThreadState_Get`. + + Releasing the GIL from extension code + ------------------------------------- +@@ -394,8 +394,8 @@ + single: Py_BEGIN_ALLOW_THREADS + single: Py_END_ALLOW_THREADS + +-The :cmacro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a +-hidden local variable; the :cmacro:`Py_END_ALLOW_THREADS` macro closes the ++The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a ++hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the + block. These two macros are still available when Python is compiled without + thread support (they simply have an empty expansion). + +@@ -445,7 +445,7 @@ + API. When you are done, you should reset the thread state pointer, release + the GIL, and finally free the thread state data structure. + +-The :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` functions do ++The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do + all of the above automatically. The typical idiom for calling into Python + from a C thread is:: + +@@ -459,14 +459,14 @@ + /* Release the thread. No Python API allowed beyond this point. */ + PyGILState_Release(gstate); + +-Note that the :cfunc:`PyGILState_\*` functions assume there is only one global +-interpreter (created automatically by :cfunc:`Py_Initialize`). Python ++Note that the :c:func:`PyGILState_\*` functions assume there is only one global ++interpreter (created automatically by :c:func:`Py_Initialize`). Python + supports the creation of additional interpreters (using +-:cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the +-:cfunc:`PyGILState_\*` API is unsupported. ++:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the ++:c:func:`PyGILState_\*` API is unsupported. + + Another important thing to note about threads is their behaviour in the face +-of the C :cfunc:`fork` call. On most systems with :cfunc:`fork`, after a ++of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a + process forks only the thread that issued the fork will exist. That also + means any locks held by other threads will never be released. Python solves + this for :func:`os.fork` by acquiring the locks it uses internally before +@@ -474,12 +474,12 @@ + :ref:`lock-objects` in the child. When extending or embedding Python, there + is no way to inform Python of additional (non-Python) locks that need to be + acquired before or reset after a fork. OS facilities such as +-:cfunc:`pthread_atfork` would need to be used to accomplish the same thing. +-Additionally, when extending or embedding Python, calling :cfunc:`fork` ++:c:func:`pthread_atfork` would need to be used to accomplish the same thing. ++Additionally, when extending or embedding Python, calling :c:func:`fork` + directly rather than through :func:`os.fork` (and returning to or calling + into Python) may result in a deadlock by one of Python's internal locks + being held by a thread that is defunct after the fork. +-:cfunc:`PyOS_AfterFork` tries to reset the necessary locks, but is not ++:c:func:`PyOS_AfterFork` tries to reset the necessary locks, but is not + always able to. + + +@@ -489,7 +489,7 @@ + These are the most commonly used types and functions when writing C extension + code, or when embedding the Python interpreter: + +-.. ctype:: PyInterpreterState ++.. c:type:: PyInterpreterState + + This data structure represents the state shared by a number of cooperating + threads. Threads belonging to the same interpreter share their module +@@ -502,14 +502,14 @@ + interpreter they belong. + + +-.. ctype:: PyThreadState ++.. c:type:: PyThreadState + + This data structure represents the state of a single thread. The only public +- data member is :ctype:`PyInterpreterState \*`:attr:`interp`, which points to ++ data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to + this thread's interpreter state. + + +-.. cfunction:: void PyEval_InitThreads() ++.. c:function:: void PyEval_InitThreads() + + .. index:: + single: PyEval_ReleaseLock() +@@ -519,14 +519,14 @@ + + Initialize and acquire the global interpreter lock. It should be called in the + main thread before creating a second thread or engaging in any other thread +- operations such as :cfunc:`PyEval_ReleaseLock` or ++ operations such as :c:func:`PyEval_ReleaseLock` or + ``PyEval_ReleaseThread(tstate)``. It is not needed before calling +- :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_RestoreThread`. ++ :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`. + + .. index:: single: Py_Initialize() + + This is a no-op when called for a second time. It is safe to call this function +- before calling :cfunc:`Py_Initialize`. ++ before calling :c:func:`Py_Initialize`. + + .. index:: module: thread + +@@ -539,7 +539,7 @@ + when this function initializes the global interpreter lock, it also acquires + it. Before the Python :mod:`_thread` module creates a new thread, knowing + that either it has the lock or the lock hasn't been created yet, it calls +- :cfunc:`PyEval_InitThreads`. When this call returns, it is guaranteed that ++ :c:func:`PyEval_InitThreads`. When this call returns, it is guaranteed that + the lock has been created and that the calling thread has acquired it. + + It is **not** safe to call this function when it is unknown which thread (if +@@ -548,9 +548,9 @@ + This function is not available when thread support is disabled at compile time. + + +-.. cfunction:: int PyEval_ThreadsInitialized() ++.. c:function:: int PyEval_ThreadsInitialized() + +- Returns a non-zero value if :cfunc:`PyEval_InitThreads` has been called. This ++ Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called. This + function can be called without holding the GIL, and therefore can be used to + avoid calls to the locking API when running single-threaded. This function is + not available when thread support is disabled at compile time. +@@ -558,7 +558,7 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyThreadState* PyEval_SaveThread() ++.. c:function:: PyThreadState* PyEval_SaveThread() + + Release the global interpreter lock (if it has been created and thread + support is enabled) and reset the thread state to *NULL*, returning the +@@ -567,7 +567,7 @@ + when thread support is disabled at compile time.) + + +-.. cfunction:: void PyEval_RestoreThread(PyThreadState *tstate) ++.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate) + + Acquire the global interpreter lock (if it has been created and thread + support is enabled) and set the thread state to *tstate*, which must not be +@@ -576,23 +576,23 @@ + when thread support is disabled at compile time.) + + +-.. cfunction:: PyThreadState* PyThreadState_Get() ++.. c:function:: PyThreadState* PyThreadState_Get() + + Return the current thread state. The global interpreter lock must be held. + When the current thread state is *NULL*, this issues a fatal error (so that + the caller needn't check for *NULL*). + + +-.. cfunction:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate) ++.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate) + + Swap the current thread state with the thread state given by the argument + *tstate*, which may be *NULL*. The global interpreter lock must be held + and is not released. + + +-.. cfunction:: void PyEval_ReInitThreads() ++.. c:function:: void PyEval_ReInitThreads() + +- This function is called from :cfunc:`PyOS_AfterFork` to ensure that newly ++ This function is called from :c:func:`PyOS_AfterFork` to ensure that newly + created child processes don't hold locks referring to threads which + are not running in the child process. + +@@ -600,24 +600,24 @@ + The following functions use thread-local storage, and are not compatible + with sub-interpreters: + +-.. cfunction:: PyGILState_STATE PyGILState_Ensure() ++.. c:function:: PyGILState_STATE PyGILState_Ensure() + + Ensure that the current thread is ready to call the Python C API regardless + of the current state of Python, or of the global interpreter lock. This may + be called as many times as desired by a thread as long as each call is +- matched with a call to :cfunc:`PyGILState_Release`. In general, other +- thread-related APIs may be used between :cfunc:`PyGILState_Ensure` and +- :cfunc:`PyGILState_Release` calls as long as the thread state is restored to ++ matched with a call to :c:func:`PyGILState_Release`. In general, other ++ thread-related APIs may be used between :c:func:`PyGILState_Ensure` and ++ :c:func:`PyGILState_Release` calls as long as the thread state is restored to + its previous state before the Release(). For example, normal usage of the +- :cmacro:`Py_BEGIN_ALLOW_THREADS` and :cmacro:`Py_END_ALLOW_THREADS` macros is ++ :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is + acceptable. + + The return value is an opaque "handle" to the thread state when +- :cfunc:`PyGILState_Ensure` was called, and must be passed to +- :cfunc:`PyGILState_Release` to ensure Python is left in the same state. Even ++ :c:func:`PyGILState_Ensure` was called, and must be passed to ++ :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even + though recursive calls are allowed, these handles *cannot* be shared - each +- unique call to :cfunc:`PyGILState_Ensure` must save the handle for its call +- to :cfunc:`PyGILState_Release`. ++ unique call to :c:func:`PyGILState_Ensure` must save the handle for its call ++ to :c:func:`PyGILState_Release`. + + When the function returns, the current thread will hold the GIL and be able + to call arbitrary Python code. Failure is a fatal error. +@@ -625,15 +625,25 @@ + .. versionadded:: 2.3 + + +-.. cfunction:: void PyGILState_Release(PyGILState_STATE) ++.. c:function:: void PyGILState_Release(PyGILState_STATE) + + Release any resources previously acquired. After this call, Python's state will +- be the same as it was prior to the corresponding :cfunc:`PyGILState_Ensure` call ++ be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call + (but generally this state will be unknown to the caller, hence the use of the + GILState API). + +- Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to +- :cfunc:`PyGILState_Release` on the same thread. ++ Every call to :c:func:`PyGILState_Ensure` must be matched by a call to ++ :c:func:`PyGILState_Release` on the same thread. ++ ++ .. versionadded:: 2.3 ++ ++ ++.. c:function:: PyThreadState PyGILState_GetThisThreadState() ++ ++ Get the current thread state for this thread. May return ``NULL`` if no ++ GILState API has been used on the current thread. Note that the main thread ++ always has such a thread-state, even if no auto-thread-state call has been ++ made on the main thread. This is mainly a helper/diagnostic function. + + .. versionadded:: 2.3 + +@@ -642,33 +652,33 @@ + example usage in the Python source distribution. + + +-.. cmacro:: Py_BEGIN_ALLOW_THREADS ++.. c:macro:: Py_BEGIN_ALLOW_THREADS + + This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``. + Note that it contains an opening brace; it must be matched with a following +- :cmacro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this ++ :c:macro:`Py_END_ALLOW_THREADS` macro. See above for further discussion of this + macro. It is a no-op when thread support is disabled at compile time. + + +-.. cmacro:: Py_END_ALLOW_THREADS ++.. c:macro:: Py_END_ALLOW_THREADS + + This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains + a closing brace; it must be matched with an earlier +- :cmacro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of ++ :c:macro:`Py_BEGIN_ALLOW_THREADS` macro. See above for further discussion of + this macro. It is a no-op when thread support is disabled at compile time. + + +-.. cmacro:: Py_BLOCK_THREADS ++.. c:macro:: Py_BLOCK_THREADS + + This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to +- :cmacro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when ++ :c:macro:`Py_END_ALLOW_THREADS` without the closing brace. It is a no-op when + thread support is disabled at compile time. + + +-.. cmacro:: Py_UNBLOCK_THREADS ++.. c:macro:: Py_UNBLOCK_THREADS + + This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to +- :cmacro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable ++ :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable + declaration. It is a no-op when thread support is disabled at compile time. + + +@@ -680,47 +690,47 @@ + been created. + + +-.. cfunction:: PyInterpreterState* PyInterpreterState_New() ++.. c:function:: PyInterpreterState* PyInterpreterState_New() + + Create a new interpreter state object. The global interpreter lock need not + be held, but may be held if it is necessary to serialize calls to this + function. + + +-.. cfunction:: void PyInterpreterState_Clear(PyInterpreterState *interp) ++.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp) + + Reset all information in an interpreter state object. The global interpreter + lock must be held. + + +-.. cfunction:: void PyInterpreterState_Delete(PyInterpreterState *interp) ++.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp) + + Destroy an interpreter state object. The global interpreter lock need not be + held. The interpreter state must have been reset with a previous call to +- :cfunc:`PyInterpreterState_Clear`. ++ :c:func:`PyInterpreterState_Clear`. + + +-.. cfunction:: PyThreadState* PyThreadState_New(PyInterpreterState *interp) ++.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp) + + Create a new thread state object belonging to the given interpreter object. + The global interpreter lock need not be held, but may be held if it is + necessary to serialize calls to this function. + + +-.. cfunction:: void PyThreadState_Clear(PyThreadState *tstate) ++.. c:function:: void PyThreadState_Clear(PyThreadState *tstate) + + Reset all information in a thread state object. The global interpreter lock + must be held. + + +-.. cfunction:: void PyThreadState_Delete(PyThreadState *tstate) ++.. c:function:: void PyThreadState_Delete(PyThreadState *tstate) + + Destroy a thread state object. The global interpreter lock need not be held. + The thread state must have been reset with a previous call to +- :cfunc:`PyThreadState_Clear`. ++ :c:func:`PyThreadState_Clear`. + + +-.. cfunction:: PyObject* PyThreadState_GetDict() ++.. c:function:: PyObject* PyThreadState_GetDict() + + Return a dictionary in which extensions can store thread-specific state + information. Each extension should use a unique key to use to store state in +@@ -733,7 +743,7 @@ + meant that an exception was raised. + + +-.. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc) ++.. c:function:: int PyThreadState_SetAsyncExc(long id, PyObject *exc) + + Asynchronously raise an exception in a thread. The *id* argument is the thread + id of the target thread; *exc* is the exception object to be raised. This +@@ -746,18 +756,18 @@ + .. versionadded:: 2.3 + + +-.. cfunction:: void PyEval_AcquireThread(PyThreadState *tstate) ++.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate) + + Acquire the global interpreter lock and set the current thread state to + *tstate*, which should not be *NULL*. The lock must have been created earlier. + If this thread already has the lock, deadlock ensues. + +- :cfunc:`PyEval_RestoreThread` is a higher-level function which is always ++ :c:func:`PyEval_RestoreThread` is a higher-level function which is always + available (even when thread support isn't enabled or when threads have + not been initialized). + + +-.. cfunction:: void PyEval_ReleaseThread(PyThreadState *tstate) ++.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate) + + Reset the current thread state to *NULL* and release the global interpreter + lock. The lock must have been created earlier and must be held by the current +@@ -765,29 +775,29 @@ + that it represents the current thread state --- if it isn't, a fatal error is + reported. + +- :cfunc:`PyEval_SaveThread` is a higher-level function which is always ++ :c:func:`PyEval_SaveThread` is a higher-level function which is always + available (even when thread support isn't enabled or when threads have + not been initialized). + + +-.. cfunction:: void PyEval_AcquireLock() ++.. c:function:: void PyEval_AcquireLock() + + Acquire the global interpreter lock. The lock must have been created earlier. + If this thread already has the lock, a deadlock ensues. + + .. warning:: + This function does not change the current thread state. Please use +- :cfunc:`PyEval_RestoreThread` or :cfunc:`PyEval_AcquireThread` ++ :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread` + instead. + + +-.. cfunction:: void PyEval_ReleaseLock() ++.. c:function:: void PyEval_ReleaseLock() + + Release the global interpreter lock. The lock must have been created earlier. + + .. warning:: + This function does not change the current thread state. Please use +- :cfunc:`PyEval_SaveThread` or :cfunc:`PyEval_ReleaseThread` ++ :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread` + instead. + + +@@ -798,11 +808,11 @@ + are cases where you need to create several independent interpreters in the + same process and perhaps even in the same thread. Sub-interpreters allow + you to do that. You can switch between sub-interpreters using the +-:cfunc:`PyThreadState_Swap` function. You can create and destroy them ++:c:func:`PyThreadState_Swap` function. You can create and destroy them + using the following functions: + + +-.. cfunction:: PyThreadState* Py_NewInterpreter() ++.. c:function:: PyThreadState* Py_NewInterpreter() + + .. index:: + module: builtins +@@ -844,13 +854,13 @@ + and filled with the contents of this copy; the extension's ``init`` function is + not called. Note that this is different from what happens when an extension is + imported after the interpreter has been completely re-initialized by calling +- :cfunc:`Py_Finalize` and :cfunc:`Py_Initialize`; in that case, the extension's ++ :c:func:`Py_Finalize` and :c:func:`Py_Initialize`; in that case, the extension's + ``initmodule`` function *is* called again. + + .. index:: single: close() (in module os) + + +-.. cfunction:: void Py_EndInterpreter(PyThreadState *tstate) ++.. c:function:: void Py_EndInterpreter(PyThreadState *tstate) + + .. index:: single: Py_Finalize() + +@@ -859,7 +869,7 @@ + states below. When the call returns, the current thread state is *NULL*. All + thread states associated with this interpreter are destroyed. (The global + interpreter lock must be held before calling this function and is still held +- when it returns.) :cfunc:`Py_Finalize` will destroy all sub-interpreters that ++ when it returns.) :c:func:`Py_Finalize` will destroy all sub-interpreters that + haven't been explicitly destroyed at that point. + + +@@ -880,11 +890,11 @@ + by such objects may affect the wrong (sub-)interpreter's dictionary of loaded + modules. + +-Also note that combining this functionality with :cfunc:`PyGILState_\*` APIs ++Also note that combining this functionality with :c:func:`PyGILState_\*` APIs + is delicate, because these APIs assume a bijection between Python thread states + and OS-level threads, an assumption broken by the presence of sub-interpreters. + It is highly recommended that you don't switch sub-interpreters between a pair +-of matching :cfunc:`PyGILState_Ensure` and :cfunc:`PyGILState_Release` calls. ++of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls. + Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling + of Python code from non-Python created threads will probably be broken when using + sub-interpreters. +@@ -906,7 +916,7 @@ + main thread where it has possession of the global interpreter lock and can + perform any Python API calls. + +-.. cfunction:: int Py_AddPendingCall(int (*func)(void *), void *arg) ++.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg) + + .. index:: single: Py_AddPendingCall() + +@@ -954,10 +964,10 @@ + in previous versions. + + +-.. ctype:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) ++.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg) + +- The type of the trace function registered using :cfunc:`PyEval_SetProfile` and +- :cfunc:`PyEval_SetTrace`. The first parameter is the object passed to the ++ The type of the trace function registered using :c:func:`PyEval_SetProfile` and ++ :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the + registration function as *obj*, *frame* is the frame object to which the event + pertains, *what* is one of the constants :const:`PyTrace_CALL`, + :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`, +@@ -985,18 +995,18 @@ + +------------------------------+--------------------------------------+ + + +-.. cvar:: int PyTrace_CALL ++.. c:var:: int PyTrace_CALL + +- The value of the *what* parameter to a :ctype:`Py_tracefunc` function when a new ++ The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new + call to a function or method is being reported, or a new entry into a generator. + Note that the creation of the iterator for a generator function is not reported + as there is no control transfer to the Python bytecode in the corresponding + frame. + + +-.. cvar:: int PyTrace_EXCEPTION ++.. c:var:: int PyTrace_EXCEPTION + +- The value of the *what* parameter to a :ctype:`Py_tracefunc` function when an ++ The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an + exception has been raised. The callback function is called with this value for + *what* when after any bytecode is processed after which the exception becomes + set within the frame being executed. The effect of this is that as exception +@@ -1005,37 +1015,37 @@ + these events; they are not needed by the profiler. + + +-.. cvar:: int PyTrace_LINE ++.. c:var:: int PyTrace_LINE + + The value passed as the *what* parameter to a trace function (but not a + profiling function) when a line-number event is being reported. + + +-.. cvar:: int PyTrace_RETURN ++.. c:var:: int PyTrace_RETURN + +- The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a ++ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a + call is returning without propagating an exception. + + +-.. cvar:: int PyTrace_C_CALL ++.. c:var:: int PyTrace_C_CALL + +- The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C ++ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C + function is about to be called. + + +-.. cvar:: int PyTrace_C_EXCEPTION ++.. c:var:: int PyTrace_C_EXCEPTION + +- The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C ++ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C + function has raised an exception. + + +-.. cvar:: int PyTrace_C_RETURN ++.. c:var:: int PyTrace_C_RETURN + +- The value for the *what* parameter to :ctype:`Py_tracefunc` functions when a C ++ The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C + function has returned. + + +-.. cfunction:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj) ++.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj) + + Set the profiler function to *func*. The *obj* parameter is passed to the + function as its first parameter, and may be any Python object, or *NULL*. If +@@ -1045,13 +1055,13 @@ + events. + + +-.. cfunction:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) ++.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj) + + Set the tracing function to *func*. This is similar to +- :cfunc:`PyEval_SetProfile`, except the tracing function does receive line-number ++ :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number + events. + +-.. cfunction:: PyObject* PyEval_GetCallStats(PyObject *self) ++.. c:function:: PyObject* PyEval_GetCallStats(PyObject *self) + + Return a tuple of function call counts. There are constants defined for the + positions within the tuple: +@@ -1103,14 +1113,14 @@ + These functions are only intended to be used by advanced debugging tools. + + +-.. cfunction:: PyInterpreterState* PyInterpreterState_Head() ++.. c:function:: PyInterpreterState* PyInterpreterState_Head() + + Return the interpreter state object at the head of the list of all such objects. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) ++.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) + + Return the next interpreter state object after *interp* from the list of all + such objects. +@@ -1118,18 +1128,18 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) ++.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) + +- Return the a pointer to the first :ctype:`PyThreadState` object in the list of ++ Return the a pointer to the first :c:type:`PyThreadState` object in the list of + threads associated with the interpreter *interp*. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) ++.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) + + Return the next thread state object after *tstate* from the list of all such +- objects belonging to the same :ctype:`PyInterpreterState` object. ++ objects belonging to the same :c:type:`PyInterpreterState` object. + + .. versionadded:: 2.2 + +diff -r 8527427914a2 Doc/c-api/int.rst +--- a/Doc/c-api/int.rst ++++ b/Doc/c-api/int.rst +@@ -8,39 +8,39 @@ + .. index:: object: integer + + +-.. ctype:: PyIntObject ++.. c:type:: PyIntObject + +- This subtype of :ctype:`PyObject` represents a Python integer object. ++ This subtype of :c:type:`PyObject` represents a Python integer object. + + +-.. cvar:: PyTypeObject PyInt_Type ++.. c:var:: PyTypeObject PyInt_Type + + .. index:: single: IntType (in modules types) + +- This instance of :ctype:`PyTypeObject` represents the Python plain integer type. ++ This instance of :c:type:`PyTypeObject` represents the Python plain integer type. + This is the same object as ``int`` and ``types.IntType``. + + +-.. cfunction:: int PyInt_Check(PyObject *o) ++.. c:function:: int PyInt_Check(PyObject *o) + +- Return true if *o* is of type :cdata:`PyInt_Type` or a subtype of +- :cdata:`PyInt_Type`. ++ Return true if *o* is of type :c:data:`PyInt_Type` or a subtype of ++ :c:data:`PyInt_Type`. + + .. versionchanged:: 2.2 + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyInt_CheckExact(PyObject *o) ++.. c:function:: int PyInt_CheckExact(PyObject *o) + +- Return true if *o* is of type :cdata:`PyInt_Type`, but not a subtype of +- :cdata:`PyInt_Type`. ++ Return true if *o* is of type :c:data:`PyInt_Type`, but not a subtype of ++ :c:data:`PyInt_Type`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyInt_FromString(char *str, char **pend, int base) ++.. c:function:: PyObject* PyInt_FromString(char *str, char **pend, int base) + +- Return a new :ctype:`PyIntObject` or :ctype:`PyLongObject` based on the string ++ Return a new :c:type:`PyIntObject` or :c:type:`PyLongObject` based on the string + value in *str*, which is interpreted according to the radix in *base*. If + *pend* is non-*NULL*, ``*pend`` will point to the first character in *str* which + follows the representation of the number. If *base* is ``0``, the radix will be +@@ -49,13 +49,13 @@ + 8 will be used; otherwise radix 10 will be used. If *base* is not ``0``, it + must be between ``2`` and ``36``, inclusive. Leading spaces are ignored. If + there are no digits, :exc:`ValueError` will be raised. If the string represents +- a number too large to be contained within the machine's :ctype:`long int` type +- and overflow warnings are being suppressed, a :ctype:`PyLongObject` will be ++ a number too large to be contained within the machine's :c:type:`long int` type ++ and overflow warnings are being suppressed, a :c:type:`PyLongObject` will be + returned. If overflow warnings are not being suppressed, *NULL* will be + returned in this case. + + +-.. cfunction:: PyObject* PyInt_FromLong(long ival) ++.. c:function:: PyObject* PyInt_FromLong(long ival) + + Create a new integer object with a value of *ival*. + +@@ -66,7 +66,7 @@ + undefined. :-) + + +-.. cfunction:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival) ++.. c:function:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival) + + Create a new integer object with a value of *ival*. If the value is larger + than ``LONG_MAX`` or smaller than ``LONG_MIN``, a long integer object is +@@ -75,7 +75,7 @@ + .. versionadded:: 2.5 + + +-.. cfunction:: PyObject* PyInt_FromSize_t(size_t ival) ++.. c:function:: PyObject* PyInt_FromSize_t(size_t ival) + + Create a new integer object with a value of *ival*. If the value exceeds + ``LONG_MAX``, a long integer object is returned. +@@ -83,47 +83,47 @@ + .. versionadded:: 2.5 + + +-.. cfunction:: long PyInt_AsLong(PyObject *io) ++.. c:function:: long PyInt_AsLong(PyObject *io) + +- Will first attempt to cast the object to a :ctype:`PyIntObject`, if it is not ++ Will first attempt to cast the object to a :c:type:`PyIntObject`, if it is not + already one, and then return its value. If there is an error, ``-1`` is + returned, and the caller should check ``PyErr_Occurred()`` to find out whether + there was an error, or whether the value just happened to be -1. + + +-.. cfunction:: long PyInt_AS_LONG(PyObject *io) ++.. c:function:: long PyInt_AS_LONG(PyObject *io) + + Return the value of the object *io*. No error checking is performed. + + +-.. cfunction:: unsigned long PyInt_AsUnsignedLongMask(PyObject *io) ++.. c:function:: unsigned long PyInt_AsUnsignedLongMask(PyObject *io) + +- Will first attempt to cast the object to a :ctype:`PyIntObject` or +- :ctype:`PyLongObject`, if it is not already one, and then return its value as ++ Will first attempt to cast the object to a :c:type:`PyIntObject` or ++ :c:type:`PyLongObject`, if it is not already one, and then return its value as + unsigned long. This function does not check for overflow. + + .. versionadded:: 2.3 + + +-.. cfunction:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io) ++.. c:function:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io) + +- Will first attempt to cast the object to a :ctype:`PyIntObject` or +- :ctype:`PyLongObject`, if it is not already one, and then return its value as ++ Will first attempt to cast the object to a :c:type:`PyIntObject` or ++ :c:type:`PyLongObject`, if it is not already one, and then return its value as + unsigned long long, without checking for overflow. + + .. versionadded:: 2.3 + + +-.. cfunction:: Py_ssize_t PyInt_AsSsize_t(PyObject *io) ++.. c:function:: Py_ssize_t PyInt_AsSsize_t(PyObject *io) + +- Will first attempt to cast the object to a :ctype:`PyIntObject` or +- :ctype:`PyLongObject`, if it is not already one, and then return its value as +- :ctype:`Py_ssize_t`. ++ Will first attempt to cast the object to a :c:type:`PyIntObject` or ++ :c:type:`PyLongObject`, if it is not already one, and then return its value as ++ :c:type:`Py_ssize_t`. + + .. versionadded:: 2.5 + + +-.. cfunction:: long PyInt_GetMax() ++.. c:function:: long PyInt_GetMax() + + .. index:: single: LONG_MAX + +@@ -131,7 +131,7 @@ + (:const:`LONG_MAX`, as defined in the system header files). + + +-.. cfunction:: int PyInt_ClearFreeList() ++.. c:function:: int PyInt_ClearFreeList() + + Clear the integer free list. Return the number of items that could not + be freed. +diff -r 8527427914a2 Doc/c-api/intro.rst +--- a/Doc/c-api/intro.rst ++++ b/Doc/c-api/intro.rst +@@ -88,15 +88,15 @@ + .. index:: object: type + + Most Python/C API functions have one or more arguments as well as a return value +-of type :ctype:`PyObject\*`. This type is a pointer to an opaque data type ++of type :c:type:`PyObject\*`. This type is a pointer to an opaque data type + representing an arbitrary Python object. Since all Python object types are + treated the same way by the Python language in most situations (e.g., + assignments, scope rules, and argument passing), it is only fitting that they + should be represented by a single C type. Almost all Python objects live on the + heap: you never declare an automatic or static variable of type +-:ctype:`PyObject`, only pointer variables of type :ctype:`PyObject\*` can be ++:c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can be + declared. The sole exception are the type objects; since these must never be +-deallocated, they are typically static :ctype:`PyTypeObject` objects. ++deallocated, they are typically static :c:type:`PyTypeObject` objects. + + All Python objects (even Python integers) have a :dfn:`type` and a + :dfn:`reference count`. An object's type determines what kind of object it is +@@ -127,8 +127,8 @@ + single: Py_DECREF() + + Reference counts are always manipulated explicitly. The normal way is to use +-the macro :cfunc:`Py_INCREF` to increment an object's reference count by one, +-and :cfunc:`Py_DECREF` to decrement it by one. The :cfunc:`Py_DECREF` macro ++the macro :c:func:`Py_INCREF` to increment an object's reference count by one, ++and :c:func:`Py_DECREF` to decrement it by one. The :c:func:`Py_DECREF` macro + is considerably more complex than the incref one, since it must check whether + the reference count becomes zero and then cause the object's deallocator to be + called. The deallocator is a function pointer contained in the object's type +@@ -159,13 +159,13 @@ + conceivably remove the object from the list, decrementing its reference count + and possible deallocating it. The real danger is that innocent-looking + operations may invoke arbitrary Python code which could do this; there is a code +-path which allows control to flow back to the user from a :cfunc:`Py_DECREF`, so ++path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so + almost any operation is potentially dangerous. + + A safe approach is to always use the generic operations (functions whose name + begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``). + These operations always increment the reference count of the object they return. +-This leaves the caller with the responsibility to call :cfunc:`Py_DECREF` when ++This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when + they are done with the result; this soon becomes second nature. + + +@@ -180,7 +180,7 @@ + reference" means being responsible for calling Py_DECREF on it when the + reference is no longer needed. Ownership can also be transferred, meaning that + the code that receives ownership of the reference then becomes responsible for +-eventually decref'ing it by calling :cfunc:`Py_DECREF` or :cfunc:`Py_XDECREF` ++eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF` + when it's no longer needed---or passing on this responsibility (usually to its + caller). When a function passes ownership of a reference on to its caller, the + caller is said to receive a *new* reference. When no ownership is transferred, +@@ -198,7 +198,7 @@ + single: PyTuple_SetItem() + + Few functions steal references; the two notable exceptions are +-:cfunc:`PyList_SetItem` and :cfunc:`PyTuple_SetItem`, which steal a reference ++:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which steal a reference + to the item (but not to the tuple or list into which the item is put!). These + functions were designed to steal a reference because of a common idiom for + populating a tuple or list with newly created objects; for example, the code to +@@ -212,21 +212,21 @@ + PyTuple_SetItem(t, 1, PyInt_FromLong(2L)); + PyTuple_SetItem(t, 2, PyString_FromString("three")); + +-Here, :cfunc:`PyInt_FromLong` returns a new reference which is immediately +-stolen by :cfunc:`PyTuple_SetItem`. When you want to keep using an object +-although the reference to it will be stolen, use :cfunc:`Py_INCREF` to grab ++Here, :c:func:`PyInt_FromLong` returns a new reference which is immediately ++stolen by :c:func:`PyTuple_SetItem`. When you want to keep using an object ++although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab + another reference before calling the reference-stealing function. + +-Incidentally, :cfunc:`PyTuple_SetItem` is the *only* way to set tuple items; +-:cfunc:`PySequence_SetItem` and :cfunc:`PyObject_SetItem` refuse to do this ++Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items; ++:c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this + since tuples are an immutable data type. You should only use +-:cfunc:`PyTuple_SetItem` for tuples that you are creating yourself. ++:c:func:`PyTuple_SetItem` for tuples that you are creating yourself. + +-Equivalent code for populating a list can be written using :cfunc:`PyList_New` +-and :cfunc:`PyList_SetItem`. ++Equivalent code for populating a list can be written using :c:func:`PyList_New` ++and :c:func:`PyList_SetItem`. + + However, in practice, you will rarely use these ways of creating and populating +-a tuple or list. There's a generic function, :cfunc:`Py_BuildValue`, that can ++a tuple or list. There's a generic function, :c:func:`Py_BuildValue`, that can + create most common objects from C values, directed by a :dfn:`format string`. + For example, the above two blocks of code could be replaced by the following + (which also takes care of the error checking):: +@@ -236,7 +236,7 @@ + tuple = Py_BuildValue("(iis)", 1, 2, "three"); + list = Py_BuildValue("[iis]", 1, 2, "three"); + +-It is much more common to use :cfunc:`PyObject_SetItem` and friends with items ++It is much more common to use :c:func:`PyObject_SetItem` and friends with items + whose references you are only borrowing, like arguments that were passed in to + the function you are writing. In that case, their behaviour regarding reference + counts is much saner, since you don't have to increment a reference count so you +@@ -270,15 +270,15 @@ + you ownership of the reference. The reason is simple: in many cases, the + returned object is created on the fly, and the reference you get is the only + reference to the object. Therefore, the generic functions that return object +-references, like :cfunc:`PyObject_GetItem` and :cfunc:`PySequence_GetItem`, ++references, like :c:func:`PyObject_GetItem` and :c:func:`PySequence_GetItem`, + always return a new reference (the caller becomes the owner of the reference). + + It is important to realize that whether you own a reference returned by a + function depends on which function you call only --- *the plumage* (the type of + the object passed as an argument to the function) *doesn't enter into it!* +-Thus, if you extract an item from a list using :cfunc:`PyList_GetItem`, you ++Thus, if you extract an item from a list using :c:func:`PyList_GetItem`, you + don't own the reference --- but if you obtain the same item from the same list +-using :cfunc:`PySequence_GetItem` (which happens to take exactly the same ++using :c:func:`PySequence_GetItem` (which happens to take exactly the same + arguments), you do own a reference to the returned object. + + .. index:: +@@ -286,8 +286,8 @@ + single: PySequence_GetItem() + + Here is an example of how you could write a function that computes the sum of +-the items in a list of integers; once using :cfunc:`PyList_GetItem`, and once +-using :cfunc:`PySequence_GetItem`. :: ++the items in a list of integers; once using :c:func:`PyList_GetItem`, and once ++using :c:func:`PySequence_GetItem`. :: + + long + sum_list(PyObject *list) +@@ -340,8 +340,8 @@ + ----- + + There are few other data types that play a significant role in the Python/C +-API; most are simple C types such as :ctype:`int`, :ctype:`long`, +-:ctype:`double` and :ctype:`char\*`. A few structure types are used to ++API; most are simple C types such as :c:type:`int`, :c:type:`long`, ++:c:type:`double` and :c:type:`char\*`. A few structure types are used to + describe static tables used to list the functions exported by a module or the + data attributes of a new object type, and another is used to describe the value + of a complex number. These will be discussed together with the functions that +@@ -370,7 +370,7 @@ + A few functions return a Boolean true/false result, with false indicating an + error. Very few functions return no explicit error indicator or have an + ambiguous return value, and require explicit testing for errors with +-:cfunc:`PyErr_Occurred`. These exceptions are always explicitly documented. ++:c:func:`PyErr_Occurred`. These exceptions are always explicitly documented. + + .. index:: + single: PyErr_SetString() +@@ -379,11 +379,11 @@ + Exception state is maintained in per-thread storage (this is equivalent to + using global storage in an unthreaded application). A thread can be in one of + two states: an exception has occurred, or not. The function +-:cfunc:`PyErr_Occurred` can be used to check for this: it returns a borrowed ++:c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed + reference to the exception type object when an exception has occurred, and + *NULL* otherwise. There are a number of functions to set the exception state: +-:cfunc:`PyErr_SetString` is the most common (though not the most general) +-function to set the exception state, and :cfunc:`PyErr_Clear` clears the ++:c:func:`PyErr_SetString` is the most common (though not the most general) ++function to set the exception state, and :c:func:`PyErr_Clear` clears the + exception state. + + .. index:: +@@ -424,7 +424,7 @@ + .. index:: single: sum_sequence() + + A simple example of detecting exceptions and passing them on is shown in the +-:cfunc:`sum_sequence` example above. It so happens that that example doesn't ++:c:func:`sum_sequence` example above. It so happens that that example doesn't + need to clean up any owned references when it detects an error. The following + example function shows some error cleanup. First, to remind you why you like + Python, we show the equivalent Python code:: +@@ -491,10 +491,10 @@ + single: Py_XDECREF() + + This example represents an endorsed use of the ``goto`` statement in C! +-It illustrates the use of :cfunc:`PyErr_ExceptionMatches` and +-:cfunc:`PyErr_Clear` to handle specific exceptions, and the use of +-:cfunc:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the +-``'X'`` in the name; :cfunc:`Py_DECREF` would crash when confronted with a ++It illustrates the use of :c:func:`PyErr_ExceptionMatches` and ++:c:func:`PyErr_Clear` to handle specific exceptions, and the use of ++:c:func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the ++``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a + *NULL* reference). It is important that the variables used to hold owned + references are initialized to *NULL* for this to work; likewise, the proposed + return value is initialized to ``-1`` (failure) and only set to success after +@@ -520,20 +520,20 @@ + triple: module; search; path + single: path (in module sys) + +-The basic initialization function is :cfunc:`Py_Initialize`. This initializes ++The basic initialization function is :c:func:`Py_Initialize`. This initializes + the table of loaded modules, and creates the fundamental modules + :mod:`__builtin__`, :mod:`__main__`, :mod:`sys`, and :mod:`exceptions`. It also + initializes the module search path (``sys.path``). + + .. index:: single: PySys_SetArgvEx() + +-:cfunc:`Py_Initialize` does not set the "script argument list" (``sys.argv``). ++:c:func:`Py_Initialize` does not set the "script argument list" (``sys.argv``). + If this variable is needed by Python code that will be executed later, it must + be set explicitly with a call to ``PySys_SetArgvEx(argc, argv, updatepath)`` +-after the call to :cfunc:`Py_Initialize`. ++after the call to :c:func:`Py_Initialize`. + + On most systems (in particular, on Unix and Windows, although the details are +-slightly different), :cfunc:`Py_Initialize` calculates the module search path ++slightly different), :c:func:`Py_Initialize` calculates the module search path + based upon its best guess for the location of the standard Python interpreter + executable, assuming that the Python library is found in a fixed location + relative to the Python interpreter executable. In particular, it looks for a +@@ -557,22 +557,22 @@ + single: Py_GetProgramFullPath() + + The embedding application can steer the search by calling +-``Py_SetProgramName(file)`` *before* calling :cfunc:`Py_Initialize`. Note that ++``Py_SetProgramName(file)`` *before* calling :c:func:`Py_Initialize`. Note that + :envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still + inserted in front of the standard path. An application that requires total +-control has to provide its own implementation of :cfunc:`Py_GetPath`, +-:cfunc:`Py_GetPrefix`, :cfunc:`Py_GetExecPrefix`, and +-:cfunc:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`). ++control has to provide its own implementation of :c:func:`Py_GetPath`, ++:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and ++:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`). + + .. index:: single: Py_IsInitialized() + + Sometimes, it is desirable to "uninitialize" Python. For instance, the + application may want to start over (make another call to +-:cfunc:`Py_Initialize`) or the application is simply done with its use of ++:c:func:`Py_Initialize`) or the application is simply done with its use of + Python and wants to free memory allocated by Python. This can be accomplished +-by calling :cfunc:`Py_Finalize`. The function :cfunc:`Py_IsInitialized` returns ++by calling :c:func:`Py_Finalize`. The function :c:func:`Py_IsInitialized` returns + true if Python is currently in the initialized state. More information about +-these functions is given in a later chapter. Notice that :cfunc:`Py_Finalize` ++these functions is given in a later chapter. Notice that :c:func:`Py_Finalize` + does *not* free all memory allocated by the Python interpreter, e.g. memory + allocated by extension modules currently cannot be released. + +@@ -592,11 +592,11 @@ + allocator, or low-level profiling of the main interpreter loop. Only the most + frequently-used builds will be described in the remainder of this section. + +-Compiling the interpreter with the :cmacro:`Py_DEBUG` macro defined produces +-what is generally meant by "a debug build" of Python. :cmacro:`Py_DEBUG` is +-enabled in the Unix build by adding :option:`--with-pydebug` to the +-:file:`configure` command. It is also implied by the presence of the +-not-Python-specific :cmacro:`_DEBUG` macro. When :cmacro:`Py_DEBUG` is enabled ++Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces ++what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is ++enabled in the Unix build by adding ``--with-pydebug`` to the ++:file:`./configure` command. It is also implied by the presence of the ++not-Python-specific :c:macro:`_DEBUG` macro. When :c:macro:`Py_DEBUG` is enabled + in the Unix build, compiler optimization is disabled. + + In addition to the reference count debugging described below, the following +@@ -625,11 +625,11 @@ + + There may be additional checks not mentioned here. + +-Defining :cmacro:`Py_TRACE_REFS` enables reference tracing. When defined, a ++Defining :c:macro:`Py_TRACE_REFS` enables reference tracing. When defined, a + circular doubly linked list of active objects is maintained by adding two extra +-fields to every :ctype:`PyObject`. Total allocations are tracked as well. Upon ++fields to every :c:type:`PyObject`. Total allocations are tracked as well. Upon + exit, all existing references are printed. (In interactive mode this happens +-after every statement run by the interpreter.) Implied by :cmacro:`Py_DEBUG`. ++after every statement run by the interpreter.) Implied by :c:macro:`Py_DEBUG`. + + Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution + for more detailed information. +diff -r 8527427914a2 Doc/c-api/iter.rst +--- a/Doc/c-api/iter.rst ++++ b/Doc/c-api/iter.rst +@@ -10,12 +10,12 @@ + There are only a couple of functions specifically for working with iterators. + + +-.. cfunction:: int PyIter_Check(PyObject *o) ++.. c:function:: int PyIter_Check(PyObject *o) + + Return true if the object *o* supports the iterator protocol. + + +-.. cfunction:: PyObject* PyIter_Next(PyObject *o) ++.. c:function:: PyObject* PyIter_Next(PyObject *o) + + Return the next value from the iteration *o*. If the object is an iterator, + this retrieves the next value from the iteration, and returns *NULL* with no +diff -r 8527427914a2 Doc/c-api/iterator.rst +--- a/Doc/c-api/iterator.rst ++++ b/Doc/c-api/iterator.rst +@@ -12,23 +12,23 @@ + sentinel value is returned. + + +-.. cvar:: PyTypeObject PySeqIter_Type ++.. c:var:: PyTypeObject PySeqIter_Type + +- Type object for iterator objects returned by :cfunc:`PySeqIter_New` and the ++ Type object for iterator objects returned by :c:func:`PySeqIter_New` and the + one-argument form of the :func:`iter` built-in function for built-in sequence + types. + + .. versionadded:: 2.2 + + +-.. cfunction:: int PySeqIter_Check(op) ++.. c:function:: int PySeqIter_Check(op) + +- Return true if the type of *op* is :cdata:`PySeqIter_Type`. ++ Return true if the type of *op* is :c:data:`PySeqIter_Type`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PySeqIter_New(PyObject *seq) ++.. c:function:: PyObject* PySeqIter_New(PyObject *seq) + + Return an iterator that works with a general sequence object, *seq*. The + iteration ends when the sequence raises :exc:`IndexError` for the subscripting +@@ -37,22 +37,22 @@ + .. versionadded:: 2.2 + + +-.. cvar:: PyTypeObject PyCallIter_Type ++.. c:var:: PyTypeObject PyCallIter_Type + +- Type object for iterator objects returned by :cfunc:`PyCallIter_New` and the ++ Type object for iterator objects returned by :c:func:`PyCallIter_New` and the + two-argument form of the :func:`iter` built-in function. + + .. versionadded:: 2.2 + + +-.. cfunction:: int PyCallIter_Check(op) ++.. c:function:: int PyCallIter_Check(op) + +- Return true if the type of *op* is :cdata:`PyCallIter_Type`. ++ Return true if the type of *op* is :c:data:`PyCallIter_Type`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) ++.. c:function:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) + + Return a new iterator. The first parameter, *callable*, can be any Python + callable object that can be called with no parameters; each call to it should +diff -r 8527427914a2 Doc/c-api/list.rst +--- a/Doc/c-api/list.rst ++++ b/Doc/c-api/list.rst +@@ -8,18 +8,18 @@ + .. index:: object: list + + +-.. ctype:: PyListObject ++.. c:type:: PyListObject + +- This subtype of :ctype:`PyObject` represents a Python list object. ++ This subtype of :c:type:`PyObject` represents a Python list object. + + +-.. cvar:: PyTypeObject PyList_Type ++.. c:var:: PyTypeObject PyList_Type + +- This instance of :ctype:`PyTypeObject` represents the Python list type. This ++ This instance of :c:type:`PyTypeObject` represents the Python list type. This + is the same object as ``list`` in the Python layer. + + +-.. cfunction:: int PyList_Check(PyObject *p) ++.. c:function:: int PyList_Check(PyObject *p) + + Return true if *p* is a list object or an instance of a subtype of the list + type. +@@ -28,7 +28,7 @@ + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyList_CheckExact(PyObject *p) ++.. c:function:: int PyList_CheckExact(PyObject *p) + + Return true if *p* is a list object, but not an instance of a subtype of + the list type. +@@ -36,7 +36,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyList_New(Py_ssize_t len) ++.. c:function:: PyObject* PyList_New(Py_ssize_t len) + + Return a new list of length *len* on success, or *NULL* on failure. + +@@ -44,15 +44,15 @@ + + If *len* is greater than zero, the returned list object's items are + set to ``NULL``. Thus you cannot use abstract API functions such as +- :cfunc:`PySequence_SetItem` or expose the object to Python code before +- setting all items to a real object with :cfunc:`PyList_SetItem`. ++ :c:func:`PySequence_SetItem` or expose the object to Python code before ++ setting all items to a real object with :c:func:`PyList_SetItem`. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *size*. This might require ++ This function used an :c:type:`int` for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyList_Size(PyObject *list) ++.. c:function:: Py_ssize_t PyList_Size(PyObject *list) + + .. index:: builtin: len + +@@ -60,20 +60,20 @@ + ``len(list)`` on a list object. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int`. This might require changes in ++ This function returned an :c:type:`int`. This might require changes in + your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyList_GET_SIZE(PyObject *list) ++.. c:function:: Py_ssize_t PyList_GET_SIZE(PyObject *list) + +- Macro form of :cfunc:`PyList_Size` without error checking. ++ Macro form of :c:func:`PyList_Size` without error checking. + + .. versionchanged:: 2.5 +- This macro returned an :ctype:`int`. This might require changes in your ++ This macro returned an :c:type:`int`. This might require changes in your + code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index) ++.. c:function:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index) + + Return the object at position *index* in the list pointed to by *list*. The + position must be positive, indexing from the end of the list is not +@@ -81,20 +81,20 @@ + :exc:`IndexError` exception. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *index*. This might require ++ This function used an :c:type:`int` for *index*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i) ++.. c:function:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i) + +- Macro form of :cfunc:`PyList_GetItem` without error checking. ++ Macro form of :c:func:`PyList_GetItem` without error checking. + + .. versionchanged:: 2.5 +- This macro used an :ctype:`int` for *i*. This might require changes in ++ This macro used an :c:type:`int` for *i*. This might require changes in + your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item) ++.. c:function:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item) + + Set the item at index *index* in list to *item*. Return ``0`` on success + or ``-1`` on failure. +@@ -105,46 +105,46 @@ + an item already in the list at the affected position. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *index*. This might require ++ This function used an :c:type:`int` for *index*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o) ++.. c:function:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o) + +- Macro form of :cfunc:`PyList_SetItem` without error checking. This is ++ Macro form of :c:func:`PyList_SetItem` without error checking. This is + normally only used to fill in new lists where there is no previous content. + + .. note:: + + This macro "steals" a reference to *item*, and, unlike +- :cfunc:`PyList_SetItem`, does *not* discard a reference to any item that ++ :c:func:`PyList_SetItem`, does *not* discard a reference to any item that + it being replaced; any reference in *list* at position *i* will be + leaked. + + .. versionchanged:: 2.5 +- This macro used an :ctype:`int` for *i*. This might require ++ This macro used an :c:type:`int` for *i*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item) ++.. c:function:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item) + + Insert the item *item* into list *list* in front of index *index*. Return + ``0`` if successful; return ``-1`` and set an exception if unsuccessful. + Analogous to ``list.insert(index, item)``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *index*. This might require ++ This function used an :c:type:`int` for *index*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyList_Append(PyObject *list, PyObject *item) ++.. c:function:: int PyList_Append(PyObject *list, PyObject *item) + + Append the object *item* at the end of list *list*. Return ``0`` if + successful; return ``-1`` and set an exception if unsuccessful. Analogous + to ``list.append(item)``. + + +-.. cfunction:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high) ++.. c:function:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high) + + Return a list of the objects in *list* containing the objects *between* *low* + and *high*. Return *NULL* and set an exception if unsuccessful. Analogous +@@ -152,11 +152,11 @@ + supported. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *low* and *high*. This might ++ This function used an :c:type:`int` for *low* and *high*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist) ++.. c:function:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist) + + Set the slice of *list* between *low* and *high* to the contents of + *itemlist*. Analogous to ``list[low:high] = itemlist``. The *itemlist* may +@@ -165,23 +165,23 @@ + slicing from Python, are not supported. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *low* and *high*. This might ++ This function used an :c:type:`int` for *low* and *high*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyList_Sort(PyObject *list) ++.. c:function:: int PyList_Sort(PyObject *list) + + Sort the items of *list* in place. Return ``0`` on success, ``-1`` on + failure. This is equivalent to ``list.sort()``. + + +-.. cfunction:: int PyList_Reverse(PyObject *list) ++.. c:function:: int PyList_Reverse(PyObject *list) + + Reverse the items of *list* in place. Return ``0`` on success, ``-1`` on + failure. This is the equivalent of ``list.reverse()``. + + +-.. cfunction:: PyObject* PyList_AsTuple(PyObject *list) ++.. c:function:: PyObject* PyList_AsTuple(PyObject *list) + + .. index:: builtin: tuple + +diff -r 8527427914a2 Doc/c-api/long.rst +--- a/Doc/c-api/long.rst ++++ b/Doc/c-api/long.rst +@@ -8,100 +8,100 @@ + .. index:: object: long integer + + +-.. ctype:: PyLongObject ++.. c:type:: PyLongObject + +- This subtype of :ctype:`PyObject` represents a Python long integer object. ++ This subtype of :c:type:`PyObject` represents a Python long integer object. + + +-.. cvar:: PyTypeObject PyLong_Type ++.. c:var:: PyTypeObject PyLong_Type + + .. index:: single: LongType (in modules types) + +- This instance of :ctype:`PyTypeObject` represents the Python long integer type. ++ This instance of :c:type:`PyTypeObject` represents the Python long integer type. + This is the same object as ``long`` and ``types.LongType``. + + +-.. cfunction:: int PyLong_Check(PyObject *p) ++.. c:function:: int PyLong_Check(PyObject *p) + +- Return true if its argument is a :ctype:`PyLongObject` or a subtype of +- :ctype:`PyLongObject`. ++ Return true if its argument is a :c:type:`PyLongObject` or a subtype of ++ :c:type:`PyLongObject`. + + .. versionchanged:: 2.2 + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyLong_CheckExact(PyObject *p) ++.. c:function:: int PyLong_CheckExact(PyObject *p) + +- Return true if its argument is a :ctype:`PyLongObject`, but not a subtype of +- :ctype:`PyLongObject`. ++ Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of ++ :c:type:`PyLongObject`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyLong_FromLong(long v) ++.. c:function:: PyObject* PyLong_FromLong(long v) + +- Return a new :ctype:`PyLongObject` object from *v*, or *NULL* on failure. ++ Return a new :c:type:`PyLongObject` object from *v*, or *NULL* on failure. + + +-.. cfunction:: PyObject* PyLong_FromUnsignedLong(unsigned long v) ++.. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v) + +- Return a new :ctype:`PyLongObject` object from a C :ctype:`unsigned long`, or ++ Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long`, or + *NULL* on failure. + + +-.. cfunction:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) ++.. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) + +- Return a new :ctype:`PyLongObject` object from a C :ctype:`Py_ssize_t`, or ++ Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or + *NULL* on failure. + + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyLong_FromSize_t(size_t v) ++.. c:function:: PyObject* PyLong_FromSize_t(size_t v) + +- Return a new :ctype:`PyLongObject` object from a C :ctype:`size_t`, or ++ Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or + *NULL* on failure. + + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) ++.. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v) + +- Return a new :ctype:`PyLongObject` object with a value of *v*, or *NULL* ++ Return a new :c:type:`PyLongObject` object with a value of *v*, or *NULL* + on failure. + + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyLong_FromSize_t(size_t v) ++.. c:function:: PyObject* PyLong_FromSize_t(size_t v) + +- Return a new :ctype:`PyLongObject` object with a value of *v*, or *NULL* ++ Return a new :c:type:`PyLongObject` object with a value of *v*, or *NULL* + on failure. + + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v) ++.. c:function:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v) + +- Return a new :ctype:`PyLongObject` object from a C :ctype:`long long`, or *NULL* ++ Return a new :c:type:`PyLongObject` object from a C :c:type:`long long`, or *NULL* + on failure. + + +-.. cfunction:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v) ++.. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v) + +- Return a new :ctype:`PyLongObject` object from a C :ctype:`unsigned long long`, ++ Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long long`, + or *NULL* on failure. + + +-.. cfunction:: PyObject* PyLong_FromDouble(double v) ++.. c:function:: PyObject* PyLong_FromDouble(double v) + +- Return a new :ctype:`PyLongObject` object from the integer part of *v*, or ++ Return a new :c:type:`PyLongObject` object from the integer part of *v*, or + *NULL* on failure. + + +-.. cfunction:: PyObject* PyLong_FromString(char *str, char **pend, int base) ++.. c:function:: PyObject* PyLong_FromString(char *str, char **pend, int base) + +- Return a new :ctype:`PyLongObject` based on the string value in *str*, which is ++ Return a new :c:type:`PyLongObject` based on the string value in *str*, which is + interpreted according to the radix in *base*. If *pend* is non-*NULL*, + *\*pend* will point to the first character in *str* which follows the + representation of the number. If *base* is ``0``, the radix will be determined +@@ -112,7 +112,7 @@ + no digits, :exc:`ValueError` will be raised. + + +-.. cfunction:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) ++.. c:function:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) + + Convert a sequence of Unicode digits to a Python long integer value. The first + parameter, *u*, points to the first character of the Unicode string, *length* +@@ -123,14 +123,14 @@ + .. versionadded:: 1.6 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` for *length*. This might require ++ This function used an :c:type:`int` for *length*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyLong_FromVoidPtr(void *p) ++.. c:function:: PyObject* PyLong_FromVoidPtr(void *p) + + Create a Python integer or long integer from the pointer *p*. The pointer value +- can be retrieved from the resulting value using :cfunc:`PyLong_AsVoidPtr`. ++ can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`. + + .. versionadded:: 1.5.2 + +@@ -138,20 +138,20 @@ + If the integer is larger than LONG_MAX, a positive long integer is returned. + + +-.. cfunction:: long PyLong_AsLong(PyObject *pylong) ++.. c:function:: long PyLong_AsLong(PyObject *pylong) + + .. index:: + single: LONG_MAX + single: OverflowError (built-in exception) + +- Return a C :ctype:`long` representation of the contents of *pylong*. If ++ Return a C :c:type:`long` representation of the contents of *pylong*. If + *pylong* is greater than :const:`LONG_MAX`, an :exc:`OverflowError` is raised + and ``-1`` will be returned. + + +-.. cfunction:: long PyLong_AsLongAndOverflow(PyObject *pylong, int *overflow) ++.. c:function:: long PyLong_AsLongAndOverflow(PyObject *pylong, int *overflow) + +- Return a C :ctype:`long` representation of the contents of ++ Return a C :c:type:`long` representation of the contents of + *pylong*. If *pylong* is greater than :const:`LONG_MAX` or less + than :const:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, + respectively, and return ``-1``; otherwise, set *\*overflow* to +@@ -162,9 +162,9 @@ + .. versionadded:: 2.7 + + +-.. cfunction:: PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *pylong, int *overflow) ++.. c:function:: PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *pylong, int *overflow) + +- Return a C :ctype:`long long` representation of the contents of ++ Return a C :c:type:`long long` representation of the contents of + *pylong*. If *pylong* is greater than :const:`PY_LLONG_MAX` or less + than :const:`PY_LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, + respectively, and return ``-1``; otherwise, set *\*overflow* to +@@ -175,61 +175,61 @@ + .. versionadded:: 2.7 + + +-.. cfunction:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) ++.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) + + .. index:: + single: PY_SSIZE_T_MAX + single: OverflowError (built-in exception) + +- Return a C :ctype:`Py_ssize_t` representation of the contents of *pylong*. If ++ Return a C :c:type:`Py_ssize_t` representation of the contents of *pylong*. If + *pylong* is greater than :const:`PY_SSIZE_T_MAX`, an :exc:`OverflowError` is raised + and ``-1`` will be returned. + + .. versionadded:: 2.6 + + +-.. cfunction:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) ++.. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong) + + .. index:: + single: ULONG_MAX + single: OverflowError (built-in exception) + +- Return a C :ctype:`unsigned long` representation of the contents of *pylong*. ++ Return a C :c:type:`unsigned long` representation of the contents of *pylong*. + If *pylong* is greater than :const:`ULONG_MAX`, an :exc:`OverflowError` is + raised. + + +-.. cfunction:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) ++.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong) + + .. index:: + single: PY_SSIZE_T_MAX + +- Return a :ctype:`Py_ssize_t` representation of the contents of *pylong*. If ++ Return a :c:type:`Py_ssize_t` representation of the contents of *pylong*. If + *pylong* is greater than :const:`PY_SSIZE_T_MAX`, an :exc:`OverflowError` is + raised. + + .. versionadded:: 2.6 + + +-.. cfunction:: PY_LONG_LONG PyLong_AsLongLong(PyObject *pylong) ++.. c:function:: PY_LONG_LONG PyLong_AsLongLong(PyObject *pylong) + + .. index:: + single: OverflowError (built-in exception) + +- Return a C :ctype:`long long` from a Python long integer. If +- *pylong* cannot be represented as a :ctype:`long long`, an ++ Return a C :c:type:`long long` from a Python long integer. If ++ *pylong* cannot be represented as a :c:type:`long long`, an + :exc:`OverflowError` is raised and ``-1`` is returned. + + .. versionadded:: 2.2 + + +-.. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong) ++.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong) + + .. index:: + single: OverflowError (built-in exception) + +- Return a C :ctype:`unsigned long long` from a Python long integer. If +- *pylong* cannot be represented as an :ctype:`unsigned long long`, an ++ Return a C :c:type:`unsigned long long` from a Python long integer. If ++ *pylong* cannot be represented as an :c:type:`unsigned long long`, an + :exc:`OverflowError` is raised and ``(unsigned long long)-1`` is + returned. + +@@ -240,35 +240,35 @@ + :exc:`TypeError`. + + +-.. cfunction:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io) ++.. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io) + +- Return a C :ctype:`unsigned long` from a Python long integer, without checking ++ Return a C :c:type:`unsigned long` from a Python long integer, without checking + for overflow. + + .. versionadded:: 2.3 + + +-.. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io) ++.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io) + +- Return a C :ctype:`unsigned long long` from a Python long integer, without ++ Return a C :c:type:`unsigned long long` from a Python long integer, without + checking for overflow. + + .. versionadded:: 2.3 + + +-.. cfunction:: double PyLong_AsDouble(PyObject *pylong) ++.. c:function:: double PyLong_AsDouble(PyObject *pylong) + +- Return a C :ctype:`double` representation of the contents of *pylong*. If +- *pylong* cannot be approximately represented as a :ctype:`double`, an ++ Return a C :c:type:`double` representation of the contents of *pylong*. If ++ *pylong* cannot be approximately represented as a :c:type:`double`, an + :exc:`OverflowError` exception is raised and ``-1.0`` will be returned. + + +-.. cfunction:: void* PyLong_AsVoidPtr(PyObject *pylong) ++.. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong) + +- Convert a Python integer or long integer *pylong* to a C :ctype:`void` pointer. ++ Convert a Python integer or long integer *pylong* to a C :c:type:`void` pointer. + If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This +- is only assured to produce a usable :ctype:`void` pointer for values created +- with :cfunc:`PyLong_FromVoidPtr`. ++ is only assured to produce a usable :c:type:`void` pointer for values created ++ with :c:func:`PyLong_FromVoidPtr`. + + .. versionadded:: 1.5.2 + +diff -r 8527427914a2 Doc/c-api/mapping.rst +--- a/Doc/c-api/mapping.rst ++++ b/Doc/c-api/mapping.rst +@@ -6,13 +6,13 @@ + ================ + + +-.. cfunction:: int PyMapping_Check(PyObject *o) ++.. c:function:: int PyMapping_Check(PyObject *o) + + Return ``1`` if the object provides mapping protocol, and ``0`` otherwise. This + function always succeeds. + + +-.. cfunction:: Py_ssize_t PyMapping_Size(PyObject *o) ++.. c:function:: Py_ssize_t PyMapping_Size(PyObject *o) + Py_ssize_t PyMapping_Length(PyObject *o) + + .. index:: builtin: len +@@ -22,62 +22,62 @@ + expression ``len(o)``. + + .. versionchanged:: 2.5 +- These functions returned an :ctype:`int` type. This might require ++ These functions returned an :c:type:`int` type. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyMapping_DelItemString(PyObject *o, char *key) ++.. c:function:: int PyMapping_DelItemString(PyObject *o, char *key) + + Remove the mapping for object *key* from the object *o*. Return ``-1`` on + failure. This is equivalent to the Python statement ``del o[key]``. + + +-.. cfunction:: int PyMapping_DelItem(PyObject *o, PyObject *key) ++.. c:function:: int PyMapping_DelItem(PyObject *o, PyObject *key) + + Remove the mapping for object *key* from the object *o*. Return ``-1`` on + failure. This is equivalent to the Python statement ``del o[key]``. + + +-.. cfunction:: int PyMapping_HasKeyString(PyObject *o, char *key) ++.. c:function:: int PyMapping_HasKeyString(PyObject *o, char *key) + + On success, return ``1`` if the mapping object has the key *key* and ``0`` + otherwise. This is equivalent to ``o[key]``, returning ``True`` on success + and ``False`` on an exception. This function always succeeds. + + +-.. cfunction:: int PyMapping_HasKey(PyObject *o, PyObject *key) ++.. c:function:: int PyMapping_HasKey(PyObject *o, PyObject *key) + + Return ``1`` if the mapping object has the key *key* and ``0`` otherwise. + This is equivalent to ``o[key]``, returning ``True`` on success and ``False`` + on an exception. This function always succeeds. + + +-.. cfunction:: PyObject* PyMapping_Keys(PyObject *o) ++.. c:function:: PyObject* PyMapping_Keys(PyObject *o) + + On success, return a list of the keys in object *o*. On failure, return *NULL*. + This is equivalent to the Python expression ``o.keys()``. + + +-.. cfunction:: PyObject* PyMapping_Values(PyObject *o) ++.. c:function:: PyObject* PyMapping_Values(PyObject *o) + + On success, return a list of the values in object *o*. On failure, return + *NULL*. This is equivalent to the Python expression ``o.values()``. + + +-.. cfunction:: PyObject* PyMapping_Items(PyObject *o) ++.. c:function:: PyObject* PyMapping_Items(PyObject *o) + + On success, return a list of the items in object *o*, where each item is a tuple + containing a key-value pair. On failure, return *NULL*. This is equivalent to + the Python expression ``o.items()``. + + +-.. cfunction:: PyObject* PyMapping_GetItemString(PyObject *o, char *key) ++.. c:function:: PyObject* PyMapping_GetItemString(PyObject *o, char *key) + + Return element of *o* corresponding to the object *key* or *NULL* on failure. + This is the equivalent of the Python expression ``o[key]``. + + +-.. cfunction:: int PyMapping_SetItemString(PyObject *o, char *key, PyObject *v) ++.. c:function:: int PyMapping_SetItemString(PyObject *o, char *key, PyObject *v) + + Map the object *key* to the value *v* in object *o*. Returns ``-1`` on failure. + This is the equivalent of the Python statement ``o[key] = v``. +diff -r 8527427914a2 Doc/c-api/marshal.rst +--- a/Doc/c-api/marshal.rst ++++ b/Doc/c-api/marshal.rst +@@ -20,17 +20,17 @@ + file format (currently 2). + + +-.. cfunction:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) ++.. c:function:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version) + +- Marshal a :ctype:`long` integer, *value*, to *file*. This will only write ++ Marshal a :c:type:`long` integer, *value*, to *file*. This will only write + the least-significant 32 bits of *value*; regardless of the size of the +- native :ctype:`long` type. ++ native :c:type:`long` type. + + .. versionchanged:: 2.4 + *version* indicates the file format. + + +-.. cfunction:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) ++.. c:function:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) + + Marshal a Python object, *value*, to *file*. + +@@ -38,7 +38,7 @@ + *version* indicates the file format. + + +-.. cfunction:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) ++.. c:function:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) + + Return a string object containing the marshalled representation of *value*. + +@@ -55,31 +55,31 @@ + written using these routines? + + +-.. cfunction:: long PyMarshal_ReadLongFromFile(FILE *file) ++.. c:function:: long PyMarshal_ReadLongFromFile(FILE *file) + +- Return a C :ctype:`long` from the data stream in a :ctype:`FILE\*` opened ++ Return a C :c:type:`long` from the data stream in a :c:type:`FILE\*` opened + for reading. Only a 32-bit value can be read in using this function, +- regardless of the native size of :ctype:`long`. ++ regardless of the native size of :c:type:`long`. + + +-.. cfunction:: int PyMarshal_ReadShortFromFile(FILE *file) ++.. c:function:: int PyMarshal_ReadShortFromFile(FILE *file) + +- Return a C :ctype:`short` from the data stream in a :ctype:`FILE\*` opened ++ Return a C :c:type:`short` from the data stream in a :c:type:`FILE\*` opened + for reading. Only a 16-bit value can be read in using this function, +- regardless of the native size of :ctype:`short`. ++ regardless of the native size of :c:type:`short`. + + +-.. cfunction:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file) ++.. c:function:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file) + +- Return a Python object from the data stream in a :ctype:`FILE\*` opened for ++ Return a Python object from the data stream in a :c:type:`FILE\*` opened for + reading. On error, sets the appropriate exception (:exc:`EOFError` or + :exc:`TypeError`) and returns *NULL*. + + +-.. cfunction:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) ++.. c:function:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file) + +- Return a Python object from the data stream in a :ctype:`FILE\*` opened for +- reading. Unlike :cfunc:`PyMarshal_ReadObjectFromFile`, this function ++ Return a Python object from the data stream in a :c:type:`FILE\*` opened for ++ reading. Unlike :c:func:`PyMarshal_ReadObjectFromFile`, this function + assumes that no further objects will be read from the file, allowing it to + aggressively load file data into memory so that the de-serialization can + operate from data in memory rather than reading a byte at a time from the +@@ -88,7 +88,7 @@ + (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*. + + +-.. cfunction:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len) ++.. c:function:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len) + + Return a Python object from the data stream in a character buffer + containing *len* bytes pointed to by *string*. On error, sets the +@@ -96,5 +96,5 @@ + *NULL*. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *len*. This might require ++ This function used an :c:type:`int` type for *len*. This might require + changes in your code for properly supporting 64-bit systems. +diff -r 8527427914a2 Doc/c-api/memory.rst +--- a/Doc/c-api/memory.rst ++++ b/Doc/c-api/memory.rst +@@ -47,8 +47,8 @@ + single: free() + + To avoid memory corruption, extension writers should never try to operate on +-Python objects with the functions exported by the C library: :cfunc:`malloc`, +-:cfunc:`calloc`, :cfunc:`realloc` and :cfunc:`free`. This will result in mixed ++Python objects with the functions exported by the C library: :c:func:`malloc`, ++:c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. This will result in mixed + calls between the C allocator and the Python memory manager with fatal + consequences, because they implement different algorithms and operate on + different heaps. However, one may safely allocate and release memory blocks +@@ -94,65 +94,65 @@ + memory from the Python heap: + + +-.. cfunction:: void* PyMem_Malloc(size_t n) ++.. c:function:: void* PyMem_Malloc(size_t n) + +- Allocates *n* bytes and returns a pointer of type :ctype:`void\*` to the ++ Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the + allocated memory, or *NULL* if the request fails. Requesting zero bytes returns +- a distinct non-*NULL* pointer if possible, as if :cfunc:`PyMem_Malloc(1)` had ++ a distinct non-*NULL* pointer if possible, as if :c:func:`PyMem_Malloc(1)` had + been called instead. The memory will not have been initialized in any way. + + +-.. cfunction:: void* PyMem_Realloc(void *p, size_t n) ++.. c:function:: void* PyMem_Realloc(void *p, size_t n) + + Resizes the memory block pointed to by *p* to *n* bytes. The contents will be + unchanged to the minimum of the old and the new sizes. If *p* is *NULL*, the +- call is equivalent to :cfunc:`PyMem_Malloc(n)`; else if *n* is equal to zero, ++ call is equivalent to :c:func:`PyMem_Malloc(n)`; else if *n* is equal to zero, + the memory block is resized but is not freed, and the returned pointer is + non-*NULL*. Unless *p* is *NULL*, it must have been returned by a previous call +- to :cfunc:`PyMem_Malloc` or :cfunc:`PyMem_Realloc`. If the request fails, +- :cfunc:`PyMem_Realloc` returns *NULL* and *p* remains a valid pointer to the ++ to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. If the request fails, ++ :c:func:`PyMem_Realloc` returns *NULL* and *p* remains a valid pointer to the + previous memory area. + + +-.. cfunction:: void PyMem_Free(void *p) ++.. c:function:: void PyMem_Free(void *p) + + Frees the memory block pointed to by *p*, which must have been returned by a +- previous call to :cfunc:`PyMem_Malloc` or :cfunc:`PyMem_Realloc`. Otherwise, or +- if :cfunc:`PyMem_Free(p)` has been called before, undefined behavior occurs. If ++ previous call to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. Otherwise, or ++ if :c:func:`PyMem_Free(p)` has been called before, undefined behavior occurs. If + *p* is *NULL*, no operation is performed. + + The following type-oriented macros are provided for convenience. Note that + *TYPE* refers to any C type. + + +-.. cfunction:: TYPE* PyMem_New(TYPE, size_t n) ++.. c:function:: TYPE* PyMem_New(TYPE, size_t n) + +- Same as :cfunc:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of +- memory. Returns a pointer cast to :ctype:`TYPE\*`. The memory will not have ++ Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of ++ memory. Returns a pointer cast to :c:type:`TYPE\*`. The memory will not have + been initialized in any way. + + +-.. cfunction:: TYPE* PyMem_Resize(void *p, TYPE, size_t n) ++.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n) + +- Same as :cfunc:`PyMem_Realloc`, but the memory block is resized to ``(n * +- sizeof(TYPE))`` bytes. Returns a pointer cast to :ctype:`TYPE\*`. On return, ++ Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n * ++ sizeof(TYPE))`` bytes. Returns a pointer cast to :c:type:`TYPE\*`. On return, + *p* will be a pointer to the new memory area, or *NULL* in the event of + failure. This is a C preprocessor macro; p is always reassigned. Save + the original value of p to avoid losing memory when handling errors. + + +-.. cfunction:: void PyMem_Del(void *p) ++.. c:function:: void PyMem_Del(void *p) + +- Same as :cfunc:`PyMem_Free`. ++ Same as :c:func:`PyMem_Free`. + + In addition, the following macro sets are provided for calling the Python memory + allocator directly, without involving the C API functions listed above. However, + note that their use does not preserve binary compatibility across Python + versions and is therefore deprecated in extension modules. + +-:cfunc:`PyMem_MALLOC`, :cfunc:`PyMem_REALLOC`, :cfunc:`PyMem_FREE`. ++:c:func:`PyMem_MALLOC`, :c:func:`PyMem_REALLOC`, :c:func:`PyMem_FREE`. + +-:cfunc:`PyMem_NEW`, :cfunc:`PyMem_RESIZE`, :cfunc:`PyMem_DEL`. ++:c:func:`PyMem_NEW`, :c:func:`PyMem_RESIZE`, :c:func:`PyMem_DEL`. + + + .. _memoryexamples: +@@ -201,8 +201,8 @@ + free(buf1); /* Fatal -- should be PyMem_Del() */ + + In addition to the functions aimed at handling raw memory blocks from the Python +-heap, objects in Python are allocated and released with :cfunc:`PyObject_New`, +-:cfunc:`PyObject_NewVar` and :cfunc:`PyObject_Del`. ++heap, objects in Python are allocated and released with :c:func:`PyObject_New`, ++:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`. + + These will be explained in the next chapter on defining and implementing new + object types in C. +diff -r 8527427914a2 Doc/c-api/method.rst +--- a/Doc/c-api/method.rst ++++ b/Doc/c-api/method.rst +@@ -10,21 +10,21 @@ + There are some useful functions that are useful for working with method objects. + + +-.. cvar:: PyTypeObject PyMethod_Type ++.. c:var:: PyTypeObject PyMethod_Type + + .. index:: single: MethodType (in module types) + +- This instance of :ctype:`PyTypeObject` represents the Python method type. This ++ This instance of :c:type:`PyTypeObject` represents the Python method type. This + is exposed to Python programs as ``types.MethodType``. + + +-.. cfunction:: int PyMethod_Check(PyObject *o) ++.. c:function:: int PyMethod_Check(PyObject *o) + +- Return true if *o* is a method object (has type :cdata:`PyMethod_Type`). The ++ Return true if *o* is a method object (has type :c:data:`PyMethod_Type`). The + parameter must not be *NULL*. + + +-.. cfunction:: PyObject* PyMethod_New(PyObject *func, PyObject *self, PyObject *class) ++.. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self, PyObject *class) + + Return a new method object, with *func* being any callable object; this is the + function that will be called when the method is called. If this method should +@@ -33,39 +33,39 @@ + class which provides the unbound method.. + + +-.. cfunction:: PyObject* PyMethod_Class(PyObject *meth) ++.. c:function:: PyObject* PyMethod_Class(PyObject *meth) + + Return the class object from which the method *meth* was created; if this was + created from an instance, it will be the class of the instance. + + +-.. cfunction:: PyObject* PyMethod_GET_CLASS(PyObject *meth) ++.. c:function:: PyObject* PyMethod_GET_CLASS(PyObject *meth) + +- Macro version of :cfunc:`PyMethod_Class` which avoids error checking. ++ Macro version of :c:func:`PyMethod_Class` which avoids error checking. + + +-.. cfunction:: PyObject* PyMethod_Function(PyObject *meth) ++.. c:function:: PyObject* PyMethod_Function(PyObject *meth) + + Return the function object associated with the method *meth*. + + +-.. cfunction:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth) ++.. c:function:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth) + +- Macro version of :cfunc:`PyMethod_Function` which avoids error checking. ++ Macro version of :c:func:`PyMethod_Function` which avoids error checking. + + +-.. cfunction:: PyObject* PyMethod_Self(PyObject *meth) ++.. c:function:: PyObject* PyMethod_Self(PyObject *meth) + + Return the instance associated with the method *meth* if it is bound, otherwise + return *NULL*. + + +-.. cfunction:: PyObject* PyMethod_GET_SELF(PyObject *meth) ++.. c:function:: PyObject* PyMethod_GET_SELF(PyObject *meth) + +- Macro version of :cfunc:`PyMethod_Self` which avoids error checking. ++ Macro version of :c:func:`PyMethod_Self` which avoids error checking. + + +-.. cfunction:: int PyMethod_ClearFreeList() ++.. c:function:: int PyMethod_ClearFreeList() + + Clear the free list. Return the total number of freed items. + +diff -r 8527427914a2 Doc/c-api/module.rst +--- a/Doc/c-api/module.rst ++++ b/Doc/c-api/module.rst +@@ -10,15 +10,15 @@ + There are only a few functions special to module objects. + + +-.. cvar:: PyTypeObject PyModule_Type ++.. c:var:: PyTypeObject PyModule_Type + + .. index:: single: ModuleType (in module types) + +- This instance of :ctype:`PyTypeObject` represents the Python module type. This ++ This instance of :c:type:`PyTypeObject` represents the Python module type. This + is exposed to Python programs as ``types.ModuleType``. + + +-.. cfunction:: int PyModule_Check(PyObject *p) ++.. c:function:: int PyModule_Check(PyObject *p) + + Return true if *p* is a module object, or a subtype of a module object. + +@@ -26,15 +26,15 @@ + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyModule_CheckExact(PyObject *p) ++.. c:function:: int PyModule_CheckExact(PyObject *p) + + Return true if *p* is a module object, but not a subtype of +- :cdata:`PyModule_Type`. ++ :c:data:`PyModule_Type`. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyModule_New(const char *name) ++.. c:function:: PyObject* PyModule_New(const char *name) + + .. index:: + single: __name__ (module attribute) +@@ -46,18 +46,18 @@ + the caller is responsible for providing a :attr:`__file__` attribute. + + +-.. cfunction:: PyObject* PyModule_GetDict(PyObject *module) ++.. c:function:: PyObject* PyModule_GetDict(PyObject *module) + + .. index:: single: __dict__ (module attribute) + + Return the dictionary object that implements *module*'s namespace; this object + is the same as the :attr:`__dict__` attribute of the module object. This + function never fails. It is recommended extensions use other +- :cfunc:`PyModule_\*` and :cfunc:`PyObject_\*` functions rather than directly ++ :c:func:`PyModule_\*` and :c:func:`PyObject_\*` functions rather than directly + manipulate a module's :attr:`__dict__`. + + +-.. cfunction:: char* PyModule_GetName(PyObject *module) ++.. c:function:: char* PyModule_GetName(PyObject *module) + + .. index:: + single: __name__ (module attribute) +@@ -67,7 +67,7 @@ + or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned. + + +-.. cfunction:: char* PyModule_GetFilename(PyObject *module) ++.. c:function:: char* PyModule_GetFilename(PyObject *module) + + .. index:: + single: __file__ (module attribute) +@@ -78,7 +78,7 @@ + raise :exc:`SystemError` and return *NULL*. + + +-.. cfunction:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value) ++.. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value) + + Add an object to *module* as *name*. This is a convenience function which can + be used from the module's initialization function. This steals a reference to +@@ -87,7 +87,7 @@ + .. versionadded:: 2.0 + + +-.. cfunction:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) ++.. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) + + Add an integer constant to *module* as *name*. This convenience function can be + used from the module's initialization function. Return ``-1`` on error, ``0`` on +@@ -96,7 +96,7 @@ + .. versionadded:: 2.0 + + +-.. cfunction:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) ++.. c:function:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) + + Add a string constant to *module* as *name*. This convenience function can be + used from the module's initialization function. The string *value* must be +@@ -104,7 +104,7 @@ + + .. versionadded:: 2.0 + +-.. cfunction:: int PyModule_AddIntMacro(PyObject *module, macro) ++.. c:function:: int PyModule_AddIntMacro(PyObject *module, macro) + + Add an int constant to *module*. The name and the value are taken from + *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int +@@ -113,7 +113,7 @@ + + .. versionadded:: 2.6 + +-.. cfunction:: int PyModule_AddStringMacro(PyObject *module, macro) ++.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro) + + Add a string constant to *module*. + +diff -r 8527427914a2 Doc/c-api/none.rst +--- a/Doc/c-api/none.rst ++++ b/Doc/c-api/none.rst +@@ -7,22 +7,22 @@ + + .. index:: object: None + +-Note that the :ctype:`PyTypeObject` for ``None`` is not directly exposed in the ++Note that the :c:type:`PyTypeObject` for ``None`` is not directly exposed in the + Python/C API. Since ``None`` is a singleton, testing for object identity (using +-``==`` in C) is sufficient. There is no :cfunc:`PyNone_Check` function for the ++``==`` in C) is sufficient. There is no :c:func:`PyNone_Check` function for the + same reason. + + +-.. cvar:: PyObject* Py_None ++.. c:var:: PyObject* Py_None + + The Python ``None`` object, denoting lack of value. This object has no methods. + It needs to be treated just like any other object with respect to reference + counts. + + +-.. cmacro:: Py_RETURN_NONE ++.. c:macro:: Py_RETURN_NONE + +- Properly handle returning :cdata:`Py_None` from within a C function. ++ Properly handle returning :c:data:`Py_None` from within a C function. + + .. versionadded:: 2.4 + +diff -r 8527427914a2 Doc/c-api/number.rst +--- a/Doc/c-api/number.rst ++++ b/Doc/c-api/number.rst +@@ -6,37 +6,37 @@ + =============== + + +-.. cfunction:: int PyNumber_Check(PyObject *o) ++.. c:function:: int PyNumber_Check(PyObject *o) + + Returns ``1`` if the object *o* provides numeric protocols, and false otherwise. + This function always succeeds. + + +-.. cfunction:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2) + + Returns the result of adding *o1* and *o2*, or *NULL* on failure. This is the + equivalent of the Python expression ``o1 + o2``. + + +-.. cfunction:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2) + + Returns the result of subtracting *o2* from *o1*, or *NULL* on failure. This is + the equivalent of the Python expression ``o1 - o2``. + + +-.. cfunction:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2) + + Returns the result of multiplying *o1* and *o2*, or *NULL* on failure. This is + the equivalent of the Python expression ``o1 * o2``. + + +-.. cfunction:: PyObject* PyNumber_Divide(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Divide(PyObject *o1, PyObject *o2) + + Returns the result of dividing *o1* by *o2*, or *NULL* on failure. This is the + equivalent of the Python expression ``o1 / o2``. + + +-.. cfunction:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2) + + Return the floor of *o1* divided by *o2*, or *NULL* on failure. This is + equivalent to the "classic" division of integers. +@@ -44,7 +44,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2) + + Return a reasonable approximation for the mathematical value of *o1* divided by + *o2*, or *NULL* on failure. The return value is "approximate" because binary +@@ -55,13 +55,13 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) + + Returns the remainder of dividing *o1* by *o2*, or *NULL* on failure. This is + the equivalent of the Python expression ``o1 % o2``. + + +-.. cfunction:: PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2) + + .. index:: builtin: divmod + +@@ -69,29 +69,29 @@ + the equivalent of the Python expression ``divmod(o1, o2)``. + + +-.. cfunction:: PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3) ++.. c:function:: PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3) + + .. index:: builtin: pow + + See the built-in function :func:`pow`. Returns *NULL* on failure. This is the + equivalent of the Python expression ``pow(o1, o2, o3)``, where *o3* is optional. +- If *o3* is to be ignored, pass :cdata:`Py_None` in its place (passing *NULL* for ++ If *o3* is to be ignored, pass :c:data:`Py_None` in its place (passing *NULL* for + *o3* would cause an illegal memory access). + + +-.. cfunction:: PyObject* PyNumber_Negative(PyObject *o) ++.. c:function:: PyObject* PyNumber_Negative(PyObject *o) + + Returns the negation of *o* on success, or *NULL* on failure. This is the + equivalent of the Python expression ``-o``. + + +-.. cfunction:: PyObject* PyNumber_Positive(PyObject *o) ++.. c:function:: PyObject* PyNumber_Positive(PyObject *o) + + Returns *o* on success, or *NULL* on failure. This is the equivalent of the + Python expression ``+o``. + + +-.. cfunction:: PyObject* PyNumber_Absolute(PyObject *o) ++.. c:function:: PyObject* PyNumber_Absolute(PyObject *o) + + .. index:: builtin: abs + +@@ -99,71 +99,71 @@ + of the Python expression ``abs(o)``. + + +-.. cfunction:: PyObject* PyNumber_Invert(PyObject *o) ++.. c:function:: PyObject* PyNumber_Invert(PyObject *o) + + Returns the bitwise negation of *o* on success, or *NULL* on failure. This is + the equivalent of the Python expression ``~o``. + + +-.. cfunction:: PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2) + + Returns the result of left shifting *o1* by *o2* on success, or *NULL* on + failure. This is the equivalent of the Python expression ``o1 << o2``. + + +-.. cfunction:: PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2) + + Returns the result of right shifting *o1* by *o2* on success, or *NULL* on + failure. This is the equivalent of the Python expression ``o1 >> o2``. + + +-.. cfunction:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2) + + Returns the "bitwise and" of *o1* and *o2* on success and *NULL* on failure. + This is the equivalent of the Python expression ``o1 & o2``. + + +-.. cfunction:: PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2) + + Returns the "bitwise exclusive or" of *o1* by *o2* on success, or *NULL* on + failure. This is the equivalent of the Python expression ``o1 ^ o2``. + + +-.. cfunction:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2) + + Returns the "bitwise or" of *o1* and *o2* on success, or *NULL* on failure. + This is the equivalent of the Python expression ``o1 | o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2) + + Returns the result of adding *o1* and *o2*, or *NULL* on failure. The operation + is done *in-place* when *o1* supports it. This is the equivalent of the Python + statement ``o1 += o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2) + + Returns the result of subtracting *o2* from *o1*, or *NULL* on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 -= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2) + + Returns the result of multiplying *o1* and *o2*, or *NULL* on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 *= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2) + + Returns the result of dividing *o1* by *o2*, or *NULL* on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 /= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2) + + Returns the mathematical floor of dividing *o1* by *o2*, or *NULL* on failure. + The operation is done *in-place* when *o1* supports it. This is the equivalent +@@ -172,7 +172,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2) + + Return a reasonable approximation for the mathematical value of *o1* divided by + *o2*, or *NULL* on failure. The return value is "approximate" because binary +@@ -183,64 +183,64 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2) + + Returns the remainder of dividing *o1* by *o2*, or *NULL* on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 %= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3) ++.. c:function:: PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3) + + .. index:: builtin: pow + + See the built-in function :func:`pow`. Returns *NULL* on failure. The operation + is done *in-place* when *o1* supports it. This is the equivalent of the Python +- statement ``o1 **= o2`` when o3 is :cdata:`Py_None`, or an in-place variant of +- ``pow(o1, o2, o3)`` otherwise. If *o3* is to be ignored, pass :cdata:`Py_None` ++ statement ``o1 **= o2`` when o3 is :c:data:`Py_None`, or an in-place variant of ++ ``pow(o1, o2, o3)`` otherwise. If *o3* is to be ignored, pass :c:data:`Py_None` + in its place (passing *NULL* for *o3* would cause an illegal memory access). + + +-.. cfunction:: PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2) + + Returns the result of left shifting *o1* by *o2* on success, or *NULL* on + failure. The operation is done *in-place* when *o1* supports it. This is the + equivalent of the Python statement ``o1 <<= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2) + + Returns the result of right shifting *o1* by *o2* on success, or *NULL* on + failure. The operation is done *in-place* when *o1* supports it. This is the + equivalent of the Python statement ``o1 >>= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2) + + Returns the "bitwise and" of *o1* and *o2* on success and *NULL* on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 &= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2) + + Returns the "bitwise exclusive or" of *o1* by *o2* on success, or *NULL* on + failure. The operation is done *in-place* when *o1* supports it. This is the + equivalent of the Python statement ``o1 ^= o2``. + + +-.. cfunction:: PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2) + + Returns the "bitwise or" of *o1* and *o2* on success, or *NULL* on failure. The + operation is done *in-place* when *o1* supports it. This is the equivalent of + the Python statement ``o1 |= o2``. + + +-.. cfunction:: int PyNumber_Coerce(PyObject **p1, PyObject **p2) ++.. c:function:: int PyNumber_Coerce(PyObject **p1, PyObject **p2) + + .. index:: builtin: coerce + +- This function takes the addresses of two variables of type :ctype:`PyObject\*`. ++ This function takes the addresses of two variables of type :c:type:`PyObject\*`. + If the objects pointed to by ``*p1`` and ``*p2`` have the same type, increment + their reference count and return ``0`` (success). If the objects can be + converted to a common numeric type, replace ``*p1`` and ``*p2`` by their +@@ -250,14 +250,14 @@ + &o2)`` is equivalent to the Python statement ``o1, o2 = coerce(o1, o2)``. + + +-.. cfunction:: int PyNumber_CoerceEx(PyObject **p1, PyObject **p2) ++.. c:function:: int PyNumber_CoerceEx(PyObject **p1, PyObject **p2) + +- This function is similar to :cfunc:`PyNumber_Coerce`, except that it returns ++ This function is similar to :c:func:`PyNumber_Coerce`, except that it returns + ``1`` when the conversion is not possible and when no error is raised. + Reference counts are still not increased in this case. + + +-.. cfunction:: PyObject* PyNumber_Int(PyObject *o) ++.. c:function:: PyObject* PyNumber_Int(PyObject *o) + + .. index:: builtin: int + +@@ -266,7 +266,7 @@ + instead. This is the equivalent of the Python expression ``int(o)``. + + +-.. cfunction:: PyObject* PyNumber_Long(PyObject *o) ++.. c:function:: PyObject* PyNumber_Long(PyObject *o) + + .. index:: builtin: long + +@@ -274,7 +274,7 @@ + failure. This is the equivalent of the Python expression ``long(o)``. + + +-.. cfunction:: PyObject* PyNumber_Float(PyObject *o) ++.. c:function:: PyObject* PyNumber_Float(PyObject *o) + + .. index:: builtin: float + +@@ -282,7 +282,7 @@ + This is the equivalent of the Python expression ``float(o)``. + + +-.. cfunction:: PyObject* PyNumber_Index(PyObject *o) ++.. c:function:: PyObject* PyNumber_Index(PyObject *o) + + Returns the *o* converted to a Python int or long on success or *NULL* with a + :exc:`TypeError` exception raised on failure. +@@ -290,18 +290,18 @@ + .. versionadded:: 2.5 + + +-.. cfunction:: PyObject* PyNumber_ToBase(PyObject *n, int base) ++.. 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 +- :cfunc:`PyNumber_Index` first. ++ :c:func:`PyNumber_Index` first. + + .. versionadded:: 2.6 + + +-.. cfunction:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) ++.. c:function:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) + + Returns *o* converted to a Py_ssize_t value if *o* can be interpreted as an + integer. If *o* can be converted to a Python int or long but the attempt to +@@ -314,7 +314,7 @@ + .. versionadded:: 2.5 + + +-.. cfunction:: int PyIndex_Check(PyObject *o) ++.. c:function:: int PyIndex_Check(PyObject *o) + + Returns True if *o* is an index integer (has the nb_index slot of the + tp_as_number structure filled in). +diff -r 8527427914a2 Doc/c-api/objbuffer.rst +--- a/Doc/c-api/objbuffer.rst ++++ b/Doc/c-api/objbuffer.rst +@@ -13,7 +13,7 @@ + :ref:`bufferobjects` for more information. + + +-.. cfunction:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) ++.. c:function:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) + + Returns a pointer to a read-only memory location usable as character-based + input. The *obj* argument must support the single-segment character buffer +@@ -24,11 +24,11 @@ + .. versionadded:: 1.6 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int *` type for *buffer_len*. This might ++ This function used an :c:type:`int *` type for *buffer_len*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) ++.. c:function:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) + + Returns a pointer to a read-only memory location containing arbitrary data. + The *obj* argument must support the single-segment readable buffer +@@ -39,11 +39,11 @@ + .. versionadded:: 1.6 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int *` type for *buffer_len*. This might ++ This function used an :c:type:`int *` type for *buffer_len*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyObject_CheckReadBuffer(PyObject *o) ++.. c:function:: int PyObject_CheckReadBuffer(PyObject *o) + + Returns ``1`` if *o* supports the single-segment readable buffer interface. + Otherwise returns ``0``. +@@ -51,7 +51,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) ++.. c:function:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) + + Returns a pointer to a writeable memory location. The *obj* argument must + support the single-segment, character buffer interface. On success, +@@ -61,6 +61,6 @@ + .. versionadded:: 1.6 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int *` type for *buffer_len*. This might ++ This function used an :c:type:`int *` type for *buffer_len*. This might + require changes in your code for properly supporting 64-bit systems. + +diff -r 8527427914a2 Doc/c-api/object.rst +--- a/Doc/c-api/object.rst ++++ b/Doc/c-api/object.rst +@@ -6,7 +6,7 @@ + =============== + + +-.. cfunction:: int PyObject_Print(PyObject *o, FILE *fp, int flags) ++.. c:function:: int PyObject_Print(PyObject *o, FILE *fp, int flags) + + Print an object *o*, on file *fp*. Returns ``-1`` on error. The flags argument + is used to enable certain printing options. The only option currently supported +@@ -14,35 +14,35 @@ + instead of the :func:`repr`. + + +-.. cfunction:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name) ++.. c:function:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name) + + Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. This + is equivalent to the Python expression ``hasattr(o, attr_name)``. This function + always succeeds. + + +-.. cfunction:: int PyObject_HasAttrString(PyObject *o, const char *attr_name) ++.. c:function:: int PyObject_HasAttrString(PyObject *o, const char *attr_name) + + Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. This + is equivalent to the Python expression ``hasattr(o, attr_name)``. This function + always succeeds. + + +-.. cfunction:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name) ++.. c:function:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name) + + Retrieve an attribute named *attr_name* from object *o*. Returns the attribute + value on success, or *NULL* on failure. This is the equivalent of the Python + expression ``o.attr_name``. + + +-.. cfunction:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name) ++.. c:function:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name) + + Retrieve an attribute named *attr_name* from object *o*. Returns the attribute + value on success, or *NULL* on failure. This is the equivalent of the Python + expression ``o.attr_name``. + + +-.. cfunction:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) ++.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) + + Generic attribute getter function that is meant to be put into a type + object's ``tp_getattro`` slot. It looks for a descriptor in the dictionary +@@ -52,21 +52,21 @@ + descriptors don't. Otherwise, an :exc:`AttributeError` is raised. + + +-.. cfunction:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) ++.. c:function:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) + + Set the value of the attribute named *attr_name*, for object *o*, to the value + *v*. Returns ``-1`` on failure. This is the equivalent of the Python statement + ``o.attr_name = v``. + + +-.. cfunction:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) ++.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) + + Set the value of the attribute named *attr_name*, for object *o*, to the value + *v*. Returns ``-1`` on failure. This is the equivalent of the Python statement + ``o.attr_name = v``. + + +-.. cfunction:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value) ++.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value) + + Generic attribute setter function that is meant to be put into a type + object's ``tp_setattro`` slot. It looks for a data descriptor in the +@@ -76,19 +76,19 @@ + an :exc:`AttributeError` is raised and ``-1`` is returned. + + +-.. cfunction:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name) ++.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name) + + Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. + This is the equivalent of the Python statement ``del o.attr_name``. + + +-.. cfunction:: int PyObject_DelAttrString(PyObject *o, const char *attr_name) ++.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name) + + Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. + This is the equivalent of the Python statement ``del o.attr_name``. + + +-.. cfunction:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid) ++.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid) + + Compare the values of *o1* and *o2* using the operation specified by *opid*, + which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`, +@@ -98,7 +98,7 @@ + to *opid*. Returns the value of the comparison on success, or *NULL* on failure. + + +-.. cfunction:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid) ++.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid) + + Compare the values of *o1* and *o2* using the operation specified by *opid*, + which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`, +@@ -109,10 +109,10 @@ + *opid*. + + .. note:: +- If *o1* and *o2* are the same object, :cfunc:`PyObject_RichCompareBool` ++ If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool` + will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`. + +-.. cfunction:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result) ++.. c:function:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result) + + .. index:: builtin: cmp + +@@ -122,18 +122,18 @@ + the Python statement ``result = cmp(o1, o2)``. + + +-.. cfunction:: int PyObject_Compare(PyObject *o1, PyObject *o2) ++.. c:function:: int PyObject_Compare(PyObject *o1, PyObject *o2) + + .. index:: builtin: cmp + + Compare the values of *o1* and *o2* using a routine provided by *o1*, if one + exists, otherwise with a routine provided by *o2*. Returns the result of the + comparison on success. On error, the value returned is undefined; use +- :cfunc:`PyErr_Occurred` to detect an error. This is equivalent to the Python ++ :c:func:`PyErr_Occurred` to detect an error. This is equivalent to the Python + expression ``cmp(o1, o2)``. + + +-.. cfunction:: PyObject* PyObject_Repr(PyObject *o) ++.. c:function:: PyObject* PyObject_Repr(PyObject *o) + + .. index:: builtin: repr + +@@ -143,7 +143,7 @@ + by reverse quotes. + + +-.. cfunction:: PyObject* PyObject_Str(PyObject *o) ++.. c:function:: PyObject* PyObject_Str(PyObject *o) + + .. index:: builtin: str + +@@ -153,15 +153,15 @@ + by the :keyword:`print` statement. + + +-.. cfunction:: PyObject* PyObject_Bytes(PyObject *o) ++.. c:function:: PyObject* PyObject_Bytes(PyObject *o) + + .. index:: builtin: bytes + + Compute a bytes representation of object *o*. In 2.x, this is just a alias +- for :cfunc:`PyObject_Str`. ++ for :c:func:`PyObject_Str`. + + +-.. cfunction:: PyObject* PyObject_Unicode(PyObject *o) ++.. c:function:: PyObject* PyObject_Unicode(PyObject *o) + + .. index:: builtin: unicode + +@@ -171,11 +171,11 @@ + function. + + +-.. cfunction:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) ++.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) + + Returns ``1`` if *inst* is an instance of the class *cls* or a subclass of + *cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception. If +- *cls* is a type object rather than a class object, :cfunc:`PyObject_IsInstance` ++ *cls* is a type object rather than a class object, :c:func:`PyObject_IsInstance` + returns ``1`` if *inst* is of type *cls*. If *cls* is a tuple, the check will + be done against every entry in *cls*. The result will be ``1`` when at least one + of the checks returns ``1``, otherwise it will be ``0``. If *inst* is not a +@@ -195,13 +195,13 @@ + :class:`A` if it inherits from :class:`A` either directly or indirectly. If + either is not a class object, a more general mechanism is used to determine the + class relationship of the two objects. When testing if *B* is a subclass of +-*A*, if *A* is *B*, :cfunc:`PyObject_IsSubclass` returns true. If *A* and *B* ++*A*, if *A* is *B*, :c:func:`PyObject_IsSubclass` returns true. If *A* and *B* + are different objects, *B*'s :attr:`__bases__` attribute is searched in a + depth-first fashion for *A* --- the presence of the :attr:`__bases__` attribute + is considered sufficient for this determination. + + +-.. cfunction:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) ++.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) + + Returns ``1`` if the class *derived* is identical to or derived from the class + *cls*, otherwise returns ``0``. In case of an error, returns ``-1``. If *cls* +@@ -216,13 +216,13 @@ + Older versions of Python did not support a tuple as the second argument. + + +-.. cfunction:: int PyCallable_Check(PyObject *o) ++.. c:function:: int PyCallable_Check(PyObject *o) + + Determine if the object *o* is callable. Return ``1`` if the object is callable + and ``0`` otherwise. This function always succeeds. + + +-.. cfunction:: PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw) ++.. c:function:: PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw) + + .. index:: builtin: apply + +@@ -236,7 +236,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args) ++.. c:function:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args) + + .. index:: builtin: apply + +@@ -247,52 +247,52 @@ + ``callable_object(*args)``. + + +-.. cfunction:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...) ++.. c:function:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...) + + .. index:: builtin: apply + + Call a callable Python object *callable*, with a variable number of C arguments. +- The C arguments are described using a :cfunc:`Py_BuildValue` style format ++ The C arguments are described using a :c:func:`Py_BuildValue` style format + string. The format may be *NULL*, indicating that no arguments are provided. + Returns the result of the call on success, or *NULL* on failure. This is the + equivalent of the Python expression ``apply(callable, args)`` or +- ``callable(*args)``. Note that if you only pass :ctype:`PyObject \*` args, +- :cfunc:`PyObject_CallFunctionObjArgs` is a faster alternative. ++ ``callable(*args)``. Note that if you only pass :c:type:`PyObject \*` args, ++ :c:func:`PyObject_CallFunctionObjArgs` is a faster alternative. + + +-.. cfunction:: PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...) ++.. c:function:: PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...) + + Call the method named *method* of object *o* with a variable number of C +- arguments. The C arguments are described by a :cfunc:`Py_BuildValue` format ++ arguments. The C arguments are described by a :c:func:`Py_BuildValue` format + string that should produce a tuple. The format may be *NULL*, indicating that + no arguments are provided. Returns the result of the call on success, or *NULL* + on failure. This is the equivalent of the Python expression ``o.method(args)``. +- Note that if you only pass :ctype:`PyObject \*` args, +- :cfunc:`PyObject_CallMethodObjArgs` is a faster alternative. ++ Note that if you only pass :c:type:`PyObject \*` args, ++ :c:func:`PyObject_CallMethodObjArgs` is a faster alternative. + + +-.. cfunction:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL) ++.. c:function:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL) + + Call a callable Python object *callable*, with a variable number of +- :ctype:`PyObject\*` arguments. The arguments are provided as a variable number ++ :c:type:`PyObject\*` arguments. The arguments are provided as a variable number + of parameters followed by *NULL*. Returns the result of the call on success, or + *NULL* on failure. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) ++.. c:function:: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) + + Calls a method of the object *o*, where the name of the method is given as a + Python string object in *name*. It is called with a variable number of +- :ctype:`PyObject\*` arguments. The arguments are provided as a variable number ++ :c:type:`PyObject\*` arguments. The arguments are provided as a variable number + of parameters followed by *NULL*. Returns the result of the call on success, or + *NULL* on failure. + + .. versionadded:: 2.2 + + +-.. cfunction:: long PyObject_Hash(PyObject *o) ++.. c:function:: long PyObject_Hash(PyObject *o) + + .. index:: builtin: hash + +@@ -300,7 +300,7 @@ + This is the equivalent of the Python expression ``hash(o)``. + + +-.. cfunction:: long PyObject_HashNotImplemented(PyObject *o) ++.. c:function:: long PyObject_HashNotImplemented(PyObject *o) + + Set a :exc:`TypeError` indicating that ``type(o)`` is not hashable and return ``-1``. + This function receives special treatment when stored in a ``tp_hash`` slot, +@@ -310,21 +310,21 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: int PyObject_IsTrue(PyObject *o) ++.. c:function:: int PyObject_IsTrue(PyObject *o) + + Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise. + This is equivalent to the Python expression ``not not o``. On failure, return + ``-1``. + + +-.. cfunction:: int PyObject_Not(PyObject *o) ++.. c:function:: int PyObject_Not(PyObject *o) + + Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise. + This is equivalent to the Python expression ``not o``. On failure, return + ``-1``. + + +-.. cfunction:: PyObject* PyObject_Type(PyObject *o) ++.. c:function:: PyObject* PyObject_Type(PyObject *o) + + .. index:: builtin: type + +@@ -333,11 +333,11 @@ + is equivalent to the Python expression ``type(o)``. This function increments the + reference count of the return value. There's really no reason to use this + function instead of the common expression ``o->ob_type``, which returns a +- pointer of type :ctype:`PyTypeObject\*`, except when the incremented reference ++ pointer of type :c:type:`PyTypeObject\*`, except when the incremented reference + count is needed. + + +-.. cfunction:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) ++.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) + + Return true if the object *o* is of type *type* or a subtype of *type*. Both + parameters must be non-*NULL*. +@@ -345,7 +345,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: Py_ssize_t PyObject_Length(PyObject *o) ++.. c:function:: Py_ssize_t PyObject_Length(PyObject *o) + Py_ssize_t PyObject_Size(PyObject *o) + + .. index:: builtin: len +@@ -355,29 +355,29 @@ + returned. This is the equivalent to the Python expression ``len(o)``. + + .. versionchanged:: 2.5 +- These functions returned an :ctype:`int` type. This might require ++ These functions returned an :c:type:`int` type. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key) ++.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key) + + Return element of *o* corresponding to the object *key* or *NULL* on failure. + This is the equivalent of the Python expression ``o[key]``. + + +-.. cfunction:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) ++.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) + + Map the object *key* to the value *v*. Returns ``-1`` on failure. This is the + equivalent of the Python statement ``o[key] = v``. + + +-.. cfunction:: int PyObject_DelItem(PyObject *o, PyObject *key) ++.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key) + + Delete the mapping for *key* from *o*. Returns ``-1`` on failure. This is the + equivalent of the Python statement ``del o[key]``. + + +-.. cfunction:: int PyObject_AsFileDescriptor(PyObject *o) ++.. c:function:: int PyObject_AsFileDescriptor(PyObject *o) + + Derives a file descriptor from a Python object. If the object is an integer or + long integer, its value is returned. If not, the object's :meth:`fileno` method +@@ -385,16 +385,16 @@ + is returned as the file descriptor value. Returns ``-1`` on failure. + + +-.. cfunction:: PyObject* PyObject_Dir(PyObject *o) ++.. c:function:: PyObject* PyObject_Dir(PyObject *o) + + This is equivalent to the Python expression ``dir(o)``, returning a (possibly + empty) list of strings appropriate for the object argument, or *NULL* if there + was an error. If the argument is *NULL*, this is like the Python ``dir()``, + returning the names of the current locals; in this case, if no execution frame +- is active then *NULL* is returned but :cfunc:`PyErr_Occurred` will return false. ++ is active then *NULL* is returned but :c:func:`PyErr_Occurred` will return false. + + +-.. cfunction:: PyObject* PyObject_GetIter(PyObject *o) ++.. c:function:: PyObject* PyObject_GetIter(PyObject *o) + + This is equivalent to the Python expression ``iter(o)``. It returns a new + iterator for the object argument, or the object itself if the object is already +diff -r 8527427914a2 Doc/c-api/refcounting.rst +--- a/Doc/c-api/refcounting.rst ++++ b/Doc/c-api/refcounting.rst +@@ -11,22 +11,22 @@ + objects. + + +-.. cfunction:: void Py_INCREF(PyObject *o) ++.. c:function:: void Py_INCREF(PyObject *o) + + Increment the reference count for object *o*. The object must not be *NULL*; if +- you aren't sure that it isn't *NULL*, use :cfunc:`Py_XINCREF`. ++ you aren't sure that it isn't *NULL*, use :c:func:`Py_XINCREF`. + + +-.. cfunction:: void Py_XINCREF(PyObject *o) ++.. c:function:: void Py_XINCREF(PyObject *o) + + Increment the reference count for object *o*. The object may be *NULL*, in + which case the macro has no effect. + + +-.. cfunction:: void Py_DECREF(PyObject *o) ++.. c:function:: void Py_DECREF(PyObject *o) + + Decrement the reference count for object *o*. The object must not be *NULL*; if +- you aren't sure that it isn't *NULL*, use :cfunc:`Py_XDECREF`. If the reference ++ you aren't sure that it isn't *NULL*, use :c:func:`Py_XDECREF`. If the reference + count reaches zero, the object's type's deallocation function (which must not be + *NULL*) is invoked. + +@@ -36,25 +36,25 @@ + when a class instance with a :meth:`__del__` method is deallocated). While + exceptions in such code are not propagated, the executed code has free access to + all Python global variables. This means that any object that is reachable from +- a global variable should be in a consistent state before :cfunc:`Py_DECREF` is ++ a global variable should be in a consistent state before :c:func:`Py_DECREF` is + invoked. For example, code to delete an object from a list should copy a + reference to the deleted object in a temporary variable, update the list data +- structure, and then call :cfunc:`Py_DECREF` for the temporary variable. ++ structure, and then call :c:func:`Py_DECREF` for the temporary variable. + + +-.. cfunction:: void Py_XDECREF(PyObject *o) ++.. c:function:: void Py_XDECREF(PyObject *o) + + Decrement the reference count for object *o*. The object may be *NULL*, in + which case the macro has no effect; otherwise the effect is the same as for +- :cfunc:`Py_DECREF`, and the same warning applies. ++ :c:func:`Py_DECREF`, and the same warning applies. + + +-.. cfunction:: void Py_CLEAR(PyObject *o) ++.. c:function:: void Py_CLEAR(PyObject *o) + + Decrement the reference count for object *o*. The object may be *NULL*, in + which case the macro has no effect; otherwise the effect is the same as for +- :cfunc:`Py_DECREF`, except that the argument is also set to *NULL*. The warning +- for :cfunc:`Py_DECREF` does not apply with respect to the object passed because ++ :c:func:`Py_DECREF`, except that the argument is also set to *NULL*. The warning ++ for :c:func:`Py_DECREF` does not apply with respect to the object passed because + the macro carefully uses a temporary variable and sets the argument to *NULL* + before decrementing its reference count. + +@@ -65,10 +65,10 @@ + + The following functions are for runtime dynamic embedding of Python: + ``Py_IncRef(PyObject *o)``, ``Py_DecRef(PyObject *o)``. They are +-simply exported function versions of :cfunc:`Py_XINCREF` and +-:cfunc:`Py_XDECREF`, respectively. ++simply exported function versions of :c:func:`Py_XINCREF` and ++:c:func:`Py_XDECREF`, respectively. + + The following functions or macros are only for use within the interpreter core: +-:cfunc:`_Py_Dealloc`, :cfunc:`_Py_ForgetReference`, :cfunc:`_Py_NewReference`, +-as well as the global variable :cdata:`_Py_RefTotal`. ++:c:func:`_Py_Dealloc`, :c:func:`_Py_ForgetReference`, :c:func:`_Py_NewReference`, ++as well as the global variable :c:data:`_Py_RefTotal`. + +diff -r 8527427914a2 Doc/c-api/reflection.rst +--- a/Doc/c-api/reflection.rst ++++ b/Doc/c-api/reflection.rst +@@ -5,51 +5,51 @@ + Reflection + ========== + +-.. cfunction:: PyObject* PyEval_GetBuiltins() ++.. c:function:: PyObject* PyEval_GetBuiltins() + + Return a dictionary of the builtins in the current execution frame, + or the interpreter of the thread state if no frame is currently executing. + + +-.. cfunction:: PyObject* PyEval_GetLocals() ++.. c:function:: PyObject* PyEval_GetLocals() + + Return a dictionary of the local variables in the current execution frame, + or *NULL* if no frame is currently executing. + + +-.. cfunction:: PyObject* PyEval_GetGlobals() ++.. c:function:: PyObject* PyEval_GetGlobals() + + Return a dictionary of the global variables in the current execution frame, + or *NULL* if no frame is currently executing. + + +-.. cfunction:: PyFrameObject* PyEval_GetFrame() ++.. c:function:: PyFrameObject* PyEval_GetFrame() + + Return the current thread state's frame, which is *NULL* if no frame is + currently executing. + + +-.. cfunction:: int PyFrame_GetLineNumber(PyFrameObject *frame) ++.. c:function:: int PyFrame_GetLineNumber(PyFrameObject *frame) + + Return the line number that *frame* is currently executing. + + +-.. cfunction:: int PyEval_GetRestricted() ++.. c:function:: int PyEval_GetRestricted() + + If there is a current frame and it is executing in restricted mode, return true, + otherwise false. + + +-.. cfunction:: const char* PyEval_GetFuncName(PyObject *func) ++.. c:function:: const char* PyEval_GetFuncName(PyObject *func) + + Return the name of *func* if it is a function, class or instance object, else the + name of *func*\s type. + + +-.. cfunction:: const char* PyEval_GetFuncDesc(PyObject *func) ++.. c:function:: const char* PyEval_GetFuncDesc(PyObject *func) + + Return a description string, depending on the type of *func*. + Return values include "()" for functions and methods, " constructor", + " instance", and " object". Concatenated with the result of +- :cfunc:`PyEval_GetFuncName`, the result will be a description of ++ :c:func:`PyEval_GetFuncName`, the result will be a description of + *func*. +diff -r 8527427914a2 Doc/c-api/sequence.rst +--- a/Doc/c-api/sequence.rst ++++ b/Doc/c-api/sequence.rst +@@ -6,13 +6,13 @@ + ================= + + +-.. cfunction:: int PySequence_Check(PyObject *o) ++.. c:function:: int PySequence_Check(PyObject *o) + + Return ``1`` if the object provides sequence protocol, and ``0`` otherwise. + This function always succeeds. + + +-.. cfunction:: Py_ssize_t PySequence_Size(PyObject *o) ++.. c:function:: Py_ssize_t PySequence_Size(PyObject *o) + Py_ssize_t PySequence_Length(PyObject *o) + + .. index:: builtin: len +@@ -22,140 +22,140 @@ + Python expression ``len(o)``. + + .. versionchanged:: 2.5 +- These functions returned an :ctype:`int` type. This might require ++ These functions returned an :c:type:`int` type. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2) + + Return the concatenation of *o1* and *o2* on success, and *NULL* on failure. + This is the equivalent of the Python expression ``o1 + o2``. + + +-.. cfunction:: PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count) ++.. c:function:: PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count) + + Return the result of repeating sequence object *o* *count* times, or *NULL* on + failure. This is the equivalent of the Python expression ``o * count``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *count*. This might require ++ This function used an :c:type:`int` type for *count*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2) ++.. c:function:: PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2) + + Return the concatenation of *o1* and *o2* on success, and *NULL* on failure. + The operation is done *in-place* when *o1* supports it. This is the equivalent + of the Python expression ``o1 += o2``. + + +-.. cfunction:: PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) ++.. c:function:: PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) + + Return the result of repeating sequence object *o* *count* times, or *NULL* on + failure. The operation is done *in-place* when *o* supports it. This is the + equivalent of the Python expression ``o *= count``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *count*. This might require ++ This function used an :c:type:`int` type for *count*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i) ++.. c:function:: PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i) + + Return the *i*\ th element of *o*, or *NULL* on failure. This is the equivalent of + the Python expression ``o[i]``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i*. This might require ++ This function used an :c:type:`int` type for *i*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) ++.. c:function:: PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) + + Return the slice of sequence object *o* between *i1* and *i2*, or *NULL* on + failure. This is the equivalent of the Python expression ``o[i1:i2]``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i1* and *i2*. This might ++ This function used an :c:type:`int` type for *i1* and *i2*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v) ++.. c:function:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v) + + Assign object *v* to the *i*\ th element of *o*. Returns ``-1`` on failure. This + is the equivalent of the Python statement ``o[i] = v``. This function *does + not* steal a reference to *v*. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i*. This might require ++ This function used an :c:type:`int` type for *i*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PySequence_DelItem(PyObject *o, Py_ssize_t i) ++.. c:function:: int PySequence_DelItem(PyObject *o, Py_ssize_t i) + + Delete the *i*\ th element of object *o*. Returns ``-1`` on failure. This is the + equivalent of the Python statement ``del o[i]``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i*. This might require ++ This function used an :c:type:`int` type for *i*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v) ++.. c:function:: int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v) + + Assign the sequence object *v* to the slice in sequence object *o* from *i1* to + *i2*. This is the equivalent of the Python statement ``o[i1:i2] = v``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i1* and *i2*. This might ++ This function used an :c:type:`int` type for *i1* and *i2*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) ++.. c:function:: int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2) + + Delete the slice in sequence object *o* from *i1* to *i2*. Returns ``-1`` on + failure. This is the equivalent of the Python statement ``del o[i1:i2]``. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i1* and *i2*. This might ++ This function used an :c:type:`int` type for *i1* and *i2*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PySequence_Count(PyObject *o, PyObject *value) ++.. c:function:: Py_ssize_t PySequence_Count(PyObject *o, PyObject *value) + + Return the number of occurrences of *value* in *o*, that is, return the number + of keys for which ``o[key] == value``. On failure, return ``-1``. This is + equivalent to the Python expression ``o.count(value)``. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PySequence_Contains(PyObject *o, PyObject *value) ++.. c:function:: int PySequence_Contains(PyObject *o, PyObject *value) + + Determine if *o* contains *value*. If an item in *o* is equal to *value*, + return ``1``, otherwise return ``0``. On error, return ``-1``. This is + equivalent to the Python expression ``value in o``. + + +-.. cfunction:: Py_ssize_t PySequence_Index(PyObject *o, PyObject *value) ++.. c:function:: Py_ssize_t PySequence_Index(PyObject *o, PyObject *value) + + Return the first index *i* for which ``o[i] == value``. On error, return + ``-1``. This is equivalent to the Python expression ``o.index(value)``. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PySequence_List(PyObject *o) ++.. c:function:: PyObject* PySequence_List(PyObject *o) + + Return a list object with the same contents as the arbitrary sequence *o*. The + returned list is guaranteed to be new. + + +-.. cfunction:: PyObject* PySequence_Tuple(PyObject *o) ++.. c:function:: PyObject* PySequence_Tuple(PyObject *o) + + .. index:: builtin: tuple + +@@ -165,28 +165,28 @@ + equivalent to the Python expression ``tuple(o)``. + + +-.. cfunction:: PyObject* PySequence_Fast(PyObject *o, const char *m) ++.. c:function:: PyObject* PySequence_Fast(PyObject *o, const char *m) + + Returns the sequence *o* as a tuple, unless it is already a tuple or list, in +- which case *o* is returned. Use :cfunc:`PySequence_Fast_GET_ITEM` to access the ++ which case *o* is returned. Use :c:func:`PySequence_Fast_GET_ITEM` to access the + members of the result. Returns *NULL* on failure. If the object is not a + sequence, raises :exc:`TypeError` with *m* as the message text. + + +-.. cfunction:: PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i) ++.. c:function:: PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i) + + Return the *i*\ th element of *o*, assuming that *o* was returned by +- :cfunc:`PySequence_Fast`, *o* is not *NULL*, and that *i* is within bounds. ++ :c:func:`PySequence_Fast`, *o* is not *NULL*, and that *i* is within bounds. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i*. This might require ++ This function used an :c:type:`int` type for *i*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject** PySequence_Fast_ITEMS(PyObject *o) ++.. c:function:: PyObject** PySequence_Fast_ITEMS(PyObject *o) + + Return the underlying array of PyObject pointers. Assumes that *o* was returned +- by :cfunc:`PySequence_Fast` and *o* is not *NULL*. ++ by :c:func:`PySequence_Fast` and *o* is not *NULL*. + + Note, if a list gets resized, the reallocation may relocate the items array. + So, only use the underlying array pointer in contexts where the sequence +@@ -195,24 +195,24 @@ + .. versionadded:: 2.4 + + +-.. cfunction:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i) ++.. c:function:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i) + + Return the *i*\ th element of *o* or *NULL* on failure. Macro form of +- :cfunc:`PySequence_GetItem` but without checking that +- :cfunc:`PySequence_Check(o)` is true and without adjustment for negative ++ :c:func:`PySequence_GetItem` but without checking that ++ :c:func:`PySequence_Check` on *o* is true and without adjustment for negative + indices. + + .. versionadded:: 2.3 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *i*. This might require ++ This function used an :c:type:`int` type for *i*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) ++.. c:function:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) + + Returns the length of *o*, assuming that *o* was returned by +- :cfunc:`PySequence_Fast` and that *o* is not *NULL*. The size can also be +- gotten by calling :cfunc:`PySequence_Size` on *o*, but +- :cfunc:`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a list ++ :c:func:`PySequence_Fast` and that *o* is not *NULL*. The size can also be ++ gotten by calling :c:func:`PySequence_Size` on *o*, but ++ :c:func:`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a list + or tuple. +diff -r 8527427914a2 Doc/c-api/set.rst +--- a/Doc/c-api/set.rst ++++ b/Doc/c-api/set.rst +@@ -16,20 +16,20 @@ + + This section details the public API for :class:`set` and :class:`frozenset` + objects. Any functionality not listed below is best accessed using the either +-the abstract object protocol (including :cfunc:`PyObject_CallMethod`, +-:cfunc:`PyObject_RichCompareBool`, :cfunc:`PyObject_Hash`, +-:cfunc:`PyObject_Repr`, :cfunc:`PyObject_IsTrue`, :cfunc:`PyObject_Print`, and +-:cfunc:`PyObject_GetIter`) or the abstract number protocol (including +-:cfunc:`PyNumber_And`, :cfunc:`PyNumber_Subtract`, :cfunc:`PyNumber_Or`, +-:cfunc:`PyNumber_Xor`, :cfunc:`PyNumber_InPlaceAnd`, +-:cfunc:`PyNumber_InPlaceSubtract`, :cfunc:`PyNumber_InPlaceOr`, and +-:cfunc:`PyNumber_InPlaceXor`). ++the abstract object protocol (including :c:func:`PyObject_CallMethod`, ++:c:func:`PyObject_RichCompareBool`, :c:func:`PyObject_Hash`, ++:c:func:`PyObject_Repr`, :c:func:`PyObject_IsTrue`, :c:func:`PyObject_Print`, and ++:c:func:`PyObject_GetIter`) or the abstract number protocol (including ++:c:func:`PyNumber_And`, :c:func:`PyNumber_Subtract`, :c:func:`PyNumber_Or`, ++:c:func:`PyNumber_Xor`, :c:func:`PyNumber_InPlaceAnd`, ++:c:func:`PyNumber_InPlaceSubtract`, :c:func:`PyNumber_InPlaceOr`, and ++:c:func:`PyNumber_InPlaceXor`). + + +-.. ctype:: PySetObject ++.. c:type:: PySetObject + +- This subtype of :ctype:`PyObject` is used to hold the internal data for both +- :class:`set` and :class:`frozenset` objects. It is like a :ctype:`PyDictObject` ++ This subtype of :c:type:`PyObject` is used to hold the internal data for both ++ :class:`set` and :class:`frozenset` objects. It is like a :c:type:`PyDictObject` + in that it is a fixed size for small sets (much like tuple storage) and will + point to a separate, variable sized block of memory for medium and large sized + sets (much like list storage). None of the fields of this structure should be +@@ -37,53 +37,53 @@ + the documented API rather than by manipulating the values in the structure. + + +-.. cvar:: PyTypeObject PySet_Type ++.. c:var:: PyTypeObject PySet_Type + +- This is an instance of :ctype:`PyTypeObject` representing the Python ++ This is an instance of :c:type:`PyTypeObject` representing the Python + :class:`set` type. + + +-.. cvar:: PyTypeObject PyFrozenSet_Type ++.. c:var:: PyTypeObject PyFrozenSet_Type + +- This is an instance of :ctype:`PyTypeObject` representing the Python ++ This is an instance of :c:type:`PyTypeObject` representing the Python + :class:`frozenset` type. + + The following type check macros work on pointers to any Python object. Likewise, + the constructor functions work with any iterable Python object. + + +-.. cfunction:: int PySet_Check(PyObject *p) ++.. c:function:: int PySet_Check(PyObject *p) + + Return true if *p* is a :class:`set` object or an instance of a subtype. + + .. versionadded:: 2.6 + +-.. cfunction:: int PyFrozenSet_Check(PyObject *p) ++.. c:function:: int PyFrozenSet_Check(PyObject *p) + + Return true if *p* is a :class:`frozenset` object or an instance of a + subtype. + + .. versionadded:: 2.6 + +-.. cfunction:: int PyAnySet_Check(PyObject *p) ++.. c:function:: int PyAnySet_Check(PyObject *p) + + Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an + instance of a subtype. + + +-.. cfunction:: int PyAnySet_CheckExact(PyObject *p) ++.. c:function:: int PyAnySet_CheckExact(PyObject *p) + + Return true if *p* is a :class:`set` object or a :class:`frozenset` object but + not an instance of a subtype. + + +-.. cfunction:: int PyFrozenSet_CheckExact(PyObject *p) ++.. c:function:: int PyFrozenSet_CheckExact(PyObject *p) + + Return true if *p* is a :class:`frozenset` object but not an instance of a + subtype. + + +-.. cfunction:: PyObject* PySet_New(PyObject *iterable) ++.. c:function:: PyObject* PySet_New(PyObject *iterable) + + Return a new :class:`set` containing objects returned by the *iterable*. The + *iterable* may be *NULL* to create a new empty set. Return the new set on +@@ -92,7 +92,7 @@ + (``c=set(s)``). + + +-.. cfunction:: PyObject* PyFrozenSet_New(PyObject *iterable) ++.. c:function:: PyObject* PyFrozenSet_New(PyObject *iterable) + + Return a new :class:`frozenset` containing objects returned by the *iterable*. + The *iterable* may be *NULL* to create a new empty frozenset. Return the new +@@ -108,7 +108,7 @@ + or :class:`frozenset` or instances of their subtypes. + + +-.. cfunction:: Py_ssize_t PySet_Size(PyObject *anyset) ++.. c:function:: Py_ssize_t PySet_Size(PyObject *anyset) + + .. index:: builtin: len + +@@ -117,16 +117,16 @@ + :class:`set`, :class:`frozenset`, or an instance of a subtype. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int`. This might require changes in ++ This function returned an :c:type:`int`. This might require changes in + your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) ++.. c:function:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) + +- Macro form of :cfunc:`PySet_Size` without error checking. ++ Macro form of :c:func:`PySet_Size` without error checking. + + +-.. cfunction:: int PySet_Contains(PyObject *anyset, PyObject *key) ++.. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key) + + Return 1 if found, 0 if not found, and -1 if an error is encountered. Unlike + the Python :meth:`__contains__` method, this function does not automatically +@@ -135,7 +135,7 @@ + :class:`set`, :class:`frozenset`, or an instance of a subtype. + + +-.. cfunction:: int PySet_Add(PyObject *set, PyObject *key) ++.. c:function:: int PySet_Add(PyObject *set, PyObject *key) + + Add *key* to a :class:`set` instance. Does not apply to :class:`frozenset` + instances. Return 0 on success or -1 on failure. Raise a :exc:`TypeError` if +@@ -145,14 +145,14 @@ + + .. versionchanged:: 2.6 + Now works with instances of :class:`frozenset` or its subtypes. +- Like :cfunc:`PyTuple_SetItem` in that it can be used to fill-in the ++ Like :c:func:`PyTuple_SetItem` in that it can be used to fill-in the + values of brand new frozensets before they are exposed to other code. + + The following functions are available for instances of :class:`set` or its + subtypes but not for instances of :class:`frozenset` or its subtypes. + + +-.. cfunction:: int PySet_Discard(PyObject *set, PyObject *key) ++.. c:function:: int PySet_Discard(PyObject *set, PyObject *key) + + Return 1 if found and removed, 0 if not found (no action taken), and -1 if an + error is encountered. Does not raise :exc:`KeyError` for missing keys. Raise a +@@ -162,7 +162,7 @@ + instance of :class:`set` or its subtype. + + +-.. cfunction:: PyObject* PySet_Pop(PyObject *set) ++.. c:function:: PyObject* PySet_Pop(PyObject *set) + + Return a new reference to an arbitrary object in the *set*, and removes the + object from the *set*. Return *NULL* on failure. Raise :exc:`KeyError` if the +@@ -170,6 +170,6 @@ + :class:`set` or its subtype. + + +-.. cfunction:: int PySet_Clear(PyObject *set) ++.. c:function:: int PySet_Clear(PyObject *set) + + Empty an existing set of all elements. +diff -r 8527427914a2 Doc/c-api/slice.rst +--- a/Doc/c-api/slice.rst ++++ b/Doc/c-api/slice.rst +@@ -6,7 +6,7 @@ + ------------- + + +-.. cvar:: PyTypeObject PySlice_Type ++.. c:var:: PyTypeObject PySlice_Type + + .. index:: single: SliceType (in module types) + +@@ -14,12 +14,12 @@ + ``types.SliceType``. + + +-.. cfunction:: int PySlice_Check(PyObject *ob) ++.. c:function:: int PySlice_Check(PyObject *ob) + + Return true if *ob* is a slice object; *ob* must not be *NULL*. + + +-.. cfunction:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) ++.. c:function:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step) + + Return a new slice object with the given values. The *start*, *stop*, and + *step* parameters are used as the values of the slice object attributes of +@@ -28,7 +28,7 @@ + the new object could not be allocated. + + +-.. cfunction:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) ++.. c:function:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) + + Retrieve the start, stop and step indices from the slice object *slice*, + assuming a sequence of length *length*. Treats indices greater than +@@ -40,18 +40,18 @@ + + You probably do not want to use this function. If you want to use slice + objects in versions of Python prior to 2.3, you would probably do well to +- incorporate the source of :cfunc:`PySlice_GetIndicesEx`, suitably renamed, ++ incorporate the source of :c:func:`PySlice_GetIndicesEx`, suitably renamed, + in the source of your extension. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *length* and an +- :ctype:`int *` type for *start*, *stop*, and *step*. This might require ++ This function used an :c:type:`int` type for *length* and an ++ :c:type:`int *` type for *start*, *stop*, and *step*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) ++.. c:function:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) + +- Usable replacement for :cfunc:`PySlice_GetIndices`. Retrieve the start, ++ Usable replacement for :c:func:`PySlice_GetIndices`. Retrieve the start, + stop, and step indices from the slice object *slice* assuming a sequence of + length *length*, and store the length of the slice in *slicelength*. Out + of bounds indices are clipped in a manner consistent with the handling of +@@ -62,7 +62,7 @@ + .. versionadded:: 2.3 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *length* and an +- :ctype:`int *` type for *start*, *stop*, *step*, and *slicelength*. This ++ This function used an :c:type:`int` type for *length* and an ++ :c:type:`int *` type for *start*, *stop*, *step*, and *slicelength*. This + might require changes in your code for properly supporting 64-bit + systems. +diff -r 8527427914a2 Doc/c-api/string.rst +--- a/Doc/c-api/string.rst ++++ b/Doc/c-api/string.rst +@@ -17,20 +17,20 @@ + .. index:: object: string + + +-.. ctype:: PyStringObject ++.. c:type:: PyStringObject + +- This subtype of :ctype:`PyObject` represents a Python string object. ++ This subtype of :c:type:`PyObject` represents a Python string object. + + +-.. cvar:: PyTypeObject PyString_Type ++.. c:var:: PyTypeObject PyString_Type + + .. index:: single: StringType (in module types) + +- This instance of :ctype:`PyTypeObject` represents the Python string type; it is ++ This instance of :c:type:`PyTypeObject` represents the Python string type; it is + the same object as ``str`` and ``types.StringType`` in the Python layer. . + + +-.. cfunction:: int PyString_Check(PyObject *o) ++.. c:function:: int PyString_Check(PyObject *o) + + Return true if the object *o* is a string object or an instance of a subtype of + the string type. +@@ -39,7 +39,7 @@ + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyString_CheckExact(PyObject *o) ++.. c:function:: int PyString_CheckExact(PyObject *o) + + Return true if the object *o* is a string object, but not an instance of a + subtype of the string type. +@@ -47,27 +47,27 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyString_FromString(const char *v) ++.. c:function:: PyObject* PyString_FromString(const char *v) + + Return a new string object with a copy of the string *v* as value on success, + and *NULL* on failure. The parameter *v* must not be *NULL*; it will not be + checked. + + +-.. cfunction:: PyObject* PyString_FromStringAndSize(const char *v, Py_ssize_t len) ++.. c:function:: PyObject* PyString_FromStringAndSize(const char *v, Py_ssize_t len) + + Return a new string object with a copy of the string *v* as value and length + *len* on success, and *NULL* on failure. If *v* is *NULL*, the contents of the + string are uninitialized. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *len*. This might require ++ This function used an :c:type:`int` type for *len*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyString_FromFormat(const char *format, ...) ++.. c:function:: PyObject* PyString_FromFormat(const char *format, ...) + +- Take a C :cfunc:`printf`\ -style *format* string and a variable number of ++ Take a C :c:func:`printf`\ -style *format* string and a variable number of + arguments, calculate the size of the resulting Python string and return a string + with the values formatted into it. The variable arguments must be C types and + must correspond exactly to the format characters in the *format* string. The +@@ -144,31 +144,31 @@ + Support for `"%lld"` and `"%llu"` added. + + +-.. cfunction:: PyObject* PyString_FromFormatV(const char *format, va_list vargs) ++.. c:function:: PyObject* PyString_FromFormatV(const char *format, va_list vargs) + +- Identical to :cfunc:`PyString_FromFormat` except that it takes exactly two ++ Identical to :c:func:`PyString_FromFormat` except that it takes exactly two + arguments. + + +-.. cfunction:: Py_ssize_t PyString_Size(PyObject *string) ++.. c:function:: Py_ssize_t PyString_Size(PyObject *string) + + Return the length of the string in string object *string*. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyString_GET_SIZE(PyObject *string) ++.. c:function:: Py_ssize_t PyString_GET_SIZE(PyObject *string) + +- Macro form of :cfunc:`PyString_Size` but without error checking. ++ Macro form of :c:func:`PyString_Size` but without error checking. + + .. versionchanged:: 2.5 +- This macro returned an :ctype:`int` type. This might require changes in ++ This macro returned an :c:type:`int` type. This might require changes in + your code for properly supporting 64-bit systems. + + +-.. cfunction:: char* PyString_AsString(PyObject *string) ++.. c:function:: char* PyString_AsString(PyObject *string) + + Return a NUL-terminated representation of the contents of *string*. The pointer + refers to the internal buffer of *string*, not a copy. The data must not be +@@ -176,16 +176,16 @@ + ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If + *string* is a Unicode object, this function computes the default encoding of + *string* and operates on that. If *string* is not a string object at all, +- :cfunc:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`. ++ :c:func:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`. + + +-.. cfunction:: char* PyString_AS_STRING(PyObject *string) ++.. c:function:: char* PyString_AS_STRING(PyObject *string) + +- Macro form of :cfunc:`PyString_AsString` but without error checking. Only ++ Macro form of :c:func:`PyString_AsString` but without error checking. Only + string objects are supported; no Unicode objects should be passed. + + +-.. cfunction:: int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length) ++.. c:function:: int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length) + + Return a NUL-terminated representation of the contents of the object *obj* + through the output variables *buffer* and *length*. +@@ -200,14 +200,14 @@ + ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated. If + *string* is a Unicode object, this function computes the default encoding of + *string* and operates on that. If *string* is not a string object at all, +- :cfunc:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`. ++ :c:func:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int *` type for *length*. This might ++ This function used an :c:type:`int *` type for *length*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: void PyString_Concat(PyObject **string, PyObject *newpart) ++.. c:function:: void PyString_Concat(PyObject **string, PyObject *newpart) + + Create a new string object in *\*string* containing the contents of *newpart* + appended to *string*; the caller will own the new reference. The reference to +@@ -216,13 +216,13 @@ + *\*string* will be set to *NULL*; the appropriate exception will be set. + + +-.. cfunction:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart) ++.. c:function:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart) + + Create a new string object in *\*string* containing the contents of *newpart* + appended to *string*. This version decrements the reference count of *newpart*. + + +-.. cfunction:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize) ++.. c:function:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize) + + A way to resize a string object even though it is "immutable". Only use this to + build up a brand new string object; don't use this if the string may already be +@@ -235,16 +235,16 @@ + set to *NULL*, a memory exception is set, and ``-1`` is returned. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *newsize*. This might ++ This function used an :c:type:`int` type for *newsize*. This might + require changes in your code for properly supporting 64-bit systems. + +-.. cfunction:: PyObject* PyString_Format(PyObject *format, PyObject *args) ++.. c:function:: PyObject* PyString_Format(PyObject *format, PyObject *args) + + Return a new string object from *format* and *args*. Analogous to ``format % + args``. The *args* argument must be a tuple. + + +-.. cfunction:: void PyString_InternInPlace(PyObject **string) ++.. c:function:: void PyString_InternInPlace(PyObject **string) + + Intern the argument *\*string* in place. The argument must be the address of a + pointer variable pointing to a Python string object. If there is an existing +@@ -261,10 +261,10 @@ + This function is not available in 3.x and does not have a PyBytes alias. + + +-.. cfunction:: PyObject* PyString_InternFromString(const char *v) ++.. c:function:: PyObject* PyString_InternFromString(const char *v) + +- A combination of :cfunc:`PyString_FromString` and +- :cfunc:`PyString_InternInPlace`, returning either a new string object that has ++ A combination of :c:func:`PyString_FromString` and ++ :c:func:`PyString_InternInPlace`, returning either a new string object that has + been interned, or a new ("owned") reference to an earlier interned string object + with the same value. + +@@ -273,7 +273,7 @@ + This function is not available in 3.x and does not have a PyBytes alias. + + +-.. cfunction:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) + + Create an object by decoding *size* bytes of the encoded buffer *s* using the + codec registered for *encoding*. *encoding* and *errors* have the same meaning +@@ -286,11 +286,11 @@ + This function is not available in 3.x and does not have a PyBytes alias. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors) + + Decode a string object by passing it to the codec registered for *encoding* and + return the result as Python object. *encoding* and *errors* have the same +@@ -303,9 +303,9 @@ + This function is not available in 3.x and does not have a PyBytes alias. + + +-.. cfunction:: PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) + +- Encode the :ctype:`char` buffer of the given size by passing it to the codec ++ Encode the :c:type:`char` buffer of the given size by passing it to the codec + registered for *encoding* and return a Python object. *encoding* and *errors* + have the same meaning as the parameters of the same name in the string + :meth:`encode` method. The codec to be used is looked up using the Python codec +@@ -316,11 +316,11 @@ + This function is not available in 3.x and does not have a PyBytes alias. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors) + + Encode a string object using the codec registered for *encoding* and return the + result as Python object. *encoding* and *errors* have the same meaning as the +diff -r 8527427914a2 Doc/c-api/structures.rst +--- a/Doc/c-api/structures.rst ++++ b/Doc/c-api/structures.rst +@@ -11,12 +11,12 @@ + + All Python objects ultimately share a small number of fields at the beginning + of the object's representation in memory. These are represented by the +-:ctype:`PyObject` and :ctype:`PyVarObject` types, which are defined, in turn, ++:c:type:`PyObject` and :c:type:`PyVarObject` types, which are defined, in turn, + by the expansions of some macros also used, whether directly or indirectly, in + the definition of all other Python objects. + + +-.. ctype:: PyObject ++.. c:type:: PyObject + + All object types are extensions of this type. This is a type which + contains the information Python needs to treat a pointer to an object as an +@@ -26,79 +26,79 @@ + macro. + + +-.. ctype:: PyVarObject ++.. c:type:: PyVarObject + +- This is an extension of :ctype:`PyObject` that adds the :attr:`ob_size` ++ This is an extension of :c:type:`PyObject` that adds the :attr:`ob_size` + field. This is only used for objects that have some notion of *length*. + This type does not often appear in the Python/C API. It corresponds to the + fields defined by the expansion of the ``PyObject_VAR_HEAD`` macro. + +-These macros are used in the definition of :ctype:`PyObject` and +-:ctype:`PyVarObject`: ++These macros are used in the definition of :c:type:`PyObject` and ++:c:type:`PyVarObject`: + + +-.. cmacro:: PyObject_HEAD ++.. c:macro:: PyObject_HEAD + + This is a macro which expands to the declarations of the fields of the +- :ctype:`PyObject` type; it is used when declaring new types which represent ++ :c:type:`PyObject` type; it is used when declaring new types which represent + objects without a varying length. The specific fields it expands to depend +- on the definition of :cmacro:`Py_TRACE_REFS`. By default, that macro is +- not defined, and :cmacro:`PyObject_HEAD` expands to:: ++ on the definition of :c:macro:`Py_TRACE_REFS`. By default, that macro is ++ not defined, and :c:macro:`PyObject_HEAD` expands to:: + + Py_ssize_t ob_refcnt; + PyTypeObject *ob_type; + +- When :cmacro:`Py_TRACE_REFS` is defined, it expands to:: ++ When :c:macro:`Py_TRACE_REFS` is defined, it expands to:: + + PyObject *_ob_next, *_ob_prev; + Py_ssize_t ob_refcnt; + PyTypeObject *ob_type; + + +-.. cmacro:: PyObject_VAR_HEAD ++.. c:macro:: PyObject_VAR_HEAD + + This is a macro which expands to the declarations of the fields of the +- :ctype:`PyVarObject` type; it is used when declaring new types which ++ :c:type:`PyVarObject` type; it is used when declaring new types which + represent objects with a length that varies from instance to instance. + This macro always expands to:: + + PyObject_HEAD + Py_ssize_t ob_size; + +- Note that :cmacro:`PyObject_HEAD` is part of the expansion, and that its own +- expansion varies depending on the definition of :cmacro:`Py_TRACE_REFS`. ++ Note that :c:macro:`PyObject_HEAD` is part of the expansion, and that its own ++ expansion varies depending on the definition of :c:macro:`Py_TRACE_REFS`. + + +-.. cmacro:: PyObject_HEAD_INIT(type) ++.. c:macro:: PyObject_HEAD_INIT(type) + + This is a macro which expands to initialization values for a new +- :ctype:`PyObject` type. This macro expands to:: ++ :c:type:`PyObject` type. This macro expands to:: + + _PyObject_EXTRA_INIT + 1, type, + + +-.. cmacro:: PyVarObject_HEAD_INIT(type, size) ++.. c:macro:: PyVarObject_HEAD_INIT(type, size) + + This is a macro which expands to initialization values for a new +- :ctype:`PyVarObject` type, including the :attr:`ob_size` field. ++ :c:type:`PyVarObject` type, including the :attr:`ob_size` field. + This macro expands to:: + + _PyObject_EXTRA_INIT + 1, type, size, + + +-.. ctype:: PyCFunction ++.. c:type:: PyCFunction + + Type of the functions used to implement most Python callables in C. +- Functions of this type take two :ctype:`PyObject\*` parameters and return ++ Functions of this type take two :c:type:`PyObject\*` parameters and return + one such value. If the return value is *NULL*, an exception shall have + been set. If not *NULL*, the return value is interpreted as the return + value of the function as exposed in Python. The function must return a new + reference. + + +-.. ctype:: PyMethodDef ++.. c:type:: PyMethodDef + + Structure used to describe a method of an extension type. This structure has + four fields: +@@ -119,10 +119,10 @@ + +------------------+-------------+-------------------------------+ + + The :attr:`ml_meth` is a C function pointer. The functions may be of different +-types, but they always return :ctype:`PyObject\*`. If the function is not of +-the :ctype:`PyCFunction`, the compiler will require a cast in the method table. +-Even though :ctype:`PyCFunction` defines the first parameter as +-:ctype:`PyObject\*`, it is common that the method implementation uses a the ++types, but they always return :c:type:`PyObject\*`. If the function is not of ++the :c:type:`PyCFunction`, the compiler will require a cast in the method table. ++Even though :c:type:`PyCFunction` defines the first parameter as ++:c:type:`PyObject\*`, it is common that the method implementation uses a the + specific C type of the *self* object. + + The :attr:`ml_flags` field is a bitfield which can include the following flags. +@@ -136,27 +136,27 @@ + .. data:: METH_VARARGS + + This is the typical calling convention, where the methods have the type +- :ctype:`PyCFunction`. The function expects two :ctype:`PyObject\*` values. ++ :c:type:`PyCFunction`. The function expects two :c:type:`PyObject\*` values. + The first one is the *self* object for methods; for module functions, it is + the module object. The second parameter (often called *args*) is a tuple + object representing all arguments. This parameter is typically processed +- using :cfunc:`PyArg_ParseTuple` or :cfunc:`PyArg_UnpackTuple`. ++ using :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`. + + + .. data:: METH_KEYWORDS + +- Methods with these flags must be of type :ctype:`PyCFunctionWithKeywords`. ++ Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`. + The function expects three parameters: *self*, *args*, and a dictionary of + all the keyword arguments. The flag is typically combined with + :const:`METH_VARARGS`, and the parameters are typically processed using +- :cfunc:`PyArg_ParseTupleAndKeywords`. ++ :c:func:`PyArg_ParseTupleAndKeywords`. + + + .. data:: METH_NOARGS + + Methods without parameters don't need to check whether arguments are given if + they are listed with the :const:`METH_NOARGS` flag. They need to be of type +- :ctype:`PyCFunction`. The first parameter is typically named ``self`` and ++ :c:type:`PyCFunction`. The first parameter is typically named ``self`` and + will hold a reference to the module or object instance. In all cases the + second parameter will be *NULL*. + +@@ -164,15 +164,15 @@ + .. data:: METH_O + + Methods with a single object argument can be listed with the :const:`METH_O` +- flag, instead of invoking :cfunc:`PyArg_ParseTuple` with a ``"O"`` argument. +- They have the type :ctype:`PyCFunction`, with the *self* parameter, and a +- :ctype:`PyObject\*` parameter representing the single argument. ++ flag, instead of invoking :c:func:`PyArg_ParseTuple` with a ``"O"`` argument. ++ They have the type :c:type:`PyCFunction`, with the *self* parameter, and a ++ :c:type:`PyObject\*` parameter representing the single argument. + + + .. data:: METH_OLDARGS + + This calling convention is deprecated. The method must be of type +- :ctype:`PyCFunction`. The second argument is *NULL* if no arguments are ++ :c:type:`PyCFunction`. The second argument is *NULL* if no arguments are + given, a single object if exactly one argument is given, and a tuple of + objects if more than one argument is given. There is no way for a function + using this convention to distinguish between a call with multiple arguments +@@ -225,7 +225,7 @@ + .. versionadded:: 2.4 + + +-.. ctype:: PyMemberDef ++.. c:type:: PyMemberDef + + Structure which describes an attribute of a type which corresponds to a C + struct member. Its fields are: +@@ -277,22 +277,22 @@ + T_PYSSIZET Py_ssize_t + =============== ================== + +- :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` differ in that +- :cmacro:`T_OBJECT` returns ``None`` if the member is *NULL* and +- :cmacro:`T_OBJECT_EX` raises an :exc:`AttributeError`. Try to use +- :cmacro:`T_OBJECT_EX` over :cmacro:`T_OBJECT` because :cmacro:`T_OBJECT_EX` ++ :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` differ in that ++ :c:macro:`T_OBJECT` returns ``None`` if the member is *NULL* and ++ :c:macro:`T_OBJECT_EX` raises an :exc:`AttributeError`. Try to use ++ :c:macro:`T_OBJECT_EX` over :c:macro:`T_OBJECT` because :c:macro:`T_OBJECT_EX` + handles use of the :keyword:`del` statement on that attribute more correctly +- than :cmacro:`T_OBJECT`. ++ than :c:macro:`T_OBJECT`. + +- :attr:`flags` can be 0 for write and read access or :cmacro:`READONLY` for +- read-only access. Using :cmacro:`T_STRING` for :attr:`type` implies +- :cmacro:`READONLY`. Only :cmacro:`T_OBJECT` and :cmacro:`T_OBJECT_EX` ++ :attr:`flags` can be 0 for write and read access or :c:macro:`READONLY` for ++ read-only access. Using :c:macro:`T_STRING` for :attr:`type` implies ++ :c:macro:`READONLY`. Only :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` + members can be deleted. (They are set to *NULL*). + + +-.. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name) ++.. c:function:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name) + + Return a bound method object for an extension type implemented in C. This + can be useful in the implementation of a :attr:`tp_getattro` or + :attr:`tp_getattr` handler that does not use the +- :cfunc:`PyObject_GenericGetAttr` function. ++ :c:func:`PyObject_GenericGetAttr` function. +diff -r 8527427914a2 Doc/c-api/sys.rst +--- a/Doc/c-api/sys.rst ++++ b/Doc/c-api/sys.rst +@@ -6,16 +6,16 @@ + ========================== + + +-.. cfunction:: int Py_FdIsInteractive(FILE *fp, const char *filename) ++.. c:function:: int Py_FdIsInteractive(FILE *fp, const char *filename) + + Return true (nonzero) if the standard I/O file *fp* with name *filename* is + deemed interactive. This is the case for files for which ``isatty(fileno(fp))`` +- is true. If the global flag :cdata:`Py_InteractiveFlag` is true, this function ++ is true. If the global flag :c:data:`Py_InteractiveFlag` is true, this function + also returns true if the *filename* pointer is *NULL* or if the name is equal to + one of the strings ``''`` or ``'???'``. + + +-.. cfunction:: void PyOS_AfterFork() ++.. c:function:: void PyOS_AfterFork() + + Function to update some internal state after a process fork; this should be + called in the new process if the Python interpreter will continue to be used. +@@ -23,7 +23,7 @@ + to be called. + + +-.. cfunction:: int PyOS_CheckStack() ++.. c:function:: int PyOS_CheckStack() + + Return true when the interpreter runs out of stack space. This is a reliable + check, but is only available when :const:`USE_STACKCHECK` is defined (currently +@@ -32,20 +32,20 @@ + own code. + + +-.. cfunction:: PyOS_sighandler_t PyOS_getsig(int i) ++.. c:function:: PyOS_sighandler_t PyOS_getsig(int i) + + Return the current signal handler for signal *i*. This is a thin wrapper around +- either :cfunc:`sigaction` or :cfunc:`signal`. Do not call those functions +- directly! :ctype:`PyOS_sighandler_t` is a typedef alias for :ctype:`void ++ either :c:func:`sigaction` or :c:func:`signal`. Do not call those functions ++ directly! :c:type:`PyOS_sighandler_t` is a typedef alias for :c:type:`void + (\*)(int)`. + + +-.. cfunction:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) ++.. c:function:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) + + Set the signal handler for signal *i* to be *h*; return the old signal handler. +- This is a thin wrapper around either :cfunc:`sigaction` or :cfunc:`signal`. Do +- not call those functions directly! :ctype:`PyOS_sighandler_t` is a typedef +- alias for :ctype:`void (\*)(int)`. ++ This is a thin wrapper around either :c:func:`sigaction` or :c:func:`signal`. Do ++ not call those functions directly! :c:type:`PyOS_sighandler_t` is a typedef ++ alias for :c:type:`void (\*)(int)`. + + .. _systemfunctions: + +@@ -56,38 +56,38 @@ + accessible to C code. They all work with the current interpreter thread's + :mod:`sys` module's dict, which is contained in the internal thread state structure. + +-.. cfunction:: PyObject *PySys_GetObject(char *name) ++.. c:function:: PyObject *PySys_GetObject(char *name) + + Return the object *name* from the :mod:`sys` module or *NULL* if it does + not exist, without setting an exception. + +-.. cfunction:: FILE *PySys_GetFile(char *name, FILE *def) ++.. c:function:: FILE *PySys_GetFile(char *name, FILE *def) + +- Return the :ctype:`FILE*` associated with the object *name* in the ++ Return the :c:type:`FILE*` associated with the object *name* in the + :mod:`sys` module, or *def* if *name* is not in the module or is not associated +- with a :ctype:`FILE*`. ++ with a :c:type:`FILE*`. + +-.. cfunction:: int PySys_SetObject(char *name, PyObject *v) ++.. c:function:: int PySys_SetObject(char *name, PyObject *v) + + Set *name* in the :mod:`sys` module to *v* unless *v* is *NULL*, in which + case *name* is deleted from the sys module. Returns ``0`` on success, ``-1`` + on error. + +-.. cfunction:: void PySys_ResetWarnOptions() ++.. c:function:: void PySys_ResetWarnOptions() + + Reset :data:`sys.warnoptions` to an empty list. + +-.. cfunction:: void PySys_AddWarnOption(char *s) ++.. c:function:: void PySys_AddWarnOption(char *s) + + Append *s* to :data:`sys.warnoptions`. + +-.. cfunction:: void PySys_SetPath(char *path) ++.. c:function:: void PySys_SetPath(char *path) + + Set :data:`sys.path` to a list object of paths found in *path* which should + be a list of paths separated with the platform's search path delimiter + (``:`` on Unix, ``;`` on Windows). + +-.. cfunction:: void PySys_WriteStdout(const char *format, ...) ++.. c:function:: void PySys_WriteStdout(const char *format, ...) + + Write the output string described by *format* to :data:`sys.stdout`. No + exceptions are raised, even if truncation occurs (see below). +@@ -103,7 +103,7 @@ + If a problem occurs, or :data:`sys.stdout` is unset, the formatted message + is written to the real (C level) *stdout*. + +-.. cfunction:: void PySys_WriteStderr(const char *format, ...) ++.. c:function:: void PySys_WriteStderr(const char *format, ...) + + As above, but write to :data:`sys.stderr` or *stderr* instead. + +@@ -114,7 +114,7 @@ + =============== + + +-.. cfunction:: void Py_FatalError(const char *message) ++.. c:function:: void Py_FatalError(const char *message) + + .. index:: single: abort() + +@@ -122,30 +122,30 @@ + This function should only be invoked when a condition is detected that would + make it dangerous to continue using the Python interpreter; e.g., when the + object administration appears to be corrupted. On Unix, the standard C library +- function :cfunc:`abort` is called which will attempt to produce a :file:`core` ++ function :c:func:`abort` is called which will attempt to produce a :file:`core` + file. + + +-.. cfunction:: void Py_Exit(int status) ++.. c:function:: void Py_Exit(int status) + + .. index:: + single: Py_Finalize() + single: exit() + +- Exit the current process. This calls :cfunc:`Py_Finalize` and then calls the ++ Exit the current process. This calls :c:func:`Py_Finalize` and then calls the + standard C library function ``exit(status)``. + + +-.. cfunction:: int Py_AtExit(void (*func) ()) ++.. c:function:: int Py_AtExit(void (*func) ()) + + .. index:: + single: Py_Finalize() + single: cleanup functions + +- Register a cleanup function to be called by :cfunc:`Py_Finalize`. The cleanup ++ Register a cleanup function to be called by :c:func:`Py_Finalize`. The cleanup + function will be called with no arguments and should return no value. At most + 32 cleanup functions can be registered. When the registration is successful, +- :cfunc:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup ++ :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``. The cleanup + function registered last is called first. Each cleanup function will be called + at most once. Since Python's internal finalization will have completed before + the cleanup function, no Python APIs should be called by *func*. +diff -r 8527427914a2 Doc/c-api/tuple.rst +--- a/Doc/c-api/tuple.rst ++++ b/Doc/c-api/tuple.rst +@@ -8,20 +8,20 @@ + .. index:: object: tuple + + +-.. ctype:: PyTupleObject ++.. c:type:: PyTupleObject + +- This subtype of :ctype:`PyObject` represents a Python tuple object. ++ This subtype of :c:type:`PyObject` represents a Python tuple object. + + +-.. cvar:: PyTypeObject PyTuple_Type ++.. c:var:: PyTypeObject PyTuple_Type + + .. index:: single: TupleType (in module types) + +- This instance of :ctype:`PyTypeObject` represents the Python tuple type; it is ++ This instance of :c:type:`PyTypeObject` represents the Python tuple type; it is + the same object as ``tuple`` and ``types.TupleType`` in the Python layer.. + + +-.. cfunction:: int PyTuple_Check(PyObject *p) ++.. c:function:: int PyTuple_Check(PyObject *p) + + Return true if *p* is a tuple object or an instance of a subtype of the tuple + type. +@@ -30,7 +30,7 @@ + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyTuple_CheckExact(PyObject *p) ++.. c:function:: int PyTuple_CheckExact(PyObject *p) + + Return true if *p* is a tuple object, but not an instance of a subtype of the + tuple type. +@@ -38,16 +38,16 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyTuple_New(Py_ssize_t len) ++.. c:function:: PyObject* PyTuple_New(Py_ssize_t len) + + Return a new tuple object of size *len*, or *NULL* on failure. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *len*. This might require ++ This function used an :c:type:`int` type for *len*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyTuple_Pack(Py_ssize_t n, ...) ++.. c:function:: PyObject* PyTuple_Pack(Py_ssize_t n, ...) + + Return a new tuple object of size *n*, or *NULL* on failure. The tuple values + are initialized to the subsequent *n* C arguments pointing to Python objects. +@@ -56,59 +56,59 @@ + .. versionadded:: 2.4 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *n*. This might require ++ This function used an :c:type:`int` type for *n*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyTuple_Size(PyObject *p) ++.. c:function:: Py_ssize_t PyTuple_Size(PyObject *p) + + Take a pointer to a tuple object, and return the size of that tuple. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) ++.. c:function:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) + + Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple; + no error checking is performed. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos) ++.. c:function:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos) + + Return the object at position *pos* in the tuple pointed to by *p*. If *pos* is + out of bounds, return *NULL* and sets an :exc:`IndexError` exception. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *pos*. This might require ++ This function used an :c:type:`int` type for *pos*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos) ++.. c:function:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos) + +- Like :cfunc:`PyTuple_GetItem`, but does no checking of its arguments. ++ Like :c:func:`PyTuple_GetItem`, but does no checking of its arguments. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *pos*. This might require ++ This function used an :c:type:`int` type for *pos*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high) ++.. c:function:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high) + + Take a slice of the tuple pointed to by *p* from *low* to *high* and return it + as a new tuple. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *low* and *high*. This might ++ This function used an :c:type:`int` type for *low* and *high*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) ++.. c:function:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o) + + Insert a reference to object *o* at position *pos* of the tuple pointed to by + *p*. Return ``0`` on success. +@@ -118,13 +118,13 @@ + This function "steals" a reference to *o*. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *pos*. This might require ++ This function used an :c:type:`int` type for *pos*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o) ++.. c:function:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o) + +- Like :cfunc:`PyTuple_SetItem`, but does no error checking, and should *only* be ++ Like :c:func:`PyTuple_SetItem`, but does no error checking, and should *only* be + used to fill in brand new tuples. + + .. note:: +@@ -132,11 +132,11 @@ + This function "steals" a reference to *o*. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *pos*. This might require ++ This function used an :c:type:`int` type for *pos*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize) ++.. c:function:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize) + + Can be used to resize a tuple. *newsize* will be the new length of the tuple. + Because tuples are *supposed* to be immutable, this should only be used if there +@@ -153,11 +153,11 @@ + Removed unused third parameter, *last_is_sticky*. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *newsize*. This might ++ This function used an :c:type:`int` type for *newsize*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyTuple_ClearFreeList() ++.. c:function:: int PyTuple_ClearFreeList() + + Clear the free list. Return the total number of freed items. + +diff -r 8527427914a2 Doc/c-api/type.rst +--- a/Doc/c-api/type.rst ++++ b/Doc/c-api/type.rst +@@ -8,12 +8,12 @@ + .. index:: object: type + + +-.. ctype:: PyTypeObject ++.. c:type:: PyTypeObject + + The C structure of the objects used to describe built-in types. + + +-.. cvar:: PyObject* PyType_Type ++.. c:var:: PyObject* PyType_Type + + .. index:: single: TypeType (in module types) + +@@ -21,13 +21,13 @@ + ``types.TypeType`` in the Python layer. + + +-.. cfunction:: int PyType_Check(PyObject *o) ++.. c:function:: int PyType_Check(PyObject *o) + + Return true if the object *o* is a type object, including instances of types + derived from the standard type object. Return false in all other cases. + + +-.. cfunction:: int PyType_CheckExact(PyObject *o) ++.. c:function:: int PyType_CheckExact(PyObject *o) + + Return true if the object *o* is a type object, but not a subtype of the + standard type object. Return false in all other cases. +@@ -35,14 +35,14 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: unsigned int PyType_ClearCache() ++.. c:function:: unsigned int PyType_ClearCache() + + Clear the internal lookup cache. Return the current version tag. + + .. versionadded:: 2.6 + + +-.. cfunction:: void PyType_Modified(PyTypeObject *type) ++.. c:function:: void PyType_Modified(PyTypeObject *type) + + Invalidate the internal lookup cache for the type and all of its + subtypes. This function must be called after any manual +@@ -51,13 +51,13 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: int PyType_HasFeature(PyObject *o, int feature) ++.. c:function:: int PyType_HasFeature(PyObject *o, int feature) + + Return true if the type object *o* sets the feature *feature*. Type features + are denoted by single bit flags. + + +-.. cfunction:: int PyType_IS_GC(PyObject *o) ++.. c:function:: int PyType_IS_GC(PyObject *o) + + Return true if the type object includes support for the cycle detector; this + tests the type flag :const:`Py_TPFLAGS_HAVE_GC`. +@@ -65,28 +65,28 @@ + .. versionadded:: 2.0 + + +-.. cfunction:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) ++.. c:function:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) + + Return true if *a* is a subtype of *b*. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) ++.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) + + .. versionadded:: 2.2 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *nitems*. This might require ++ This function used an :c:type:`int` type for *nitems*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) ++.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) + + .. versionadded:: 2.2 + + +-.. cfunction:: int PyType_Ready(PyTypeObject *type) ++.. c:function:: int PyType_Ready(PyTypeObject *type) + + Finalize a type object. This should be called on all type objects to finish + their initialization. This function is responsible for adding inherited slots +diff -r 8527427914a2 Doc/c-api/typeobj.rst +--- a/Doc/c-api/typeobj.rst ++++ b/Doc/c-api/typeobj.rst +@@ -6,9 +6,9 @@ + ============ + + Perhaps one of the most important structures of the Python object system is the +-structure that defines a new type: the :ctype:`PyTypeObject` structure. Type +-objects can be handled using any of the :cfunc:`PyObject_\*` or +-:cfunc:`PyType_\*` functions, but do not offer much that's interesting to most ++structure that defines a new type: the :c:type:`PyTypeObject` structure. Type ++objects can be handled using any of the :c:func:`PyObject_\*` or ++:c:func:`PyType_\*` functions, but do not offer much that's interesting to most + Python applications. These objects are fundamental to how objects behave, so + they are very important to the interpreter itself and to any extension module + that implements new types. +@@ -25,21 +25,21 @@ + freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc, + cmpfunc, reprfunc, hashfunc + +-The structure definition for :ctype:`PyTypeObject` can be found in ++The structure definition for :c:type:`PyTypeObject` can be found in + :file:`Include/object.h`. For convenience of reference, this repeats the + definition found there: + + .. literalinclude:: ../includes/typestruct.h + + +-The type object structure extends the :ctype:`PyVarObject` structure. The ++The type object structure extends the :c:type:`PyVarObject` structure. The + :attr:`ob_size` field is used for dynamic types (created by :func:`type_new`, +-usually called from a class statement). Note that :cdata:`PyType_Type` (the ++usually called from a class statement). Note that :c:data:`PyType_Type` (the + metatype) initializes :attr:`tp_itemsize`, which means that its instances (i.e. + type objects) *must* have the :attr:`ob_size` field. + + +-.. cmember:: PyObject* PyObject._ob_next ++.. c:member:: PyObject* PyObject._ob_next + PyObject* PyObject._ob_prev + + These fields are only present when the macro ``Py_TRACE_REFS`` is defined. +@@ -54,7 +54,7 @@ + These fields are not inherited by subtypes. + + +-.. cmember:: Py_ssize_t PyObject.ob_refcnt ++.. c:member:: Py_ssize_t PyObject.ob_refcnt + + This is the type object's reference count, initialized to ``1`` by the + ``PyObject_HEAD_INIT`` macro. Note that for statically allocated type objects, +@@ -65,11 +65,11 @@ + This field is not inherited by subtypes. + + .. versionchanged:: 2.5 +- This field used to be an :ctype:`int` type. This might require changes ++ This field used to be an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cmember:: PyTypeObject* PyObject.ob_type ++.. c:member:: PyTypeObject* PyObject.ob_type + + This is the type's type, in other words its metatype. It is initialized by the + argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be +@@ -83,16 +83,16 @@ + Foo_Type.ob_type = &PyType_Type; + + This should be done before any instances of the type are created. +- :cfunc:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so, ++ :c:func:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so, + initializes it: in Python 2.2, it is set to ``&PyType_Type``; in Python 2.2.1 + and later it is initialized to the :attr:`ob_type` field of the base class. +- :cfunc:`PyType_Ready` will not change this field if it is non-zero. ++ :c:func:`PyType_Ready` will not change this field if it is non-zero. + + In Python 2.2, this field is not inherited by subtypes. In 2.2.1, and in 2.3 + and beyond, it is inherited by subtypes. + + +-.. cmember:: Py_ssize_t PyVarObject.ob_size ++.. c:member:: Py_ssize_t PyVarObject.ob_size + + For statically allocated type objects, this should be initialized to zero. For + dynamically allocated type objects, this field has a special internal meaning. +@@ -100,7 +100,7 @@ + This field is not inherited by subtypes. + + +-.. cmember:: char* PyTypeObject.tp_name ++.. c:member:: char* PyTypeObject.tp_name + + Pointer to a NUL-terminated string containing the name of the type. For types + that are accessible as module globals, the string should be the full module +@@ -127,7 +127,7 @@ + This field is not inherited by subtypes. + + +-.. cmember:: Py_ssize_t PyTypeObject.tp_basicsize ++.. c:member:: Py_ssize_t PyTypeObject.tp_basicsize + Py_ssize_t PyTypeObject.tp_itemsize + + These fields allow calculating the size in bytes of instances of the type. +@@ -149,7 +149,7 @@ + field). + + The basic size includes the fields in the instance declared by the macro +- :cmacro:`PyObject_HEAD` or :cmacro:`PyObject_VAR_HEAD` (whichever is used to ++ :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to + declare the instance struct) and this in turn includes the :attr:`_ob_prev` and + :attr:`_ob_next` fields if they are present. This means that the only correct + way to get an initializer for the :attr:`tp_basicsize` is to use the +@@ -170,14 +170,14 @@ + alignment requirement for ``double``). + + +-.. cmember:: destructor PyTypeObject.tp_dealloc ++.. c:member:: destructor PyTypeObject.tp_dealloc + + A pointer to the instance destructor function. This function must be defined + unless the type guarantees that its instances will never be deallocated (as is + the case for the singletons ``None`` and ``Ellipsis``). + +- The destructor function is called by the :cfunc:`Py_DECREF` and +- :cfunc:`Py_XDECREF` macros when the new reference count is zero. At this point, ++ The destructor function is called by the :c:func:`Py_DECREF` and ++ :c:func:`Py_XDECREF` macros when the new reference count is zero. At this point, + the instance is still in existence, but there are no references to it. The + destructor function should free all references which the instance owns, free all + memory buffers owned by the instance (using the freeing function corresponding +@@ -186,15 +186,15 @@ + subtypable (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is + permissible to call the object deallocator directly instead of via + :attr:`tp_free`. The object deallocator should be the one used to allocate the +- instance; this is normally :cfunc:`PyObject_Del` if the instance was allocated +- using :cfunc:`PyObject_New` or :cfunc:`PyObject_VarNew`, or +- :cfunc:`PyObject_GC_Del` if the instance was allocated using +- :cfunc:`PyObject_GC_New` or :cfunc:`PyObject_GC_NewVar`. ++ instance; this is normally :c:func:`PyObject_Del` if the instance was allocated ++ using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or ++ :c:func:`PyObject_GC_Del` if the instance was allocated using ++ :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`. + + This field is inherited by subtypes. + + +-.. cmember:: printfunc PyTypeObject.tp_print ++.. c:member:: printfunc PyTypeObject.tp_print + + An optional pointer to the instance print function. + +@@ -205,7 +205,7 @@ + *NULL*. A type should never implement :attr:`tp_print` in a way that produces + different output than :attr:`tp_repr` or :attr:`tp_str` would. + +- The print function is called with the same signature as :cfunc:`PyObject_Print`: ++ The print function is called with the same signature as :c:func:`PyObject_Print`: + ``int tp_print(PyObject *self, FILE *file, int flags)``. The *self* argument is + the instance to be printed. The *file* argument is the stdio file to which it + is to be printed. The *flags* argument is composed of flag bits. The only flag +@@ -223,39 +223,39 @@ + This field is inherited by subtypes. + + +-.. cmember:: getattrfunc PyTypeObject.tp_getattr ++.. c:member:: getattrfunc PyTypeObject.tp_getattr + + An optional pointer to the get-attribute-string function. + + This field is deprecated. When it is defined, it should point to a function + that acts the same as the :attr:`tp_getattro` function, but taking a C string + instead of a Python string object to give the attribute name. The signature is +- the same as for :cfunc:`PyObject_GetAttrString`. ++ the same as for :c:func:`PyObject_GetAttrString`. + + This field is inherited by subtypes together with :attr:`tp_getattro`: a subtype + inherits both :attr:`tp_getattr` and :attr:`tp_getattro` from its base type when + the subtype's :attr:`tp_getattr` and :attr:`tp_getattro` are both *NULL*. + + +-.. cmember:: setattrfunc PyTypeObject.tp_setattr ++.. c:member:: setattrfunc PyTypeObject.tp_setattr + + An optional pointer to the set-attribute-string function. + + This field is deprecated. When it is defined, it should point to a function + that acts the same as the :attr:`tp_setattro` function, but taking a C string + instead of a Python string object to give the attribute name. The signature is +- the same as for :cfunc:`PyObject_SetAttrString`. ++ the same as for :c:func:`PyObject_SetAttrString`. + + This field is inherited by subtypes together with :attr:`tp_setattro`: a subtype + inherits both :attr:`tp_setattr` and :attr:`tp_setattro` from its base type when + the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*. + + +-.. cmember:: cmpfunc PyTypeObject.tp_compare ++.. c:member:: cmpfunc PyTypeObject.tp_compare + + An optional pointer to the three-way comparison function. + +- The signature is the same as for :cfunc:`PyObject_Compare`. The function should ++ The signature is the same as for :c:func:`PyObject_Compare`. The function should + return ``1`` if *self* greater than *other*, ``0`` if *self* is equal to + *other*, and ``-1`` if *self* less than *other*. It should return ``-1`` and + set an exception condition when an error occurred during the comparison. +@@ -266,14 +266,14 @@ + :attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*. + + +-.. cmember:: reprfunc PyTypeObject.tp_repr ++.. c:member:: reprfunc PyTypeObject.tp_repr + + .. index:: builtin: repr + + An optional pointer to a function that implements the built-in function + :func:`repr`. + +- The signature is the same as for :cfunc:`PyObject_Repr`; it must return a string ++ The signature is the same as for :c:func:`PyObject_Repr`; it must return a string + or a Unicode object. Ideally, this function should return a string that, when + passed to :func:`eval`, given a suitable environment, returns an object with the + same value. If this is not feasible, it should return a string starting with +@@ -286,7 +286,7 @@ + + This field is inherited by subtypes. + +-.. cmember:: PyNumberMethods* tp_as_number ++.. c:member:: PyNumberMethods* tp_as_number + + Pointer to an additional structure that contains fields relevant only to + objects which implement the number protocol. These fields are documented in +@@ -296,7 +296,7 @@ + inherited individually. + + +-.. cmember:: PySequenceMethods* tp_as_sequence ++.. c:member:: PySequenceMethods* tp_as_sequence + + Pointer to an additional structure that contains fields relevant only to + objects which implement the sequence protocol. These fields are documented +@@ -306,7 +306,7 @@ + are inherited individually. + + +-.. cmember:: PyMappingMethods* tp_as_mapping ++.. c:member:: PyMappingMethods* tp_as_mapping + + Pointer to an additional structure that contains fields relevant only to + objects which implement the mapping protocol. These fields are documented in +@@ -316,25 +316,25 @@ + are inherited individually. + + +-.. cmember:: hashfunc PyTypeObject.tp_hash ++.. c:member:: hashfunc PyTypeObject.tp_hash + + .. index:: builtin: hash + + An optional pointer to a function that implements the built-in function + :func:`hash`. + +- The signature is the same as for :cfunc:`PyObject_Hash`; it must return a C ++ The signature is the same as for :c:func:`PyObject_Hash`; it must return a C + long. The value ``-1`` should not be returned as a normal return value; when an + error occurs during the computation of the hash value, the function should set + an exception and return ``-1``. + +- This field can be set explicitly to :cfunc:`PyObject_HashNotImplemented` to ++ This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to + block inheritance of the hash method from a parent type. This is interpreted + as the equivalent of ``__hash__ = None`` at the Python level, causing + ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note + that the converse is also true - setting ``__hash__ = None`` on a class at + the Python level will result in the ``tp_hash`` slot being set to +- :cfunc:`PyObject_HashNotImplemented`. ++ :c:func:`PyObject_HashNotImplemented`. + + When this field is not set, two possibilities exist: if the :attr:`tp_compare` + and :attr:`tp_richcompare` fields are both *NULL*, a default hash value based on +@@ -346,39 +346,39 @@ + :attr:`tp_compare`, :attr:`tp_richcompare` and :attr:`tp_hash` are all *NULL*. + + +-.. cmember:: ternaryfunc PyTypeObject.tp_call ++.. c:member:: ternaryfunc PyTypeObject.tp_call + + An optional pointer to a function that implements calling the object. This + should be *NULL* if the object is not callable. The signature is the same as +- for :cfunc:`PyObject_Call`. ++ for :c:func:`PyObject_Call`. + + This field is inherited by subtypes. + + +-.. cmember:: reprfunc PyTypeObject.tp_str ++.. c:member:: reprfunc PyTypeObject.tp_str + + An optional pointer to a function that implements the built-in operation + :func:`str`. (Note that :class:`str` is a type now, and :func:`str` calls the +- constructor for that type. This constructor calls :cfunc:`PyObject_Str` to do +- the actual work, and :cfunc:`PyObject_Str` will call this handler.) ++ constructor for that type. This constructor calls :c:func:`PyObject_Str` to do ++ the actual work, and :c:func:`PyObject_Str` will call this handler.) + +- The signature is the same as for :cfunc:`PyObject_Str`; it must return a string ++ The signature is the same as for :c:func:`PyObject_Str`; it must return a string + or a Unicode object. This function should return a "friendly" string + representation of the object, as this is the representation that will be used by + the print statement. + +- When this field is not set, :cfunc:`PyObject_Repr` is called to return a string ++ When this field is not set, :c:func:`PyObject_Repr` is called to return a string + representation. + + This field is inherited by subtypes. + + +-.. cmember:: getattrofunc PyTypeObject.tp_getattro ++.. c:member:: getattrofunc PyTypeObject.tp_getattro + + An optional pointer to the get-attribute function. + +- The signature is the same as for :cfunc:`PyObject_GetAttr`. It is usually +- convenient to set this field to :cfunc:`PyObject_GenericGetAttr`, which ++ The signature is the same as for :c:func:`PyObject_GetAttr`. It is usually ++ convenient to set this field to :c:func:`PyObject_GenericGetAttr`, which + implements the normal way of looking for object attributes. + + This field is inherited by subtypes together with :attr:`tp_getattr`: a subtype +@@ -386,12 +386,12 @@ + the subtype's :attr:`tp_getattr` and :attr:`tp_getattro` are both *NULL*. + + +-.. cmember:: setattrofunc PyTypeObject.tp_setattro ++.. c:member:: setattrofunc PyTypeObject.tp_setattro + + An optional pointer to the set-attribute function. + +- The signature is the same as for :cfunc:`PyObject_SetAttr`. It is usually +- convenient to set this field to :cfunc:`PyObject_GenericSetAttr`, which ++ The signature is the same as for :c:func:`PyObject_SetAttr`. It is usually ++ convenient to set this field to :c:func:`PyObject_GenericSetAttr`, which + implements the normal way of setting object attributes. + + This field is inherited by subtypes together with :attr:`tp_setattr`: a subtype +@@ -399,7 +399,7 @@ + the subtype's :attr:`tp_setattr` and :attr:`tp_setattro` are both *NULL*. + + +-.. cmember:: PyBufferProcs* PyTypeObject.tp_as_buffer ++.. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer + + Pointer to an additional structure that contains fields relevant only to objects + which implement the buffer interface. These fields are documented in +@@ -409,7 +409,7 @@ + inherited individually. + + +-.. cmember:: long PyTypeObject.tp_flags ++.. c:member:: long PyTypeObject.tp_flags + + This field is a bit mask of various flags. Some flags indicate variant + semantics for certain situations; others are used to indicate that certain +@@ -433,19 +433,19 @@ + + The following bit masks are currently defined; these can be ORed together using + the ``|`` operator to form the value of the :attr:`tp_flags` field. The macro +- :cfunc:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and ++ :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and + checks whether ``tp->tp_flags & f`` is non-zero. + + + .. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER + +- If this bit is set, the :ctype:`PyBufferProcs` struct referenced by ++ If this bit is set, the :c:type:`PyBufferProcs` struct referenced by + :attr:`tp_as_buffer` has the :attr:`bf_getcharbuffer` field. + + + .. data:: Py_TPFLAGS_HAVE_SEQUENCE_IN + +- If this bit is set, the :ctype:`PySequenceMethods` struct referenced by ++ If this bit is set, the :c:type:`PySequenceMethods` struct referenced by + :attr:`tp_as_sequence` has the :attr:`sq_contains` field. + + +@@ -457,23 +457,23 @@ + + .. data:: Py_TPFLAGS_HAVE_INPLACEOPS + +- If this bit is set, the :ctype:`PySequenceMethods` struct referenced by +- :attr:`tp_as_sequence` and the :ctype:`PyNumberMethods` structure referenced by ++ If this bit is set, the :c:type:`PySequenceMethods` struct referenced by ++ :attr:`tp_as_sequence` and the :c:type:`PyNumberMethods` structure referenced by + :attr:`tp_as_number` contain the fields for in-place operators. In particular, +- this means that the :ctype:`PyNumberMethods` structure has the fields ++ this means that the :c:type:`PyNumberMethods` structure has the fields + :attr:`nb_inplace_add`, :attr:`nb_inplace_subtract`, + :attr:`nb_inplace_multiply`, :attr:`nb_inplace_divide`, + :attr:`nb_inplace_remainder`, :attr:`nb_inplace_power`, + :attr:`nb_inplace_lshift`, :attr:`nb_inplace_rshift`, :attr:`nb_inplace_and`, + :attr:`nb_inplace_xor`, and :attr:`nb_inplace_or`; and the +- :ctype:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and ++ :c:type:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and + :attr:`sq_inplace_repeat`. + + + .. data:: Py_TPFLAGS_CHECKTYPES + + If this bit is set, the binary and ternary operations in the +- :ctype:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept ++ :c:type:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept + arguments of arbitrary object types, and do their own type conversions if + needed. If this bit is clear, those operations require that all arguments have + the current type as their type, and the caller is supposed to perform a coercion +@@ -532,20 +532,20 @@ + .. data:: Py_TPFLAGS_READY + + This bit is set when the type object has been fully initialized by +- :cfunc:`PyType_Ready`. ++ :c:func:`PyType_Ready`. + + + .. data:: Py_TPFLAGS_READYING + +- This bit is set while :cfunc:`PyType_Ready` is in the process of initializing ++ This bit is set while :c:func:`PyType_Ready` is in the process of initializing + the type object. + + + .. data:: Py_TPFLAGS_HAVE_GC + + This bit is set when the object supports garbage collection. If this bit +- is set, instances must be created using :cfunc:`PyObject_GC_New` and +- destroyed using :cfunc:`PyObject_GC_Del`. More information in section ++ is set, instances must be created using :c:func:`PyObject_GC_New` and ++ destroyed using :c:func:`PyObject_GC_Del`. More information in section + :ref:`supporting-cycle-detection`. This bit also implies that the + GC-related fields :attr:`tp_traverse` and :attr:`tp_clear` are present in + the type object; but those fields also exist when +@@ -563,7 +563,7 @@ + :const:`Py_TPFLAGS_HAVE_ITER`, and :const:`Py_TPFLAGS_HAVE_CLASS`. + + +-.. cmember:: char* PyTypeObject.tp_doc ++.. c:member:: char* PyTypeObject.tp_doc + + An optional pointer to a NUL-terminated C string giving the docstring for this + type object. This is exposed as the :attr:`__doc__` attribute on the type and +@@ -575,7 +575,7 @@ + :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit is set. + + +-.. cmember:: traverseproc PyTypeObject.tp_traverse ++.. c:member:: traverseproc PyTypeObject.tp_traverse + + An optional pointer to a traversal function for the garbage collector. This is + only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. More information +@@ -584,8 +584,8 @@ + + The :attr:`tp_traverse` pointer is used by the garbage collector to detect + reference cycles. A typical implementation of a :attr:`tp_traverse` function +- simply calls :cfunc:`Py_VISIT` on each of the instance's members that are Python +- objects. For example, this is function :cfunc:`local_traverse` from the ++ simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python ++ objects. For example, this is function :c:func:`local_traverse` from the + :mod:`thread` extension module:: + + static int +@@ -597,7 +597,7 @@ + return 0; + } + +- Note that :cfunc:`Py_VISIT` is called only on those members that can participate ++ Note that :c:func:`Py_VISIT` is called only on those members that can participate + in reference cycles. Although there is also a ``self->key`` member, it can only + be *NULL* or a Python string and therefore cannot be part of a reference cycle. + +@@ -605,8 +605,8 @@ + debugging aid you may want to visit it anyway just so the :mod:`gc` module's + :func:`get_referents` function will include it. + +- Note that :cfunc:`Py_VISIT` requires the *visit* and *arg* parameters to +- :cfunc:`local_traverse` to have these specific names; don't name them just ++ Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to ++ :c:func:`local_traverse` to have these specific names; don't name them just + anything. + + This field is inherited by subtypes together with :attr:`tp_clear` and the +@@ -616,7 +616,7 @@ + bit set. + + +-.. cmember:: inquiry PyTypeObject.tp_clear ++.. c:member:: inquiry PyTypeObject.tp_clear + + An optional pointer to a clear function for the garbage collector. This is only + used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set. +@@ -645,7 +645,7 @@ + return 0; + } + +- The :cfunc:`Py_CLEAR` macro should be used, because clearing references is ++ The :c:func:`Py_CLEAR` macro should be used, because clearing references is + delicate: the reference to the contained object must not be decremented until + after the pointer to the contained object is set to *NULL*. This is because + decrementing the reference count may cause the contained object to become trash, +@@ -654,7 +654,7 @@ + contained object). If it's possible for such code to reference *self* again, + it's important that the pointer to the contained object be *NULL* at that time, + so that *self* knows the contained object can no longer be used. The +- :cfunc:`Py_CLEAR` macro performs the operations in a safe order. ++ :c:func:`Py_CLEAR` macro performs the operations in a safe order. + + Because the goal of :attr:`tp_clear` functions is to break reference cycles, + it's not necessary to clear contained objects like Python strings or Python +@@ -672,7 +672,7 @@ + bit set. + + +-.. cmember:: richcmpfunc PyTypeObject.tp_richcompare ++.. c:member:: richcmpfunc PyTypeObject.tp_richcompare + + An optional pointer to the rich comparison function, whose signature is + ``PyObject *tp_richcompare(PyObject *a, PyObject *b, int op)``. +@@ -694,7 +694,7 @@ + :attr:`tp_compare`, :attr:`tp_richcompare`, and :attr:`tp_hash` are all *NULL*. + + The following constants are defined to be used as the third argument for +- :attr:`tp_richcompare` and for :cfunc:`PyObject_RichCompare`: ++ :attr:`tp_richcompare` and for :c:func:`PyObject_RichCompare`: + + +----------------+------------+ + | Constant | Comparison | +@@ -716,13 +716,13 @@ + The next field only exists if the :const:`Py_TPFLAGS_HAVE_WEAKREFS` flag bit is + set. + +-.. cmember:: long PyTypeObject.tp_weaklistoffset ++.. c:member:: long PyTypeObject.tp_weaklistoffset + + If the instances of this type are weakly referenceable, this field is greater + than zero and contains the offset in the instance structure of the weak + reference list head (ignoring the GC header, if present); this offset is used by +- :cfunc:`PyObject_ClearWeakRefs` and the :cfunc:`PyWeakref_\*` functions. The +- instance structure needs to include a field of type :ctype:`PyObject\*` which is ++ :c:func:`PyObject_ClearWeakRefs` and the :c:func:`PyWeakref_\*` functions. The ++ instance structure needs to include a field of type :c:type:`PyObject\*` which is + initialized to *NULL*. + + Do not confuse this field with :attr:`tp_weaklist`; that is the list head for +@@ -751,19 +751,19 @@ + set. + + +-.. cmember:: getiterfunc PyTypeObject.tp_iter ++.. c:member:: getiterfunc PyTypeObject.tp_iter + + An optional pointer to a function that returns an iterator for the object. Its + presence normally signals that the instances of this type are iterable (although + sequences may be iterable without this function, and classic instances always + have this function, even if they don't define an :meth:`__iter__` method). + +- This function has the same signature as :cfunc:`PyObject_GetIter`. ++ This function has the same signature as :c:func:`PyObject_GetIter`. + + This field is inherited by subtypes. + + +-.. cmember:: iternextfunc PyTypeObject.tp_iternext ++.. c:member:: iternextfunc PyTypeObject.tp_iternext + + An optional pointer to a function that returns the next item in an iterator. + When the iterator is exhausted, it must return *NULL*; a :exc:`StopIteration` +@@ -776,7 +776,7 @@ + function should return the iterator instance itself (not a new iterator + instance). + +- This function has the same signature as :cfunc:`PyIter_Next`. ++ This function has the same signature as :c:func:`PyIter_Next`. + + This field is inherited by subtypes. + +@@ -784,9 +784,9 @@ + :const:`Py_TPFLAGS_HAVE_CLASS` flag bit is set. + + +-.. cmember:: struct PyMethodDef* PyTypeObject.tp_methods ++.. c:member:: struct PyMethodDef* PyTypeObject.tp_methods + +- An optional pointer to a static *NULL*-terminated array of :ctype:`PyMethodDef` ++ An optional pointer to a static *NULL*-terminated array of :c:type:`PyMethodDef` + structures, declaring regular methods of this type. + + For each entry in the array, an entry is added to the type's dictionary (see +@@ -796,9 +796,9 @@ + different mechanism). + + +-.. cmember:: struct PyMemberDef* PyTypeObject.tp_members ++.. c:member:: struct PyMemberDef* PyTypeObject.tp_members + +- An optional pointer to a static *NULL*-terminated array of :ctype:`PyMemberDef` ++ An optional pointer to a static *NULL*-terminated array of :c:type:`PyMemberDef` + structures, declaring regular data members (fields or slots) of instances of + this type. + +@@ -809,9 +809,9 @@ + different mechanism). + + +-.. cmember:: struct PyGetSetDef* PyTypeObject.tp_getset ++.. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset + +- An optional pointer to a static *NULL*-terminated array of :ctype:`PyGetSetDef` ++ An optional pointer to a static *NULL*-terminated array of :c:type:`PyGetSetDef` + structures, declaring computed attributes of instances of this type. + + For each entry in the array, an entry is added to the type's dictionary (see +@@ -836,7 +836,7 @@ + } PyGetSetDef; + + +-.. cmember:: PyTypeObject* PyTypeObject.tp_base ++.. c:member:: PyTypeObject* PyTypeObject.tp_base + + An optional pointer to a base type from which type properties are inherited. At + this level, only single inheritance is supported; multiple inheritance require +@@ -847,13 +847,13 @@ + :class:`object`). + + +-.. cmember:: PyObject* PyTypeObject.tp_dict ++.. c:member:: PyObject* PyTypeObject.tp_dict + +- The type's dictionary is stored here by :cfunc:`PyType_Ready`. ++ The type's dictionary is stored here by :c:func:`PyType_Ready`. + + This field should normally be initialized to *NULL* before PyType_Ready is + called; it may also be initialized to a dictionary containing initial attributes +- for the type. Once :cfunc:`PyType_Ready` has initialized the type, extra ++ for the type. Once :c:func:`PyType_Ready` has initialized the type, extra + attributes for the type may be added to this dictionary only if they don't + correspond to overloaded operations (like :meth:`__add__`). + +@@ -861,7 +861,7 @@ + are inherited through a different mechanism). + + +-.. cmember:: descrgetfunc PyTypeObject.tp_descr_get ++.. c:member:: descrgetfunc PyTypeObject.tp_descr_get + + An optional pointer to a "descriptor get" function. + +@@ -874,7 +874,7 @@ + This field is inherited by subtypes. + + +-.. cmember:: descrsetfunc PyTypeObject.tp_descr_set ++.. c:member:: descrsetfunc PyTypeObject.tp_descr_set + + An optional pointer to a "descriptor set" function. + +@@ -887,12 +887,12 @@ + .. XXX explain. + + +-.. cmember:: long PyTypeObject.tp_dictoffset ++.. c:member:: long PyTypeObject.tp_dictoffset + + If the instances of this type have a dictionary containing instance variables, + this field is non-zero and contains the offset in the instances of the type of + the instance variable dictionary; this offset is used by +- :cfunc:`PyObject_GenericGetAttr`. ++ :c:func:`PyObject_GenericGetAttr`. + + Do not confuse this field with :attr:`tp_dict`; that is the dictionary for + attributes of the type object itself. +@@ -920,7 +920,7 @@ + taken from the type object, and :attr:`ob_size` is taken from the instance. The + absolute value is taken because long ints use the sign of :attr:`ob_size` to + store the sign of the number. (There's never a need to do this calculation +- yourself; it is done for you by :cfunc:`_PyObject_GetDictPtr`.) ++ yourself; it is done for you by :c:func:`_PyObject_GetDictPtr`.) + + This field is inherited by subtypes, but see the rules listed below. A subtype + may override this offset; this means that the subtype instances store the +@@ -940,7 +940,7 @@ + added as a feature just like :attr:`__weakref__` though.) + + +-.. cmember:: initproc PyTypeObject.tp_init ++.. c:member:: initproc PyTypeObject.tp_init + + An optional pointer to an instance initialization function. + +@@ -970,7 +970,7 @@ + This field is inherited by subtypes. + + +-.. cmember:: allocfunc PyTypeObject.tp_alloc ++.. c:member:: allocfunc PyTypeObject.tp_alloc + + An optional pointer to an instance allocation function. + +@@ -993,11 +993,11 @@ + + This field is inherited by static subtypes, but not by dynamic subtypes + (subtypes created by a class statement); in the latter, this field is always set +- to :cfunc:`PyType_GenericAlloc`, to force a standard heap allocation strategy. ++ to :c:func:`PyType_GenericAlloc`, to force a standard heap allocation strategy. + That is also the recommended value for statically defined types. + + +-.. cmember:: newfunc PyTypeObject.tp_new ++.. c:member:: newfunc PyTypeObject.tp_new + + An optional pointer to an instance creation function. + +@@ -1029,16 +1029,16 @@ + being linked with Python 2.2. + + +-.. cmember:: destructor PyTypeObject.tp_free ++.. c:member:: destructor PyTypeObject.tp_free + + An optional pointer to an instance deallocation function. + + The signature of this function has changed slightly: in Python 2.2 and 2.2.1, +- its signature is :ctype:`destructor`:: ++ its signature is :c:type:`destructor`:: + + void tp_free(PyObject *) + +- In Python 2.3 and beyond, its signature is :ctype:`freefunc`:: ++ In Python 2.3 and beyond, its signature is :c:type:`freefunc`:: + + void tp_free(void *) + +@@ -1047,11 +1047,11 @@ + + This field is inherited by static subtypes, but not by dynamic subtypes + (subtypes created by a class statement); in the latter, this field is set to a +- deallocator suitable to match :cfunc:`PyType_GenericAlloc` and the value of the ++ deallocator suitable to match :c:func:`PyType_GenericAlloc` and the value of the + :const:`Py_TPFLAGS_HAVE_GC` flag bit. + + +-.. cmember:: inquiry PyTypeObject.tp_is_gc ++.. c:member:: inquiry PyTypeObject.tp_is_gc + + An optional pointer to a function called by the garbage collector. + +@@ -1066,14 +1066,14 @@ + int tp_is_gc(PyObject *self) + + (The only example of this are types themselves. The metatype, +- :cdata:`PyType_Type`, defines this function to distinguish between statically ++ :c:data:`PyType_Type`, defines this function to distinguish between statically + and dynamically allocated types.) + + This field is inherited by subtypes. (VERSION NOTE: in Python 2.2, it was not + inherited. It is inherited in 2.2.1 and later versions.) + + +-.. cmember:: PyObject* PyTypeObject.tp_bases ++.. c:member:: PyObject* PyTypeObject.tp_bases + + Tuple of base types. + +@@ -1083,25 +1083,25 @@ + This field is not inherited. + + +-.. cmember:: PyObject* PyTypeObject.tp_mro ++.. c:member:: PyObject* PyTypeObject.tp_mro + + Tuple containing the expanded set of base types, starting with the type itself + and ending with :class:`object`, in Method Resolution Order. + +- This field is not inherited; it is calculated fresh by :cfunc:`PyType_Ready`. ++ This field is not inherited; it is calculated fresh by :c:func:`PyType_Ready`. + + +-.. cmember:: PyObject* PyTypeObject.tp_cache ++.. c:member:: PyObject* PyTypeObject.tp_cache + + Unused. Not inherited. Internal use only. + + +-.. cmember:: PyObject* PyTypeObject.tp_subclasses ++.. c:member:: PyObject* PyTypeObject.tp_subclasses + + List of weak references to subclasses. Not inherited. Internal use only. + + +-.. cmember:: PyObject* PyTypeObject.tp_weaklist ++.. c:member:: PyObject* PyTypeObject.tp_weaklist + + Weak reference list head, for weak references to this type object. Not + inherited. Internal use only. +@@ -1112,22 +1112,22 @@ + subtypes. + + +-.. cmember:: Py_ssize_t PyTypeObject.tp_allocs ++.. c:member:: Py_ssize_t PyTypeObject.tp_allocs + + Number of allocations. + + +-.. cmember:: Py_ssize_t PyTypeObject.tp_frees ++.. c:member:: Py_ssize_t PyTypeObject.tp_frees + + Number of frees. + + +-.. cmember:: Py_ssize_t PyTypeObject.tp_maxalloc ++.. c:member:: Py_ssize_t PyTypeObject.tp_maxalloc + + Maximum simultaneously allocated objects. + + +-.. cmember:: PyTypeObject* PyTypeObject.tp_next ++.. c:member:: PyTypeObject* PyTypeObject.tp_next + + Pointer to the next type object with a non-zero :attr:`tp_allocs` field. + +@@ -1150,7 +1150,7 @@ + .. sectionauthor:: Amaury Forgeot d'Arc + + +-.. ctype:: PyNumberMethods ++.. c:type:: PyNumberMethods + + This structure holds pointers to the functions which an object uses to + implement the number protocol. Almost every function below is used by the +@@ -1215,9 +1215,9 @@ + the coercion method specified by the :attr:`nb_coerce` member to convert the + arguments: + +- .. cmember:: coercion PyNumberMethods.nb_coerce ++ .. c:member:: coercion PyNumberMethods.nb_coerce + +- This function is used by :cfunc:`PyNumber_CoerceEx` and has the same ++ This function is used by :c:func:`PyNumber_CoerceEx` and has the same + signature. The first argument is always a pointer to an object of the + defined type. If the conversion to a common "larger" type is possible, the + function replaces the pointers with new references to the converted objects +@@ -1243,26 +1243,26 @@ + .. sectionauthor:: Amaury Forgeot d'Arc + + +-.. ctype:: PyMappingMethods ++.. c:type:: PyMappingMethods + + This structure holds pointers to the functions which an object uses to + implement the mapping protocol. It has three members: + +-.. cmember:: lenfunc PyMappingMethods.mp_length ++.. c:member:: lenfunc PyMappingMethods.mp_length + +- This function is used by :cfunc:`PyMapping_Length` and +- :cfunc:`PyObject_Size`, and has the same signature. This slot may be set to ++ This function is used by :c:func:`PyMapping_Length` and ++ :c:func:`PyObject_Size`, and has the same signature. This slot may be set to + *NULL* if the object has no defined length. + +-.. cmember:: binaryfunc PyMappingMethods.mp_subscript ++.. c:member:: binaryfunc PyMappingMethods.mp_subscript + +- This function is used by :cfunc:`PyObject_GetItem` and has the same +- signature. This slot must be filled for the :cfunc:`PyMapping_Check` ++ This function is used by :c:func:`PyObject_GetItem` and has the same ++ signature. This slot must be filled for the :c:func:`PyMapping_Check` + function to return ``1``, it can be *NULL* otherwise. + +-.. cmember:: objobjargproc PyMappingMethods.mp_ass_subscript ++.. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript + +- This function is used by :cfunc:`PyObject_SetItem` and has the same ++ This function is used by :c:func:`PyObject_SetItem` and has the same + signature. If this slot is *NULL*, the object does not support item + assignment. + +@@ -1275,32 +1275,32 @@ + .. sectionauthor:: Amaury Forgeot d'Arc + + +-.. ctype:: PySequenceMethods ++.. c:type:: PySequenceMethods + + This structure holds pointers to the functions which an object uses to + implement the sequence protocol. + +-.. cmember:: lenfunc PySequenceMethods.sq_length ++.. c:member:: lenfunc PySequenceMethods.sq_length + +- This function is used by :cfunc:`PySequence_Size` and :cfunc:`PyObject_Size`, ++ This function is used by :c:func:`PySequence_Size` and :c:func:`PyObject_Size`, + and has the same signature. + +-.. cmember:: binaryfunc PySequenceMethods.sq_concat ++.. c:member:: binaryfunc PySequenceMethods.sq_concat + +- This function is used by :cfunc:`PySequence_Concat` and has the same ++ This function is used by :c:func:`PySequence_Concat` and has the same + signature. It is also used by the ``+`` operator, after trying the numeric + addition via the :attr:`tp_as_number.nb_add` slot. + +-.. cmember:: ssizeargfunc PySequenceMethods.sq_repeat ++.. c:member:: ssizeargfunc PySequenceMethods.sq_repeat + +- This function is used by :cfunc:`PySequence_Repeat` and has the same ++ This function is used by :c:func:`PySequence_Repeat` and has the same + signature. It is also used by the ``*`` operator, after trying numeric + multiplication via the :attr:`tp_as_number.nb_mul` slot. + +-.. cmember:: ssizeargfunc PySequenceMethods.sq_item ++.. c:member:: ssizeargfunc PySequenceMethods.sq_item + +- This function is used by :cfunc:`PySequence_GetItem` and has the same +- signature. This slot must be filled for the :cfunc:`PySequence_Check` ++ This function is used by :c:func:`PySequence_GetItem` and has the same ++ signature. This slot must be filled for the :c:func:`PySequence_Check` + function to return ``1``, it can be *NULL* otherwise. + + Negative indexes are handled as follows: if the :attr:`sq_length` slot is +@@ -1308,27 +1308,27 @@ + index which is passed to :attr:`sq_item`. If :attr:`sq_length` is *NULL*, + the index is passed as is to the function. + +-.. cmember:: ssizeobjargproc PySequenceMethods.sq_ass_item ++.. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item + +- This function is used by :cfunc:`PySequence_SetItem` and has the same ++ This function is used by :c:func:`PySequence_SetItem` and has the same + signature. This slot may be left to *NULL* if the object does not support + item assignment. + +-.. cmember:: objobjproc PySequenceMethods.sq_contains ++.. c:member:: objobjproc PySequenceMethods.sq_contains + +- This function may be used by :cfunc:`PySequence_Contains` and has the same ++ This function may be used by :c:func:`PySequence_Contains` and has the same + signature. This slot may be left to *NULL*, in this case +- :cfunc:`PySequence_Contains` simply traverses the sequence until it finds a ++ :c:func:`PySequence_Contains` simply traverses the sequence until it finds a + match. + +-.. cmember:: binaryfunc PySequenceMethods.sq_inplace_concat ++.. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat + +- This function is used by :cfunc:`PySequence_InPlaceConcat` and has the same ++ This function is used by :c:func:`PySequence_InPlaceConcat` and has the same + signature. It should modify its first operand, and return it. + +-.. cmember:: ssizeargfunc PySequenceMethods.sq_inplace_repeat ++.. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat + +- This function is used by :cfunc:`PySequence_InPlaceRepeat` and has the same ++ This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same + signature. It should modify its first operand, and return it. + + .. XXX need to explain precedence between mapping and sequence +@@ -1349,45 +1349,45 @@ + to be non-contiguous in memory. + + If an object does not export the buffer interface, then its :attr:`tp_as_buffer` +-member in the :ctype:`PyTypeObject` structure should be *NULL*. Otherwise, the +-:attr:`tp_as_buffer` will point to a :ctype:`PyBufferProcs` structure. ++member in the :c:type:`PyTypeObject` structure should be *NULL*. Otherwise, the ++:attr:`tp_as_buffer` will point to a :c:type:`PyBufferProcs` structure. + + .. note:: + +- It is very important that your :ctype:`PyTypeObject` structure uses ++ It is very important that your :c:type:`PyTypeObject` structure uses + :const:`Py_TPFLAGS_DEFAULT` for the value of the :attr:`tp_flags` member rather +- than ``0``. This tells the Python runtime that your :ctype:`PyBufferProcs` ++ than ``0``. This tells the Python runtime that your :c:type:`PyBufferProcs` + structure contains the :attr:`bf_getcharbuffer` slot. Older versions of Python + did not have this member, so a new Python interpreter using an old extension + needs to be able to test for its presence before using it. + + +-.. ctype:: PyBufferProcs ++.. c:type:: PyBufferProcs + + Structure used to hold the function pointers which define an implementation of + the buffer protocol. + +- The first slot is :attr:`bf_getreadbuffer`, of type :ctype:`getreadbufferproc`. ++ The first slot is :attr:`bf_getreadbuffer`, of type :c:type:`getreadbufferproc`. + If this slot is *NULL*, then the object does not support reading from the + internal data. This is non-sensical, so implementors should fill this in, but + callers should test that the slot contains a non-*NULL* value. + + The next slot is :attr:`bf_getwritebuffer` having type +- :ctype:`getwritebufferproc`. This slot may be *NULL* if the object does not ++ :c:type:`getwritebufferproc`. This slot may be *NULL* if the object does not + allow writing into its returned buffers. + +- The third slot is :attr:`bf_getsegcount`, with type :ctype:`getsegcountproc`. ++ The third slot is :attr:`bf_getsegcount`, with type :c:type:`getsegcountproc`. + This slot must not be *NULL* and is used to inform the caller how many segments +- the object contains. Simple objects such as :ctype:`PyString_Type` and +- :ctype:`PyBuffer_Type` objects contain a single segment. ++ the object contains. Simple objects such as :c:type:`PyString_Type` and ++ :c:type:`PyBuffer_Type` objects contain a single segment. + + .. index:: single: PyType_HasFeature() + +- The last slot is :attr:`bf_getcharbuffer`, of type :ctype:`getcharbufferproc`. ++ The last slot is :attr:`bf_getcharbuffer`, of type :c:type:`getcharbufferproc`. + This slot will only be present if the :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER` + flag is present in the :attr:`tp_flags` field of the object's +- :ctype:`PyTypeObject`. Before using this slot, the caller should test whether it +- is present by using the :cfunc:`PyType_HasFeature` function. If the flag is ++ :c:type:`PyTypeObject`. Before using this slot, the caller should test whether it ++ is present by using the :c:func:`PyType_HasFeature` function. If the flag is + present, :attr:`bf_getcharbuffer` may be *NULL*, indicating that the object's + contents cannot be used as *8-bit characters*. The slot function may also raise + an error if the object's contents cannot be interpreted as 8-bit characters. +@@ -1411,7 +1411,7 @@ + buffer interface or that the :attr:`bf_getcharbuffer` slot is non-*NULL*. + + +-.. ctype:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr) ++.. c:type:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr) + + Return a pointer to a readable segment of the buffer in ``*ptrptr``. This + function is allowed to raise an exception, in which case it must return ``-1``. +@@ -1421,7 +1421,7 @@ + ``*ptrptr`` to a pointer to that memory. + + +-.. ctype:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr) ++.. c:type:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr) + + Return a pointer to a writable memory buffer in ``*ptrptr``, and the length of + that segment as the function return value. The memory buffer must correspond to +@@ -1435,14 +1435,14 @@ + segment. That indicates a blatant programming error in the C code. + + +-.. ctype:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp) ++.. c:type:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp) + + Return the number of memory segments which comprise the buffer. If *lenp* is + not *NULL*, the implementation must report the sum of the sizes (in bytes) of + all segments in ``*lenp``. The function cannot fail. + + +-.. ctype:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, const char **ptrptr) ++.. c:type:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, const char **ptrptr) + + Return the size of the segment *segment* that *ptrptr* is set to. ``*ptrptr`` + is set to the memory buffer. Returns ``-1`` on error. +diff -r 8527427914a2 Doc/c-api/unicode.rst +--- a/Doc/c-api/unicode.rst ++++ b/Doc/c-api/unicode.rst +@@ -18,39 +18,39 @@ + Python: + + +-.. ctype:: Py_UNICODE ++.. c:type:: Py_UNICODE + + This type represents the storage type which is used by Python internally as + basis for holding Unicode ordinals. Python's default builds use a 16-bit type +- for :ctype:`Py_UNICODE` and store Unicode values internally as UCS2. It is also ++ for :c:type:`Py_UNICODE` and store Unicode values internally as UCS2. It is also + possible to build a UCS4 version of Python (most recent Linux distributions come + with UCS4 builds of Python). These builds then use a 32-bit type for +- :ctype:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms +- where :ctype:`wchar_t` is available and compatible with the chosen Python +- Unicode build variant, :ctype:`Py_UNICODE` is a typedef alias for +- :ctype:`wchar_t` to enhance native platform compatibility. On all other +- platforms, :ctype:`Py_UNICODE` is a typedef alias for either :ctype:`unsigned +- short` (UCS2) or :ctype:`unsigned long` (UCS4). ++ :c:type:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms ++ where :c:type:`wchar_t` is available and compatible with the chosen Python ++ Unicode build variant, :c:type:`Py_UNICODE` is a typedef alias for ++ :c:type:`wchar_t` to enhance native platform compatibility. On all other ++ platforms, :c:type:`Py_UNICODE` is a typedef alias for either :c:type:`unsigned ++ short` (UCS2) or :c:type:`unsigned long` (UCS4). + + Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep + this in mind when writing extensions or interfaces. + + +-.. ctype:: PyUnicodeObject ++.. c:type:: PyUnicodeObject + +- This subtype of :ctype:`PyObject` represents a Python Unicode object. ++ This subtype of :c:type:`PyObject` represents a Python Unicode object. + + +-.. cvar:: PyTypeObject PyUnicode_Type ++.. c:var:: PyTypeObject PyUnicode_Type + +- This instance of :ctype:`PyTypeObject` represents the Python Unicode type. It ++ This instance of :c:type:`PyTypeObject` represents the Python Unicode type. It + is exposed to Python code as ``unicode`` and ``types.UnicodeType``. + + The following APIs are really C macros and can be used to do fast checks and to + access internal read-only data of Unicode objects: + + +-.. cfunction:: int PyUnicode_Check(PyObject *o) ++.. c:function:: int PyUnicode_Check(PyObject *o) + + Return true if the object *o* is a Unicode object or an instance of a Unicode + subtype. +@@ -59,7 +59,7 @@ + Allowed subtypes to be accepted. + + +-.. cfunction:: int PyUnicode_CheckExact(PyObject *o) ++.. c:function:: int PyUnicode_CheckExact(PyObject *o) + + Return true if the object *o* is a Unicode object, but not an instance of a + subtype. +@@ -67,39 +67,39 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o) ++.. c:function:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o) + +- Return the size of the object. *o* has to be a :ctype:`PyUnicodeObject` (not ++ Return the size of the object. *o* has to be a :c:type:`PyUnicodeObject` (not + checked). + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o) ++.. c:function:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o) + + Return the size of the object's internal buffer in bytes. *o* has to be a +- :ctype:`PyUnicodeObject` (not checked). ++ :c:type:`PyUnicodeObject` (not checked). + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o) ++.. c:function:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o) + +- Return a pointer to the internal :ctype:`Py_UNICODE` buffer of the object. *o* +- has to be a :ctype:`PyUnicodeObject` (not checked). ++ Return a pointer to the internal :c:type:`Py_UNICODE` buffer of the object. *o* ++ has to be a :c:type:`PyUnicodeObject` (not checked). + + +-.. cfunction:: const char* PyUnicode_AS_DATA(PyObject *o) ++.. c:function:: const char* PyUnicode_AS_DATA(PyObject *o) + + Return a pointer to the internal buffer of the object. *o* has to be a +- :ctype:`PyUnicodeObject` (not checked). ++ :c:type:`PyUnicodeObject` (not checked). + + +-.. cfunction:: int PyUnicode_ClearFreeList() ++.. c:function:: int PyUnicode_ClearFreeList() + + Clear the free list. Return the total number of freed items. + +@@ -114,86 +114,86 @@ + the Python configuration. + + +-.. cfunction:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISSPACE(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a whitespace character. + + +-.. cfunction:: int Py_UNICODE_ISLOWER(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISLOWER(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a lowercase character. + + +-.. cfunction:: int Py_UNICODE_ISUPPER(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISUPPER(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is an uppercase character. + + +-.. cfunction:: int Py_UNICODE_ISTITLE(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISTITLE(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a titlecase character. + + +-.. cfunction:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a linebreak character. + + +-.. cfunction:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a decimal character. + + +-.. cfunction:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a digit character. + + +-.. cfunction:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is a numeric character. + + +-.. cfunction:: int Py_UNICODE_ISALPHA(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISALPHA(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is an alphabetic character. + + +-.. cfunction:: int Py_UNICODE_ISALNUM(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_ISALNUM(Py_UNICODE ch) + + Return 1 or 0 depending on whether *ch* is an alphanumeric character. + + These APIs can be used for fast direct character conversions: + + +-.. cfunction:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch) ++.. c:function:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch) + + Return the character *ch* converted to lower case. + + +-.. cfunction:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch) ++.. c:function:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch) + + Return the character *ch* converted to upper case. + + +-.. cfunction:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch) ++.. c:function:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch) + + Return the character *ch* converted to title case. + + +-.. cfunction:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch) + + Return the character *ch* converted to a decimal positive integer. Return + ``-1`` if this is not possible. This macro does not raise exceptions. + + +-.. cfunction:: int Py_UNICODE_TODIGIT(Py_UNICODE ch) ++.. c:function:: int Py_UNICODE_TODIGIT(Py_UNICODE ch) + + Return the character *ch* converted to a single digit integer. Return ``-1`` if + this is not possible. This macro does not raise exceptions. + + +-.. cfunction:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch) ++.. c:function:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch) + + Return the character *ch* converted to a double. Return ``-1.0`` if this is not + possible. This macro does not raise exceptions. +@@ -206,7 +206,7 @@ + APIs: + + +-.. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) ++.. c:function:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) + + Create a Unicode object from the Py_UNICODE buffer *u* of the given size. *u* + may be *NULL* which causes the contents to be undefined. It is the user's +@@ -216,11 +216,11 @@ + is *NULL*. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) ++.. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) + + Create a Unicode object from the char buffer *u*. The bytes will be interpreted + as being UTF-8 encoded. *u* may also be *NULL* which +@@ -232,7 +232,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject *PyUnicode_FromString(const char *u) ++.. c:function:: PyObject *PyUnicode_FromString(const char *u) + + Create a Unicode object from an UTF-8 encoded null-terminated char buffer + *u*. +@@ -240,9 +240,9 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyUnicode_FromFormat(const char *format, ...) ++.. c:function:: PyObject* PyUnicode_FromFormat(const char *format, ...) + +- Take a C :cfunc:`printf`\ -style *format* string and a variable number of ++ Take a C :c:func:`printf`\ -style *format* string and a variable number of + arguments, calculate the size of the resulting Python unicode string and return + a string with the values formatted into it. The variable arguments must be C + types and must correspond exactly to the format characters in the *format* +@@ -317,7 +317,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs) ++.. c:function:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs) + + Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two + arguments. +@@ -325,22 +325,25 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) ++.. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) + +- Return a read-only pointer to the Unicode object's internal :ctype:`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. + + +-.. cfunction:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode) ++.. c:function:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode) + + Return the length of the Unicode object. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type. This might require changes ++ This function returned an :c:type:`int` type. This might require changes + in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors) + + Coerce an encoded object *obj* to an Unicode object and return a reference with + incremented refcount. +@@ -357,44 +360,46 @@ + decref'ing the returned objects. + + +-.. cfunction:: PyObject* PyUnicode_FromObject(PyObject *obj) ++.. c:function:: PyObject* PyUnicode_FromObject(PyObject *obj) + + Shortcut for ``PyUnicode_FromEncodedObject(obj, NULL, "strict")`` which is used + throughout the interpreter whenever coercion to Unicode is needed. + +-If the platform supports :ctype:`wchar_t` and provides a header file wchar.h, ++If the platform supports :c:type:`wchar_t` and provides a header file wchar.h, + Python can interface directly to this type using the following functions. +-Support is optimized if Python's own :ctype:`Py_UNICODE` type is identical to +-the system's :ctype:`wchar_t`. ++Support is optimized if Python's own :c:type:`Py_UNICODE` type is identical to ++the system's :c:type:`wchar_t`. + + + wchar_t Support + """"""""""""""" + +-:ctype:`wchar_t` support for platforms which support it: ++:c:type:`wchar_t` support for platforms which support it: + +-.. cfunction:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) ++.. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) + +- Create a Unicode object from the :ctype:`wchar_t` buffer *w* of the given *size*. ++ Create a Unicode object from the :c:type:`wchar_t` buffer *w* of the given *size*. + Return *NULL* on failure. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size) ++.. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size) + +- Copy the Unicode object contents into the :ctype:`wchar_t` buffer *w*. At most +- *size* :ctype:`wchar_t` characters are copied (excluding a possibly trailing +- 0-termination character). Return the number of :ctype:`wchar_t` characters +- copied or -1 in case of an error. Note that the resulting :ctype:`wchar_t` ++ Copy the Unicode object contents into the :c:type:`wchar_t` buffer *w*. At most ++ *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing ++ 0-termination character). Return the number of :c:type:`wchar_t` characters ++ 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 :ctype:`wchar_t` string is 0-terminated in case this is +- required by the application. ++ to make sure that the :c:type:`wchar_t` string is 0-terminated in case this is ++ 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. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type and used an :ctype:`int` ++ This function returned an :c:type:`int` type and used an :c:type:`int` + type for *size*. This might require changes in your code for properly + supporting 64-bit systems. + +@@ -412,7 +417,7 @@ + object constructor. + + Setting encoding to *NULL* causes the default encoding to be used which is +-ASCII. The file system calls should use :cdata:`Py_FileSystemDefaultEncoding` ++ASCII. The file system calls should use :c:data:`Py_FileSystemDefaultEncoding` + as the encoding for file names. This variable should be treated as read-only: on + some systems, it will be a pointer to a static string, on others, it will change + at run-time (such as when the application invokes setlocale). +@@ -431,7 +436,7 @@ + These are the generic codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) + + Create a Unicode object by decoding *size* bytes of the encoded string *s*. + *encoding* and *errors* have the same meaning as the parameters of the same name +@@ -440,24 +445,24 @@ + the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer *s* of the given *size* and return a Python ++ Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* and return a Python + string object. *encoding* and *errors* have the same meaning as the parameters + of the same name in the Unicode :meth:`encode` method. The codec to be used is + looked up using the Python codec registry. Return *NULL* if an exception was + raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) ++.. c:function:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) + + Encode a Unicode object and return the result as Python string object. + *encoding* and *errors* have the same meaning as the parameters of the same name +@@ -472,19 +477,19 @@ + These are the UTF-8 codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string + *s*. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) ++.. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) + +- If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF8`. If ++ If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF8`. If + *consumed* is not *NULL*, trailing incomplete UTF-8 byte sequences will not be + treated as an error. Those bytes will not be decoded and the number of bytes + that have been decoded will be stored in *consumed*. +@@ -492,21 +497,21 @@ + .. versionadded:: 2.4 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer *s* of the given *size* using UTF-8 and return a ++ Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* using UTF-8 and return a + Python string object. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode) + + Encode a Unicode object using UTF-8 and return the result as Python string + object. Error handling is "strict". Return *NULL* if an exception was raised +@@ -519,7 +524,7 @@ + These are the UTF-32 codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) ++.. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) + + Decode *size* bytes from a UTF-32 encoded buffer string and return the + corresponding Unicode object. *errors* (if non-*NULL*) defines the error +@@ -549,10 +554,10 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) ++.. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) + +- If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF32`. If +- *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF32Stateful` will not treat ++ If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF32`. If ++ *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeUTF32Stateful` will not treat + trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible + by four) as an error. Those bytes will not be decoded and the number of bytes + that have been decoded will be stored in *consumed*. +@@ -560,7 +565,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) ++.. c:function:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) + + Return a Python bytes object holding the UTF-32 encoded value of the Unicode + data in *s*. Output is written according to the following byte order:: +@@ -580,7 +585,7 @@ + .. versionadded:: 2.6 + + +-.. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) + + Return a Python string using the UTF-32 encoding in native byte order. The + string always starts with a BOM mark. Error handling is "strict". Return +@@ -595,7 +600,7 @@ + These are the UTF-16 codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) ++.. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) + + Decode *size* bytes from a UTF-16 encoded buffer string and return the + corresponding Unicode object. *errors* (if non-*NULL*) defines the error +@@ -622,14 +627,14 @@ + Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) ++.. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) + +- If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF16`. If +- *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeUTF16Stateful` will not treat ++ If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF16`. If ++ *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeUTF16Stateful` will not treat + trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a + split surrogate pair) as an error. Those bytes will not be decoded and the + number of bytes that have been decoded will be stored in *consumed*. +@@ -637,12 +642,12 @@ + .. versionadded:: 2.4 + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size* and an :ctype:`int *` ++ This function used an :c:type:`int` type for *size* and an :c:type:`int *` + type for *consumed*. This might require changes in your code for + properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) ++.. c:function:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) + + Return a Python string object holding the UTF-16 encoded value of the Unicode + data in *s*. Output is written according to the following byte order:: +@@ -654,18 +659,18 @@ + If byteorder is ``0``, the output string will always start with the Unicode BOM + mark (U+FEFF). In the other two modes, no BOM mark is prepended. + +- If *Py_UNICODE_WIDE* is defined, a single :ctype:`Py_UNICODE` value may get +- represented as a surrogate pair. If it is not defined, each :ctype:`Py_UNICODE` ++ If *Py_UNICODE_WIDE* is defined, a single :c:type:`Py_UNICODE` value may get ++ represented as a surrogate pair. If it is not defined, each :c:type:`Py_UNICODE` + values is interpreted as an UCS-2 character. + + Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode) + + Return a Python string using the UTF-16 encoding in native byte order. The + string always starts with a BOM mark. Error handling is "strict". Return +@@ -678,23 +683,23 @@ + These are the UTF-7 codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string + *s*. Return *NULL* if an exception was raised by the codec. + + +-.. cfunction:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) ++.. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) + +- If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeUTF7`. If ++ If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF7`. If + *consumed* is not *NULL*, trailing incomplete UTF-7 base-64 sections will not + be treated as an error. Those bytes will not be decoded and the number of + bytes that have been decoded will be stored in *consumed*. + + +-.. cfunction:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer of the given size using UTF-7 and ++ Encode the :c:type:`Py_UNICODE` buffer of the given size using UTF-7 and + return a Python bytes object. Return *NULL* if an exception was raised by + the codec. + +@@ -710,28 +715,28 @@ + These are the "Unicode Escape" codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded + string *s*. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) ++.. c:function:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) + +- Encode the :ctype:`Py_UNICODE` buffer of the given *size* using Unicode-Escape and ++ Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Unicode-Escape and + return a Python string object. Return *NULL* if an exception was raised by the + codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode) + + Encode a Unicode object using Unicode-Escape and return the result as Python + string object. Error handling is "strict". Return *NULL* if an exception was +@@ -744,28 +749,28 @@ + These are the "Raw Unicode Escape" codec APIs: + + +-.. cfunction:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape + encoded string *s*. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer of the given *size* using Raw-Unicode-Escape ++ Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Raw-Unicode-Escape + and return a Python string object. Return *NULL* if an exception was raised by + the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) + + Encode a Unicode object using Raw-Unicode-Escape and return the result as + Python string object. Error handling is "strict". Return *NULL* if an exception +@@ -779,27 +784,27 @@ + ordinals and only these are accepted by the codecs during encoding. + + +-.. cfunction:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string + *s*. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer of the given *size* using Latin-1 and return ++ Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Latin-1 and return + a Python string object. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode) + + Encode a Unicode object using Latin-1 and return the result as Python string + object. Error handling is "strict". Return *NULL* if an exception was raised +@@ -813,27 +818,27 @@ + codes generate errors. + + +-.. cfunction:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the ASCII encoded string + *s*. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer of the given *size* using ASCII and return a ++ Encode the :c:type:`Py_UNICODE` buffer of the given *size* using ASCII and return a + Python string object. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode) + + Encode a Unicode object using ASCII and return the result as Python string + object. Error handling is "strict". Return *NULL* if an exception was raised +@@ -866,7 +871,7 @@ + + These are the mapping codec APIs: + +-.. cfunction:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors) + + Create a Unicode object by decoding *size* bytes of the encoded string *s* using + the given *mapping* object. Return *NULL* if an exception was raised by the +@@ -879,22 +884,22 @@ + Allowed unicode string as mapping argument. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer of the given *size* using the given ++ Encode the :c:type:`Py_UNICODE` buffer of the given *size* using the given + *mapping* object and return a Python string object. Return *NULL* if an + exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) ++.. c:function:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) + + Encode a Unicode object using the given *mapping* object and return the result + as Python string object. Error handling is "strict". Return *NULL* if an +@@ -903,9 +908,9 @@ + The following codec API is special in that maps Unicode to Unicode. + + +-.. cfunction:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors) ++.. c:function:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors) + +- Translate a :ctype:`Py_UNICODE` buffer of the given *size* by applying a ++ Translate a :c:type:`Py_UNICODE` buffer of the given *size* by applying a + character mapping *table* to it and return the resulting Unicode object. Return + *NULL* when an exception was raised by the codec. + +@@ -917,7 +922,7 @@ + :exc:`LookupError`) are left untouched and are copied as-is. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +@@ -930,37 +935,37 @@ + the user settings on the machine running the codec. + + +-.. cfunction:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors) + + Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*. + Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed) ++.. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed) + +- If *consumed* is *NULL*, behave like :cfunc:`PyUnicode_DecodeMBCS`. If +- *consumed* is not *NULL*, :cfunc:`PyUnicode_DecodeMBCSStateful` will not decode ++ If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeMBCS`. If ++ *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeMBCSStateful` will not decode + trailing lead byte and the number of bytes that have been decoded will be stored + in *consumed*. + + .. versionadded:: 2.5 + + +-.. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors) ++.. c:function:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors) + +- Encode the :ctype:`Py_UNICODE` buffer of the given *size* using MBCS and return a ++ Encode the :c:type:`Py_UNICODE` buffer of the given *size* using MBCS and return a + Python string object. Return *NULL* if an exception was raised by the codec. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *size*. This might require ++ This function used an :c:type:`int` type for *size*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode) ++.. c:function:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode) + + Encode a Unicode object using MBCS and return the result as Python string + object. Error handling is "strict". Return *NULL* if an exception was raised +@@ -982,12 +987,12 @@ + They all return *NULL* or ``-1`` if an exception occurs. + + +-.. cfunction:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right) ++.. c:function:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right) + + Concat two strings giving a new Unicode string. + + +-.. cfunction:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) ++.. c:function:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) + + Split a string giving a list of Unicode strings. If *sep* is *NULL*, splitting + will be done at all whitespace substrings. Otherwise, splits occur at the given +@@ -995,18 +1000,18 @@ + set. Separators are not included in the resulting list. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *maxsplit*. This might require ++ This function used an :c:type:`int` type for *maxsplit*. This might require + changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend) ++.. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend) + + Split a Unicode string at line breaks, returning a list of Unicode strings. + CRLF is considered to be one line break. If *keepend* is 0, the Line break + characters are not included in the resulting strings. + + +-.. cfunction:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors) ++.. c:function:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors) + + Translate a string by applying a character mapping table to it and return the + resulting Unicode object. +@@ -1022,25 +1027,25 @@ + use the default error handling. + + +-.. cfunction:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq) ++.. c:function:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq) + + Join a sequence of strings using the given *separator* and return the resulting + Unicode string. + + +-.. cfunction:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) ++.. c:function:: int PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) + + Return 1 if *substr* matches ``str[start:end]`` at the given tail end + (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match), + 0 otherwise. Return ``-1`` if an error occurred. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *start* and *end*. This ++ This function used an :c:type:`int` type for *start* and *end*. This + might require changes in your code for properly supporting 64-bit + systems. + + +-.. cfunction:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) ++.. c:function:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) + + Return the first position of *substr* in ``str[start:end]`` using the given + *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a +@@ -1049,40 +1054,40 @@ + occurred and an exception has been set. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *start* and *end*. This ++ This function used an :c:type:`int` type for *start* and *end*. This + might require changes in your code for properly supporting 64-bit + systems. + + +-.. cfunction:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end) ++.. c:function:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end) + + Return the number of non-overlapping occurrences of *substr* in + ``str[start:end]``. Return ``-1`` if an error occurred. + + .. versionchanged:: 2.5 +- This function returned an :ctype:`int` type and used an :ctype:`int` ++ This function returned an :c:type:`int` type and used an :c:type:`int` + type for *start* and *end*. This might require changes in your code for + properly supporting 64-bit systems. + + +-.. cfunction:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount) ++.. c:function:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount) + + Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and + return the resulting Unicode object. *maxcount* == -1 means replace all + occurrences. + + .. versionchanged:: 2.5 +- This function used an :ctype:`int` type for *maxcount*. This might ++ This function used an :c:type:`int` type for *maxcount*. This might + require changes in your code for properly supporting 64-bit systems. + + +-.. cfunction:: int PyUnicode_Compare(PyObject *left, PyObject *right) ++.. c:function:: int PyUnicode_Compare(PyObject *left, PyObject *right) + + Compare two strings and return -1, 0, 1 for less than, equal, and greater than, + respectively. + + +-.. cfunction:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) ++.. c:function:: int PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) + + Rich compare two unicode strings and return one of the following: + +@@ -1098,13 +1103,13 @@ + :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`. + + +-.. cfunction:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args) ++.. c:function:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args) + + Return a new string object from *format* and *args*; this is analogous to + ``format % args``. The *args* argument must be a tuple. + + +-.. cfunction:: int PyUnicode_Contains(PyObject *container, PyObject *element) ++.. c:function:: int PyUnicode_Contains(PyObject *container, PyObject *element) + + Check whether *element* is contained in *container* and return true or false + accordingly. +diff -r 8527427914a2 Doc/c-api/veryhigh.rst +--- a/Doc/c-api/veryhigh.rst ++++ b/Doc/c-api/veryhigh.rst +@@ -16,23 +16,23 @@ + :const:`Py_file_input`, and :const:`Py_single_input`. These are described + following the functions which accept them as parameters. + +-Note also that several of these functions take :ctype:`FILE\*` parameters. One +-particular issue which needs to be handled carefully is that the :ctype:`FILE` ++Note also that several of these functions take :c:type:`FILE\*` parameters. One ++particular issue which needs to be handled carefully is that the :c:type:`FILE` + structure for different C libraries can be different and incompatible. Under + Windows (at least), it is possible for dynamically linked extensions to actually +-use different libraries, so care should be taken that :ctype:`FILE\*` parameters ++use different libraries, so care should be taken that :c:type:`FILE\*` parameters + are only passed to these functions if it is certain that they were created by + the same library that the Python runtime is using. + + +-.. cfunction:: int Py_Main(int argc, char **argv) ++.. c:function:: int Py_Main(int argc, char **argv) + + The main program for the standard interpreter. This is made available for + programs which embed Python. The *argc* and *argv* parameters should be +- prepared exactly as those which are passed to a C program's :cfunc:`main` ++ prepared exactly as those which are passed to a C program's :c:func:`main` + function. It is important to note that the argument list may be modified (but + the contents of the strings pointed to by the argument list are not). The return +- value will be ```0``` if the interpreter exits normally (ie, without an ++ value will be ``0`` if the interpreter exits normally (ie, without an + exception), ``1`` if the interpreter exits due to an exception, or ``2`` + if the parameter list does not represent a valid Python command line. + +@@ -41,40 +41,40 @@ + ``Py_InspectFlag`` is not set. + + +-.. cfunction:: int PyRun_AnyFile(FILE *fp, const char *filename) ++.. c:function:: int PyRun_AnyFile(FILE *fp, const char *filename) + +- This is a simplified interface to :cfunc:`PyRun_AnyFileExFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving + *closeit* set to ``0`` and *flags* set to *NULL*. + + +-.. cfunction:: int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) ++.. c:function:: int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + +- This is a simplified interface to :cfunc:`PyRun_AnyFileExFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving + the *closeit* argument set to ``0``. + + +-.. cfunction:: int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit) ++.. c:function:: int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit) + +- This is a simplified interface to :cfunc:`PyRun_AnyFileExFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving + the *flags* argument set to *NULL*. + + +-.. cfunction:: int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) ++.. c:function:: int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) + + If *fp* refers to a file associated with an interactive device (console or + terminal input or Unix pseudo-terminal), return the value of +- :cfunc:`PyRun_InteractiveLoop`, otherwise return the result of +- :cfunc:`PyRun_SimpleFile`. If *filename* is *NULL*, this function uses ++ :c:func:`PyRun_InteractiveLoop`, otherwise return the result of ++ :c:func:`PyRun_SimpleFile`. If *filename* is *NULL*, this function uses + ``"???"`` as the filename. + + +-.. cfunction:: int PyRun_SimpleString(const char *command) ++.. c:function:: int PyRun_SimpleString(const char *command) + +- This is a simplified interface to :cfunc:`PyRun_SimpleStringFlags` below, ++ This is a simplified interface to :c:func:`PyRun_SimpleStringFlags` below, + leaving the *PyCompilerFlags\** argument set to NULL. + + +-.. cfunction:: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) ++.. c:function:: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) + + Executes the Python source code from *command* in the :mod:`__main__` module + according to the *flags* argument. If :mod:`__main__` does not already exist, it +@@ -87,39 +87,39 @@ + ``Py_InspectFlag`` is not set. + + +-.. cfunction:: int PyRun_SimpleFile(FILE *fp, const char *filename) ++.. c:function:: int PyRun_SimpleFile(FILE *fp, const char *filename) + +- This is a simplified interface to :cfunc:`PyRun_SimpleFileExFlags` below, ++ This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, + leaving *closeit* set to ``0`` and *flags* set to *NULL*. + + +-.. cfunction:: int PyRun_SimpleFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) ++.. c:function:: int PyRun_SimpleFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + +- This is a simplified interface to :cfunc:`PyRun_SimpleFileExFlags` below, ++ This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, + leaving *closeit* set to ``0``. + + +-.. cfunction:: int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit) ++.. c:function:: int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit) + +- This is a simplified interface to :cfunc:`PyRun_SimpleFileExFlags` below, ++ This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below, + leaving *flags* set to *NULL*. + + +-.. cfunction:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) ++.. c:function:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) + +- Similar to :cfunc:`PyRun_SimpleStringFlags`, but the Python source code is read ++ Similar to :c:func:`PyRun_SimpleStringFlags`, but the Python source code is read + from *fp* instead of an in-memory string. *filename* should be the name of the + file. If *closeit* is true, the file is closed before PyRun_SimpleFileExFlags + returns. + + +-.. cfunction:: int PyRun_InteractiveOne(FILE *fp, const char *filename) ++.. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename) + +- This is a simplified interface to :cfunc:`PyRun_InteractiveOneFlags` below, ++ This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below, + leaving *flags* set to *NULL*. + + +-.. cfunction:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) ++.. c:function:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + + Read and execute a single statement from a file associated with an + interactive device according to the *flags* argument. The user will be +@@ -130,34 +130,34 @@ + :file:`Python.h`, so must be included specifically if needed.) + + +-.. cfunction:: int PyRun_InteractiveLoop(FILE *fp, const char *filename) ++.. c:function:: int PyRun_InteractiveLoop(FILE *fp, const char *filename) + +- This is a simplified interface to :cfunc:`PyRun_InteractiveLoopFlags` below, ++ This is a simplified interface to :c:func:`PyRun_InteractiveLoopFlags` below, + leaving *flags* set to *NULL*. + + +-.. cfunction:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) ++.. c:function:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) + + Read and execute statements from a file associated with an interactive device + until EOF is reached. The user will be prompted using ``sys.ps1`` and + ``sys.ps2``. Returns ``0`` at EOF. + + +-.. cfunction:: struct _node* PyParser_SimpleParseString(const char *str, int start) ++.. c:function:: struct _node* PyParser_SimpleParseString(const char *str, int start) + + This is a simplified interface to +- :cfunc:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set ++ :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set + to *NULL* and *flags* set to ``0``. + + +-.. cfunction:: struct _node* PyParser_SimpleParseStringFlags( const char *str, int start, int flags) ++.. c:function:: struct _node* PyParser_SimpleParseStringFlags( const char *str, int start, int flags) + + This is a simplified interface to +- :cfunc:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set ++ :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving *filename* set + to *NULL*. + + +-.. cfunction:: struct _node* PyParser_SimpleParseStringFlagsFilename( const char *str, const char *filename, int start, int flags) ++.. c:function:: struct _node* PyParser_SimpleParseStringFlagsFilename( const char *str, const char *filename, int start, int flags) + + Parse Python source code from *str* using the start token *start* according to + the *flags* argument. The result can be used to create a code object which can +@@ -165,25 +165,25 @@ + many times. + + +-.. cfunction:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) ++.. c:function:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) + +- This is a simplified interface to :cfunc:`PyParser_SimpleParseFileFlags` below, ++ This is a simplified interface to :c:func:`PyParser_SimpleParseFileFlags` below, + leaving *flags* set to ``0`` + + +-.. cfunction:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) ++.. c:function:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) + +- Similar to :cfunc:`PyParser_SimpleParseStringFlagsFilename`, but the Python ++ Similar to :c:func:`PyParser_SimpleParseStringFlagsFilename`, but the Python + source code is read from *fp* instead of an in-memory string. + + +-.. cfunction:: PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) ++.. c:function:: PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) + +- This is a simplified interface to :cfunc:`PyRun_StringFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_StringFlags` below, leaving + *flags* set to *NULL*. + + +-.. cfunction:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) ++.. c:function:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) + + Execute Python source code from *str* in the context specified by the + dictionaries *globals* and *locals* with the compiler flags specified by +@@ -194,39 +194,39 @@ + exception was raised. + + +-.. cfunction:: PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) ++.. c:function:: PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) + +- This is a simplified interface to :cfunc:`PyRun_FileExFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving + *closeit* set to ``0`` and *flags* set to *NULL*. + + +-.. cfunction:: PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit) ++.. c:function:: PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit) + +- This is a simplified interface to :cfunc:`PyRun_FileExFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving + *flags* set to *NULL*. + + +-.. cfunction:: PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) ++.. c:function:: PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) + +- This is a simplified interface to :cfunc:`PyRun_FileExFlags` below, leaving ++ This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving + *closeit* set to ``0``. + + +-.. cfunction:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) ++.. c:function:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) + +- Similar to :cfunc:`PyRun_StringFlags`, but the Python source code is read from ++ Similar to :c:func:`PyRun_StringFlags`, but the Python source code is read from + *fp* instead of an in-memory string. *filename* should be the name of the file. +- If *closeit* is true, the file is closed before :cfunc:`PyRun_FileExFlags` ++ If *closeit* is true, the file is closed before :c:func:`PyRun_FileExFlags` + returns. + + +-.. cfunction:: PyObject* Py_CompileString(const char *str, const char *filename, int start) ++.. c:function:: PyObject* Py_CompileString(const char *str, const char *filename, int start) + +- This is a simplified interface to :cfunc:`Py_CompileStringFlags` below, leaving ++ This is a simplified interface to :c:func:`Py_CompileStringFlags` below, leaving + *flags* set to *NULL*. + + +-.. cfunction:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags) ++.. c:function:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags) + + Parse and compile the Python source code in *str*, returning the resulting code + object. The start token is given by *start*; this can be used to constrain the +@@ -237,14 +237,14 @@ + be parsed or compiled. + + +-.. cfunction:: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) ++.. c:function:: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals) + +- This is a simplified interface to :cfunc:`PyEval_EvalCodeEx`, with just ++ This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just + the code object, and the dictionaries of global and local variables. + The other arguments are set to *NULL*. + + +-.. cfunction:: PyObject* PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure) ++.. c:function:: PyObject* PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure) + + Evaluate a precompiled code object, given a particular environment for its + evaluation. This environment consists of dictionaries of global and local +@@ -252,13 +252,13 @@ + cells. + + +-.. cfunction:: PyObject* PyEval_EvalFrame(PyFrameObject *f) ++.. c:function:: PyObject* PyEval_EvalFrame(PyFrameObject *f) + + Evaluate an execution frame. This is a simplified interface to + PyEval_EvalFrameEx, for backward compatibility. + + +-.. cfunction:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) ++.. c:function:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) + + This is the main, unvarnished function of Python interpretation. It is + literally 2000 lines long. The code object associated with the execution +@@ -268,39 +268,39 @@ + :meth:`throw` methods of generator objects. + + +-.. cfunction:: int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) ++.. c:function:: int PyEval_MergeCompilerFlags(PyCompilerFlags *cf) + + This function changes the flags of the current evaluation frame, and returns + true on success, false on failure. + + +-.. cvar:: int Py_eval_input ++.. c:var:: int Py_eval_input + + .. index:: single: Py_CompileString() + + The start symbol from the Python grammar for isolated expressions; for use with +- :cfunc:`Py_CompileString`. ++ :c:func:`Py_CompileString`. + + +-.. cvar:: int Py_file_input ++.. c:var:: int Py_file_input + + .. index:: single: Py_CompileString() + + The start symbol from the Python grammar for sequences of statements as read +- from a file or other source; for use with :cfunc:`Py_CompileString`. This is ++ from a file or other source; for use with :c:func:`Py_CompileString`. This is + the symbol to use when compiling arbitrarily long Python source code. + + +-.. cvar:: int Py_single_input ++.. c:var:: int Py_single_input + + .. index:: single: Py_CompileString() + + The start symbol from the Python grammar for a single statement; for use with +- :cfunc:`Py_CompileString`. This is the symbol used for the interactive ++ :c:func:`Py_CompileString`. This is the symbol used for the interactive + interpreter loop. + + +-.. ctype:: struct PyCompilerFlags ++.. c:type:: struct PyCompilerFlags + + This is the structure used to hold compiler flags. In cases where code is only + being compiled, it is passed as ``int flags``, and in cases where code is being +@@ -316,7 +316,7 @@ + } + + +-.. cvar:: int CO_FUTURE_DIVISION ++.. c:var:: int CO_FUTURE_DIVISION + + This bit can be set in *flags* to cause division operator ``/`` to be + interpreted as "true division" according to :pep:`238`. +diff -r 8527427914a2 Doc/c-api/weakref.rst +--- a/Doc/c-api/weakref.rst ++++ b/Doc/c-api/weakref.rst +@@ -11,28 +11,28 @@ + as much as it can. + + +-.. cfunction:: int PyWeakref_Check(ob) ++.. c:function:: int PyWeakref_Check(ob) + + Return true if *ob* is either a reference or proxy object. + + .. versionadded:: 2.2 + + +-.. cfunction:: int PyWeakref_CheckRef(ob) ++.. c:function:: int PyWeakref_CheckRef(ob) + + Return true if *ob* is a reference object. + + .. versionadded:: 2.2 + + +-.. cfunction:: int PyWeakref_CheckProxy(ob) ++.. c:function:: int PyWeakref_CheckProxy(ob) + + Return true if *ob* is a proxy object. + + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) ++.. c:function:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) + + Return a weak reference object for the object *ob*. This will always return + a new reference, but is not guaranteed to create a new object; an existing +@@ -46,7 +46,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) ++.. c:function:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) + + Return a weak reference proxy object for the object *ob*. This will always + return a new reference, but is not guaranteed to create a new object; an +@@ -60,7 +60,7 @@ + .. versionadded:: 2.2 + + +-.. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref) ++.. c:function:: PyObject* PyWeakref_GetObject(PyObject *ref) + + Return the referenced object from a weak reference, *ref*. If the referent is + no longer live, returns :const:`Py_None`. +@@ -70,14 +70,14 @@ + .. warning:: + + This function returns a **borrowed reference** to the referenced object. +- This means that you should always call :cfunc:`Py_INCREF` on the object ++ This means that you should always call :c:func:`Py_INCREF` on the object + except if you know that it cannot be destroyed while you are still + using it. + + +-.. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref) ++.. c:function:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref) + +- Similar to :cfunc:`PyWeakref_GetObject`, but implemented as a macro that does no ++ Similar to :c:func:`PyWeakref_GetObject`, but implemented as a macro that does no + error checking. + + .. versionadded:: 2.2 +diff -r 8527427914a2 Doc/conf.py +--- a/Doc/conf.py ++++ b/Doc/conf.py +@@ -63,6 +63,9 @@ + # 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' +@@ -83,7 +86,7 @@ + } + + # Output an OpenSearch description file. +-html_use_opensearch = 'http://docs.python.org/dev' ++html_use_opensearch = 'http://docs.python.org/' + + # Additional static files. + html_static_path = ['tools/sphinxext/static'] +@@ -112,8 +115,6 @@ + 'The Python/C API', _stdauthor, 'manual'), + ('distutils/index', 'distutils.tex', + 'Distributing Python Modules', _stdauthor, 'manual'), +- ('documenting/index', 'documenting.tex', +- 'Documenting Python', 'Georg Brandl', 'manual'), + ('extending/index', 'extending.tex', + 'Extending and Embedding Python', _stdauthor, 'manual'), + ('install/index', 'install.tex', +@@ -151,7 +152,7 @@ + latex_appendices = ['glossary', 'about', 'license', 'copyright'] + + # Get LaTeX to handle Unicode correctly +-latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}'} ++latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''} + + # Options for the coverage checker + # -------------------------------- +diff -r 8527427914a2 Doc/contents.rst +--- a/Doc/contents.rst ++++ b/Doc/contents.rst +@@ -13,7 +13,6 @@ + c-api/index.rst + distutils/index.rst + install/index.rst +- documenting/index.rst + howto/index.rst + faq/index.rst + glossary.rst +diff -r 8527427914a2 Doc/copyright.rst +--- a/Doc/copyright.rst ++++ b/Doc/copyright.rst +@@ -4,7 +4,7 @@ + + Python and this documentation is: + +-Copyright © 2001-2010 Python Software Foundation. All rights reserved. ++Copyright © 2001-2012 Python Software Foundation. All rights reserved. + + Copyright © 2000 BeOpen.com. All rights reserved. + +diff -r 8527427914a2 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 at | +- | | | http://pypi.python.org/pypi?:action=list_classifiers. | ++ | *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 | | +@@ -1736,7 +1736,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`. + +@@ -1815,7 +1815,7 @@ + .. module:: distutils.command.bdist_msi + :synopsis: Build a binary distribution as a Windows MSI file + +-.. class:: bdist_msi(Command) ++.. class:: bdist_msi + + Builds a `Windows Installer`_ (.msi) binary package. + +diff -r 8527427914a2 Doc/distutils/builtdist.rst +--- a/Doc/distutils/builtdist.rst ++++ b/Doc/distutils/builtdist.rst +@@ -426,7 +426,7 @@ + + Which folders are available depends on the exact Windows version, and probably + also the configuration. For details refer to Microsoft's documentation of the +- :cfunc:`SHGetSpecialFolderPath` function. ++ :c:func:`SHGetSpecialFolderPath` function. + + + .. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]]) +diff -r 8527427914a2 Doc/distutils/introduction.rst +--- a/Doc/distutils/introduction.rst ++++ b/Doc/distutils/introduction.rst +@@ -79,11 +79,17 @@ + for an example) + + To create a source distribution for this module, you would create a setup +-script, :file:`setup.py`, containing the above code, and run:: ++script, :file:`setup.py`, containing the above code, and run this command from a ++terminal:: + + python setup.py sdist + +-which will create an archive file (e.g., tarball on Unix, ZIP file on Windows) ++For Windows, open a command prompt windows (:menuselection:`Start --> ++Accessories`) and change the command to:: ++ ++ setup.py sdist ++ ++:command:`sdist` will create an archive file (e.g., tarball on Unix, ZIP file on Windows) + containing your setup script :file:`setup.py`, and your module :file:`foo.py`. + The archive file will be named :file:`foo-1.0.tar.gz` (or :file:`.zip`), and + will unpack into a directory :file:`foo-1.0`. +diff -r 8527427914a2 Doc/distutils/setupscript.rst +--- a/Doc/distutils/setupscript.rst ++++ b/Doc/distutils/setupscript.rst +@@ -72,7 +72,7 @@ + promising that the Distutils will find a file :file:`foo/__init__.py` (which + might be spelled differently on your system, but you get the idea) relative to + the directory where your setup script lives. If you break this promise, the +-Distutils will issue a warning but still process the broken package anyways. ++Distutils will issue a warning but still process the broken package anyway. + + If you use a different convention to lay out your source directory, that's no + problem: you just have to supply the :option:`package_dir` option to tell the +@@ -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 +@@ -334,10 +334,6 @@ + + There are still some other options which can be used to handle special cases. + +-The :option:`optional` option is a boolean; if it is true, +-a build failure in the extension will not abort the build process, but +-instead simply not install the failing extension. +- + The :option:`extra_objects` option is a list of object files to be passed to the + linker. These files must not have extensions, as the default extension for the + compiler is used. +diff -r 8527427914a2 Doc/distutils/sourcedist.rst +--- a/Doc/distutils/sourcedist.rst ++++ b/Doc/distutils/sourcedist.rst +@@ -111,12 +111,22 @@ + :file:`MANIFEST`, you must specify everything: the default set of files + described above does not apply in this case. + +-.. versionadded:: 2.7 ++.. versionchanged:: 2.7 ++ An existing generated :file:`MANIFEST` will be regenerated without ++ :command:`sdist` comparing its modification time to the one of ++ :file:`MANIFEST.in` or :file:`setup.py`. ++ ++.. versionchanged:: 2.7.1 + :file:`MANIFEST` files start with a comment indicating they are generated. + Files without this comment are not overwritten or removed. + ++.. versionchanged:: 2.7.3 ++ :command:`sdist` will read a :file:`MANIFEST` file if no :file:`MANIFEST.in` ++ exists, like it did before 2.7. ++ + See :ref:`manifest_template` section for a syntax reference. + ++ + .. _manifest-options: + + Manifest-related options +@@ -124,16 +134,16 @@ + + The normal course of operations for the :command:`sdist` command is as follows: + +-* if the manifest file, :file:`MANIFEST` doesn't exist, read :file:`MANIFEST.in` +- and create the manifest ++* if the manifest file (:file:`MANIFEST` by default) exists and the first line ++ does not have a comment indicating it is generated from :file:`MANIFEST.in`, ++ then it is used as is, unaltered ++ ++* if the manifest file doesn't exist or has been previously automatically ++ generated, read :file:`MANIFEST.in` and create the manifest + + * if neither :file:`MANIFEST` nor :file:`MANIFEST.in` exist, create a manifest + with just the default file set + +-* if either :file:`MANIFEST.in` or the setup script (:file:`setup.py`) are more +- recent than :file:`MANIFEST`, recreate :file:`MANIFEST` by reading +- :file:`MANIFEST.in` +- + * use the list of files now in :file:`MANIFEST` (either just generated or read + in) to create the source distribution archive(s) + +@@ -271,8 +281,3 @@ + ``a-z``, ``a-zA-Z``, ``a-f0-9_.``). The definition of "regular filename + character" is platform-specific: on Unix it is anything except slash; on Windows + anything except backslash or colon. +- +-.. versionchanged:: 2.7 +- An existing generated :file:`MANIFEST` will be regenerated without +- :command:`sdist` comparing its modification time to the one of +- :file:`MANIFEST.in` or :file:`setup.py`. +diff -r 8527427914a2 Doc/documenting/building.rst +--- a/Doc/documenting/building.rst ++++ /dev/null +@@ -1,91 +0,0 @@ +-Building the documentation +-========================== +- +-You need to have Python 2.4 or higher installed; the toolset used to build the +-docs is written in Python. It is called *Sphinx*, it is not included in this +-tree, but maintained separately. Also needed are the docutils, supplying the +-base markup that Sphinx uses, Jinja, a templating engine, and optionally +-Pygments, a code highlighter. +- +- +-Using make +----------- +- +-Luckily, a Makefile has been prepared so that on Unix, provided you have +-installed Python and Subversion, you can just run :: +- +- make html +- +-to check out the necessary toolset in the `tools/` subdirectory and build the +-HTML output files. To view the generated HTML, point your favorite browser at +-the top-level index `build/html/index.html` after running "make". +- +-Available make targets are: +- +- * "html", which builds standalone HTML files for offline viewing. +- +- * "htmlhelp", which builds HTML files and a HTML Help project file usable to +- convert them into a single Compiled HTML (.chm) file -- these are popular +- under Microsoft Windows, but very handy on every platform. +- +- To create the CHM file, you need to run the Microsoft HTML Help Workshop +- over the generated project (.hhp) file. +- +- * "latex", which builds LaTeX source files as input to "pdflatex" to produce +- PDF documents. +- +- * "text", which builds a plain text file for each source file. +- +- * "linkcheck", which checks all external references to see whether they are +- broken, redirected or malformed, and outputs this information to stdout +- as well as a plain-text (.txt) file. +- +- * "changes", which builds an overview over all versionadded/versionchanged/ +- deprecated items in the current version. This is meant as a help for the +- writer of the "What's New" document. +- +- * "coverage", which builds a coverage overview for standard library modules +- and C API. +- +- * "pydoc-topics", which builds a Python module containing a dictionary with +- plain text documentation for the labels defined in +- `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and +- keyword help. +- +-A "make update" updates the Subversion checkouts in `tools/`. +- +- +-Without make +------------- +- +-You'll need to install the Sphinx package, either by checking it out via :: +- +- svn co http://svn.python.org/projects/external/Sphinx-0.6.5/sphinx tools/sphinx +- +-or by installing it from PyPI. +- +-Then, you need to install Docutils, either by checking it out via :: +- +- svn co http://svn.python.org/projects/external/docutils-0.6/docutils tools/docutils +- +-or by installing it from http://docutils.sf.net/. +- +-You also need Jinja2, either by checking it out via :: +- +- svn co http://svn.python.org/projects/external/Jinja-2.3.1/jinja2 tools/jinja2 +- +-or by installing it from PyPI. +- +-You can optionally also install Pygments, either as a checkout via :: +- +- svn co http://svn.python.org/projects/external/Pygments-1.3.1/pygments tools/pygments +- +-or from PyPI at http://pypi.python.org/pypi/Pygments. +- +- +-Then, make an output directory, e.g. under `build/`, and run :: +- +- python tools/sphinx-build.py -b . build/ +- +-where `` is one of html, text, latex, or htmlhelp (for explanations see +-the make targets above). +diff -r 8527427914a2 Doc/documenting/fromlatex.rst +--- a/Doc/documenting/fromlatex.rst ++++ /dev/null +@@ -1,202 +0,0 @@ +-.. highlightlang:: rest +- +-Differences to the LaTeX markup +-=============================== +- +-Though the markup language is different, most of the concepts and markup types +-of the old LaTeX docs have been kept -- environments as reST directives, inline +-commands as reST roles and so forth. +- +-However, there are some differences in the way these work, partly due to the +-differences in the markup languages, partly due to improvements in Sphinx. This +-section lists these differences, in order to give those familiar with the old +-format a quick overview of what they might run into. +- +-Inline markup +-------------- +- +-These changes have been made to inline markup: +- +-* **Cross-reference roles** +- +- Most of the following semantic roles existed previously as inline commands, +- but didn't do anything except formatting the content as code. Now, they +- cross-reference to known targets (some names have also been shortened): +- +- | *mod* (previously *refmodule* or *module*) +- | *func* (previously *function*) +- | *data* (new) +- | *const* +- | *class* +- | *meth* (previously *method*) +- | *attr* (previously *member*) +- | *exc* (previously *exception*) +- | *cdata* +- | *cfunc* (previously *cfunction*) +- | *cmacro* (previously *csimplemacro*) +- | *ctype* +- +- Also different is the handling of *func* and *meth*: while previously +- parentheses were added to the callable name (like ``\func{str()}``), they are +- now appended by the build system -- appending them in the source will result +- in double parentheses. This also means that ``:func:`str(object)``` will not +- work as expected -- use ````str(object)```` instead! +- +-* **Inline commands implemented as directives** +- +- These were inline commands in LaTeX, but are now directives in reST: +- +- | *deprecated* +- | *versionadded* +- | *versionchanged* +- +- These are used like so:: +- +- .. deprecated:: 2.5 +- Reason of deprecation. +- +- Also, no period is appended to the text for *versionadded* and +- *versionchanged*. +- +- | *note* +- | *warning* +- +- These are used like so:: +- +- .. note:: +- +- Content of note. +- +-* **Otherwise changed commands** +- +- The *samp* command previously formatted code and added quotation marks around +- it. The *samp* role, however, features a new highlighting system just like +- *file* does: +- +- ``:samp:`open({filename}, {mode})``` results in :samp:`open({filename}, {mode})` +- +-* **Dropped commands** +- +- These were commands in LaTeX, but are not available as roles: +- +- | *bfcode* +- | *character* (use :samp:`\`\`'c'\`\``) +- | *citetitle* (use ```Title `_``) +- | *code* (use ````code````) +- | *email* (just write the address in body text) +- | *filenq* +- | *filevar* (use the ``{...}`` highlighting feature of *file*) +- | *programopt*, *longprogramopt* (use *option*) +- | *ulink* (use ```Title `_``) +- | *url* (just write the URL in body text) +- | *var* (use ``*var*``) +- | *infinity*, *plusminus* (use the Unicode character) +- | *shortversion*, *version* (use the ``|version|`` and ``|release|`` substitutions) +- | *emph*, *strong* (use the reST markup) +- +-* **Backslash escaping** +- +- In reST, a backslash must be escaped in normal text, and in the content of +- roles. However, in code literals and literal blocks, it must not be escaped. +- Example: ``:file:`C:\\Temp\\my.tmp``` vs. ````open("C:\Temp\my.tmp")````. +- +- +-Information units +------------------ +- +-Information units (*...desc* environments) have been made reST directives. +-These changes to information units should be noted: +- +-* **New names** +- +- "desc" has been removed from every name. Additionally, these directives have +- new names: +- +- | *cfunction* (previously *cfuncdesc*) +- | *cmacro* (previously *csimplemacrodesc*) +- | *exception* (previously *excdesc*) +- | *function* (previously *funcdesc*) +- | *attribute* (previously *memberdesc*) +- +- The *classdesc\** and *excclassdesc* environments have been dropped, the +- *class* and *exception* directives support classes documented with and without +- constructor arguments. +- +-* **Multiple objects** +- +- The equivalent of the *...line* commands is:: +- +- .. function:: do_foo(bar) +- do_bar(baz) +- +- Description of the functions. +- +- IOW, just give one signatures per line, at the same indentation level. +- +-* **Arguments** +- +- There is no *optional* command. Just give function signatures like they +- should appear in the output:: +- +- .. function:: open(filename[, mode[, buffering]]) +- +- Description. +- +- Note: markup in the signature is not supported. +- +-* **Indexing** +- +- The *...descni* environments have been dropped. To mark an information unit +- as unsuitable for index entry generation, use the *noindex* option like so:: +- +- .. function:: foo_* +- :noindex: +- +- Description. +- +-* **New information units** +- +- There are new generic information units: One is called "describe" and can be +- used to document things that are not covered by the other units:: +- +- .. describe:: a == b +- +- The equals operator. +- +- The others are:: +- +- .. cmdoption:: -O +- +- Describes a command-line option. +- +- .. envvar:: PYTHONINSPECT +- +- Describes an environment variable. +- +- +-Structure +---------- +- +-The LaTeX docs were split in several toplevel manuals. Now, all files are part +-of the same documentation tree, as indicated by the *toctree* directives in the +-sources (though individual output formats may choose to split them up into parts +-again). Every *toctree* directive embeds other files as subdocuments of the +-current file (this structure is not necessarily mirrored in the filesystem +-layout). The toplevel file is :file:`contents.rst`. +- +-However, most of the old directory structure has been kept, with the +-directories renamed as follows: +- +-* :file:`api` -> :file:`c-api` +-* :file:`dist` -> :file:`distutils`, with the single TeX file split up +-* :file:`doc` -> :file:`documenting` +-* :file:`ext` -> :file:`extending` +-* :file:`inst` -> :file:`installing` +-* :file:`lib` -> :file:`library` +-* :file:`mac` -> merged into :file:`library`, with :file:`mac/using.tex` +- moved to :file:`using/mac.rst` +-* :file:`ref` -> :file:`reference` +-* :file:`tut` -> :file:`tutorial`, with the single TeX file split up +- +- +-.. XXX more (index-generating, production lists, ...) +diff -r 8527427914a2 Doc/documenting/index.rst +--- a/Doc/documenting/index.rst ++++ /dev/null +@@ -1,38 +0,0 @@ +-.. _documenting-index: +- +-###################### +- Documenting Python +-###################### +- +- +-The Python language has a substantial body of documentation, much of it +-contributed by various authors. The markup used for the Python documentation is +-`reStructuredText`_, developed by the `docutils`_ project, amended by custom +-directives and using a toolset named `Sphinx`_ to postprocess the HTML output. +- +-This document describes the style guide for our documentation as well as the +-custom reStructuredText markup introduced by Sphinx to support Python +-documentation and how it should be used. +- +-.. _reStructuredText: http://docutils.sf.net/rst.html +-.. _docutils: http://docutils.sf.net/ +-.. _Sphinx: http://sphinx.pocoo.org/ +- +-.. note:: +- +- If you're interested in contributing to Python's documentation, there's no +- need to write reStructuredText if you're not so inclined; plain text +- contributions are more than welcome as well. Send an e-mail to +- docs@python.org or open an issue on the :ref:`tracker `. +- +- +-.. toctree:: +- :numbered: +- :maxdepth: 1 +- +- intro.rst +- style.rst +- rest.rst +- markup.rst +- fromlatex.rst +- building.rst +diff -r 8527427914a2 Doc/documenting/intro.rst +--- a/Doc/documenting/intro.rst ++++ /dev/null +@@ -1,29 +0,0 @@ +-Introduction +-============ +- +-Python's documentation has long been considered to be good for a free +-programming language. There are a number of reasons for this, the most +-important being the early commitment of Python's creator, Guido van Rossum, to +-providing documentation on the language and its libraries, and the continuing +-involvement of the user community in providing assistance for creating and +-maintaining documentation. +- +-The involvement of the community takes many forms, from authoring to bug reports +-to just plain complaining when the documentation could be more complete or +-easier to use. +- +-This document is aimed at authors and potential authors of documentation for +-Python. More specifically, it is for people contributing to the standard +-documentation and developing additional documents using the same tools as the +-standard documents. This guide will be less useful for authors using the Python +-documentation tools for topics other than Python, and less useful still for +-authors not using the tools at all. +- +-If your interest is in contributing to the Python documentation, but you don't +-have the time or inclination to learn reStructuredText and the markup structures +-documented here, there's a welcoming place for you among the Python contributors +-as well. Any time you feel that you can clarify existing documentation or +-provide documentation that's missing, the existing documentation team will +-gladly work with you to integrate your text, dealing with the markup for you. +-Please don't let the material in this document stand between the documentation +-and your desire to help out! +\ No newline at end of file +diff -r 8527427914a2 Doc/documenting/markup.rst +--- a/Doc/documenting/markup.rst ++++ /dev/null +@@ -1,857 +0,0 @@ +-.. highlightlang:: rest +- +-Additional Markup Constructs +-============================ +- +-Sphinx adds a lot of new directives and interpreted text roles to standard reST +-markup. This section contains the reference material for these facilities. +-Documentation for "standard" reST constructs is not included here, though +-they are used in the Python documentation. +- +-.. note:: +- +- This is just an overview of Sphinx' extended markup capabilities; full +- coverage can be found in `its own documentation +- `_. +- +- +-Meta-information markup +------------------------ +- +-.. describe:: sectionauthor +- +- Identifies the author of the current section. The argument should include +- the author's name such that it can be used for presentation (though it isn't) +- and email address. The domain name portion of the address should be lower +- case. Example:: +- +- .. sectionauthor:: Guido van Rossum +- +- Currently, this markup isn't reflected in the output in any way, but it helps +- keep track of contributions. +- +- +-Module-specific markup +----------------------- +- +-The markup described in this section is used to provide information about a +-module being documented. Each module should be documented in its own file. +-Normally this markup appears after the title heading of that file; a typical +-file might start like this:: +- +- :mod:`parrot` -- Dead parrot access +- =================================== +- +- .. module:: parrot +- :platform: Unix, Windows +- :synopsis: Analyze and reanimate dead parrots. +- .. moduleauthor:: Eric Cleese +- .. moduleauthor:: John Idle +- +-As you can see, the module-specific markup consists of two directives, the +-``module`` directive and the ``moduleauthor`` directive. +- +-.. describe:: module +- +- This directive marks the beginning of the description of a module (or package +- submodule, in which case the name should be fully qualified, including the +- package name). +- +- The ``platform`` option, if present, is a comma-separated list of the +- platforms on which the module is available (if it is available on all +- platforms, the option should be omitted). The keys are short identifiers; +- examples that are in use include "IRIX", "Mac", "Windows", and "Unix". It is +- important to use a key which has already been used when applicable. +- +- The ``synopsis`` option should consist of one sentence describing the +- module's purpose -- it is currently only used in the Global Module Index. +- +- The ``deprecated`` option can be given (with no value) to mark a module as +- deprecated; it will be designated as such in various locations then. +- +-.. describe:: moduleauthor +- +- The ``moduleauthor`` directive, which can appear multiple times, names the +- authors of the module code, just like ``sectionauthor`` names the author(s) +- of a piece of documentation. It too does not result in any output currently. +- +-.. note:: +- +- It is important to make the section title of a module-describing file +- meaningful since that value will be inserted in the table-of-contents trees +- in overview files. +- +- +-Information units +------------------ +- +-There are a number of directives used to describe specific features provided by +-modules. Each directive requires one or more signatures to provide basic +-information about what is being described, and the content should be the +-description. The basic version makes entries in the general index; if no index +-entry is desired, you can give the directive option flag ``:noindex:``. The +-following example shows all of the features of this directive type:: +- +- .. function:: spam(eggs) +- ham(eggs) +- :noindex: +- +- Spam or ham the foo. +- +-The signatures of object methods or data attributes should always include the +-type name (``.. method:: FileInput.input(...)``), even if it is obvious from the +-context which type they belong to; this is to enable consistent +-cross-references. If you describe methods belonging to an abstract protocol, +-such as "context managers", include a (pseudo-)type name too to make the +-index entries more informative. +- +-The directives are: +- +-.. describe:: cfunction +- +- Describes a C function. The signature should be given as in C, e.g.:: +- +- .. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) +- +- This is also used to describe function-like preprocessor macros. The names +- of the arguments should be given so they may be used in the description. +- +- Note that you don't have to backslash-escape asterisks in the signature, +- as it is not parsed by the reST inliner. +- +-.. describe:: cmember +- +- Describes a C struct member. Example signature:: +- +- .. cmember:: PyObject* PyTypeObject.tp_bases +- +- The text of the description should include the range of values allowed, how +- the value should be interpreted, and whether the value can be changed. +- References to structure members in text should use the ``member`` role. +- +-.. describe:: cmacro +- +- Describes a "simple" C macro. Simple macros are macros which are used +- for code expansion, but which do not take arguments so cannot be described as +- functions. This is not to be used for simple constant definitions. Examples +- of its use in the Python documentation include :cmacro:`PyObject_HEAD` and +- :cmacro:`Py_BEGIN_ALLOW_THREADS`. +- +-.. describe:: ctype +- +- Describes a C type. The signature should just be the type name. +- +-.. describe:: cvar +- +- Describes a global C variable. The signature should include the type, such +- as:: +- +- .. cvar:: PyObject* PyClass_Type +- +-.. describe:: data +- +- Describes global data in a module, including both variables and values used +- as "defined constants." Class and object attributes are not documented +- using this directive. +- +-.. describe:: exception +- +- Describes an exception class. The signature can, but need not include +- parentheses with constructor arguments. +- +-.. describe:: function +- +- Describes a module-level function. The signature should include the +- parameters, enclosing optional parameters in brackets. Default values can be +- given if it enhances clarity. For example:: +- +- .. function:: repeat([repeat=3[, number=1000000]]) +- +- Object methods are not documented using this directive. Bound object methods +- placed in the module namespace as part of the public interface of the module +- are documented using this, as they are equivalent to normal functions for +- most purposes. +- +- The description should include information about the parameters required and +- how they are used (especially whether mutable objects passed as parameters +- are modified), side effects, and possible exceptions. A small example may be +- provided. +- +-.. describe:: class +- +- Describes a class. The signature can include parentheses with parameters +- which will be shown as the constructor arguments. +- +-.. describe:: attribute +- +- Describes an object data attribute. The description should include +- information about the type of the data to be expected and whether it may be +- changed directly. This directive should be nested in a class directive, +- like in this example:: +- +- .. class:: Spam +- +- Description of the class. +- +- .. data:: ham +- +- Description of the attribute. +- +- If is also possible to document an attribute outside of a class directive, +- for example if the documentation for different attributes and methods is +- split in multiple sections. The class name should then be included +- explicitly:: +- +- .. data:: Spam.eggs +- +-.. describe:: method +- +- Describes an object method. The parameters should not include the ``self`` +- parameter. The description should include similar information to that +- described for ``function``. This directive should be nested in a class +- directive, like in the example above. +- +-.. describe:: opcode +- +- Describes a Python :term:`bytecode` instruction. +- +-.. describe:: cmdoption +- +- Describes a Python command line option or switch. Option argument names +- should be enclosed in angle brackets. Example:: +- +- .. cmdoption:: -m +- +- Run a module as a script. +- +-.. describe:: envvar +- +- Describes an environment variable that Python uses or defines. +- +- +-There is also a generic version of these directives: +- +-.. describe:: describe +- +- This directive produces the same formatting as the specific ones explained +- above but does not create index entries or cross-referencing targets. It is +- used, for example, to describe the directives in this document. Example:: +- +- .. describe:: opcode +- +- Describes a Python bytecode instruction. +- +- +-Showing code examples +---------------------- +- +-Examples of Python source code or interactive sessions are represented using +-standard reST literal blocks. They are started by a ``::`` at the end of the +-preceding paragraph and delimited by indentation. +- +-Representing an interactive session requires including the prompts and output +-along with the Python code. No special markup is required for interactive +-sessions. After the last line of input or output presented, there should not be +-an "unused" primary prompt; this is an example of what *not* to do:: +- +- >>> 1 + 1 +- 2 +- >>> +- +-Syntax highlighting is handled in a smart way: +- +-* There is a "highlighting language" for each source file. Per default, +- this is ``'python'`` as the majority of files will have to highlight Python +- snippets. +- +-* Within Python highlighting mode, interactive sessions are recognized +- automatically and highlighted appropriately. +- +-* The highlighting language can be changed using the ``highlightlang`` +- directive, used as follows:: +- +- .. highlightlang:: c +- +- This language is used until the next ``highlightlang`` directive is +- encountered. +- +-* The values normally used for the highlighting language are: +- +- * ``python`` (the default) +- * ``c`` +- * ``rest`` +- * ``none`` (no highlighting) +- +-* If highlighting with the current language fails, the block is not highlighted +- in any way. +- +-Longer displays of verbatim text may be included by storing the example text in +-an external file containing only plain text. The file may be included using the +-``literalinclude`` directive. [1]_ For example, to include the Python source file +-:file:`example.py`, use:: +- +- .. literalinclude:: example.py +- +-The file name is relative to the current file's path. Documentation-specific +-include files should be placed in the ``Doc/includes`` subdirectory. +- +- +-Inline markup +-------------- +- +-As said before, Sphinx uses interpreted text roles to insert semantic markup in +-documents. +- +-Names of local variables, such as function/method arguments, are an exception, +-they should be marked simply with ``*var*``. +- +-For all other roles, you have to write ``:rolename:`content```. +- +-There are some additional facilities that make cross-referencing roles more +-versatile: +- +-* You may supply an explicit title and reference target, like in reST direct +- hyperlinks: ``:role:`title ``` will refer to *target*, but the link +- text will be *title*. +- +-* If you prefix the content with ``!``, no reference/hyperlink will be created. +- +-* For the Python object roles, if you prefix the content with ``~``, the link +- text will only be the last component of the target. For example, +- ``:meth:`~Queue.Queue.get``` will refer to ``Queue.Queue.get`` but only +- display ``get`` as the link text. +- +- In HTML output, the link's ``title`` attribute (that is e.g. shown as a +- tool-tip on mouse-hover) will always be the full target name. +- +-The following roles refer to objects in modules and are possibly hyperlinked if +-a matching identifier is found: +- +-.. describe:: mod +- +- The name of a module; a dotted name may be used. This should also be used for +- package names. +- +-.. describe:: func +- +- The name of a Python function; dotted names may be used. The role text +- should not include trailing parentheses to enhance readability. The +- parentheses are stripped when searching for identifiers. +- +-.. describe:: data +- +- The name of a module-level variable or constant. +- +-.. describe:: const +- +- The name of a "defined" constant. This may be a C-language ``#define`` +- or a Python variable that is not intended to be changed. +- +-.. describe:: class +- +- A class name; a dotted name may be used. +- +-.. describe:: meth +- +- The name of a method of an object. The role text should include the type +- name and the method name. A dotted name may be used. +- +-.. describe:: attr +- +- The name of a data attribute of an object. +- +-.. describe:: exc +- +- The name of an exception. A dotted name may be used. +- +-The name enclosed in this markup can include a module name and/or a class name. +-For example, ``:func:`filter``` could refer to a function named ``filter`` in +-the current module, or the built-in function of that name. In contrast, +-``:func:`foo.filter``` clearly refers to the ``filter`` function in the ``foo`` +-module. +- +-Normally, names in these roles are searched first without any further +-qualification, then with the current module name prepended, then with the +-current module and class name (if any) prepended. If you prefix the name with a +-dot, this order is reversed. For example, in the documentation of the +-:mod:`codecs` module, ``:func:`open``` always refers to the built-in function, +-while ``:func:`.open``` refers to :func:`codecs.open`. +- +-A similar heuristic is used to determine whether the name is an attribute of +-the currently documented class. +- +-The following roles create cross-references to C-language constructs if they +-are defined in the API documentation: +- +-.. describe:: cdata +- +- The name of a C-language variable. +- +-.. describe:: cfunc +- +- The name of a C-language function. Should include trailing parentheses. +- +-.. describe:: cmacro +- +- The name of a "simple" C macro, as defined above. +- +-.. describe:: ctype +- +- The name of a C-language type. +- +- +-The following role does possibly create a cross-reference, but does not refer +-to objects: +- +-.. describe:: token +- +- The name of a grammar token (used in the reference manual to create links +- between production displays). +- +- +-The following role creates a cross-reference to the term in the glossary: +- +-.. describe:: term +- +- Reference to a term in the glossary. The glossary is created using the +- ``glossary`` directive containing a definition list with terms and +- definitions. It does not have to be in the same file as the ``term`` +- markup, in fact, by default the Python docs have one global glossary +- in the ``glossary.rst`` file. +- +- If you use a term that's not explained in a glossary, you'll get a warning +- during build. +- +---------- +- +-The following roles don't do anything special except formatting the text +-in a different style: +- +-.. describe:: command +- +- The name of an OS-level command, such as ``rm``. +- +-.. describe:: dfn +- +- Mark the defining instance of a term in the text. (No index entries are +- generated.) +- +-.. describe:: envvar +- +- An environment variable. Index entries are generated. +- +-.. describe:: file +- +- The name of a file or directory. Within the contents, you can use curly +- braces to indicate a "variable" part, for example:: +- +- ... is installed in :file:`/usr/lib/python2.{x}/site-packages` ... +- +- In the built documentation, the ``x`` will be displayed differently to +- indicate that it is to be replaced by the Python minor version. +- +-.. describe:: guilabel +- +- Labels presented as part of an interactive user interface should be marked +- using ``guilabel``. This includes labels from text-based interfaces such as +- those created using :mod:`curses` or other text-based libraries. Any label +- used in the interface should be marked with this role, including button +- labels, window titles, field names, menu and menu selection names, and even +- values in selection lists. +- +-.. describe:: kbd +- +- Mark a sequence of keystrokes. What form the key sequence takes may depend +- on platform- or application-specific conventions. When there are no relevant +- conventions, the names of modifier keys should be spelled out, to improve +- accessibility for new users and non-native speakers. For example, an +- *xemacs* key sequence may be marked like ``:kbd:`C-x C-f```, but without +- reference to a specific application or platform, the same sequence should be +- marked as ``:kbd:`Control-x Control-f```. +- +-.. describe:: keyword +- +- The name of a keyword in Python. +- +-.. describe:: mailheader +- +- The name of an RFC 822-style mail header. This markup does not imply that +- the header is being used in an email message, but can be used to refer to any +- header of the same "style." This is also used for headers defined by the +- various MIME specifications. The header name should be entered in the same +- way it would normally be found in practice, with the camel-casing conventions +- being preferred where there is more than one common usage. For example: +- ``:mailheader:`Content-Type```. +- +-.. describe:: makevar +- +- The name of a :command:`make` variable. +- +-.. describe:: manpage +- +- A reference to a Unix manual page including the section, +- e.g. ``:manpage:`ls(1)```. +- +-.. describe:: menuselection +- +- Menu selections should be marked using the ``menuselection`` role. This is +- used to mark a complete sequence of menu selections, including selecting +- submenus and choosing a specific operation, or any subsequence of such a +- sequence. The names of individual selections should be separated by +- ``-->``. +- +- For example, to mark the selection "Start > Programs", use this markup:: +- +- :menuselection:`Start --> Programs` +- +- When including a selection that includes some trailing indicator, such as the +- ellipsis some operating systems use to indicate that the command opens a +- dialog, the indicator should be omitted from the selection name. +- +-.. describe:: mimetype +- +- The name of a MIME type, or a component of a MIME type (the major or minor +- portion, taken alone). +- +-.. describe:: newsgroup +- +- The name of a Usenet newsgroup. +- +-.. describe:: option +- +- A command-line option of Python. The leading hyphen(s) must be included. +- If a matching ``cmdoption`` directive exists, it is linked to. For options +- of other programs or scripts, use simple ````code```` markup. +- +-.. describe:: program +- +- The name of an executable program. This may differ from the file name for +- the executable for some platforms. In particular, the ``.exe`` (or other) +- extension should be omitted for Windows programs. +- +-.. describe:: regexp +- +- A regular expression. Quotes should not be included. +- +-.. describe:: samp +- +- A piece of literal text, such as code. Within the contents, you can use +- curly braces to indicate a "variable" part, as in ``:file:``. +- +- If you don't need the "variable part" indication, use the standard +- ````code```` instead. +- +- +-The following roles generate external links: +- +-.. describe:: pep +- +- A reference to a Python Enhancement Proposal. This generates appropriate +- index entries. The text "PEP *number*\ " is generated; in the HTML output, +- this text is a hyperlink to an online copy of the specified PEP. +- +-.. describe:: rfc +- +- A reference to an Internet Request for Comments. This generates appropriate +- index entries. The text "RFC *number*\ " is generated; in the HTML output, +- this text is a hyperlink to an online copy of the specified RFC. +- +- +-Note that there are no special roles for including hyperlinks as you can use +-the standard reST markup for that purpose. +- +- +-.. _doc-ref-role: +- +-Cross-linking markup +--------------------- +- +-To support cross-referencing to arbitrary sections in the documentation, the +-standard reST labels are "abused" a bit: Every label must precede a section +-title; and every label name must be unique throughout the entire documentation +-source. +- +-You can then reference to these sections using the ``:ref:`label-name``` role. +- +-Example:: +- +- .. _my-reference-label: +- +- Section to cross-reference +- -------------------------- +- +- This is the text of the section. +- +- It refers to the section itself, see :ref:`my-reference-label`. +- +-The ``:ref:`` invocation is replaced with the section title. +- +- +-Paragraph-level markup +----------------------- +- +-These directives create short paragraphs and can be used inside information +-units as well as normal text: +- +-.. describe:: note +- +- An especially important bit of information about an API that a user should be +- aware of when using whatever bit of API the note pertains to. The content of +- the directive should be written in complete sentences and include all +- appropriate punctuation. +- +- Example:: +- +- .. note:: +- +- This function is not suitable for sending spam e-mails. +- +-.. describe:: warning +- +- An important bit of information about an API that a user should be aware of +- when using whatever bit of API the warning pertains to. The content of the +- directive should be written in complete sentences and include all appropriate +- punctuation. In the interest of not scaring users away from pages filled +- with warnings, this directive should only be chosen over ``note`` for +- information regarding the possibility of crashes, data loss, or security +- implications. +- +-.. describe:: versionadded +- +- This directive documents the version of Python which added the described +- feature to the library or C API. When this applies to an entire module, it +- should be placed at the top of the module section before any prose. +- +- The first argument must be given and is the version in question; you can add +- a second argument consisting of a *brief* explanation of the change. +- +- Example:: +- +- .. versionadded:: 2.5 +- The *spam* parameter. +- +- Note that there must be no blank line between the directive head and the +- explanation; this is to make these blocks visually continuous in the markup. +- +-.. describe:: versionchanged +- +- Similar to ``versionadded``, but describes when and what changed in the named +- feature in some way (new parameters, changed side effects, etc.). +- +--------------- +- +-.. describe:: impl-detail +- +- This directive is used to mark CPython-specific information. Use either with +- a block content or a single sentence as an argument, i.e. either :: +- +- .. impl-detail:: +- +- This describes some implementation detail. +- +- More explanation. +- +- or :: +- +- .. impl-detail:: This shortly mentions an implementation detail. +- +- "\ **CPython implementation detail:**\ " is automatically prepended to the +- content. +- +-.. describe:: seealso +- +- Many sections include a list of references to module documentation or +- external documents. These lists are created using the ``seealso`` directive. +- +- The ``seealso`` directive is typically placed in a section just before any +- sub-sections. For the HTML output, it is shown boxed off from the main flow +- of the text. +- +- The content of the ``seealso`` directive should be a reST definition list. +- Example:: +- +- .. seealso:: +- +- Module :mod:`zipfile` +- Documentation of the :mod:`zipfile` standard module. +- +- `GNU tar manual, Basic Tar Format `_ +- Documentation for tar archive files, including GNU tar extensions. +- +-.. describe:: rubric +- +- This directive creates a paragraph heading that is not used to create a +- table of contents node. It is currently used for the "Footnotes" caption. +- +-.. describe:: centered +- +- This directive creates a centered boldfaced paragraph. Use it as follows:: +- +- .. centered:: +- +- Paragraph contents. +- +- +-Table-of-contents markup +------------------------- +- +-Since reST does not have facilities to interconnect several documents, or split +-documents into multiple output files, Sphinx uses a custom directive to add +-relations between the single files the documentation is made of, as well as +-tables of contents. The ``toctree`` directive is the central element. +- +-.. describe:: toctree +- +- This directive inserts a "TOC tree" at the current location, using the +- individual TOCs (including "sub-TOC trees") of the files given in the +- directive body. A numeric ``maxdepth`` option may be given to indicate the +- depth of the tree; by default, all levels are included. +- +- Consider this example (taken from the library reference index):: +- +- .. toctree:: +- :maxdepth: 2 +- +- intro +- strings +- datatypes +- numeric +- (many more files listed here) +- +- This accomplishes two things: +- +- * Tables of contents from all those files are inserted, with a maximum depth +- of two, that means one nested heading. ``toctree`` directives in those +- files are also taken into account. +- * Sphinx knows that the relative order of the files ``intro``, +- ``strings`` and so forth, and it knows that they are children of the +- shown file, the library index. From this information it generates "next +- chapter", "previous chapter" and "parent chapter" links. +- +- In the end, all files included in the build process must occur in one +- ``toctree`` directive; Sphinx will emit a warning if it finds a file that is +- not included, because that means that this file will not be reachable through +- standard navigation. +- +- The special file ``contents.rst`` at the root of the source directory is the +- "root" of the TOC tree hierarchy; from it the "Contents" page is generated. +- +- +-Index-generating markup +------------------------ +- +-Sphinx automatically creates index entries from all information units (like +-functions, classes or attributes) like discussed before. +- +-However, there is also an explicit directive available, to make the index more +-comprehensive and enable index entries in documents where information is not +-mainly contained in information units, such as the language reference. +- +-The directive is ``index`` and contains one or more index entries. Each entry +-consists of a type and a value, separated by a colon. +- +-For example:: +- +- .. index:: +- single: execution; context +- module: __main__ +- module: sys +- triple: module; search; path +- +-This directive contains five entries, which will be converted to entries in the +-generated index which link to the exact location of the index statement (or, in +-case of offline media, the corresponding page number). +- +-The possible entry types are: +- +-single +- Creates a single index entry. Can be made a subentry by separating the +- subentry text with a semicolon (this notation is also used below to describe +- what entries are created). +-pair +- ``pair: loop; statement`` is a shortcut that creates two index entries, +- namely ``loop; statement`` and ``statement; loop``. +-triple +- Likewise, ``triple: module; search; path`` is a shortcut that creates three +- index entries, which are ``module; search path``, ``search; path, module`` and +- ``path; module search``. +-module, keyword, operator, object, exception, statement, builtin +- These all create two index entries. For example, ``module: hashlib`` creates +- the entries ``module; hashlib`` and ``hashlib; module``. +- +-For index directives containing only "single" entries, there is a shorthand +-notation:: +- +- .. index:: BNF, grammar, syntax, notation +- +-This creates four index entries. +- +- +-Grammar production displays +---------------------------- +- +-Special markup is available for displaying the productions of a formal grammar. +-The markup is simple and does not attempt to model all aspects of BNF (or any +-derived forms), but provides enough to allow context-free grammars to be +-displayed in a way that causes uses of a symbol to be rendered as hyperlinks to +-the definition of the symbol. There is this directive: +- +-.. describe:: productionlist +- +- This directive is used to enclose a group of productions. Each production is +- given on a single line and consists of a name, separated by a colon from the +- following definition. If the definition spans multiple lines, each +- continuation line must begin with a colon placed at the same column as in the +- first line. +- +- Blank lines are not allowed within ``productionlist`` directive arguments. +- +- The definition can contain token names which are marked as interpreted text +- (e.g. ``unaryneg ::= "-" `integer```) -- this generates cross-references +- to the productions of these tokens. +- +- Note that no further reST parsing is done in the production, so that you +- don't have to escape ``*`` or ``|`` characters. +- +- +-.. XXX describe optional first parameter +- +-The following is an example taken from the Python Reference Manual:: +- +- .. productionlist:: +- try_stmt: try1_stmt | try2_stmt +- try1_stmt: "try" ":" `suite` +- : ("except" [`expression` ["," `target`]] ":" `suite`)+ +- : ["else" ":" `suite`] +- : ["finally" ":" `suite`] +- try2_stmt: "try" ":" `suite` +- : "finally" ":" `suite` +- +- +-Substitutions +-------------- +- +-The documentation system provides three substitutions that are defined by default. +-They are set in the build configuration file :file:`conf.py`. +- +-.. describe:: |release| +- +- Replaced by the Python release the documentation refers to. This is the full +- version string including alpha/beta/release candidate tags, e.g. ``2.5.2b3``. +- +-.. describe:: |version| +- +- Replaced by the Python version the documentation refers to. This consists +- only of the major and minor version parts, e.g. ``2.5``, even for version +- 2.5.1. +- +-.. describe:: |today| +- +- Replaced by either today's date, or the date set in the build configuration +- file. Normally has the format ``April 14, 2007``. +- +- +-.. rubric:: Footnotes +- +-.. [1] There is a standard ``.. include`` directive, but it raises errors if the +- file is not found. This one only emits a warning. +diff -r 8527427914a2 Doc/documenting/rest.rst +--- a/Doc/documenting/rest.rst ++++ /dev/null +@@ -1,243 +0,0 @@ +-.. highlightlang:: rest +- +-reStructuredText Primer +-======================= +- +-This section is a brief introduction to reStructuredText (reST) concepts and +-syntax, intended to provide authors with enough information to author documents +-productively. Since reST was designed to be a simple, unobtrusive markup +-language, this will not take too long. +- +-.. seealso:: +- +- The authoritative `reStructuredText User +- Documentation `_. +- +- +-Paragraphs +----------- +- +-The paragraph is the most basic block in a reST document. Paragraphs are simply +-chunks of text separated by one or more blank lines. As in Python, indentation +-is significant in reST, so all lines of the same paragraph must be left-aligned +-to the same level of indentation. +- +- +-Inline markup +-------------- +- +-The standard reST inline markup is quite simple: use +- +-* one asterisk: ``*text*`` for emphasis (italics), +-* two asterisks: ``**text**`` for strong emphasis (boldface), and +-* backquotes: ````text```` for code samples. +- +-If asterisks or backquotes appear in running text and could be confused with +-inline markup delimiters, they have to be escaped with a backslash. +- +-Be aware of some restrictions of this markup: +- +-* it may not be nested, +-* content may not start or end with whitespace: ``* text*`` is wrong, +-* it must be separated from surrounding text by non-word characters. Use a +- backslash escaped space to work around that: ``thisis\ *one*\ word``. +- +-These restrictions may be lifted in future versions of the docutils. +- +-reST also allows for custom "interpreted text roles"', which signify that the +-enclosed text should be interpreted in a specific way. Sphinx uses this to +-provide semantic markup and cross-referencing of identifiers, as described in +-the appropriate section. The general syntax is ``:rolename:`content```. +- +- +-Lists and Quotes +----------------- +- +-List markup is natural: just place an asterisk at the start of a paragraph and +-indent properly. The same goes for numbered lists; they can also be +-autonumbered using a ``#`` sign:: +- +- * This is a bulleted list. +- * It has two items, the second +- item uses two lines. +- +- 1. This is a numbered list. +- 2. It has two items too. +- +- #. This is a numbered list. +- #. It has two items too. +- +- +-Nested lists are possible, but be aware that they must be separated from the +-parent list items by blank lines:: +- +- * this is +- * a list +- +- * with a nested list +- * and some subitems +- +- * and here the parent list continues +- +-Definition lists are created as follows:: +- +- term (up to a line of text) +- Definition of the term, which must be indented +- +- and can even consist of multiple paragraphs +- +- next term +- Description. +- +- +-Paragraphs are quoted by just indenting them more than the surrounding +-paragraphs. +- +- +-Source Code +------------ +- +-Literal code blocks are introduced by ending a paragraph with the special marker +-``::``. The literal block must be indented:: +- +- This is a normal text paragraph. The next paragraph is a code sample:: +- +- It is not processed in any way, except +- that the indentation is removed. +- +- It can span multiple lines. +- +- This is a normal text paragraph again. +- +-The handling of the ``::`` marker is smart: +- +-* If it occurs as a paragraph of its own, that paragraph is completely left +- out of the document. +-* If it is preceded by whitespace, the marker is removed. +-* If it is preceded by non-whitespace, the marker is replaced by a single +- colon. +- +-That way, the second sentence in the above example's first paragraph would be +-rendered as "The next paragraph is a code sample:". +- +- +-Hyperlinks +----------- +- +-External links +-^^^^^^^^^^^^^^ +- +-Use ```Link text `_`` for inline web links. If the link text +-should be the web address, you don't need special markup at all, the parser +-finds links and mail addresses in ordinary text. +- +-Internal links +-^^^^^^^^^^^^^^ +- +-Internal linking is done via a special reST role, see the section on specific +-markup, :ref:`doc-ref-role`. +- +- +-Sections +--------- +- +-Section headers are created by underlining (and optionally overlining) the +-section title with a punctuation character, at least as long as the text:: +- +- ================= +- This is a heading +- ================= +- +-Normally, there are no heading levels assigned to certain characters as the +-structure is determined from the succession of headings. However, for the +-Python documentation, we use this convention: +- +-* ``#`` with overline, for parts +-* ``*`` with overline, for chapters +-* ``=``, for sections +-* ``-``, for subsections +-* ``^``, for subsubsections +-* ``"``, for paragraphs +- +- +-Explicit Markup +---------------- +- +-"Explicit markup" is used in reST for most constructs that need special +-handling, such as footnotes, specially-highlighted paragraphs, comments, and +-generic directives. +- +-An explicit markup block begins with a line starting with ``..`` followed by +-whitespace and is terminated by the next paragraph at the same level of +-indentation. (There needs to be a blank line between explicit markup and normal +-paragraphs. This may all sound a bit complicated, but it is intuitive enough +-when you write it.) +- +- +-Directives +----------- +- +-A directive is a generic block of explicit markup. Besides roles, it is one of +-the extension mechanisms of reST, and Sphinx makes heavy use of it. +- +-Basically, a directive consists of a name, arguments, options and content. (Keep +-this terminology in mind, it is used in the next chapter describing custom +-directives.) Looking at this example, :: +- +- .. function:: foo(x) +- foo(y, z) +- :bar: no +- +- Return a line of text input from the user. +- +-``function`` is the directive name. It is given two arguments here, the +-remainder of the first line and the second line, as well as one option ``bar`` +-(as you can see, options are given in the lines immediately following the +-arguments and indicated by the colons). +- +-The directive content follows after a blank line and is indented relative to the +-directive start. +- +- +-Footnotes +---------- +- +-For footnotes, use ``[#]_`` to mark the footnote location, and add the footnote +-body at the bottom of the document after a "Footnotes" rubric heading, like so:: +- +- Lorem ipsum [#]_ dolor sit amet ... [#]_ +- +- .. rubric:: Footnotes +- +- .. [#] Text of the first footnote. +- .. [#] Text of the second footnote. +- +-You can also explicitly number the footnotes for better context. +- +- +-Comments +--------- +- +-Every explicit markup block which isn't a valid markup construct (like the +-footnotes above) is regarded as a comment. +- +- +-Source encoding +---------------- +- +-Since the easiest way to include special characters like em dashes or copyright +-signs in reST is to directly write them as Unicode characters, one has to +-specify an encoding: +- +-All Python documentation source files must be in UTF-8 encoding, and the HTML +-documents written from them will be in that encoding as well. +- +- +-Gotchas +-------- +- +-There are some problems one commonly runs into while authoring reST documents: +- +-* **Separation of inline markup:** As said above, inline markup spans must be +- separated from the surrounding text by non-word characters, you have to use +- an escaped space to get around that. +diff -r 8527427914a2 Doc/documenting/style.rst +--- a/Doc/documenting/style.rst ++++ /dev/null +@@ -1,174 +0,0 @@ +-.. highlightlang:: rest +- +-Style Guide +-=========== +- +-The Python documentation should follow the `Apple Publications Style Guide`_ +-wherever possible. This particular style guide was selected mostly because it +-seems reasonable and is easy to get online. +- +-Topics which are not covered in Apple's style guide will be discussed in +-this document. +- +-All reST files use an indentation of 3 spaces. The maximum line length is 80 +-characters for normal text, but tables, deeply indented code samples and long +-links may extend beyond that. +- +-Make generous use of blank lines where applicable; they help grouping things +-together. +- +-A sentence-ending period may be followed by one or two spaces; while reST +-ignores the second space, it is customarily put in by some users, for example +-to aid Emacs' auto-fill mode. +- +-Footnotes are generally discouraged, though they may be used when they are the +-best way to present specific information. When a footnote reference is added at +-the end of the sentence, it should follow the sentence-ending punctuation. The +-reST markup should appear something like this:: +- +- This sentence has a footnote reference. [#]_ This is the next sentence. +- +-Footnotes should be gathered at the end of a file, or if the file is very long, +-at the end of a section. The docutils will automatically create backlinks to +-the footnote reference. +- +-Footnotes may appear in the middle of sentences where appropriate. +- +-Many special names are used in the Python documentation, including the names of +-operating systems, programming languages, standards bodies, and the like. Most +-of these entities are not assigned any special markup, but the preferred +-spellings are given here to aid authors in maintaining the consistency of +-presentation in the Python documentation. +- +-Other terms and words deserve special mention as well; these conventions should +-be used to ensure consistency throughout the documentation: +- +-CPU +- For "central processing unit." Many style guides say this should be spelled +- out on the first use (and if you must use it, do so!). For the Python +- documentation, this abbreviation should be avoided since there's no +- reasonable way to predict which occurrence will be the first seen by the +- reader. It is better to use the word "processor" instead. +- +-POSIX +- The name assigned to a particular group of standards. This is always +- uppercase. +- +-Python +- The name of our favorite programming language is always capitalized. +- +-Unicode +- The name of a character set and matching encoding. This is always written +- capitalized. +- +-Unix +- The name of the operating system developed at AT&T Bell Labs in the early +- 1970s. +- +-Affirmative Tone +----------------- +- +-The documentation focuses on affirmatively stating what the language does and +-how to use it effectively. +- +-Except for certain security risks or segfault risks, the docs should avoid +-wording along the lines of "feature x is dangerous" or "experts only". These +-kinds of value judgments belong in external blogs and wikis, not in the core +-documentation. +- +-Bad example (creating worry in the mind of a reader): +- +- Warning: failing to explicitly close a file could result in lost data or +- excessive resource consumption. Never rely on reference counting to +- automatically close a file. +- +-Good example (establishing confident knowledge in the effective use of the language): +- +- A best practice for using files is use a try/finally pair to explicitly +- close a file after it is used. Alternatively, using a with-statement can +- achieve the same effect. This assures that files are flushed and file +- descriptor resources are released in a timely manner. +- +-Economy of Expression +---------------------- +- +-More documentation is not necessarily better documentation. Err on the side +-of being succinct. +- +-It is an unfortunate fact that making documentation longer can be an impediment +-to understanding and can result in even more ways to misread or misinterpret the +-text. Long descriptions full of corner cases and caveats can create the +-impression that a function is more complex or harder to use than it actually is. +- +-The documentation for :func:`super` is an example of where a good deal of +-information was condensed into a few short paragraphs. Discussion of +-:func:`super` could have filled a chapter in a book, but it is often easier to +-grasp a terse description than a lengthy narrative. +- +- +-Code Examples +-------------- +- +-Short code examples can be a useful adjunct to understanding. Readers can often +-grasp a simple example more quickly than they can digest a formal description in +-prose. +- +-People learn faster with concrete, motivating examples that match the context of +-a typical use case. For instance, the :func:`str.rpartition` method is better +-demonstrated with an example splitting the domain from a URL than it would be +-with an example of removing the last word from a line of Monty Python dialog. +- +-The ellipsis for the :attr:`sys.ps2` secondary interpreter prompt should only be +-used sparingly, where it is necessary to clearly differentiate between input +-lines and output lines. Besides contributing visual clutter, it makes it +-difficult for readers to cut-and-paste examples so they can experiment with +-variations. +- +-Code Equivalents +----------------- +- +-Giving pure Python code equivalents (or approximate equivalents) can be a useful +-adjunct to a prose description. A documenter should carefully weigh whether the +-code equivalent adds value. +- +-A good example is the code equivalent for :func:`all`. The short 4-line code +-equivalent is easily digested; it re-emphasizes the early-out behavior; and it +-clarifies the handling of the corner-case where the iterable is empty. In +-addition, it serves as a model for people wanting to implement a commonly +-requested alternative where :func:`all` would return the specific object +-evaluating to False whenever the function terminates early. +- +-A more questionable example is the code for :func:`itertools.groupby`. Its code +-equivalent borders on being too complex to be a quick aid to understanding. +-Despite its complexity, the code equivalent was kept because it serves as a +-model to alternative implementations and because the operation of the "grouper" +-is more easily shown in code than in English prose. +- +-An example of when not to use a code equivalent is for the :func:`oct` function. +-The exact steps in converting a number to octal doesn't add value for a user +-trying to learn what the function does. +- +-Audience +--------- +- +-The tone of the tutorial (and all the docs) needs to be respectful of the +-reader's intelligence. Don't presume that the readers are stupid. Lay out the +-relevant information, show motivating use cases, provide glossary links, and do +-your best to connect the dots, but don't talk down to them or waste their time. +- +-The tutorial is meant for newcomers, many of whom will be using the tutorial to +-evaluate the language as a whole. The experience needs to be positive and not +-leave the reader with worries that something bad will happen if they make a +-misstep. The tutorial serves as guide for intelligent and curious readers, +-saving details for the how-to guides and other sources. +- +-Be careful accepting requests for documentation changes from the rare but vocal +-category of reader who is looking for vindication for one of their programming +-errors ("I made a mistake, therefore the docs must be wrong ..."). Typically, +-the documentation wasn't consulted until after the error was made. It is +-unfortunate, but typically no documentation edit would have saved the user from +-making false assumptions about the language ("I was surprised by ..."). +- +- +-.. _Apple Publications Style Guide: http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/APStyleGuide/APSG_2009.pdf +- +diff -r 8527427914a2 Doc/extending/embedding.rst +--- a/Doc/extending/embedding.rst ++++ b/Doc/extending/embedding.rst +@@ -25,14 +25,14 @@ + + So if you are embedding Python, you are providing your own main program. One of + the things this main program has to do is initialize the Python interpreter. At +-the very least, you have to call the function :cfunc:`Py_Initialize`. There are ++the very least, you have to call the function :c:func:`Py_Initialize`. There are + optional calls to pass command line arguments to Python. Then later you can + call the interpreter from any part of the application. + + There are several different ways to call the interpreter: you can pass a string +-containing Python statements to :cfunc:`PyRun_SimpleString`, or you can pass a ++containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a + stdio file pointer and a file name (for identification in error messages only) +-to :cfunc:`PyRun_SimpleFile`. You can also call the lower-level operations ++to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations + described in the previous chapters to construct and use Python objects. + + A simple demo of embedding Python can be found in the directory +@@ -69,12 +69,12 @@ + } + + The above code first initializes the Python interpreter with +-:cfunc:`Py_Initialize`, followed by the execution of a hard-coded Python script +-that print the date and time. Afterwards, the :cfunc:`Py_Finalize` call shuts ++:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script ++that print the date and time. Afterwards, the :c:func:`Py_Finalize` call shuts + the interpreter down, followed by the end of the program. In a real program, + you may want to get the Python script from another source, perhaps a text-editor + routine, a file, or a database. Getting the Python code from a file can better +-be done by using the :cfunc:`PyRun_SimpleFile` function, which saves you the ++be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the + trouble of allocating memory space and loading the file contents. + + +@@ -162,8 +162,8 @@ + pModule = PyImport_Import(pName); + + After initializing the interpreter, the script is loaded using +-:cfunc:`PyImport_Import`. This routine needs a Python string as its argument, +-which is constructed using the :cfunc:`PyString_FromString` data conversion ++:c:func:`PyImport_Import`. This routine needs a Python string as its argument, ++which is constructed using the :c:func:`PyString_FromString` data conversion + routine. :: + + pFunc = PyObject_GetAttrString(pModule, argv[2]); +@@ -175,7 +175,7 @@ + Py_XDECREF(pFunc); + + Once the script is loaded, the name we're looking for is retrieved using +-:cfunc:`PyObject_GetAttrString`. If the name exists, and the object returned is ++:c:func:`PyObject_GetAttrString`. If the name exists, and the object returned is + callable, you can safely assume that it is a function. The program then + proceeds by constructing a tuple of arguments as normal. The call to the Python + function is then made with:: +@@ -218,8 +218,8 @@ + {NULL, NULL, 0, NULL} + }; + +-Insert the above code just above the :cfunc:`main` function. Also, insert the +-following two statements directly after :cfunc:`Py_Initialize`:: ++Insert the above code just above the :c:func:`main` function. Also, insert the ++following two statements directly after :c:func:`Py_Initialize`:: + + numargs = argc; + Py_InitModule("emb", EmbMethods); +diff -r 8527427914a2 Doc/extending/extending.rst +--- a/Doc/extending/extending.rst ++++ b/Doc/extending/extending.rst +@@ -35,7 +35,7 @@ + + Let's create an extension module called ``spam`` (the favorite food of Monty + Python fans...) and let's say we want to create a Python interface to the C +-library function :cfunc:`system`. [#]_ This function takes a null-terminated ++library function :c:func:`system`. [#]_ This function takes a null-terminated + character string as argument and returns an integer. We want this function to + be callable from Python as follows:: + +@@ -65,8 +65,8 @@ + since they are used extensively by the Python interpreter, ``"Python.h"`` + includes a few standard header files: ````, ````, + ````, and ````. If the latter header file does not exist on +-your system, it declares the functions :cfunc:`malloc`, :cfunc:`free` and +-:cfunc:`realloc` directly. ++your system, it declares the functions :c:func:`malloc`, :c:func:`free` and ++:c:func:`realloc` directly. + + The next thing we add to our module file is the C function that will be called + when the Python expression ``spam.system(string)`` is evaluated (we'll see +@@ -96,12 +96,12 @@ + arguments. Each item of the tuple corresponds to an argument in the call's + argument list. The arguments are Python objects --- in order to do anything + with them in our C function we have to convert them to C values. The function +-:cfunc:`PyArg_ParseTuple` in the Python API checks the argument types and ++:c:func:`PyArg_ParseTuple` in the Python API checks the argument types and + converts them to C values. It uses a template string to determine the required + types of the arguments as well as the types of the C variables into which to + store the converted values. More about this later. + +-:cfunc:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right ++:c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right + type and its components have been stored in the variables whose addresses are + passed. It returns false (zero) if an invalid argument list was passed. In the + latter case it also raises an appropriate exception so the calling function can +@@ -127,77 +127,77 @@ + + The Python API defines a number of functions to set various types of exceptions. + +-The most common one is :cfunc:`PyErr_SetString`. Its arguments are an exception ++The most common one is :c:func:`PyErr_SetString`. Its arguments are an exception + object and a C string. The exception object is usually a predefined object like +-:cdata:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error ++:c:data:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error + and is converted to a Python string object and stored as the "associated value" + of the exception. + +-Another useful function is :cfunc:`PyErr_SetFromErrno`, which only takes an ++Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an + exception argument and constructs the associated value by inspection of the +-global variable :cdata:`errno`. The most general function is +-:cfunc:`PyErr_SetObject`, which takes two object arguments, the exception and +-its associated value. You don't need to :cfunc:`Py_INCREF` the objects passed ++global variable :c:data:`errno`. The most general function is ++:c:func:`PyErr_SetObject`, which takes two object arguments, the exception and ++its associated value. You don't need to :c:func:`Py_INCREF` the objects passed + to any of these functions. + + You can test non-destructively whether an exception has been set with +-:cfunc:`PyErr_Occurred`. This returns the current exception object, or *NULL* ++:c:func:`PyErr_Occurred`. This returns the current exception object, or *NULL* + if no exception has occurred. You normally don't need to call +-:cfunc:`PyErr_Occurred` to see whether an error occurred in a function call, ++:c:func:`PyErr_Occurred` to see whether an error occurred in a function call, + since you should be able to tell from the return value. + + When a function *f* that calls another function *g* detects that the latter + fails, *f* should itself return an error value (usually *NULL* or ``-1``). It +-should *not* call one of the :cfunc:`PyErr_\*` functions --- one has already ++should *not* call one of the :c:func:`PyErr_\*` functions --- one has already + been called by *g*. *f*'s caller is then supposed to also return an error +-indication to *its* caller, again *without* calling :cfunc:`PyErr_\*`, and so on ++indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on + --- the most detailed cause of the error was already reported by the function + that first detected it. Once the error reaches the Python interpreter's main + loop, this aborts the currently executing Python code and tries to find an + exception handler specified by the Python programmer. + + (There are situations where a module can actually give a more detailed error +-message by calling another :cfunc:`PyErr_\*` function, and in such cases it is ++message by calling another :c:func:`PyErr_\*` function, and in such cases it is + fine to do so. As a general rule, however, this is not necessary, and can cause + information about the cause of the error to be lost: most operations can fail + for a variety of reasons.) + + To ignore an exception set by a function call that failed, the exception +-condition must be cleared explicitly by calling :cfunc:`PyErr_Clear`. The only +-time C code should call :cfunc:`PyErr_Clear` is if it doesn't want to pass the ++condition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The only ++time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the + error on to the interpreter but wants to handle it completely by itself + (possibly by trying something else, or pretending nothing went wrong). + +-Every failing :cfunc:`malloc` call must be turned into an exception --- the +-direct caller of :cfunc:`malloc` (or :cfunc:`realloc`) must call +-:cfunc:`PyErr_NoMemory` and return a failure indicator itself. All the +-object-creating functions (for example, :cfunc:`PyInt_FromLong`) already do +-this, so this note is only relevant to those who call :cfunc:`malloc` directly. ++Every failing :c:func:`malloc` call must be turned into an exception --- the ++direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call ++:c:func:`PyErr_NoMemory` and return a failure indicator itself. All the ++object-creating functions (for example, :c:func:`PyInt_FromLong`) already do ++this, so this note is only relevant to those who call :c:func:`malloc` directly. + +-Also note that, with the important exception of :cfunc:`PyArg_ParseTuple` and ++Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and + friends, functions that return an integer status usually return a positive value + or zero for success and ``-1`` for failure, like Unix system calls. + +-Finally, be careful to clean up garbage (by making :cfunc:`Py_XDECREF` or +-:cfunc:`Py_DECREF` calls for objects you have already created) when you return ++Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or ++:c:func:`Py_DECREF` calls for objects you have already created) when you return + an error indicator! + + The choice of which exception to raise is entirely yours. There are predeclared + C objects corresponding to all built-in Python exceptions, such as +-:cdata:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you +-should choose exceptions wisely --- don't use :cdata:`PyExc_TypeError` to mean +-that a file couldn't be opened (that should probably be :cdata:`PyExc_IOError`). +-If something's wrong with the argument list, the :cfunc:`PyArg_ParseTuple` +-function usually raises :cdata:`PyExc_TypeError`. If you have an argument whose ++:c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you ++should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean ++that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`). ++If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple` ++function usually raises :c:data:`PyExc_TypeError`. If you have an argument whose + value must be in a particular range or must satisfy other conditions, +-:cdata:`PyExc_ValueError` is appropriate. ++:c:data:`PyExc_ValueError` is appropriate. + + You can also define a new exception that is unique to your module. For this, you + usually declare a static object variable at the beginning of your file:: + + static PyObject *SpamError; + +-and initialize it in your module's initialization function (:cfunc:`initspam`) ++and initialize it in your module's initialization function (:c:func:`initspam`) + with an exception object (leaving out the error checking for now):: + + PyMODINIT_FUNC +@@ -215,14 +215,14 @@ + } + + Note that the Python name for the exception object is :exc:`spam.error`. The +-:cfunc:`PyErr_NewException` function may create a class with the base class ++:c:func:`PyErr_NewException` function may create a class with the base class + being :exc:`Exception` (unless another class is passed in instead of *NULL*), + described in :ref:`bltin-exceptions`. + +-Note also that the :cdata:`SpamError` variable retains a reference to the newly ++Note also that the :c:data:`SpamError` variable retains a reference to the newly + created exception class; this is intentional! Since the exception could be + removed from the module by external code, an owned reference to the class is +-needed to ensure that it will not be discarded, causing :cdata:`SpamError` to ++needed to ensure that it will not be discarded, causing :c:data:`SpamError` to + become a dangling pointer. Should it become a dangling pointer, C code which + raises the exception could cause a core dump or other unintended side effects. + +@@ -230,7 +230,7 @@ + sample. + + The :exc:`spam.error` exception can be raised in your extension module using a +-call to :cfunc:`PyErr_SetString` as shown below:: ++call to :c:func:`PyErr_SetString` as shown below:: + + static PyObject * + spam_system(PyObject *self, PyObject *args) +@@ -262,22 +262,22 @@ + + It returns *NULL* (the error indicator for functions returning object pointers) + if an error is detected in the argument list, relying on the exception set by +-:cfunc:`PyArg_ParseTuple`. Otherwise the string value of the argument has been +-copied to the local variable :cdata:`command`. This is a pointer assignment and ++:c:func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been ++copied to the local variable :c:data:`command`. This is a pointer assignment and + you are not supposed to modify the string to which it points (so in Standard C, +-the variable :cdata:`command` should properly be declared as ``const char ++the variable :c:data:`command` should properly be declared as ``const char + *command``). + +-The next statement is a call to the Unix function :cfunc:`system`, passing it +-the string we just got from :cfunc:`PyArg_ParseTuple`:: ++The next statement is a call to the Unix function :c:func:`system`, passing it ++the string we just got from :c:func:`PyArg_ParseTuple`:: + + sts = system(command); + +-Our :func:`spam.system` function must return the value of :cdata:`sts` as a +-Python object. This is done using the function :cfunc:`Py_BuildValue`, which is +-something like the inverse of :cfunc:`PyArg_ParseTuple`: it takes a format ++Our :func:`spam.system` function must return the value of :c:data:`sts` as a ++Python object. This is done using the function :c:func:`Py_BuildValue`, which is ++something like the inverse of :c:func:`PyArg_ParseTuple`: it takes a format + string and an arbitrary number of C values, and returns a new Python object. +-More info on :cfunc:`Py_BuildValue` is given later. :: ++More info on :c:func:`Py_BuildValue` is given later. :: + + return Py_BuildValue("i", sts); + +@@ -285,14 +285,14 @@ + on the heap in Python!) + + If you have a C function that returns no useful argument (a function returning +-:ctype:`void`), the corresponding Python function must return ``None``. You +-need this idiom to do so (which is implemented by the :cmacro:`Py_RETURN_NONE` ++:c:type:`void`), the corresponding Python function must return ``None``. You ++need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE` + macro):: + + Py_INCREF(Py_None); + return Py_None; + +-:cdata:`Py_None` is the C name for the special Python object ``None``. It is a ++:c:data:`Py_None` is the C name for the special Python object ``None``. It is a + genuine Python object rather than a *NULL* pointer, which means "error" in most + contexts, as we have seen. + +@@ -302,7 +302,7 @@ + The Module's Method Table and Initialization Function + ===================================================== + +-I promised to show how :cfunc:`spam_system` is called from Python programs. ++I promised to show how :c:func:`spam_system` is called from Python programs. + First, we need to list its name and address in a "method table":: + + static PyMethodDef SpamMethods[] = { +@@ -316,21 +316,21 @@ + Note the third entry (``METH_VARARGS``). This is a flag telling the interpreter + the calling convention to be used for the C function. It should normally always + be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means +-that an obsolete variant of :cfunc:`PyArg_ParseTuple` is used. ++that an obsolete variant of :c:func:`PyArg_ParseTuple` is used. + + When using only ``METH_VARARGS``, the function should expect the Python-level + parameters to be passed in as a tuple acceptable for parsing via +-:cfunc:`PyArg_ParseTuple`; more information on this function is provided below. ++:c:func:`PyArg_ParseTuple`; more information on this function is provided below. + + The :const:`METH_KEYWORDS` bit may be set in the third field if keyword + arguments should be passed to the function. In this case, the C function should + accept a third ``PyObject *`` parameter which will be a dictionary of keywords. +-Use :cfunc:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a ++Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a + function. + + The method table must be passed to the interpreter in the module's + initialization function. The initialization function must be named +-:cfunc:`initname`, where *name* is the name of the module, and should be the ++:c:func:`initname`, where *name* is the name of the module, and should be the + only non-\ ``static`` item defined in the module file:: + + PyMODINIT_FUNC +@@ -344,21 +344,21 @@ + declares the function as ``extern "C"``. + + When the Python program imports module :mod:`spam` for the first time, +-:cfunc:`initspam` is called. (See below for comments about embedding Python.) +-It calls :cfunc:`Py_InitModule`, which creates a "module object" (which is ++:c:func:`initspam` is called. (See below for comments about embedding Python.) ++It calls :c:func:`Py_InitModule`, which creates a "module object" (which is + inserted in the dictionary ``sys.modules`` under the key ``"spam"``), and + inserts built-in function objects into the newly created module based upon the +-table (an array of :ctype:`PyMethodDef` structures) that was passed as its +-second argument. :cfunc:`Py_InitModule` returns a pointer to the module object ++table (an array of :c:type:`PyMethodDef` structures) that was passed as its ++second argument. :c:func:`Py_InitModule` returns a pointer to the module object + that it creates (which is unused here). It may abort with a fatal error for + certain errors, or return *NULL* if the module could not be initialized + satisfactorily. + +-When embedding Python, the :cfunc:`initspam` function is not called +-automatically unless there's an entry in the :cdata:`_PyImport_Inittab` table. ++When embedding Python, the :c:func:`initspam` function is not called ++automatically unless there's an entry in the :c:data:`_PyImport_Inittab` table. + The easiest way to handle this is to statically initialize your +-statically-linked modules by directly calling :cfunc:`initspam` after the call +-to :cfunc:`Py_Initialize`:: ++statically-linked modules by directly calling :c:func:`initspam` after the call ++to :c:func:`Py_Initialize`:: + + int + main(int argc, char *argv[]) +@@ -378,12 +378,12 @@ + .. note:: + + Removing entries from ``sys.modules`` or importing compiled modules into +- multiple interpreters within a process (or following a :cfunc:`fork` without an +- intervening :cfunc:`exec`) can create problems for some extension modules. ++ multiple interpreters within a process (or following a :c:func:`fork` without an ++ intervening :c:func:`exec`) can create problems for some extension modules. + Extension module authors should exercise caution when initializing internal data + structures. Note also that the :func:`reload` function can be used with + extension modules, and will call the module initialization function +- (:cfunc:`initspam` in the example), but will not load the module again if it was ++ (:c:func:`initspam` in the example), but will not load the module again if it was + loaded from a dynamically loadable object file (:file:`.so` on Unix, + :file:`.dll` on Windows). + +@@ -447,7 +447,7 @@ + Calling a Python function is easy. First, the Python program must somehow pass + you the Python function object. You should provide a function (or some other + interface) to do this. When this function is called, save a pointer to the +-Python function object (be careful to :cfunc:`Py_INCREF` it!) in a global ++Python function object (be careful to :c:func:`Py_INCREF` it!) in a global + variable --- or wherever you see fit. For example, the following function might + be part of a module definition:: + +@@ -476,10 +476,10 @@ + + This function must be registered with the interpreter using the + :const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The +-:cfunc:`PyArg_ParseTuple` function and its arguments are documented in section ++:c:func:`PyArg_ParseTuple` function and its arguments are documented in section + :ref:`parsetuple`. + +-The macros :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF` increment/decrement the ++The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the + reference count of an object and are safe in the presence of *NULL* pointers + (but note that *temp* will not be *NULL* in this context). More info on them + in section :ref:`refcounts`. +@@ -487,12 +487,12 @@ + .. index:: single: PyObject_CallObject() + + Later, when it is time to call the function, you call the C function +-:cfunc:`PyObject_CallObject`. This function has two arguments, both pointers to ++:c:func:`PyObject_CallObject`. This function has two arguments, both pointers to + arbitrary Python objects: the Python function, and the argument list. The + argument list must always be a tuple object, whose length is the number of + arguments. To call the Python function with no arguments, pass in NULL, or + an empty tuple; to call it with one argument, pass a singleton tuple. +-:cfunc:`Py_BuildValue` returns a tuple when its format string consists of zero ++:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero + or more format codes between parentheses. For example:: + + int arg; +@@ -506,25 +506,25 @@ + result = PyObject_CallObject(my_callback, arglist); + Py_DECREF(arglist); + +-:cfunc:`PyObject_CallObject` returns a Python object pointer: this is the return +-value of the Python function. :cfunc:`PyObject_CallObject` is ++:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return ++value of the Python function. :c:func:`PyObject_CallObject` is + "reference-count-neutral" with respect to its arguments. In the example a new +-tuple was created to serve as the argument list, which is :cfunc:`Py_DECREF`\ ++tuple was created to serve as the argument list, which is :c:func:`Py_DECREF`\ + -ed immediately after the call. + +-The return value of :cfunc:`PyObject_CallObject` is "new": either it is a brand ++The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand + new object, or it is an existing object whose reference count has been + incremented. So, unless you want to save it in a global variable, you should +-somehow :cfunc:`Py_DECREF` the result, even (especially!) if you are not ++somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not + interested in its value. + + Before you do this, however, it is important to check that the return value + isn't *NULL*. If it is, the Python function terminated by raising an exception. +-If the C code that called :cfunc:`PyObject_CallObject` is called from Python, it ++If the C code that called :c:func:`PyObject_CallObject` is called from Python, it + should now return an error indication to its Python caller, so the interpreter + can print a stack trace, or the calling Python code can handle the exception. + If this is not possible or desirable, the exception should be cleared by calling +-:cfunc:`PyErr_Clear`. For example:: ++:c:func:`PyErr_Clear`. For example:: + + if (result == NULL) + return NULL; /* Pass error back */ +@@ -532,12 +532,12 @@ + Py_DECREF(result); + + Depending on the desired interface to the Python callback function, you may also +-have to provide an argument list to :cfunc:`PyObject_CallObject`. In some cases ++have to provide an argument list to :c:func:`PyObject_CallObject`. In some cases + the argument list is also provided by the Python program, through the same + interface that specified the callback function. It can then be saved and used + in the same manner as the function object. In other cases, you may have to + construct a new tuple to pass as the argument list. The simplest way to do this +-is to call :cfunc:`Py_BuildValue`. For example, if you want to pass an integral ++is to call :c:func:`Py_BuildValue`. For example, if you want to pass an integral + event code, you might use the following code:: + + PyObject *arglist; +@@ -552,11 +552,11 @@ + + Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before + the error check! Also note that strictly speaking this code is not complete: +-:cfunc:`Py_BuildValue` may run out of memory, and this should be checked. ++:c:func:`Py_BuildValue` may run out of memory, and this should be checked. + + You may also call a function with keyword arguments by using +-:cfunc:`PyObject_Call`, which supports arguments and keyword arguments. As in +-the above example, we use :cfunc:`Py_BuildValue` to construct the dictionary. :: ++:c:func:`PyObject_Call`, which supports arguments and keyword arguments. As in ++the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. :: + + PyObject *dict; + ... +@@ -576,7 +576,7 @@ + + .. index:: single: PyArg_ParseTuple() + +-The :cfunc:`PyArg_ParseTuple` function is declared as follows:: ++The :c:func:`PyArg_ParseTuple` function is declared as follows:: + + int PyArg_ParseTuple(PyObject *arg, char *format, ...); + +@@ -586,7 +586,7 @@ + Manual. The remaining arguments must be addresses of variables whose type is + determined by the format string. + +-Note that while :cfunc:`PyArg_ParseTuple` checks that the Python arguments have ++Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have + the required types, it cannot check the validity of the addresses of C variables + passed to the call: if you make mistakes there, your code will probably crash or + at least overwrite random bits in memory. So be careful! +@@ -663,17 +663,17 @@ + + .. index:: single: PyArg_ParseTupleAndKeywords() + +-The :cfunc:`PyArg_ParseTupleAndKeywords` function is declared as follows:: ++The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows:: + + int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, + char *format, char *kwlist[], ...); + + The *arg* and *format* parameters are identical to those of the +-:cfunc:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of ++:c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of + keywords received as the third parameter from the Python runtime. The *kwlist* + parameter is a *NULL*-terminated list of strings which identify the parameters; + the names are matched with the type information from *format* from left to +-right. On success, :cfunc:`PyArg_ParseTupleAndKeywords` returns true, otherwise ++right. On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise + it returns false and raises an appropriate exception. + + .. note:: +@@ -737,19 +737,19 @@ + Building Arbitrary Values + ========================= + +-This function is the counterpart to :cfunc:`PyArg_ParseTuple`. It is declared ++This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is declared + as follows:: + + PyObject *Py_BuildValue(char *format, ...); + + It recognizes a set of format units similar to the ones recognized by +-:cfunc:`PyArg_ParseTuple`, but the arguments (which are input to the function, ++:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function, + not output) must not be pointers, just values. It returns a new Python object, + suitable for returning from a C function called from Python. + +-One difference with :cfunc:`PyArg_ParseTuple`: while the latter requires its ++One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its + first argument to be a tuple (since Python argument lists are always represented +-as tuples internally), :cfunc:`Py_BuildValue` does not always build a tuple. It ++as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple. It + builds a tuple only if its format string contains two or more format units. If + the format string is empty, it returns ``None``; if it contains exactly one + format unit, it returns whatever object is described by that format unit. To +@@ -781,18 +781,18 @@ + + In languages like C or C++, the programmer is responsible for dynamic allocation + and deallocation of memory on the heap. In C, this is done using the functions +-:cfunc:`malloc` and :cfunc:`free`. In C++, the operators ``new`` and ++:c:func:`malloc` and :c:func:`free`. In C++, the operators ``new`` and + ``delete`` are used with essentially the same meaning and we'll restrict + the following discussion to the C case. + +-Every block of memory allocated with :cfunc:`malloc` should eventually be +-returned to the pool of available memory by exactly one call to :cfunc:`free`. +-It is important to call :cfunc:`free` at the right time. If a block's address +-is forgotten but :cfunc:`free` is not called for it, the memory it occupies ++Every block of memory allocated with :c:func:`malloc` should eventually be ++returned to the pool of available memory by exactly one call to :c:func:`free`. ++It is important to call :c:func:`free` at the right time. If a block's address ++is forgotten but :c:func:`free` is not called for it, the memory it occupies + cannot be reused until the program terminates. This is called a :dfn:`memory +-leak`. On the other hand, if a program calls :cfunc:`free` for a block and then ++leak`. On the other hand, if a program calls :c:func:`free` for a block and then + continues to use the block, it creates a conflict with re-use of the block +-through another :cfunc:`malloc` call. This is called :dfn:`using freed memory`. ++through another :c:func:`malloc` call. This is called :dfn:`using freed memory`. + It has the same bad consequences as referencing uninitialized data --- core + dumps, wrong results, mysterious crashes. + +@@ -809,7 +809,7 @@ + important to prevent leaks from happening by having a coding convention or + strategy that minimizes this kind of errors. + +-Since Python makes heavy use of :cfunc:`malloc` and :cfunc:`free`, it needs a ++Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a + strategy to avoid memory leaks as well as the use of freed memory. The chosen + method is called :dfn:`reference counting`. The principle is simple: every + object contains a counter, which is incremented when a reference to the object +@@ -821,11 +821,11 @@ + (Sometimes, reference counting is also referred to as a garbage collection + strategy, hence my use of "automatic" to distinguish the two.) The big + advantage of automatic garbage collection is that the user doesn't need to call +-:cfunc:`free` explicitly. (Another claimed advantage is an improvement in speed ++:c:func:`free` explicitly. (Another claimed advantage is an improvement in speed + or memory usage --- this is no hard fact however.) The disadvantage is that for + C, there is no truly portable automatic garbage collector, while reference +-counting can be implemented portably (as long as the functions :cfunc:`malloc` +-and :cfunc:`free` are available --- which the C Standard guarantees). Maybe some ++counting can be implemented portably (as long as the functions :c:func:`malloc` ++and :c:func:`free` are available --- which the C Standard guarantees). Maybe some + day a sufficiently portable automatic garbage collector will be available for C. + Until then, we'll have to live with reference counts. + +@@ -861,9 +861,9 @@ + ---------------------------- + + There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the +-incrementing and decrementing of the reference count. :cfunc:`Py_DECREF` also ++incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also + frees the object when the count reaches zero. For flexibility, it doesn't call +-:cfunc:`free` directly --- rather, it makes a call through a function pointer in ++:c:func:`free` directly --- rather, it makes a call through a function pointer in + the object's :dfn:`type object`. For this purpose (and others), every object + also contains a pointer to its type object. + +@@ -871,13 +871,13 @@ + Let's first introduce some terms. Nobody "owns" an object; however, you can + :dfn:`own a reference` to an object. An object's reference count is now defined + as the number of owned references to it. The owner of a reference is +-responsible for calling :cfunc:`Py_DECREF` when the reference is no longer ++responsible for calling :c:func:`Py_DECREF` when the reference is no longer + needed. Ownership of a reference can be transferred. There are three ways to +-dispose of an owned reference: pass it on, store it, or call :cfunc:`Py_DECREF`. ++dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`. + Forgetting to dispose of an owned reference creates a memory leak. + + It is also possible to :dfn:`borrow` [#]_ a reference to an object. The +-borrower of a reference should not call :cfunc:`Py_DECREF`. The borrower must ++borrower of a reference should not call :c:func:`Py_DECREF`. The borrower must + not hold on to the object longer than the owner from which it was borrowed. + Using a borrowed reference after the owner has disposed of it risks using freed + memory and should be avoided completely. [#]_ +@@ -891,7 +891,7 @@ + disposed of it. + + A borrowed reference can be changed into an owned reference by calling +-:cfunc:`Py_INCREF`. This does not affect the status of the owner from which the ++:c:func:`Py_INCREF`. This does not affect the status of the owner from which the + reference was borrowed --- it creates a new owned reference, and gives full + owner responsibilities (the new owner must dispose of the reference properly, as + well as the previous owner). +@@ -908,36 +908,36 @@ + + Most functions that return a reference to an object pass on ownership with the + reference. In particular, all functions whose function it is to create a new +-object, such as :cfunc:`PyInt_FromLong` and :cfunc:`Py_BuildValue`, pass ++object, such as :c:func:`PyInt_FromLong` and :c:func:`Py_BuildValue`, pass + ownership to the receiver. Even if the object is not actually new, you still + receive ownership of a new reference to that object. For instance, +-:cfunc:`PyInt_FromLong` maintains a cache of popular values and can return a ++:c:func:`PyInt_FromLong` maintains a cache of popular values and can return a + reference to a cached item. + + Many functions that extract objects from other objects also transfer ownership +-with the reference, for instance :cfunc:`PyObject_GetAttrString`. The picture ++with the reference, for instance :c:func:`PyObject_GetAttrString`. The picture + is less clear, here, however, since a few common routines are exceptions: +-:cfunc:`PyTuple_GetItem`, :cfunc:`PyList_GetItem`, :cfunc:`PyDict_GetItem`, and +-:cfunc:`PyDict_GetItemString` all return references that you borrow from the ++:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and ++:c:func:`PyDict_GetItemString` all return references that you borrow from the + tuple, list or dictionary. + +-The function :cfunc:`PyImport_AddModule` also returns a borrowed reference, even ++The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even + though it may actually create the object it returns: this is possible because an + owned reference to the object is stored in ``sys.modules``. + + When you pass an object reference into another function, in general, the + function borrows the reference from you --- if it needs to store it, it will use +-:cfunc:`Py_INCREF` to become an independent owner. There are exactly two +-important exceptions to this rule: :cfunc:`PyTuple_SetItem` and +-:cfunc:`PyList_SetItem`. These functions take over ownership of the item passed +-to them --- even if they fail! (Note that :cfunc:`PyDict_SetItem` and friends ++:c:func:`Py_INCREF` to become an independent owner. There are exactly two ++important exceptions to this rule: :c:func:`PyTuple_SetItem` and ++:c:func:`PyList_SetItem`. These functions take over ownership of the item passed ++to them --- even if they fail! (Note that :c:func:`PyDict_SetItem` and friends + don't take over ownership --- they are "normal.") + + When a C function is called from Python, it borrows references to its arguments + from the caller. The caller owns a reference to the object, so the borrowed + reference's lifetime is guaranteed until the function returns. Only when such a + borrowed reference must be stored or passed on, it must be turned into an owned +-reference by calling :cfunc:`Py_INCREF`. ++reference by calling :c:func:`Py_INCREF`. + + The object reference returned from a C function that is called from Python must + be an owned reference --- ownership is transferred from the function to its +@@ -953,7 +953,7 @@ + can lead to problems. These all have to do with implicit invocations of the + interpreter, which can cause the owner of a reference to dispose of it. + +-The first and most important case to know about is using :cfunc:`Py_DECREF` on ++The first and most important case to know about is using :c:func:`Py_DECREF` on + an unrelated object while borrowing a reference to a list item. For instance:: + + void +@@ -969,7 +969,7 @@ + ``list[1]`` with the value ``0``, and finally prints the borrowed reference. + Looks harmless, right? But it's not! + +-Let's follow the control flow into :cfunc:`PyList_SetItem`. The list owns ++Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns + references to all its items, so when item 1 is replaced, it has to dispose of + the original item 1. Now let's suppose the original item 1 was an instance of a + user-defined class, and let's further suppose that the class defined a +@@ -978,8 +978,8 @@ + + Since it is written in Python, the :meth:`__del__` method can execute arbitrary + Python code. Could it perhaps do something to invalidate the reference to +-``item`` in :cfunc:`bug`? You bet! Assuming that the list passed into +-:cfunc:`bug` is accessible to the :meth:`__del__` method, it could execute a ++``item`` in :c:func:`bug`? You bet! Assuming that the list passed into ++:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a + statement to the effect of ``del list[0]``, and assuming this was the last + reference to that object, it would free the memory associated with it, thereby + invalidating ``item``. +@@ -1006,8 +1006,8 @@ + threads. Normally, multiple threads in the Python interpreter can't get in each + other's way, because there is a global lock protecting Python's entire object + space. However, it is possible to temporarily release this lock using the macro +-:cmacro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using +-:cmacro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to ++:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using ++:c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to + let other threads use the processor while waiting for the I/O to complete. + Obviously, the following function has the same problem as the previous one:: + +@@ -1036,11 +1036,11 @@ + redundant tests and the code would run more slowly. + + It is better to test for *NULL* only at the "source:" when a pointer that may be +-*NULL* is received, for example, from :cfunc:`malloc` or from a function that ++*NULL* is received, for example, from :c:func:`malloc` or from a function that + may raise an exception. + +-The macros :cfunc:`Py_INCREF` and :cfunc:`Py_DECREF` do not check for *NULL* +-pointers --- however, their variants :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF` ++The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for *NULL* ++pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` + do. + + The macros for checking for a particular object type (``Pytype_Check()``) don't +@@ -1114,7 +1114,7 @@ + + Python provides a special mechanism to pass C-level information (pointers) from + one extension module to another one: Capsules. A Capsule is a Python data type +-which stores a pointer (:ctype:`void \*`). Capsules can only be created and ++which stores a pointer (:c:type:`void \*`). Capsules can only be created and + accessed via their C API, but they can be passed around like any other Python + object. In particular, they can be assigned to a name in an extension module's + namespace. Other extension modules can then import this module, retrieve the +@@ -1127,8 +1127,8 @@ + different ways between the module providing the code and the client modules. + + Whichever method you choose, it's important to name your Capsules properly. +-The function :cfunc:`PyCapsule_New` takes a name parameter +-(:ctype:`const char \*`); you're permitted to pass in a *NULL* name, but ++The function :c:func:`PyCapsule_New` takes a name parameter ++(:c:type:`const char \*`); you're permitted to pass in a *NULL* name, but + we strongly encourage you to specify a name. Properly named Capsules provide + a degree of runtime type-safety; there is no feasible way to tell one unnamed + Capsule from another. +@@ -1138,7 +1138,7 @@ + + modulename.attributename + +-The convenience function :cfunc:`PyCapsule_Import` makes it easy to ++The convenience function :c:func:`PyCapsule_Import` makes it easy to + load a C API provided via a Capsule, but only if the Capsule's name + matches this convention. This behavior gives C API users a high degree + of certainty that the Capsule they load contains the correct C API. +@@ -1146,19 +1146,19 @@ + The following example demonstrates an approach that puts most of the burden on + the writer of the exporting module, which is appropriate for commonly used + library modules. It stores all C API pointers (just one in the example!) in an +-array of :ctype:`void` pointers which becomes the value of a Capsule. The header ++array of :c:type:`void` pointers which becomes the value of a Capsule. The header + file corresponding to the module provides a macro that takes care of importing + the module and retrieving its C API pointers; client modules only have to call + this macro before accessing the C API. + + The exporting module is a modification of the :mod:`spam` module from section + :ref:`extending-simpleexample`. The function :func:`spam.system` does not call +-the C library function :cfunc:`system` directly, but a function +-:cfunc:`PySpam_System`, which would of course do something more complicated in ++the C library function :c:func:`system` directly, but a function ++:c:func:`PySpam_System`, which would of course do something more complicated in + reality (such as adding "spam" to every command). This function +-:cfunc:`PySpam_System` is also exported to other extension modules. ++:c:func:`PySpam_System` is also exported to other extension modules. + +-The function :cfunc:`PySpam_System` is a plain C function, declared ++The function :c:func:`PySpam_System` is a plain C function, declared + ``static`` like everything else:: + + static int +@@ -1167,7 +1167,7 @@ + return system(command); + } + +-The function :cfunc:`spam_system` is modified in a trivial way:: ++The function :c:func:`spam_system` is modified in a trivial way:: + + static PyObject * + spam_system(PyObject *self, PyObject *args) +@@ -1270,8 +1270,8 @@ + #endif /* !defined(Py_SPAMMODULE_H) */ + + All that a client module must do in order to have access to the function +-:cfunc:`PySpam_System` is to call the function (or rather macro) +-:cfunc:`import_spam` in its initialization function:: ++:c:func:`PySpam_System` is to call the function (or rather macro) ++:c:func:`import_spam` in its initialization function:: + + PyMODINIT_FUNC + initclient(void) +diff -r 8527427914a2 Doc/extending/newtypes.rst +--- a/Doc/extending/newtypes.rst ++++ b/Doc/extending/newtypes.rst +@@ -34,12 +34,11 @@ + ========== + + The Python runtime sees all Python objects as variables of type +-:ctype:`PyObject\*`. A :ctype:`PyObject` is not a very magnificent object - it ++:c:type:`PyObject\*`. A :c:type:`PyObject` is not a very magnificent object - it + just contains the refcount and a pointer to the object's "type object". This is + where the action is; the type object determines which (C) functions get called + when, for instance, an attribute gets looked up on an object or it is multiplied +-by another object. These C functions are called "type methods" to distinguish +-them from things like ``[].append`` (which we call "object methods"). ++by another object. These C functions are called "type methods". + + So, if you want to define a new object type, you need to create a new type + object. +@@ -104,7 +103,7 @@ + "Noddy objects", /* tp_doc */ + }; + +-Now if you go and look up the definition of :ctype:`PyTypeObject` in ++Now if you go and look up the definition of :c:type:`PyTypeObject` in + :file:`object.h` you'll see that it has many more fields that the definition + above. The remaining fields will be filled with zeros by the C compiler, and + it's common practice to not specify them explicitly unless you need them. +@@ -120,7 +119,7 @@ + + as the type of a type object is "type", but this isn't strictly conforming C and + some compilers complain. Fortunately, this member will be filled in for us by +-:cfunc:`PyType_Ready`. :: ++:c:func:`PyType_Ready`. :: + + 0, /* ob_size */ + +@@ -146,7 +145,7 @@ + sizeof(noddy_NoddyObject), /* tp_basicsize */ + + This is so that Python knows how much memory to allocate when you call +-:cfunc:`PyObject_New`. ++:c:func:`PyObject_New`. + + .. note:: + +@@ -186,12 +185,12 @@ + For now, all we want to be able to do is to create new :class:`Noddy` objects. + To enable object creation, we have to provide a :attr:`tp_new` implementation. + In this case, we can just use the default implementation provided by the API +-function :cfunc:`PyType_GenericNew`. We'd like to just assign this to the ++function :c:func:`PyType_GenericNew`. We'd like to just assign this to the + :attr:`tp_new` slot, but we can't, for portability sake, On some platforms or + compilers, we can't statically initialize a structure member with a function + defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot + in the module initialization function just before calling +-:cfunc:`PyType_Ready`:: ++:c:func:`PyType_Ready`:: + + noddy_NoddyType.tp_new = PyType_GenericNew; + if (PyType_Ready(&noddy_NoddyType) < 0) +@@ -201,7 +200,7 @@ + for a later section! + + Everything else in the file should be familiar, except for some code in +-:cfunc:`initnoddy`:: ++:c:func:`initnoddy`:: + + if (PyType_Ready(&noddy_NoddyType) < 0) + return; +@@ -289,7 +288,7 @@ + (destructor)Noddy_dealloc, /*tp_dealloc*/ + + This method decrements the reference counts of the two Python attributes. We use +-:cfunc:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members ++:c:func:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members + could be *NULL*. It then calls the :attr:`tp_free` member of the object's type + to free the object's memory. Note that the object's type might not be + :class:`NoddyType`, because the object may be an instance of a subclass. +@@ -335,8 +334,8 @@ + the initial values of instance variables. In this case, we use the new method + to make sure that the initial values of the members :attr:`first` and + :attr:`last` are not *NULL*. If we didn't care whether the initial values were +-*NULL*, we could have used :cfunc:`PyType_GenericNew` as our new method, as we +-did before. :cfunc:`PyType_GenericNew` initializes all of the instance variable ++*NULL*, we could have used :c:func:`PyType_GenericNew` as our new method, as we ++did before. :c:func:`PyType_GenericNew` initializes all of the instance variable + members to *NULL*. + + The new method is a static method that is passed the type being instantiated and +@@ -346,7 +345,7 @@ + methods. Note that if the type supports subclassing, the type passed may not be + the type being defined. The new method calls the tp_alloc slot to allocate + memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather +-:cfunc:`PyType_Ready` fills it for us by inheriting it from our base class, ++:c:func:`PyType_Ready` fills it for us by inheriting it from our base class, + which is :class:`object` by default. Most types use the default allocation. + + .. note:: +@@ -531,8 +530,8 @@ + + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + +-We rename :cfunc:`initnoddy` to :cfunc:`initnoddy2` and update the module name +-passed to :cfunc:`Py_InitModule3`. ++We rename :c:func:`initnoddy` to :c:func:`initnoddy2` and update the module name ++passed to :c:func:`Py_InitModule3`. + + Finally, we update our :file:`setup.py` file to build the new module:: + +@@ -598,7 +597,7 @@ + deleted. In our setter, we raise an error if the attribute is deleted or if the + attribute value is not a string. + +-We create an array of :ctype:`PyGetSetDef` structures:: ++We create an array of :c:type:`PyGetSetDef` structures:: + + static PyGetSetDef Noddy_getseters[] = { + {"first", +@@ -618,7 +617,7 @@ + + to register our attribute getters and setters. + +-The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned ++The last item in a :c:type:`PyGetSetDef` structure is the closure mentioned + above. In this case, we aren't using the closure, so we just pass *NULL*. + + We also remove the member definitions for these attributes:: +@@ -663,8 +662,8 @@ + + With these changes, we can assure that the :attr:`first` and :attr:`last` + members are never *NULL* so we can remove checks for *NULL* values in almost all +-cases. This means that most of the :cfunc:`Py_XDECREF` calls can be converted to +-:cfunc:`Py_DECREF` calls. The only place we can't change these calls is in the ++cases. This means that most of the :c:func:`Py_XDECREF` calls can be converted to ++:c:func:`Py_DECREF` calls. The only place we can't change these calls is in the + deallocator, where there is the possibility that the initialization of these + members failed in the constructor. + +@@ -729,13 +728,13 @@ + } + + For each subobject that can participate in cycles, we need to call the +-:cfunc:`visit` function, which is passed to the traversal method. The +-:cfunc:`visit` function takes as arguments the subobject and the extra argument ++:c:func:`visit` function, which is passed to the traversal method. The ++:c:func:`visit` function takes as arguments the subobject and the extra argument + *arg* passed to the traversal method. It returns an integer value that must be + returned if it is non-zero. + +-Python 2.4 and higher provide a :cfunc:`Py_VISIT` macro that automates calling +-visit functions. With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be ++Python 2.4 and higher provide a :c:func:`Py_VISIT` macro that automates calling ++visit functions. With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be + simplified:: + + static int +@@ -749,7 +748,7 @@ + .. note:: + + Note that the :attr:`tp_traverse` implementation must name its arguments exactly +- *visit* and *arg* in order to use :cfunc:`Py_VISIT`. This is to encourage ++ *visit* and *arg* in order to use :c:func:`Py_VISIT`. This is to encourage + uniformity across these boring implementations. + + We also need to provide a method for clearing any subobjects that can +@@ -779,19 +778,19 @@ + self->ob_type->tp_free((PyObject*)self); + } + +-Notice the use of a temporary variable in :cfunc:`Noddy_clear`. We use the ++Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the + temporary variable so that we can set each member to *NULL* before decrementing + its reference count. We do this because, as was discussed earlier, if the + reference count drops to zero, we might cause code to run that calls back into + the object. In addition, because we now support garbage collection, we also + have to worry about code being run that triggers garbage collection. If garbage + collection is run, our :attr:`tp_traverse` handler could get called. We can't +-take a chance of having :cfunc:`Noddy_traverse` called when a member's reference ++take a chance of having :c:func:`Noddy_traverse` called when a member's reference + count has dropped to zero and its value hasn't been set to *NULL*. + +-Python 2.4 and higher provide a :cfunc:`Py_CLEAR` that automates the careful +-decrementing of reference counts. With :cfunc:`Py_CLEAR`, the +-:cfunc:`Noddy_clear` function can be simplified:: ++Python 2.4 and higher provide a :c:func:`Py_CLEAR` that automates the careful ++decrementing of reference counts. With :c:func:`Py_CLEAR`, the ++:c:func:`Noddy_clear` function can be simplified:: + + static int + Noddy_clear(Noddy *self) +@@ -846,7 +845,7 @@ + + The primary difference for derived type objects is that the base type's object + structure must be the first value. The base type will already include the +-:cfunc:`PyObject_HEAD` at the beginning of its structure. ++:c:func:`PyObject_HEAD` at the beginning of its structure. + + When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can + be safely cast to both *PyListObject\** and *Shoddy\**. :: +@@ -868,10 +867,10 @@ + memory for the object with :attr:`tp_alloc`, that will be handled by the base + class when calling its :attr:`tp_new`. + +-When filling out the :cfunc:`PyTypeObject` for the :class:`Shoddy` type, you see +-a slot for :cfunc:`tp_base`. Due to cross platform compiler issues, you can't +-fill that field directly with the :cfunc:`PyList_Type`; it can be done later in +-the module's :cfunc:`init` function. :: ++When filling out the :c:func:`PyTypeObject` for the :class:`Shoddy` type, you see ++a slot for :c:func:`tp_base`. Due to cross platform compiler issues, you can't ++fill that field directly with the :c:func:`PyList_Type`; it can be done later in ++the module's :c:func:`init` function. :: + + PyMODINIT_FUNC + initshoddy(void) +@@ -890,12 +889,12 @@ + PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType); + } + +-Before calling :cfunc:`PyType_Ready`, the type structure must have the ++Before calling :c:func:`PyType_Ready`, the type structure must have the + :attr:`tp_base` slot filled in. When we are deriving a new type, it is not +-necessary to fill out the :attr:`tp_alloc` slot with :cfunc:`PyType_GenericNew` ++necessary to fill out the :attr:`tp_alloc` slot with :c:func:`PyType_GenericNew` + -- the allocate function from the base type will be inherited. + +-After that, calling :cfunc:`PyType_Ready` and adding the type object to the ++After that, calling :c:func:`PyType_Ready` and adding the type object to the + module is the same as with the basic :class:`Noddy` examples. + + +@@ -907,7 +906,7 @@ + This section aims to give a quick fly-by on the various type methods you can + implement and what they do. + +-Here is the definition of :ctype:`PyTypeObject`, with some fields only used in ++Here is the definition of :c:type:`PyTypeObject`, with some fields only used in + debug builds omitted: + + .. literalinclude:: ../includes/typestruct.h +@@ -985,8 +984,8 @@ + executed may detect that an exception has been set. This can lead to misleading + errors from the interpreter. The proper way to protect against this is to save + a pending exception before performing the unsafe action, and restoring it when +-done. This can be done using the :cfunc:`PyErr_Fetch` and +-:cfunc:`PyErr_Restore` functions:: ++done. This can be done using the :c:func:`PyErr_Fetch` and ++:c:func:`PyErr_Restore` functions:: + + static void + my_dealloc(PyObject *obj) +@@ -1027,7 +1026,7 @@ + object: the :func:`repr` function (or equivalent back-tick syntax), the + :func:`str` function, and the :keyword:`print` statement. For most objects, the + :keyword:`print` statement is equivalent to the :func:`str` function, but it is +-possible to special-case printing to a :ctype:`FILE\*` if necessary; this should ++possible to special-case printing to a :c:type:`FILE\*` if necessary; this should + only be done if efficiency is identified as a problem and profiling suggests + that creating a temporary string object to be written to a file is too + expensive. +@@ -1111,8 +1110,8 @@ + + Python supports two pairs of attribute handlers; a type that supports attributes + only needs to implement the functions for one pair. The difference is that one +-pair takes the name of the attribute as a :ctype:`char\*`, while the other +-accepts a :ctype:`PyObject\*`. Each type can use whichever pair makes more ++pair takes the name of the attribute as a :c:type:`char\*`, while the other ++accepts a :c:type:`PyObject\*`. Each type can use whichever pair makes more + sense for the implementation's convenience. :: + + getattrfunc tp_getattr; /* char * version */ +@@ -1123,7 +1122,7 @@ + + If accessing attributes of an object is always a simple operation (this will be + explained shortly), there are generic implementations which can be used to +-provide the :ctype:`PyObject\*` version of the attribute management functions. ++provide the :c:type:`PyObject\*` version of the attribute management functions. + The actual need for type-specific attribute handlers almost completely + disappeared starting with Python 2.2, though there are many examples which have + not been updated to use some of the new generic mechanism that is available. +@@ -1139,7 +1138,7 @@ + Most extension types only use *simple* attributes. So, what makes the + attributes simple? There are only a couple of conditions that must be met: + +-#. The name of the attributes must be known when :cfunc:`PyType_Ready` is ++#. The name of the attributes must be known when :c:func:`PyType_Ready` is + called. + + #. No special processing is needed to record that an attribute was looked up or +@@ -1148,7 +1147,7 @@ + Note that this list does not place any restrictions on the values of the + attributes, when the values are computed, or how relevant data is stored. + +-When :cfunc:`PyType_Ready` is called, it uses three tables referenced by the ++When :c:func:`PyType_Ready` is called, it uses three tables referenced by the + type object to create :term:`descriptor`\s which are placed in the dictionary of the + type object. Each descriptor controls access to one attribute of the instance + object. Each of the tables is optional; if all three are *NULL*, instances of +@@ -1163,7 +1162,7 @@ + struct PyGetSetDef *tp_getset; + + If :attr:`tp_methods` is not *NULL*, it must refer to an array of +-:ctype:`PyMethodDef` structures. Each entry in the table is an instance of this ++:c:type:`PyMethodDef` structures. Each entry in the table is an instance of this + structure:: + + typedef struct PyMethodDef { +@@ -1248,9 +1247,9 @@ + Type-specific Attribute Management + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +-For simplicity, only the :ctype:`char\*` version will be demonstrated here; the +-type of the name parameter is the only difference between the :ctype:`char\*` +-and :ctype:`PyObject\*` flavors of the interface. This example effectively does ++For simplicity, only the :c:type:`char\*` version will be demonstrated here; the ++type of the name parameter is the only difference between the :c:type:`char\*` ++and :c:type:`PyObject\*` flavors of the interface. This example effectively does + the same thing as the generic example above, but does not use the generic + support added in Python 2.2. The value in showing this is two-fold: it + demonstrates how basic attribute management can be done in a way that is +@@ -1263,7 +1262,7 @@ + method of a class would be called. + + A likely way to handle this is (1) to implement a set of functions (such as +-:cfunc:`newdatatype_getSize` and :cfunc:`newdatatype_setSize` in the example ++:c:func:`newdatatype_getSize` and :c:func:`newdatatype_setSize` in the example + below), (2) provide a method table listing these functions, and (3) provide a + getattr function that returns the result of a lookup in that table. The method + table uses the same structure as the :attr:`tp_methods` field of the type +@@ -1309,7 +1308,7 @@ + The :attr:`tp_compare` handler is called when comparisons are needed and the + object does not implement the specific rich comparison method which matches the + requested comparison. (It is always used if defined and the +-:cfunc:`PyObject_Compare` or :cfunc:`PyObject_Cmp` functions are used, or if ++:c:func:`PyObject_Compare` or :c:func:`PyObject_Cmp` functions are used, or if + :func:`cmp` is used from Python.) It is analogous to the :meth:`__cmp__` method. + This function should return ``-1`` if *obj1* is less than *obj2*, ``0`` if they + are equal, and ``1`` if *obj1* is greater than *obj2*. (It was previously +@@ -1319,7 +1318,7 @@ + + A :attr:`tp_compare` handler may raise an exception. In this case it should + return a negative value. The caller has to test for the exception using +-:cfunc:`PyErr_Occurred`. ++:c:func:`PyErr_Occurred`. + + Here is a sample implementation:: + +@@ -1367,8 +1366,8 @@ + + If you wish your object to be able to act like a number, a sequence, or a + mapping object, then you place the address of a structure that implements the C +-type :ctype:`PyNumberMethods`, :ctype:`PySequenceMethods`, or +-:ctype:`PyMappingMethods`, respectively. It is up to you to fill in this ++type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or ++:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this + structure with appropriate values. You can find examples of the use of each of + these in the :file:`Objects` directory of the Python source distribution. :: + +@@ -1400,11 +1399,11 @@ + the call is ``obj1('hello')``, then *arg1* is ``obj1``. + + #. *arg2* is a tuple containing the arguments to the call. You can use +- :cfunc:`PyArg_ParseTuple` to extract the arguments. ++ :c:func:`PyArg_ParseTuple` to extract the arguments. + + #. *arg3* is a dictionary of keyword arguments that were passed. If this is + non-*NULL* and you support keyword arguments, use +- :cfunc:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not ++ :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not + want to support keyword arguments and this is non-*NULL*, raise a + :exc:`TypeError` with a message saying that keyword arguments are not supported. + +@@ -1479,7 +1478,7 @@ + those objects which do not benefit by weak referencing (such as numbers). + + For an object to be weakly referencable, the extension must include a +-:ctype:`PyObject\*` field in the instance structure for the use of the weak ++:c:type:`PyObject\*` field in the instance structure for the use of the weak + reference mechanism; it must be initialized to *NULL* by the object's + constructor. It must also set the :attr:`tp_weaklistoffset` field of the + corresponding type object to the offset of the field. For example, the instance +@@ -1555,7 +1554,7 @@ + examples of the function you want to implement. + + When you need to verify that an object is an instance of the type you are +-implementing, use the :cfunc:`PyObject_TypeCheck` function. A sample of its use ++implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of its use + might be something like the following:: + + if (! PyObject_TypeCheck(some_object, &MyType)) { +diff -r 8527427914a2 Doc/extending/windows.rst +--- a/Doc/extending/windows.rst ++++ b/Doc/extending/windows.rst +@@ -98,8 +98,8 @@ + it. Copy your C sources into it. Note that the module source file name does + not necessarily have to match the module name, but the name of the + initialization function should match the module name --- you can only import a +- module :mod:`spam` if its initialization function is called :cfunc:`initspam`, +- and it should call :cfunc:`Py_InitModule` with the string ``"spam"`` as its ++ module :mod:`spam` if its initialization function is called :c:func:`initspam`, ++ and it should call :c:func:`Py_InitModule` with the string ``"spam"`` as its + first argument (use the minimal :file:`example.c` in this directory as a guide). + By convention, it lives in a file called :file:`spam.c` or :file:`spammodule.c`. + The output file should be called :file:`spam.pyd` (in Release mode) or +@@ -263,7 +263,7 @@ + + The first command created three files: :file:`spam.obj`, :file:`spam.dll` and + :file:`spam.lib`. :file:`Spam.dll` does not contain any Python functions (such +-as :cfunc:`PyArg_ParseTuple`), but it does know how to find the Python code ++as :c:func:`PyArg_ParseTuple`), but it does know how to find the Python code + thanks to :file:`pythonXY.lib`. + + The second command created :file:`ni.dll` (and :file:`.obj` and :file:`.lib`), +diff -r 8527427914a2 Doc/faq/design.rst +--- a/Doc/faq/design.rst ++++ b/Doc/faq/design.rst +@@ -684,7 +684,7 @@ + Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes + (ABCs). You can then use :func:`isinstance` and :func:`issubclass` to check + whether an instance or a class implements a particular ABC. The +-:mod:`collections` modules defines a set of useful ABCs such as ++:mod:`collections` module defines a set of useful ABCs such as + :class:`Iterable`, :class:`Container`, and :class:`MutableMapping`. + + For Python, many of the advantages of interface specifications can be obtained +diff -r 8527427914a2 Doc/faq/extending.rst +--- a/Doc/faq/extending.rst ++++ b/Doc/faq/extending.rst +@@ -60,41 +60,41 @@ + How can I execute arbitrary Python statements from C? + ----------------------------------------------------- + +-The highest-level function to do this is :cfunc:`PyRun_SimpleString` which takes ++The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes + a single string argument to be executed in the context of the module + ``__main__`` and returns 0 for success and -1 when an exception occurred + (including ``SyntaxError``). If you want more control, use +-:cfunc:`PyRun_String`; see the source for :cfunc:`PyRun_SimpleString` in ++:c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in + ``Python/pythonrun.c``. + + + How can I evaluate an arbitrary Python expression from C? + --------------------------------------------------------- + +-Call the function :cfunc:`PyRun_String` from the previous question with the +-start symbol :cdata:`Py_eval_input`; it parses an expression, evaluates it and ++Call the function :c:func:`PyRun_String` from the previous question with the ++start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and + returns its value. + + + How do I extract C values from a Python object? + ----------------------------------------------- + +-That depends on the object's type. If it's a tuple, :cfunc:`PyTuple_Size` +-returns its length and :cfunc:`PyTuple_GetItem` returns the item at a specified +-index. Lists have similar functions, :cfunc:`PyListSize` and +-:cfunc:`PyList_GetItem`. ++That depends on the object's type. If it's a tuple, :c:func:`PyTuple_Size` ++returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified ++index. Lists have similar functions, :c:func:`PyListSize` and ++:c:func:`PyList_GetItem`. + +-For strings, :cfunc:`PyString_Size` returns its length and +-:cfunc:`PyString_AsString` a pointer to its value. Note that Python strings may +-contain null bytes so C's :cfunc:`strlen` should not be used. ++For strings, :c:func:`PyString_Size` returns its length and ++:c:func:`PyString_AsString` a pointer to its value. Note that Python strings may ++contain null bytes so C's :c:func:`strlen` should not be used. + + To test the type of an object, first make sure it isn't *NULL*, and then use +-:cfunc:`PyString_Check`, :cfunc:`PyTuple_Check`, :cfunc:`PyList_Check`, etc. ++:c:func:`PyString_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, 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 interfacing with any kind of Python sequence using calls +-like :cfunc:`PySequence_Length`, :cfunc:`PySequence_GetItem`, etc.) as well as ++like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc.) as well as + many other useful protocols. + + +@@ -103,7 +103,7 @@ + + 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 :cfunc:`Py_INCREF` it. Lists have similar functions ++``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. +@@ -112,9 +112,9 @@ + How do I call an object's method from C? + ---------------------------------------- + +-The :cfunc:`PyObject_CallMethod` function can be used to call an arbitrary ++The :c:func:`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 :cfunc:`Py_BuildValue`, and the ++call, a format string like that used with :c:func:`Py_BuildValue`, and the + argument values:: + + PyObject * +@@ -122,7 +122,7 @@ + char *arg_format, ...); + + This works for any object that has methods -- whether built-in or user-defined. +-You are responsible for eventually :cfunc:`Py_DECREF`\ 'ing the return value. ++You are responsible for eventually :c:func:`Py_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"):: +@@ -135,7 +135,7 @@ + Py_DECREF(res); + } + +-Note that since :cfunc:`PyObject_CallObject` *always* wants a tuple for the ++Note that since :c:func:`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)". +@@ -186,7 +186,7 @@ + + attr = PyObject_GetAttrString(module, ""); + +-Calling :cfunc:`PyObject_SetAttrString` to assign to variables in the module ++Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module + also works. + + +@@ -267,16 +267,16 @@ + In Python you can use the :mod:`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 :cfunc:`PyRun_InteractiveLoop` (perhaps ++The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps + in a separate thread) and let the Python interpreter handle the input for +-you. You can also set the :cfunc:`PyOS_ReadlineFunctionPointer` to point at your ++you. You can also set the :c:func:`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 +-:cfunc:`PyRun_InteractiveLoop` to stop while waiting for user input. The one +-solution then is to call :cfunc:`PyParser_ParseString` and test for ``e.error`` ++:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input. The one ++solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error`` + equal to ``E_EOF``, which means the input is incomplete). Here's a sample code + fragment, untested, inspired by code from Alex Farber:: + +@@ -307,8 +307,8 @@ + } + + Another solution is trying to compile the received string with +-:cfunc:`Py_CompileString`. If it compiles without errors, try to execute the +-returned code object by calling :cfunc:`PyEval_EvalCode`. Otherwise save the ++:c:func:`Py_CompileString`. If it compiles without errors, try to execute the ++returned code object by calling :c:func:`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 string "unexpected EOF while parsing". Here is a +@@ -460,8 +460,8 @@ + 7.x, in particular, provided 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 an extension uses any of +-the Unicode-related format specifiers for :cfunc:`Py_BuildValue` (or similar) or +-parameter specifications for :cfunc:`PyArg_ParseTuple`. ++the Unicode-related format specifiers for :c:func:`Py_BuildValue` (or similar) or ++parameter specifications for :c:func:`PyArg_ParseTuple`. + + You can check the size of the Unicode character a Python interpreter is using by + checking the value of sys.maxunicode: +diff -r 8527427914a2 Doc/faq/general.rst +--- a/Doc/faq/general.rst ++++ b/Doc/faq/general.rst +@@ -157,16 +157,14 @@ + + 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 Subversion at http://svn.python.org/projects/python/trunk. ++via anonymous Mercurial access at http://hg.python.org/cpython. + + The source distribution is a gzipped tar file containing the complete C source, + Sphinx-formatted documentation, Python library modules, example programs, and + 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? +diff -r 8527427914a2 Doc/faq/gui.rst +--- a/Doc/faq/gui.rst ++++ b/Doc/faq/gui.rst +@@ -117,7 +117,7 @@ + (http://tix.sourceforge.net/). + + Build Tix with SAM enabled, perform the appropriate call to +-:cfunc:`Tclsam_init`, etc. inside Python's ++:c:func:`Tclsam_init`, etc. inside Python's + :file:`Modules/tkappinit.c`, and link with libtclsam and libtksam (you + might include the Tix libraries as well). + +@@ -126,7 +126,7 @@ + --------------------------------------------------- + + 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 :cfunc:`XtAddInput()` call, which allows you ++code a bit. Tk has the equivalent of Xt's :c:func:`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:: + +diff -r 8527427914a2 Doc/faq/library.rst +--- a/Doc/faq/library.rst ++++ b/Doc/faq/library.rst +@@ -410,7 +410,7 @@ + + 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, and users who don't +-use threads would not be happy if their code ran at half at the speed. Greg's ++use threads would not be happy if their code ran at half the speed. 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! +diff -r 8527427914a2 Doc/faq/programming.rst +--- a/Doc/faq/programming.rst ++++ b/Doc/faq/programming.rst +@@ -171,7 +171,7 @@ + Thus to get the same effect as:: + + L2 = [] +- for i in range[3]: ++ for i in range(3): + L2.append(L1[i]) + + it is much shorter and far faster to use :: +@@ -980,7 +980,7 @@ + if the line uses something other than whitespace as a separator. + + For more complicated input parsing, regular expressions are more powerful +-than C's :cfunc:`sscanf` and better suited for the task. ++than C's :c:func:`sscanf` and better suited for the task. + + + What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean? +diff -r 8527427914a2 Doc/faq/windows.rst +--- a/Doc/faq/windows.rst ++++ b/Doc/faq/windows.rst +@@ -537,12 +537,12 @@ + The Python 1.5.* DLLs (``python15.dll``) are all compiled with MS VC++ 5.0 and + with multithreading-DLL options (``/MD``). + +-If you can't change compilers or flags, try using :cfunc:`Py_RunSimpleString`. ++If you can't change compilers or flags, try using :c:func:`Py_RunSimpleString`. + A trick to get it to run an arbitrary file is to construct a call to + :func:`execfile` with the name of your file as argument. + + 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" ++wish to use the Debug Multithreaded DLL, then your module *must* have ``_d`` + appended to the base name. + + +diff -r 8527427914a2 Doc/glossary.rst +--- a/Doc/glossary.rst ++++ b/Doc/glossary.rst +@@ -27,12 +27,16 @@ + :ref:`2to3-reference`. + + abstract base class +- :ref:`abstract-base-classes` complement :term:`duck-typing` by ++ Abstract base classes complement :term:`duck-typing` by + providing a way to define interfaces when other techniques like +- :func:`hasattr` would be clumsy. Python comes with many built-in ABCs for ++ :func:`hasattr` would be clumsy or subtly wrong (for example with ++ :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), and streams (in the :mod:`io` module). You can +- create your own ABC with the :mod:`abc` module. ++ create your own ABCs with the :mod:`abc` module. + + argument + A value passed to a function or method, assigned to a named local +@@ -57,11 +61,14 @@ + + bytecode + Python source code is compiled into bytecode, the internal representation +- of a Python program in the interpreter. The bytecode is also cached in +- ``.pyc`` and ``.pyo`` files so that executing the same file is faster the +- second time (recompilation from source to bytecode can be avoided). This +- "intermediate language" is said to run on a :term:`virtual machine` +- that executes the machine code corresponding to each bytecode. ++ of a Python program in the CPython interpreter. The bytecode is also ++ cached in ``.pyc`` and ``.pyo`` files so that executing the same file is ++ faster the second time (recompilation from source to bytecode can be ++ avoided). This "intermediate language" is said to run on a ++ :term:`virtual machine` that executes the machine code corresponding to ++ each bytecode. Do note that bytecodes are not expected to work between ++ different Python virtual machines, nor to be stable between Python ++ releases. + + A list of bytecode instructions can be found in the documentation for + :ref:`the dis module `. +@@ -127,8 +134,9 @@ + def f(...): + ... + +- See :ref:`the documentation for function definition ` for more +- about decorators. ++ The same concept exists for classes, but is less commonly used there. See ++ the documentation for :ref:`function definitions ` and ++ :ref:`class definitions ` for more about decorators. + + descriptor + Any *new-style* object which defines the methods :meth:`__get__`, +@@ -164,8 +172,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 +@@ -177,17 +185,34 @@ + + expression + A piece of syntax which can be evaluated to some value. In other words, +- an expression is an accumulation of expression elements like literals, names, +- attribute access, operators or function calls which all return a value. +- In contrast to many other languages, not all language constructs are expressions. +- There are also :term:`statement`\s which cannot be used as expressions, +- such as :keyword:`print` or :keyword:`if`. Assignments are also statements, +- not expressions. ++ an expression is an accumulation of expression elements like literals, ++ names, attribute access, operators or function calls which all return a ++ value. In contrast to many other languages, not all language constructs ++ are expressions. There are also :term:`statement`\s which cannot be used ++ as expressions, such as :keyword:`print` or :keyword:`if`. Assignments ++ are also statements, not expressions. + + extension module + A module written in C or C++, using Python's C API to interact with the + core and with user code. + ++ file object ++ An object exposing a file-oriented API (with methods such as ++ :meth:`read()` or :meth:`write()`) to an underlying resource. Depending ++ on the way it was created, a file object can mediate access to a real ++ on-disk file or to another other type of storage or communication device ++ (for example standard input/output, in-memory buffers, sockets, pipes, ++ etc.). File objects are also called :dfn:`file-like objects` or ++ :dfn:`streams`. ++ ++ There are actually three categories of file objects: raw binary files, ++ buffered binary files and text files. Their interfaces are defined in the ++ :mod:`io` module. The canonical way to create a file object is by using ++ the :func:`open` function. ++ ++ file-like object ++ A synonym for :term:`file object`. ++ + finder + An object that tries to find the :term:`loader` for a module. It must + implement a method named :meth:`find_module`. See :pep:`302` for +@@ -334,7 +359,7 @@ + slowly. See also :term:`interactive`. + + iterable +- A container object capable of returning its members one at a ++ An object capable of returning its members one at a + time. Examples of iterables include all sequence types (such as + :class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence + types like :class:`dict` and :class:`file` and objects of any classes you +@@ -403,6 +428,12 @@ + the :term:`EAFP` approach and is characterized by the presence of many + :keyword:`if` statements. + ++ In a multi-threaded environment, the LBYL approach can risk introducing a ++ race condition between "the looking" and "the leaping". For example, the ++ code, ``if key in mapping: return mapping[key]`` can fail if another ++ thread removes *key* from *mapping* after the test, but before the lookup. ++ This issue can be solved with locks or by using the EAFP approach. ++ + list + A built-in Python :term:`sequence`. Despite its name it is more akin + to an array in other languages than to a linked list since access to +@@ -423,9 +454,10 @@ + + mapping + A container object that supports arbitrary key lookups and implements the +- methods specified in the :class:`Mapping` or :class:`MutableMapping` +- :ref:`abstract base classes `. Examples include +- :class:`dict`, :class:`collections.defaultdict`, ++ methods specified in the :class:`~collections.Mapping` or ++ :class:`~collections.MutableMapping` ++ :ref:`abstract base classes `. Examples ++ include :class:`dict`, :class:`collections.defaultdict`, + :class:`collections.OrderedDict` and :class:`collections.Counter`. + + metaclass +@@ -447,6 +479,14 @@ + its first :term:`argument` (which is usually called ``self``). + See :term:`function` and :term:`nested scope`. + ++ method resolution order ++ Method Resolution Order is the order in which base classes are searched ++ for a member during lookup. See `The Python 2.3 Method Resolution Order ++ `_. ++ ++ MRO ++ See :term:`method resolution order`. ++ + mutable + Mutable objects can change their value but keep their :func:`id`. See + also :term:`immutable`. +@@ -505,9 +545,9 @@ + :term:`argument`. + + Python 3000 +- Nickname for the next major Python version, 3.0 (coined long ago +- when the release of version 3 was something in the distant future.) This +- is also abbreviated "Py3k". ++ Nickname for the Python 3.x release line (coined long ago when the release ++ of version 3 was something in the distant future.) This is also ++ abbreviated "Py3k". + + Pythonic + An idea or piece of code which closely follows the most common idioms +@@ -530,7 +570,7 @@ + object drops to zero, it is deallocated. Reference counting is + generally not visible to Python code, but it is a key element of the + :term:`CPython` implementation. The :mod:`sys` module defines a +- :func:`getrefcount` function that programmers can call to return the ++ :func:`~sys.getrefcount` function that programmers can call to return the + reference count for a particular object. + + __slots__ +@@ -566,7 +606,15 @@ + statement + A statement is part of a suite (a "block" of code). A statement is either + an :term:`expression` or a one of several constructs with a keyword, such +- as :keyword:`if`, :keyword:`while` or :keyword:`print`. ++ as :keyword:`if`, :keyword:`while` or :keyword:`for`. ++ ++ struct sequence ++ A tuple with named elements. Struct sequences expose an interface similiar ++ to :term:`named tuple` in that elements can either be accessed either by ++ index or as an attribute. However, they do not have any of the named tuple ++ methods like :meth:`~collections.somenamedtuple._make` or ++ :meth:`~collections.somenamedtuple._asdict`. Examples of struct sequences ++ include :data:`sys.float_info` and the return value of :func:`os.stat`. + + triple-quoted string + A string which is bound by three instances of either a quotation mark +diff -r 8527427914a2 Doc/howto/cporting.rst +--- a/Doc/howto/cporting.rst ++++ b/Doc/howto/cporting.rst +@@ -1,5 +1,7 @@ + .. highlightlang:: c + ++.. _cporting-howto: ++ + ******************************** + Porting Extension Modules to 3.0 + ******************************** +@@ -20,7 +22,7 @@ + ======================= + + The easiest way to compile only some code for 3.0 is to check if +-:cmacro:`PY_MAJOR_VERSION` is greater than or equal to 3. :: ++:c:macro:`PY_MAJOR_VERSION` is greater than or equal to 3. :: + + #if PY_MAJOR_VERSION >= 3 + #define IS_PY3K +@@ -45,12 +47,12 @@ + 2.x's :func:`unicode` (``PyUnicode_*``). The old 8-bit string type has become + :func:`bytes`. Python 2.6 and later provide a compatibility header, + :file:`bytesobject.h`, mapping ``PyBytes`` names to ``PyString`` ones. For best +-compatibility with 3.0, :ctype:`PyUnicode` should be used for textual data and +-:ctype:`PyBytes` for binary data. It's also important to remember that +-:ctype:`PyBytes` and :ctype:`PyUnicode` in 3.0 are not interchangeable like +-:ctype:`PyString` and :ctype:`PyUnicode` are in 2.x. The following example +-shows best practices with regards to :ctype:`PyUnicode`, :ctype:`PyString`, +-and :ctype:`PyBytes`. :: ++compatibility with 3.0, :c:type:`PyUnicode` should be used for textual data and ++:c:type:`PyBytes` for binary data. It's also important to remember that ++:c:type:`PyBytes` and :c:type:`PyUnicode` in 3.0 are not interchangeable like ++:c:type:`PyString` and :c:type:`PyUnicode` are in 2.x. The following example ++shows best practices with regards to :c:type:`PyUnicode`, :c:type:`PyString`, ++and :c:type:`PyBytes`. :: + + #include "stdlib.h" + #include "Python.h" +@@ -207,6 +209,58 @@ + } + + ++CObject replaced with Capsule ++============================= ++ ++The :c:type:`Capsule` object was introduced in Python 3.1 and 2.7 to replace ++:c:type:`CObject`. CObjects were useful, ++but the :c:type:`CObject` API was problematic: it didn't permit distinguishing ++between valid CObjects, which allowed mismatched CObjects to crash the ++interpreter, and some of its APIs relied on undefined behavior in C. ++(For further reading on the rationale behind Capsules, please see :issue:`5630`.) ++ ++If you're currently using CObjects, and you want to migrate to 3.1 or newer, ++you'll need to switch to Capsules. ++:c:type:`CObject` was deprecated in 3.1 and 2.7 and completely removed in ++Python 3.2. If you only support 2.7, or 3.1 and above, you ++can simply switch to :c:type:`Capsule`. If you need to support 3.0 or ++versions of Python earlier than 2.7 you'll have to support both CObjects ++and Capsules. ++ ++The following example header file :file:`capsulethunk.h` may ++solve the problem for you; ++simply write your code against the :c:type:`Capsule` API, include ++this header file after ``"Python.h"``, and you'll automatically use CObjects ++in Python 3.0 or versions earlier than 2.7. ++ ++:file:`capsulethunk.h` simulates Capsules using CObjects. However, ++:c:type:`CObject` provides no place to store the capsule's "name". As a ++result the simulated :c:type:`Capsule` objects created by :file:`capsulethunk.h` ++behave slightly differently from real Capsules. Specifically: ++ ++ * The name parameter passed in to :c:func:`PyCapsule_New` is ignored. ++ ++ * The name parameter passed in to :c:func:`PyCapsule_IsValid` and ++ :c:func:`PyCapsule_GetPointer` is ignored, and no error checking ++ of the name is performed. ++ ++ * :c:func:`PyCapsule_GetName` always returns NULL. ++ ++ * :c:func:`PyCapsule_SetName` always throws an exception and ++ returns failure. (Since there's no way to store a name ++ in a CObject, noisy failure of :c:func:`PyCapsule_SetName` ++ was deemed preferable to silent failure here. If this is ++ inconveient, feel free to modify your local ++ copy as you see fit.) ++ ++You can find :file:`capsulethunk.h` in the Python source distribution ++in the :file:`Doc/includes` directory. We also include it here for ++your reference; here is :file:`capsulethunk.h`: ++ ++.. literalinclude:: ../includes/capsulethunk.h ++ ++ ++ + Other options + ============= + +diff -r 8527427914a2 Doc/howto/descriptor.rst +--- a/Doc/howto/descriptor.rst ++++ b/Doc/howto/descriptor.rst +@@ -42,7 +42,7 @@ + + Descriptors are a powerful, general purpose protocol. They are the mechanism + behind properties, methods, static methods, class methods, and :func:`super()`. +-They are used used throughout Python itself to implement the new style classes ++They are used throughout Python itself to implement the new style classes + introduced in version 2.2. Descriptors simplify the underlying C-code and offer + a flexible set of new tools for everyday Python programs. + +@@ -97,7 +97,7 @@ + implementation works through a precedence chain that gives data descriptors + priority over instance variables, instance variables priority over non-data + descriptors, and assigns lowest priority to :meth:`__getattr__` if provided. The +-full C implementation can be found in :cfunc:`PyObject_GenericGetAttr()` in ++full C implementation can be found in :c:func:`PyObject_GenericGetAttr()` in + `Objects/object.c `_\. + + For classes, the machinery is in :meth:`type.__getattribute__` which transforms +@@ -131,7 +131,7 @@ + Note, in Python 2.2, ``super(B, obj).m()`` would only invoke :meth:`__get__` if + ``m`` was a data descriptor. In Python 2.3, non-data descriptors also get + invoked unless an old-style class is involved. The implementation details are +-in :cfunc:`super_getattro()` in ++in :c:func:`super_getattro()` in + `Objects/typeobject.c `_ + and a pure Python equivalent can be found in `Guido's Tutorial`_. + +@@ -297,7 +297,7 @@ + + The output suggests that bound and unbound methods are two different types. + While they could have been implemented that way, the actual C implementation of +-:ctype:`PyMethod_Type` in ++:c:type:`PyMethod_Type` in + `Objects/classobject.c `_ + is a single object with two different representations depending on whether the + :attr:`im_self` field is set or is *NULL* (the C equivalent of *None*). +diff -r 8527427914a2 Doc/howto/doanddont.rst +--- a/Doc/howto/doanddont.rst ++++ b/Doc/howto/doanddont.rst +@@ -32,8 +32,8 @@ + versions of Python do not check for the invalidity, it does not make it more + valid, no more than having a smart lawyer makes a man innocent. Do not use it + like that ever. Even in versions where it was accepted, it made the function +-execution slower, because the compiler could not be certain which names are +-local and which are global. In Python 2.1 this construct causes warnings, and ++execution slower, because the compiler could not be certain which names were ++local and which were global. In Python 2.1 this construct causes warnings, and + sometimes even errors. + + +@@ -46,7 +46,7 @@ + in your favourite editor. You also open yourself to trouble in the future, if + some module grows additional functions or classes. + +-One of the most awful question asked on the newsgroup is why this code:: ++One of the most awful questions asked on the newsgroup is why this code:: + + f = open("www") + f.read() +@@ -113,7 +113,7 @@ + + This is a "don't" which is much weaker than the previous "don't"s but is still + something you should not do if you don't have good reasons to do that. The +-reason it is usually bad idea is because you suddenly have an object which lives ++reason it is usually a bad idea is because you suddenly have an object which lives + in two separate namespaces. When the binding in one namespace changes, the + binding in the other will not, so there will be a discrepancy between them. This + happens when, for example, one module is reloaded, or changes the definition of +diff -r 8527427914a2 Doc/howto/functional.rst +--- a/Doc/howto/functional.rst ++++ b/Doc/howto/functional.rst +@@ -44,15 +44,14 @@ + functional languages include the ML family (Standard ML, OCaml, and other + variants) and Haskell. + +-The designers of some computer languages choose to emphasize one +-particular approach to programming. This often makes it difficult to +-write programs that use a different approach. Other languages are +-multi-paradigm languages that support several different approaches. +-Lisp, C++, and Python are multi-paradigm; you can write programs or +-libraries that are largely procedural, object-oriented, or functional +-in all of these languages. In a large program, different sections +-might be written using different approaches; the GUI might be +-object-oriented while the processing logic is procedural or ++The designers of some computer languages choose to emphasize one particular ++approach to programming. This often makes it difficult to write programs that ++use a different approach. Other languages are multi-paradigm languages that ++support several different approaches. Lisp, C++, and Python are ++multi-paradigm; you can write programs or libraries that are largely ++procedural, object-oriented, or functional in all of these languages. In a ++large program, different sections might be written using different approaches; ++the GUI might be object-oriented while the processing logic is procedural or + functional, for example. + + In a functional program, input flows through a set of functions. Each function +@@ -1115,132 +1114,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 ``reduce()``, +-``compose()`` and ``partial()`` (the last of which is provided by both +-``functional`` and ``functools``). :: +- +- from functional import compose, partial +- +- multi_compose = partial(reduce, compose) +- +- +-We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of +-``"".join(...)`` that converts its arguments to string:: +- +- from functional import compose, partial +- +- join = compose("".join, partial(map, str)) +- +- +-``flip(func)`` +- +-``flip()`` wraps the callable in ``func`` and causes it to receive its +-non-keyword arguments in reverse order. :: +- +- >>> def triple(a, b, c): +- ... return (a, b, c) +- ... +- >>> triple(5, 6, 7) +- (5, 6, 7) +- >>> +- >>> flipped_triple = flip(triple) +- >>> flipped_triple(5, 6, 7) +- (7, 6, 5) +- +-``foldl(func, start, iterable)`` +- +-``foldl()`` takes a binary function, a starting value (usually some kind of +-'zero'), and an iterable. The function is applied to the starting value and the +-first element of the list, then the result of that and the second element of the +-list, then the result of that and the third element of the list, and so on. +- +-This means that a call such as:: +- +- foldl(f, 0, [1, 2, 3]) +- +-is equivalent to:: +- +- f(f(f(0, 1), 2), 3) +- +- +-``foldl()`` is roughly equivalent to the following recursive function:: +- +- def foldl(func, start, seq): +- if len(seq) == 0: +- return start +- +- return foldl(func, func(start, seq[0]), seq[1:]) +- +-Speaking of equivalence, the above ``foldl`` call can be expressed in terms of +-the built-in ``reduce`` like so:: +- +- reduce(f, [1, 2, 3], 0) +- +- +-We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a +-cleaner, more aesthetically-pleasing version of Python's ``"".join(...)`` +-idiom:: +- +- from functional import foldl, partial from operator import concat +- +- join = partial(foldl, concat, "") +- +- + Revision History and Acknowledgements + ===================================== + +@@ -1296,9 +1169,10 @@ + + Mertz also wrote a 3-part series of articles on functional programming + for IBM's DeveloperWorks site; see +-`part 1 `__, +-`part 2 `__, and +-`part 3 `__, ++ ++`part 1 `__, ++`part 2 `__, and ++`part 3 `__, + + + Python documentation +diff -r 8527427914a2 Doc/howto/index.rst +--- a/Doc/howto/index.rst ++++ b/Doc/howto/index.rst +@@ -14,6 +14,7 @@ + :maxdepth: 1 + + advocacy.rst ++ pyporting.rst + cporting.rst + curses.rst + descriptor.rst +diff -r 8527427914a2 Doc/howto/logging-cookbook.rst +--- a/Doc/howto/logging-cookbook.rst ++++ b/Doc/howto/logging-cookbook.rst +@@ -610,9 +610,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 +@@ -679,6 +680,68 @@ + ``.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. + ++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 8527427914a2 Doc/howto/logging.rst +--- a/Doc/howto/logging.rst ++++ b/Doc/howto/logging.rst +@@ -670,7 +670,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 8527427914a2 Doc/howto/pyporting.rst +--- /dev/null ++++ b/Doc/howto/pyporting.rst +@@ -0,0 +1,703 @@ ++.. _pyporting-howto: ++ ++********************************* ++Porting Python 2 Code to Python 3 ++********************************* ++ ++:author: Brett Cannon ++ ++.. topic:: Abstract ++ ++ With Python 3 being the future of Python while Python 2 is still in active ++ use, it is good to have your project available for both major releases of ++ Python. This guide is meant to help you choose which strategy works best ++ for your project to support both Python 2 & 3 along with how to execute ++ that strategy. ++ ++ If you are looking to port an extension module instead of pure Python code, ++ please see :ref:`cporting-howto`. ++ ++ ++Choosing a Strategy ++=================== ++ ++When a project makes the decision that it's time to support both Python 2 & 3, ++a decision needs to be made as to how to go about accomplishing that goal. ++The chosen strategy will depend on how large the project's existing ++codebase is and how much divergence you want from your Python 2 codebase from ++your Python 3 one (e.g., starting a new version with Python 3). ++ ++If your project is brand-new or does not have a large codebase, then you may ++want to consider writing/porting :ref:`all of your code for Python 3 ++and use 3to2 ` to port your code for Python 2. ++ ++If you would prefer to maintain a codebase which is semantically **and** ++syntactically compatible with Python 2 & 3 simultaneously, you can write ++:ref:`use_same_source`. While this tends to lead to somewhat non-idiomatic ++code, it does mean you keep a rapid development process for you, the developer. ++ ++Finally, you do have the option of :ref:`using 2to3 ` to translate ++Python 2 code into Python 3 code (with some manual help). This can take the ++form of branching your code and using 2to3 to start a Python 3 branch. You can ++also have users perform the translation as installation time automatically so ++that you only have to maintain a Python 2 codebase. ++ ++Regardless of which approach you choose, porting is not as hard or ++time-consuming as you might initially think. You can also tackle the problem ++piece-meal as a good portion of porting is simply updating your code to follow ++current best practices in a Python 2/3 compatible way. ++ ++ ++Universal Bits of Advice ++------------------------ ++ ++Regardless of what strategy you pick, there are a few things you should ++consider. ++ ++One is make sure you have a robust test suite. You need to make sure everything ++continues to work, just like when you support a new minor version of Python. ++This means making sure your test suite is thorough and is ported properly ++between Python 2 & 3. You will also most likely want to use something like tox_ ++to automate testing between both a Python 2 and Python 3 VM. ++ ++Two, once your project has Python 3 support, make sure to add the proper ++classifier on the Cheeseshop_ (PyPI_). To have your project listed as Python 3 ++compatible it must have the ++`Python 3 classifier `_ ++(from ++http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/):: ++ ++ setup( ++ name='Your Library', ++ version='1.0', ++ classifiers=[ ++ # make sure to use :: Python *and* :: Python :: 3 so ++ # that pypi can list the package on the python 3 page ++ 'Programming Language :: Python', ++ 'Programming Language :: Python :: 3' ++ ], ++ packages=['yourlibrary'], ++ # make sure to add custom_fixers to the MANIFEST.in ++ include_package_data=True, ++ # ... ++ ) ++ ++ ++Doing so will cause your project to show up in the ++`Python 3 packages list ++`_. You will know ++you set the classifier properly as visiting your project page on the Cheeseshop ++will show a Python 3 logo in the upper-left corner of the page. ++ ++Three, the six_ project provides a library which helps iron out differences ++between Python 2 & 3. If you find there is a sticky point that is a continual ++point of contention in your translation or maintenance of code, consider using ++a source-compatible solution relying on six. If you have to create your own ++Python 2/3 compatible solution, you can use ``sys.version_info[0] >= 3`` as a ++guard. ++ ++Four, read all the approaches. Just because some bit of advice applies to one ++approach more than another doesn't mean that some advice doesn't apply to other ++strategies. ++ ++Five, drop support for older Python versions if possible. `Python 2.5`_ ++introduced a lot of useful syntax and libraries which have become idiomatic ++in Python 3. `Python 2.6`_ introduced future statements which makes ++compatibility much easier if you are going from Python 2 to 3. ++`Python 2.7`_ continues the trend in the stdlib. So choose the newest version ++of Python which you believe can be your minimum support version ++and work from there. ++ ++ ++.. _tox: http://codespeak.net/tox/ ++.. _Cheeseshop: ++.. _PyPI: http://pypi.python.org/ ++.. _six: http://packages.python.org/six ++.. _Python 2.7: http://www.python.org/2.7.x ++.. _Python 2.6: http://www.python.org/2.6.x ++.. _Python 2.5: http://www.python.org/2.5.x ++.. _Python 2.4: http://www.python.org/2.4.x ++.. _Python 2.3: http://www.python.org/2.3.x ++.. _Python 2.2: http://www.python.org/2.2.x ++ ++ ++.. _use_3to2: ++ ++Python 3 and 3to2 ++================= ++ ++If you are starting a new project or your codebase is small enough, you may ++want to consider writing your code for Python 3 and backporting to Python 2 ++using 3to2_. Thanks to Python 3 being more strict about things than Python 2 ++(e.g., bytes vs. strings), the source translation can be easier and more ++straightforward than from Python 2 to 3. Plus it gives you more direct ++experience developing in Python 3 which, since it is the future of Python, is a ++good thing long-term. ++ ++A drawback of this approach is that 3to2 is a third-party project. This means ++that the Python core developers (and thus this guide) can make no promises ++about how well 3to2 works at any time. There is nothing to suggest, though, ++that 3to2 is not a high-quality project. ++ ++ ++.. _3to2: https://bitbucket.org/amentajo/lib3to2/overview ++ ++ ++.. _use_2to3: ++ ++Python 2 and 2to3 ++================= ++ ++Included with Python since 2.6, the 2to3_ tool (and :mod:`lib2to3` module) ++helps with porting Python 2 to Python 3 by performing various source ++translations. This is a perfect solution for projects which wish to branch ++their Python 3 code from their Python 2 codebase and maintain them as ++independent codebases. You can even begin preparing to use this approach ++today by writing future-compatible Python code which works cleanly in ++Python 2 in conjunction with 2to3; all steps outlined below will work ++with Python 2 code up to the point when the actual use of 2to3 occurs. ++ ++Use of 2to3 as an on-demand translation step at install time is also possible, ++preventing the need to maintain a separate Python 3 codebase, but this approach ++does come with some drawbacks. While users will only have to pay the ++translation cost once at installation, you as a developer will need to pay the ++cost regularly during development. If your codebase is sufficiently large ++enough then the translation step ends up acting like a compilation step, ++robbing you of the rapid development process you are used to with Python. ++Obviously the time required to translate a project will vary, so do an ++experimental translation just to see how long it takes to evaluate whether you ++prefer this approach compared to using :ref:`use_same_source` or simply keeping ++a separate Python 3 codebase. ++ ++Below are the typical steps taken by a project which uses a 2to3-based approach ++to supporting Python 2 & 3. ++ ++ ++Support Python 2.7 ++------------------ ++ ++As a first step, make sure that your project is compatible with `Python 2.7`_. ++This is just good to do as Python 2.7 is the last release of Python 2 and thus ++will be used for a rather long time. It also allows for use of the ``-3`` flag ++to Python to help discover places in your code which 2to3 cannot handle but are ++known to cause issues. ++ ++Try to Support `Python 2.6`_ and Newer Only ++------------------------------------------- ++ ++While not possible for all projects, if you can support `Python 2.6`_ and newer ++**only**, your life will be much easier. Various future statements, stdlib ++additions, etc. exist only in Python 2.6 and later which greatly assist in ++porting to Python 3. But if you project must keep support for `Python 2.5`_ (or ++even `Python 2.4`_) then it is still possible to port to Python 3. ++ ++Below are the benefits you gain if you only have to support Python 2.6 and ++newer. Some of these options are personal choice while others are ++**strongly** recommended (the ones that are more for personal choice are ++labeled as such). If you continue to support older versions of Python then you ++at least need to watch out for situations that these solutions fix. ++ ++ ++``from __future__ import print_function`` ++''''''''''''''''''''''''''''''''''''''''' ++ ++This is a personal choice. 2to3 handles the translation from the print ++statement to the print function rather well so this is an optional step. This ++future statement does help, though, with getting used to typing ++``print('Hello, World')`` instead of ``print 'Hello, World'``. ++ ++ ++``from __future__ import unicode_literals`` ++''''''''''''''''''''''''''''''''''''''''''' ++ ++Another personal choice. You can always mark what you want to be a (unicode) ++string with a ``u`` prefix to get the same effect. But regardless of whether ++you use this future statement or not, you **must** make sure you know exactly ++which Python 2 strings you want to be bytes, and which are to be strings. This ++means you should, **at minimum** mark all strings that are meant to be text ++strings with a ``u`` prefix if you do not use this future statement. ++ ++ ++Bytes literals ++'''''''''''''' ++ ++This is a **very** important one. The ability to prefix Python 2 strings that ++are meant to contain bytes with a ``b`` prefix help to very clearly delineate ++what is and is not a Python 3 string. When you run 2to3 on code, all Python 2 ++strings become Python 3 strings **unless** they are prefixed with ``b``. ++ ++There are some differences between byte literals in Python 2 and those in ++Python 3 thanks to the bytes type just being an alias to ``str`` in Python 2. ++Probably the biggest "gotcha" is that indexing results in different values. In ++Python 2, the value of ``b'py'[1]`` is ``'y'``, while in Python 3 it's ``121``. ++You can avoid this disparity by always slicing at the size of a single element: ++``b'py'[1:2]`` is ``'y'`` in Python 2 and ``b'y'`` in Python 3 (i.e., close ++enough). ++ ++You cannot concatenate bytes and strings in Python 3. But since in Python ++2 has bytes aliased to ``str``, it will succeed: ``b'a' + u'b'`` works in ++Python 2, but ``b'a' + 'b'`` in Python 3 is a :exc:`TypeError`. A similar issue ++also comes about when doing comparisons between bytes and strings. ++ ++ ++Supporting `Python 2.5`_ and Newer Only ++--------------------------------------- ++ ++If you are supporting `Python 2.5`_ and newer there are still some features of ++Python that you can utilize. ++ ++ ++``from __future__ import absolute_import`` ++'''''''''''''''''''''''''''''''''''''''''' ++ ++Implicit relative imports (e.g., importing ``spam.bacon`` from within ++``spam.eggs`` with the statement ``import bacon``) does not work in Python 3. ++This future statement moves away from that and allows the use of explicit ++relative imports (e.g., ``from . import bacon``). ++ ++In `Python 2.5`_ you must use ++the __future__ statement to get to use explicit relative imports and prevent ++implicit ones. In `Python 2.6`_ explicit relative imports are available without ++the statement, but you still want the __future__ statement to prevent implicit ++relative imports. In `Python 2.7`_ the __future__ statement is not needed. In ++other words, unless you are only supporting Python 2.7 or a version earlier ++than Python 2.5, use the __future__ statement. ++ ++ ++ ++Handle Common "Gotchas" ++----------------------- ++ ++There are a few things that just consistently come up as sticking points for ++people which 2to3 cannot handle automatically or can easily be done in Python 2 ++to help modernize your code. ++ ++ ++``from __future__ import division`` ++''''''''''''''''''''''''''''''''''' ++ ++While the exact same outcome can be had by using the ``-Qnew`` argument to ++Python, using this future statement lifts the requirement that your users use ++the flag to get the expected behavior of division in Python 3 ++(e.g., ``1/2 == 0.5; 1//2 == 0``). ++ ++ ++ ++Specify when opening a file as binary ++''''''''''''''''''''''''''''''''''''' ++ ++Unless you have been working on Windows, there is a chance you have not always ++bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for ++binary reading). Under Python 3, binary files and text files are clearly ++distinct and mutually incompatible; see the :mod:`io` module for details. ++Therefore, you **must** make a decision of whether a file will be used for ++binary access (allowing to read and/or write bytes data) or text access ++(allowing to read and/or write unicode data). ++ ++Text files ++'''''''''' ++ ++Text files created using ``open()`` under Python 2 return byte strings, ++while under Python 3 they return unicode strings. Depending on your porting ++strategy, this can be an issue. ++ ++If you want text files to return unicode strings in Python 2, you have two ++possibilities: ++ ++* Under Python 2.6 and higher, use :func:`io.open`. Since :func:`io.open` ++ is essentially the same function in both Python 2 and Python 3, it will ++ help iron out any issues that might arise. ++ ++* If pre-2.6 compatibility is needed, then you should use :func:`codecs.open` ++ instead. This will make sure that you get back unicode strings in Python 2. ++ ++Subclass ``object`` ++''''''''''''''''''' ++ ++New-style classes have been around since `Python 2.2`_. You need to make sure ++you are subclassing from ``object`` to avoid odd edge cases involving method ++resolution order, etc. This continues to be totally valid in Python 3 (although ++unneeded as all classes implicitly inherit from ``object``). ++ ++ ++Deal With the Bytes/String Dichotomy ++'''''''''''''''''''''''''''''''''''' ++ ++One of the biggest issues people have when porting code to Python 3 is handling ++the bytes/string dichotomy. Because Python 2 allowed the ``str`` type to hold ++textual data, people have over the years been rather loose in their delineation ++of what ``str`` instances held text compared to bytes. In Python 3 you cannot ++be so care-free anymore and need to properly handle the difference. The key ++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. ++ ++ ++Mark Up Python 2 String Literals ++******************************** ++ ++First thing you must do is designate every single string literal in Python 2 ++as either textual or bytes data. If you are only supporting Python 2.6 or ++newer, this can be accomplished by marking bytes literals with a ``b`` prefix ++and then designating textual data with a ``u`` prefix or using the ++``unicode_literals`` future statement. ++ ++If your project supports versions of Python pre-dating 2.6, then you should use ++the six_ project and its ``b()`` function to denote bytes literals. For text ++literals you can either use six's ``u()`` function or use a ``u`` prefix. ++ ++ ++Decide what APIs Will Accept ++**************************** ++ ++In Python 2 it was very easy to accidentally create an API that accepted both ++bytes and textual data. But in Python 3, thanks to the more strict handling of ++disparate types, this loose usage of bytes and text together tends to fail. ++ ++Take the dict ``{b'a': 'bytes', u'a': 'text'}`` in Python 2.6. It creates the ++dict ``{u'a': 'text'}`` since ``b'a' == u'a'``. But in Python 3 the equivalent ++dict creates ``{b'a': 'bytes', 'a': 'text'}``, i.e., no lost data. Similar ++issues can crop up when transitioning Python 2 code to Python 3. ++ ++This means you need to choose what an API is going to accept and create and ++consistently stick to that API in both Python 2 and 3. ++ ++ ++Bytes / Unicode Comparison ++************************** ++ ++In Python 3, mixing bytes and unicode is forbidden in most situations; it ++will raise a :class:`TypeError` where Python 2 would have attempted an implicit ++coercion between types. However, there is one case where it doesn't and ++it can be very misleading:: ++ ++ >>> b"" == "" ++ False ++ ++This is because an equality comparison is required by the language to always ++succeed (and return ``False`` for incompatible types). However, this also ++means that code incorrectly ported to Python 3 can display buggy behaviour ++if such comparisons are silently executed. To detect such situations, ++Python 3 has a ``-b`` flag that will display a warning:: ++ ++ $ python3 -b ++ >>> b"" == "" ++ __main__:1: BytesWarning: Comparison between bytes and string ++ False ++ ++To turn the warning into an exception, use the ``-bb`` flag instead:: ++ ++ $ python3 -bb ++ >>> b"" == "" ++ Traceback (most recent call last): ++ File "", line 1, in ++ BytesWarning: Comparison between bytes and string ++ ++ ++Indexing bytes objects ++'''''''''''''''''''''' ++ ++Another potentially surprising change is the indexing behaviour of bytes ++objects in Python 3:: ++ ++ >>> b"xyz"[0] ++ 120 ++ ++Indeed, Python 3 bytes objects (as well as :class:`bytearray` objects) ++are sequences of integers. But code converted from Python 2 will often ++assume that indexing a bytestring produces another bytestring, not an ++integer. To reconcile both behaviours, use slicing:: ++ ++ >>> b"xyz"[0:1] ++ b'x' ++ >>> n = 1 ++ >>> b"xyz"[n:n+1] ++ b'y' ++ ++The only remaining gotcha is that an out-of-bounds slice returns an empty ++bytes object instead of raising ``IndexError``: ++ ++ >>> b"xyz"[3] ++ Traceback (most recent call last): ++ File "", line 1, in ++ IndexError: index out of range ++ >>> b"xyz"[3:4] ++ b'' ++ ++ ++``__str__()``/``__unicode__()`` ++''''''''''''''''''''''''''''''' ++ ++In Python 2, objects can specify both a string and unicode representation of ++themselves. In Python 3, though, there is only a string representation. This ++becomes an issue as people can inadvertently do things in their ``__str__()`` ++methods which have unpredictable results (e.g., infinite recursion if you ++happen to use the ``unicode(self).encode('utf8')`` idiom as the body of your ++``__str__()`` method). ++ ++There are two ways to solve this issue. One is to use a custom 2to3 fixer. The ++blog post at http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ ++specifies how to do this. That will allow 2to3 to change all instances of ``def ++__unicode(self): ...`` to ``def __str__(self): ...``. This does require you ++define your ``__str__()`` method in Python 2 before your ``__unicode__()`` ++method. ++ ++The other option is to use a mixin class. This allows you to only define a ++``__unicode__()`` method for your class and let the mixin derive ++``__str__()`` for you (code from ++http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/):: ++ ++ import sys ++ ++ class UnicodeMixin(object): ++ ++ """Mixin class to handle defining the proper __str__/__unicode__ ++ methods in Python 2 or 3.""" ++ ++ if sys.version_info[0] >= 3: # Python 3 ++ def __str__(self): ++ return self.__unicode__() ++ else: # Python 2 ++ def __str__(self): ++ return self.__unicode__().encode('utf8') ++ ++ ++ class Spam(UnicodeMixin): ++ ++ def __unicode__(self): ++ return u'spam-spam-bacon-spam' # 2to3 will remove the 'u' prefix ++ ++ ++Don't Index on Exceptions ++''''''''''''''''''''''''' ++ ++In Python 2, the following worked:: ++ ++ >>> exc = Exception(1, 2, 3) ++ >>> exc.args[1] ++ 2 ++ >>> exc[1] # Python 2 only! ++ 2 ++ ++But in Python 3, indexing directly on an exception is an error. You need to ++make sure to only index on the :attr:`BaseException.args` attribute which is a ++sequence containing all arguments passed to the :meth:`__init__` method. ++ ++Even better is to use the documented attributes the exception provides. ++ ++Don't use ``__getslice__`` & Friends ++'''''''''''''''''''''''''''''''''''' ++ ++Been deprecated for a while, but Python 3 finally drops support for ++``__getslice__()``, etc. Move completely over to :meth:`__getitem__` and ++friends. ++ ++ ++Updating doctests ++''''''''''''''''' ++ ++2to3_ will attempt to generate fixes for doctests that it comes across. It's ++not perfect, though. If you wrote a monolithic set of doctests (e.g., a single ++docstring containing all of your doctests), you should at least consider ++breaking the doctests up into smaller pieces to make it more manageable to fix. ++Otherwise it might very well be worth your time and effort to port your tests ++to :mod:`unittest`. ++ ++ ++Eliminate ``-3`` Warnings ++------------------------- ++ ++When you run your application's test suite, run it using the ``-3`` flag passed ++to Python. This will cause various warnings to be raised during execution about ++things that 2to3 cannot handle automatically (e.g., modules that have been ++removed). Try to eliminate those warnings to make your code even more portable ++to Python 3. ++ ++ ++Run 2to3 ++-------- ++ ++Once you have made your Python 2 code future-compatible with Python 3, it's ++time to use 2to3_ to actually port your code. ++ ++ ++Manually ++'''''''' ++ ++To manually convert source code using 2to3_, you use the ``2to3`` script that ++is installed with Python 2.6 and later.:: ++ ++ 2to3 ++ ++This will cause 2to3 to write out a diff with all of the fixers applied for the ++converted source code. If you would like 2to3 to go ahead and apply the changes ++you can pass it the ``-w`` flag:: ++ ++ 2to3 -w ++ ++There are other flags available to control exactly which fixers are applied, ++etc. ++ ++ ++During Installation ++''''''''''''''''''' ++ ++When a user installs your project for Python 3, you can have either ++:mod:`distutils` or Distribute_ run 2to3_ on your behalf. ++For distutils, use the following idiom:: ++ ++ try: # Python 3 ++ from distutils.command.build_py import build_py_2to3 as build_py ++ except ImportError: # Python 2 ++ from distutils.command.build_py import build_py ++ ++ setup(cmdclass = {'build_py': build_py}, ++ # ... ++ ) ++ ++For Distribute:: ++ ++ setup(use_2to3=True, ++ # ... ++ ) ++ ++This will allow you to not have to distribute a separate Python 3 version of ++your project. It does require, though, that when you perform development that ++you at least build your project and use the built Python 3 source for testing. ++ ++ ++Verify & Test ++------------- ++ ++At this point you should (hopefully) have your project converted in such a way ++that it works in Python 3. Verify it by running your unit tests and making sure ++nothing has gone awry. If you miss something then figure out how to fix it in ++Python 3, backport to your Python 2 code, and run your code through 2to3 again ++to verify the fix transforms properly. ++ ++ ++.. _2to3: http://docs.python.org/py3k/library/2to3.html ++.. _Distribute: http://packages.python.org/distribute/ ++ ++ ++.. _use_same_source: ++ ++Python 2/3 Compatible Source ++============================ ++ ++While it may seem counter-intuitive, you can write Python code which is ++source-compatible between Python 2 & 3. It does lead to code that is not ++entirely idiomatic Python (e.g., having to extract the currently raised ++exception from ``sys.exc_info()[1]``), but it can be run under Python 2 ++**and** Python 3 without using 2to3_ as a translation step (although the tool ++should be used to help find potential portability problems). This allows you to ++continue to have a rapid development process regardless of whether you are ++developing under Python 2 or Python 3. Whether this approach or using ++:ref:`use_2to3` works best for you will be a per-project decision. ++ ++To get a complete idea of what issues you will need to deal with, see the ++`What's New in Python 3.0`_. Others have reorganized the data in other formats ++such as http://docs.pythonsprints.com/python3_porting/py-porting.html . ++ ++The following are some steps to take to try to support both Python 2 & 3 from ++the same source code. ++ ++ ++.. _What's New in Python 3.0: http://docs.python.org/release/3.0/whatsnew/3.0.html ++ ++ ++Follow The Steps for Using 2to3_ ++-------------------------------- ++ ++All of the steps outlined in how to ++:ref:`port Python 2 code with 2to3 ` apply ++to creating a Python 2/3 codebase. This includes trying only support Python 2.6 ++or newer (the :mod:`__future__` statements work in Python 3 without issue), ++eliminating warnings that are triggered by ``-3``, etc. ++ ++You should even consider running 2to3_ over your code (without committing the ++changes). This will let you know where potential pain points are within your ++code so that you can fix them properly before they become an issue. ++ ++ ++Use six_ ++-------- ++ ++The six_ project contains many things to help you write portable Python code. ++You should make sure to read its documentation from beginning to end and use ++any and all features it provides. That way you will minimize any mistakes you ++might make in writing cross-version code. ++ ++ ++Capturing the Currently Raised Exception ++---------------------------------------- ++ ++One change between Python 2 and 3 that will require changing how you code (if ++you support `Python 2.5`_ and earlier) is ++accessing the currently raised exception. In Python 2.5 and earlier the syntax ++to access the current exception is:: ++ ++ try: ++ raise Exception() ++ except Exception, exc: ++ # Current exception is 'exc' ++ pass ++ ++This syntax changed in Python 3 (and backported to `Python 2.6`_ and later) ++to:: ++ ++ try: ++ raise Exception() ++ except Exception as exc: ++ # Current exception is 'exc' ++ # In Python 3, 'exc' is restricted to the block; Python 2.6 will "leak" ++ pass ++ ++Because of this syntax change you must change to capturing the current ++exception to:: ++ ++ try: ++ raise Exception() ++ except Exception: ++ import sys ++ exc = sys.exc_info()[1] ++ # Current exception is 'exc' ++ pass ++ ++You can get more information about the raised exception from ++:func:`sys.exc_info` than simply the current exception instance, but you most ++likely don't need it. ++ ++.. note:: ++ In Python 3, the traceback is attached to the exception instance ++ through the ``__traceback__`` attribute. If the instance is saved in ++ a local variable that persists outside of the ``except`` block, the ++ traceback will create a reference cycle with the current frame and its ++ dictionary of local variables. This will delay reclaiming dead ++ resources until the next cyclic :term:`garbage collection` pass. ++ ++ In Python 2, this problem only occurs if you save the traceback itself ++ (e.g. the third element of the tuple returned by :func:`sys.exc_info`) ++ in a variable. ++ ++ ++Other Resources ++=============== ++ ++The authors of the following blog posts, wiki pages, and books deserve special ++thanks for making public their tips for porting Python 2 code to Python 3 (and ++thus helping provide information for this document): ++ ++* http://python3porting.com/ ++* http://docs.pythonsprints.com/python3_porting/py-porting.html ++* http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/ ++* http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html ++* http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/ ++* http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/ ++* http://wiki.python.org/moin/PortingPythonToPy3k ++ ++If you feel there is something missing from this document that should be added, ++please email the python-porting_ mailing list. ++ ++.. _python-porting: http://mail.python.org/mailman/listinfo/python-porting +diff -r 8527427914a2 Doc/howto/sockets.rst +--- a/Doc/howto/sockets.rst ++++ b/Doc/howto/sockets.rst +@@ -1,3 +1,5 @@ ++.. _socket-howto: ++ + **************************** + Socket Programming HOWTO + **************************** +diff -r 8527427914a2 Doc/howto/sorting.rst +--- a/Doc/howto/sorting.rst ++++ b/Doc/howto/sorting.rst +@@ -111,6 +111,15 @@ + >>> sorted(student_objects, key=attrgetter('grade', 'age')) + [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] + ++The :func:`operator.methodcaller` function makes method calls with fixed ++parameters for each object being sorted. For example, the :meth:`str.count` ++method could be used to compute message priority by counting the ++number of exclamation marks in a message: ++ ++ >>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!'] ++ >>> sorted(messages, key=methodcaller('count', '!')) ++ ['standby', 'hurry!', 'immediate!!', 'critical!!!'] ++ + Ascending and Descending + ======================== + +@@ -259,28 +268,36 @@ + * For locale aware sorting, use :func:`locale.strxfrm` for a key function or + :func:`locale.strcoll` for a comparison function. + +-* The *reverse* parameter still maintains sort stability (i.e. records with +- equal keys retain the original order). Interestingly, that effect can be ++* The *reverse* parameter still maintains sort stability (so that records with ++ equal keys retain their original order). Interestingly, that effect can be + simulated without the parameter by using the builtin :func:`reversed` function + twice: + + >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] + >>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data)))) + +-* The sort routines are guaranteed to use :meth:`__lt__` when making comparisons +- between two objects. So, it is easy to add a standard sort order to a class by +- defining an :meth:`__lt__` method:: ++* To create a standard sort order for a class, just add the appropriate rich ++ comparison methods: + ++ >>> Student.__eq__ = lambda self, other: self.age == other.age ++ >>> Student.__ne__ = lambda self, other: self.age != other.age + >>> Student.__lt__ = lambda self, other: self.age < other.age ++ >>> Student.__le__ = lambda self, other: self.age <= other.age ++ >>> Student.__gt__ = lambda self, other: self.age > other.age ++ >>> Student.__ge__ = lambda self, other: self.age >= other.age + >>> sorted(student_objects) + [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] + ++ For general purpose comparisons, the recommended approach is to define all six ++ rich comparison operators. The :func:`functools.total_ordering` class ++ decorator makes this easy to implement. ++ + * Key functions need not depend directly on the objects being sorted. A key + function can also access external resources. For instance, if the student grades + are stored in a dictionary, they can be used to sort a separate list of student + names: + + >>> students = ['dave', 'john', 'jane'] +- >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'} +- >>> sorted(students, key=newgrades.__getitem__) ++ >>> grades = {'john': 'F', 'jane':'A', 'dave': 'C'} ++ >>> sorted(students, key=grades.__getitem__) + ['jane', 'dave', 'john'] +diff -r 8527427914a2 Doc/howto/urllib2.rst +--- a/Doc/howto/urllib2.rst ++++ b/Doc/howto/urllib2.rst +@@ -138,7 +138,7 @@ + name=Somebody+Here&language=Python&location=Northampton + >>> url = 'http://www.example.com/example.cgi' + >>> full_url = url + '?' + url_values +- >>> data = urllib2.open(full_url) ++ >>> data = urllib2.urlopen(full_url) + + Notice that the full URL is created by adding a ``?`` to the URL, followed by + the encoded values. +diff -r 8527427914a2 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. + + +@@ -274,7 +274,7 @@ + Each web server requires a specific module. + + * Apache has both `mod_fastcgi `_ and `mod_fcgid +- `_. ``mod_fastcgi`` is the original one, but it ++ `_. ``mod_fastcgi`` is the original one, but it + has some licensing issues, which is why it is sometimes considered non-free. + ``mod_fcgid`` is a smaller, compatible alternative. One of these modules needs + to be loaded by Apache. +@@ -364,7 +364,7 @@ + + A really great WSGI feature is middleware. Middleware is a layer around your + program which can add various functionality to it. There is quite a bit of +-`middleware `_ already ++`middleware `_ already + available. For example, instead of writing your own session management (HTTP + is a stateless protocol, so to associate multiple HTTP requests with a single + user your application must create and manage such state via a session), you can +@@ -395,9 +395,9 @@ + + .. seealso:: + +- A good overview of WSGI-related code can be found in the `WSGI wiki +- `_, which contains an extensive list of `WSGI servers +- `_ which can be used by *any* application ++ A good overview of WSGI-related code can be found in the `WSGI homepage ++ `_, which contains an extensive list of `WSGI servers ++ `_ which can be used by *any* application + supporting WSGI. + + You might be interested in some WSGI-supporting modules already contained in +diff -r 8527427914a2 Doc/includes/capsulethunk.h +--- /dev/null ++++ b/Doc/includes/capsulethunk.h +@@ -0,0 +1,134 @@ ++#ifndef __CAPSULETHUNK_H ++#define __CAPSULETHUNK_H ++ ++#if ( (PY_VERSION_HEX < 0x02070000) \ ++ || ((PY_VERSION_HEX >= 0x03000000) \ ++ && (PY_VERSION_HEX < 0x03010000)) ) ++ ++#define __PyCapsule_GetField(capsule, field, default_value) \ ++ ( PyCapsule_CheckExact(capsule) \ ++ ? (((PyCObject *)capsule)->field) \ ++ : (default_value) \ ++ ) \ ++ ++#define __PyCapsule_SetField(capsule, field, value) \ ++ ( PyCapsule_CheckExact(capsule) \ ++ ? (((PyCObject *)capsule)->field = value), 1 \ ++ : 0 \ ++ ) \ ++ ++ ++#define PyCapsule_Type PyCObject_Type ++ ++#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule)) ++#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule)) ++ ++ ++#define PyCapsule_New(pointer, name, destructor) \ ++ (PyCObject_FromVoidPtr(pointer, destructor)) ++ ++ ++#define PyCapsule_GetPointer(capsule, name) \ ++ (PyCObject_AsVoidPtr(capsule)) ++ ++/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */ ++#define PyCapsule_SetPointer(capsule, pointer) \ ++ __PyCapsule_SetField(capsule, cobject, pointer) ++ ++ ++#define PyCapsule_GetDestructor(capsule) \ ++ __PyCapsule_GetField(capsule, destructor) ++ ++#define PyCapsule_SetDestructor(capsule, dtor) \ ++ __PyCapsule_SetField(capsule, destructor, dtor) ++ ++ ++/* ++ * Sorry, there's simply no place ++ * to store a Capsule "name" in a CObject. ++ */ ++#define PyCapsule_GetName(capsule) NULL ++ ++static int ++PyCapsule_SetName(PyObject *capsule, const char *unused) ++{ ++ unused = unused; ++ PyErr_SetString(PyExc_NotImplementedError, ++ "can't use PyCapsule_SetName with CObjects"); ++ return 1; ++} ++ ++ ++ ++#define PyCapsule_GetContext(capsule) \ ++ __PyCapsule_GetField(capsule, descr) ++ ++#define PyCapsule_SetContext(capsule, context) \ ++ __PyCapsule_SetField(capsule, descr, context) ++ ++ ++static void * ++PyCapsule_Import(const char *name, int no_block) ++{ ++ PyObject *object = NULL; ++ void *return_value = NULL; ++ char *trace; ++ size_t name_length = (strlen(name) + 1) * sizeof(char); ++ char *name_dup = (char *)PyMem_MALLOC(name_length); ++ ++ if (!name_dup) { ++ return NULL; ++ } ++ ++ memcpy(name_dup, name, name_length); ++ ++ trace = name_dup; ++ while (trace) { ++ char *dot = strchr(trace, '.'); ++ if (dot) { ++ *dot++ = '\0'; ++ } ++ ++ if (object == NULL) { ++ if (no_block) { ++ object = PyImport_ImportModuleNoBlock(trace); ++ } else { ++ object = PyImport_ImportModule(trace); ++ if (!object) { ++ PyErr_Format(PyExc_ImportError, ++ "PyCapsule_Import could not " ++ "import module \"%s\"", trace); ++ } ++ } ++ } else { ++ PyObject *object2 = PyObject_GetAttrString(object, trace); ++ Py_DECREF(object); ++ object = object2; ++ } ++ if (!object) { ++ goto EXIT; ++ } ++ ++ trace = dot; ++ } ++ ++ if (PyCObject_Check(object)) { ++ PyCObject *cobject = (PyCObject *)object; ++ return_value = cobject->cobject; ++ } else { ++ PyErr_Format(PyExc_AttributeError, ++ "PyCapsule_Import \"%s\" is not valid", ++ name); ++ } ++ ++EXIT: ++ Py_XDECREF(object); ++ if (name_dup) { ++ PyMem_FREE(name_dup); ++ } ++ return return_value; ++} ++ ++#endif /* #if PY_VERSION_HEX < 0x02070000 */ ++ ++#endif /* __CAPSULETHUNK_H */ +diff -r 8527427914a2 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 8527427914a2 Doc/install/index.rst +--- a/Doc/install/index.rst ++++ b/Doc/install/index.rst +@@ -72,7 +72,7 @@ + do the obvious thing with it: run it if it's an executable installer, ``rpm + --install`` it if it's an RPM, etc. You don't need to run Python or a setup + script, you don't need to compile anything---you might not even need to read any +-instructions (although it's always a good idea to do so anyways). ++instructions (although it's always a good idea to do so anyway). + + Of course, things will not always be that easy. You might be interested in a + module distribution that doesn't have an easy-to-use installer for your +@@ -96,10 +96,16 @@ + directory: :file:`foo-1.0` or :file:`widget-0.9.7`. Additionally, the + distribution will contain a setup script :file:`setup.py`, and a file named + :file:`README.txt` or possibly just :file:`README`, which should explain that +-building and installing the module distribution is a simple matter of running :: ++building and installing the module distribution is a simple matter of running ++one command from a terminal:: + + python setup.py install + ++For Windows, this command should be run from a command prompt window ++(:menuselection:`Start --> Accessories`):: ++ ++ setup.py install ++ + If all these things are true, then you already know how to build and install the + modules you've just downloaded: Run the command above. Unless you need to + install things in a non-standard way or customize the build process, you don't +@@ -113,14 +119,11 @@ + ========================== + + As described in section :ref:`inst-new-standard`, building and installing a module +-distribution using the Distutils is usually one simple command:: ++distribution using the Distutils is usually one simple command to run from a ++terminal:: + + python setup.py install + +-On Unix, you'd run this command from a shell prompt; on Windows, you have to +-open a command prompt window ("DOS box") and do it there; on Mac OS X, you open +-a :command:`Terminal` window to get a shell prompt. +- + + .. _inst-platform-variations: + +@@ -141,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 +@@ -276,6 +279,12 @@ + >>> sys.exec_prefix + '/usr' + ++A few other placeholders are used in this document: :file:`{X.Y}` stands for the ++version of Python, for example ``2.7``; :file:`{distname}` will be replaced by ++the name of the module distribution being installed. Dots and capitalization ++are important in the paths; for example, a value that uses ``python2.7`` on UNIX ++will typically use ``Python27`` on Windows. ++ + If you don't want to install modules to the standard location, or if you don't + have permission to write there, then you need to read about alternate + installations in section :ref:`inst-alt-install`. If you want to customize your +@@ -304,8 +313,61 @@ + differ across platforms, so read whichever of the following sections applies to + you. + ++Note that the various alternate installation schemes are mutually exclusive: you ++can pass ``--user``, or ``--home``, or ``--prefix`` and ``--exec-prefix``, or ++``--install-base`` and ``--install-platbase``, but you can't mix from these ++groups. + +-.. _inst-alt-install-prefix: ++ ++.. _inst-alt-install-user: ++ ++Alternate installation: the user scheme ++--------------------------------------- ++ ++This scheme is designed to be the most convenient solution for users that don't ++have write permission to the global site-packages directory or don't want to ++install into it. It is enabled with a simple option:: ++ ++ python setup.py install --user ++ ++Files will be installed into subdirectories of :data:`site.USER_BASE` (written ++as :file:`{userbase}` hereafter). This scheme installs pure Python modules and ++extension modules in the same location (also known as :data:`site.USER_SITE`). ++Here are the values for UNIX, including Mac OS X: ++ ++=============== =========================================================== ++Type of file Installation directory ++=============== =========================================================== ++modules :file:`{userbase}/lib/python{X.Y}/site-packages` ++scripts :file:`{userbase}/bin` ++data :file:`{userbase}` ++C headers :file:`{userbase}/include/python{X.Y}/{distname}` ++=============== =========================================================== ++ ++And here are the values used on Windows: ++ ++=============== =========================================================== ++Type of file Installation directory ++=============== =========================================================== ++modules :file:`{userbase}\\Python{XY}\\site-packages` ++scripts :file:`{userbase}\\Scripts` ++data :file:`{userbase}` ++C headers :file:`{userbase}\\Python{XY}\\Include\\{distname}` ++=============== =========================================================== ++ ++The advantage of using this scheme compared to the other ones described below is ++that the user site-packages directory is under normal conditions always included ++in :data:`sys.path` (see :mod:`site` for more information), which means that ++there is no additional step to perform after running the :file:`setup.py` script ++to finalize the installation. ++ ++The :command:`build_ext` command also has a ``--user`` option to add ++:file:`{userbase}/include` to the compiler search path for header files and ++:file:`{userbase}/lib` to the compiler search path for libraries as well as to ++the runtime search path for shared C libraries (rpath). ++ ++ ++.. _inst-alt-install-home: + + Alternate installation: the home scheme + --------------------------------------- +@@ -327,26 +389,30 @@ + + python setup.py install --home=~ + ++To make Python find the distributions installed with this scheme, you may have ++to :ref:`modify Python's search path ` or edit ++:mod:`sitecustomize` (see :mod:`site`) to call :func:`site.addsitedir` or edit ++:data:`sys.path`. ++ + The :option:`--home` option defines the installation base directory. Files are + installed to the following directories under the installation base as follows: + +-+------------------------------+---------------------------+-----------------------------+ +-| Type of file | Installation Directory | Override option | +-+==============================+===========================+=============================+ +-| pure module distribution | :file:`{home}/lib/python` | :option:`--install-purelib` | +-+------------------------------+---------------------------+-----------------------------+ +-| non-pure module distribution | :file:`{home}/lib/python` | :option:`--install-platlib` | +-+------------------------------+---------------------------+-----------------------------+ +-| scripts | :file:`{home}/bin` | :option:`--install-scripts` | +-+------------------------------+---------------------------+-----------------------------+ +-| data | :file:`{home}/share` | :option:`--install-data` | +-+------------------------------+---------------------------+-----------------------------+ ++=============== =========================================================== ++Type of file Installation directory ++=============== =========================================================== ++modules :file:`{home}/lib/python` ++scripts :file:`{home}/bin` ++data :file:`{home}` ++C headers :file:`{home}/include/python/{distname}` ++=============== =========================================================== ++ ++(Mentally replace slashes with backslashes if you're on Windows.) + + .. versionchanged:: 2.4 + The :option:`--home` option used to be supported only on Unix. + + +-.. _inst-alt-install-home: ++.. _inst-alt-install-prefix-unix: + + Alternate installation: Unix (the prefix scheme) + ------------------------------------------------ +@@ -355,7 +421,7 @@ + perform the build/install (i.e., to run the setup script), but install modules + into the third-party module directory of a different Python installation (or + something that looks like a different Python installation). If this sounds a +-trifle unusual, it is---that's why the "home scheme" comes first. However, ++trifle unusual, it is---that's why the user and home schemes come before. However, + there are at least two known cases where the prefix scheme will be useful. + + First, consider that many Linux distributions put Python in :file:`/usr`, rather +@@ -383,17 +449,15 @@ + executables, etc.) If :option:`--exec-prefix` is not supplied, it defaults to + :option:`--prefix`. Files are installed as follows: + +-+------------------------------+-----------------------------------------------------+-----------------------------+ +-| Type of file | Installation Directory | Override option | +-+==============================+=====================================================+=============================+ +-| pure module distribution | :file:`{prefix}/lib/python{X.Y}/site-packages` | :option:`--install-purelib` | +-+------------------------------+-----------------------------------------------------+-----------------------------+ +-| non-pure module distribution | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :option:`--install-platlib` | +-+------------------------------+-----------------------------------------------------+-----------------------------+ +-| scripts | :file:`{prefix}/bin` | :option:`--install-scripts` | +-+------------------------------+-----------------------------------------------------+-----------------------------+ +-| data | :file:`{prefix}/share` | :option:`--install-data` | +-+------------------------------+-----------------------------------------------------+-----------------------------+ ++================= ========================================================== ++Type of file Installation directory ++================= ========================================================== ++Python modules :file:`{prefix}/lib/python{X.Y}/site-packages` ++extension modules :file:`{exec-prefix}/lib/python{X.Y}/site-packages` ++scripts :file:`{prefix}/bin` ++data :file:`{prefix}` ++C headers :file:`{prefix}/include/python{X.Y}/{distname}` ++================= ========================================================== + + There is no requirement that :option:`--prefix` or :option:`--exec-prefix` + actually point to an alternate Python installation; if the directories listed +@@ -418,7 +482,7 @@ + alternate Python installation, this is immaterial.) + + +-.. _inst-alt-install-windows: ++.. _inst-alt-install-prefix-windows: + + Alternate installation: Windows (the prefix scheme) + --------------------------------------------------- +@@ -433,20 +497,18 @@ + to install modules to the :file:`\\Temp\\Python` directory on the current drive. + + The installation base is defined by the :option:`--prefix` option; the +-:option:`--exec-prefix` option is not supported under Windows. Files are +-installed as follows: ++:option:`--exec-prefix` option is not supported under Windows, which means that ++pure Python modules and extension modules are installed into the same location. ++Files are installed as follows: + +-+------------------------------+---------------------------+-----------------------------+ +-| Type of file | Installation Directory | Override option | +-+==============================+===========================+=============================+ +-| pure module distribution | :file:`{prefix}` | :option:`--install-purelib` | +-+------------------------------+---------------------------+-----------------------------+ +-| non-pure module distribution | :file:`{prefix}` | :option:`--install-platlib` | +-+------------------------------+---------------------------+-----------------------------+ +-| scripts | :file:`{prefix}\\Scripts` | :option:`--install-scripts` | +-+------------------------------+---------------------------+-----------------------------+ +-| data | :file:`{prefix}\\Data` | :option:`--install-data` | +-+------------------------------+---------------------------+-----------------------------+ ++=============== ========================================================== ++Type of file Installation directory ++=============== ========================================================== ++modules :file:`{prefix}\\Lib\\site-packages` ++scripts :file:`{prefix}\\Scripts` ++data :file:`{prefix}` ++C headers :file:`{prefix}\\Include\\{distname}` ++=============== ========================================================== + + + .. _inst-custom-install: +@@ -460,13 +522,29 @@ + or you might want to completely redefine the installation scheme. In either + case, you're creating a *custom installation scheme*. + +-You probably noticed the column of "override options" in the tables describing +-the alternate installation schemes above. Those options are how you define a +-custom installation scheme. These override options can be relative, absolute, ++To create a custom installation scheme, you start with one of the alternate ++schemes and override some of the installation directories used for the various ++types of files, using these options: ++ ++====================== ======================= ++Type of file Override option ++====================== ======================= ++Python modules ``--install-purelib`` ++extension modules ``--install-platlib`` ++all modules ``--install-lib`` ++scripts ``--install-scripts`` ++data ``--install-data`` ++C headers ``--install-headers`` ++====================== ======================= ++ ++These override options can be relative, absolute, + or explicitly defined in terms of one of the installation base directories. + (There are two installation base directories, and they are normally the same--- + they only differ when you use the Unix "prefix scheme" and supply different +-:option:`--prefix` and :option:`--exec-prefix` options.) ++``--prefix`` and ``--exec-prefix`` options; using ``--install-lib`` will ++override values computed or given for ``--install-purelib`` and ++``--install-platlib``, and is recommended for schemes that don't make a ++difference between Python and extension modules.) + + For example, say you're installing a module distribution to your home directory + under Unix---but you want scripts to go in :file:`~/scripts` rather than +@@ -493,15 +571,16 @@ + a subdirectory of :file:`{prefix}`, rather than right in :file:`{prefix}` + itself. This is almost as easy as customizing the script installation directory + ---you just have to remember that there are two types of modules to worry about, +-pure modules and non-pure modules (i.e., modules from a non-pure distribution). +-For example:: ++Python and extension modules, which can conveniently be both controlled by one ++option:: + +- python setup.py install --install-purelib=Site --install-platlib=Site ++ python setup.py install --install-lib=Site + +-The specified installation directories are relative to :file:`{prefix}`. Of +-course, you also have to ensure that these directories are in Python's module +-search path, such as by putting a :file:`.pth` file in :file:`{prefix}`. See +-section :ref:`inst-search-path` to find out how to modify Python's search path. ++The specified installation directory is relative to :file:`{prefix}`. Of ++course, you also have to ensure that this directory is in Python's module ++search path, such as by putting a :file:`.pth` file in a site directory (see ++:mod:`site`). See section :ref:`inst-search-path` to find out how to modify ++Python's search path. + + If you want to define an entire installation scheme, you just have to supply all + of the installation directory options. The recommended way to do this is to +@@ -553,8 +632,8 @@ + + python setup.py install --install-base=/tmp + +-would install pure modules to :file:`{/tmp/python/lib}` in the first case, and +-to :file:`{/tmp/lib}` in the second case. (For the second case, you probably ++would install pure modules to :file:`/tmp/python/lib` in the first case, and ++to :file:`/tmp/lib` in the second case. (For the second case, you probably + want to supply an installation base of :file:`/tmp/python`.) + + You probably noticed the use of ``$HOME`` and ``$PLAT`` in the sample +@@ -571,7 +650,7 @@ + needed on those platforms? + + +-.. XXX I'm not sure where this section should go. ++.. XXX Move this to Doc/using + + .. _inst-search-path: + +diff -r 8527427914a2 Doc/library/2to3.rst +--- a/Doc/library/2to3.rst ++++ b/Doc/library/2to3.rst +@@ -94,6 +94,38 @@ + :option:`-p` to run fixers on code that already has had its print statements + converted. + ++The :option:`-o` or :option:`--output-dir` option allows specification of an ++alternate directory for processed output files to be written to. The ++:option:`-n` flag is required when using this as backup files do not make sense ++when not overwriting the input files. ++ ++.. versionadded:: 2.7.3 ++ The :option:`-o` option was added. ++ ++The :option:`-W` or :option:`--write-unchanged-files` flag tells 2to3 to always ++write output files even if no changes were required to the file. This is most ++useful with :option:`-o` so that an entire Python source tree is copied with ++translation from one directory to another. ++This option implies the :option:`-w` flag as it would not make sense otherwise. ++ ++.. versionadded:: 2.7.3 ++ The :option:`-W` flag was added. ++ ++The :option:`--add-suffix` option specifies a string to append to all output ++filenames. The :option:`-n` flag is required when specifying this as backups ++are not necessary when writing to different filenames. Example:: ++ ++ $ 2to3 -n -W --add-suffix=3 example.py ++ ++Will cause a converted file named ``example.py3`` to be written. ++ ++.. versionadded:: 2.7.3 ++ The :option:`--add-suffix` option was added. ++ ++To translate an entire project from one directory tree to another use:: ++ ++ $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode ++ + + .. _2to3-fixers: + +@@ -123,7 +155,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 + +@@ -230,7 +264,7 @@ + + .. 2to3fixer:: long + +- Strips the ``L`` prefix on long literals and renames :class:`long` to ++ Strips the ``L`` suffix on long literals and renames :class:`long` to + :class:`int`. + + .. 2to3fixer:: map +diff -r 8527427914a2 Doc/library/__builtin__.rst +--- a/Doc/library/__builtin__.rst ++++ b/Doc/library/__builtin__.rst +@@ -8,7 +8,9 @@ + + This module provides direct access to all 'built-in' identifiers of Python; for + example, ``__builtin__.open`` is the full name for the built-in function +-:func:`open`. ++:func:`open`. See :ref:`built-in-funcs` and :ref:`built-in-consts` for ++documentation. ++ + + This module is not normally accessed explicitly by most applications, but can be + useful in modules that provide objects with the same name as a built-in value, +diff -r 8527427914a2 Doc/library/__future__.rst +--- a/Doc/library/__future__.rst ++++ b/Doc/library/__future__.rst +@@ -4,6 +4,9 @@ + .. module:: __future__ + :synopsis: Future statement definitions + ++**Source code:** :source:`Lib/__future__.py` ++ ++-------------- + + :mod:`__future__` is a real module, and serves three purposes: + +diff -r 8527427914a2 Doc/library/abc.rst +--- a/Doc/library/abc.rst ++++ b/Doc/library/abc.rst +@@ -9,8 +9,12 @@ + + .. versionadded:: 2.6 + +-This module provides the infrastructure for defining an :term:`abstract base +-class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this ++**Source code:** :source:`Lib/abc.py` ++ ++-------------- ++ ++This module provides the infrastructure for defining :term:`abstract base ++classes ` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this + was added to Python. (See also :pep:`3141` and the :mod:`numbers` module + regarding a type hierarchy for numbers based on ABCs.) + +diff -r 8527427914a2 Doc/library/aifc.rst +--- a/Doc/library/aifc.rst ++++ b/Doc/library/aifc.rst +@@ -10,6 +10,10 @@ + single: AIFF + single: AIFF-C + ++**Source code:** :source:`Lib/aifc.py` ++ ++-------------- ++ + This module provides support for reading and writing AIFF and AIFF-C files. + AIFF is Audio Interchange File Format, a format for storing digital audio + samples in a file. AIFF-C is a newer version of the format that includes the +diff -r 8527427914a2 Doc/library/al.rst +--- a/Doc/library/al.rst ++++ b/Doc/library/al.rst +@@ -53,7 +53,7 @@ + .. function:: queryparams(device) + + The device argument is an integer. The return value is a list of integers +- containing the data returned by :cfunc:`ALqueryparams`. ++ containing the data returned by :c:func:`ALqueryparams`. + + + .. function:: getparams(device, list) +diff -r 8527427914a2 Doc/library/argparse.rst +--- a/Doc/library/argparse.rst ++++ b/Doc/library/argparse.rst +@@ -2,11 +2,15 @@ + =============================================================================== + + .. module:: argparse +- :synopsis: Command-line option and argument-parsing library. ++ :synopsis: Command-line option and argument parsing library. + .. moduleauthor:: Steven Bethard +-.. versionadded:: 2.7 + .. sectionauthor:: Steven Bethard + ++.. versionadded:: 2.7 ++ ++**Source code:** :source:`Lib/argparse.py` ++ ++-------------- + + The :mod:`argparse` module makes it easy to write user-friendly command-line + interfaces. The program defines what arguments it requires, and :mod:`argparse` +@@ -103,10 +107,10 @@ + Parsing arguments + ^^^^^^^^^^^^^^^^^ + +-:class:`ArgumentParser` parses args through the ++: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. +-In most cases, this means a simple namespace object will be built up from ++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:: + + >>> parser.parse_args(['--sum', '7', '-1', '42']) +@@ -114,7 +118,7 @@ + + In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no + arguments, and the :class:`ArgumentParser` will automatically determine the +-command-line args from :data:`sys.argv`. ++command-line arguments from :data:`sys.argv`. + + + ArgumentParser objects +@@ -149,7 +153,7 @@ + conflicting optionals. + + * prog_ - The name of the program (default: +- :data:`sys.argv[0]`) ++ ``sys.argv[0]``) + + * usage_ - The string describing the program usage (default: generated) + +@@ -238,7 +242,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:: +@@ -254,7 +258,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 +@@ -267,7 +271,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. + + +@@ -389,7 +393,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:: + +@@ -415,7 +419,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`, +@@ -642,11 +646,11 @@ + action + ^^^^^^ + +-:class:`ArgumentParser` objects associate command-line args with actions. These +-actions can do just about anything with the command-line args associated with ++:class:`ArgumentParser` objects associate command-line arguments with actions. These ++actions can do just about anything with the command-line arguments associated with + them, though most actions simply add an attribute to the object returned by + :meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies +-how the command-line args should be handled. The supported actions are: ++how the command-line arguments should be handled. The supported actions are: + + * ``'store'`` - This just stores the argument's value. This is the default + action. For example:: +@@ -666,15 +670,17 @@ + >>> parser.parse_args('--foo'.split()) + Namespace(foo=42) + +-* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and +- ``False`` respectively. These are special cases of ``'store_const'``. For +- example:: ++* ``'store_true'`` and ``'store_false'`` - These are special cases of ++ ``'store_const'`` using for storing the values ``True`` and ``False`` ++ respectively. In addition, they create default values of *False* and *True* ++ respectively. For example:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo', action='store_true') + >>> parser.add_argument('--bar', action='store_false') ++ >>> parser.add_argument('--baz', action='store_false') + >>> parser.parse_args('--foo --bar'.split()) +- Namespace(bar=False, foo=True) ++ Namespace(bar=False, baz=True, foo=True) + + * ``'append'`` - This stores a list, and appends each argument value to the + list. This is useful to allow an option to be specified multiple times. +@@ -697,6 +703,19 @@ + >>> parser.parse_args('--str --int'.split()) + Namespace(types=[, ]) + ++* ``'count'`` - This counts the number of times a keyword argument occurs. For ++ example, this is useful for increasing verbosity levels:: ++ ++ >>> parser = argparse.ArgumentParser() ++ >>> parser.add_argument('--verbose', '-v', action='count') ++ >>> parser.parse_args('-vvv'.split()) ++ Namespace(verbose=3) ++ ++* ``'help'`` - This prints a complete help message for all the options in the ++ current parser and then exits. By default a help action is automatically ++ added to the parser. See :class:`ArgumentParser` for details of how the ++ output is created. ++ + * ``'version'`` - This expects a ``version=`` keyword argument in the + :meth:`~ArgumentParser.add_argument` call, and prints version information + and exits when invoked. +@@ -714,12 +733,12 @@ + + * ``parser`` - The ArgumentParser object which contains this action. + +-* ``namespace`` - The namespace object that will be returned by ++* ``namespace`` - The :class:`Namespace` object that will be returned by + :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this + object. + +-* ``values`` - The associated command-line args, with any type-conversions +- applied. (Type-conversions are specified with the type_ keyword argument to ++* ``values`` - The associated command-line arguments, with any type conversions ++ applied. (Type conversions are specified with the type_ keyword argument to + :meth:`~ArgumentParser.add_argument`. + + * ``option_string`` - The option string that was used to invoke this action. +@@ -751,7 +770,7 @@ + different number of command-line arguments with a single action. The supported + values are: + +-* N (an integer). N args 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() +@@ -763,11 +782,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() +@@ -795,7 +814,7 @@ + Namespace(infile=', mode 'r' at 0x...>, + outfile=', mode 'w' at 0x...>) + +-* ``'*'``. All command-line args present are gathered into a list. Note that ++* ``'*'``. All command-line arguments present are gathered into a list. Note that + it generally doesn't make much sense to have more than one positional argument + with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is + possible. For example:: +@@ -809,7 +828,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='+') +@@ -819,8 +838,19 @@ + usage: PROG [-h] foo [foo ...] + PROG: error: too few arguments + +-If the ``nargs`` keyword argument is not provided, the number of args consumed +-is determined by the action_. Generally this means a single command-line arg ++* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered ++ into a list. This is commonly useful for command line utilities that dispatch ++ to other command line utilities. ++ ++ >>> parser = argparse.ArgumentParser(prog='PROG') ++ >>> parser.add_argument('--foo') ++ >>> parser.add_argument('command') ++ >>> parser.add_argument('args', nargs=argparse.REMAINDER) ++ >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()) ++ Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B') ++ ++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 argument + will be consumed and a single item (not a list) will be produced. + + +@@ -837,9 +867,9 @@ + + * When :meth:`~ArgumentParser.add_argument` is called with option strings + (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional +- argument that can be followed by zero or one command-line args. ++ 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``. +@@ -851,7 +881,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:: + +@@ -862,8 +892,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) +@@ -887,12 +917,12 @@ + type + ^^^^ + +-By default, ArgumentParser objects read command-line args in as simple strings. +-However, quite often the command-line string should instead be interpreted as +-another type, like a :class:`float`, :class:`int` or :class:`file`. The ++By default, :class:`ArgumentParser` objects read command-line arguments in as simple ++strings. However, quite often the command-line string should instead be ++interpreted as another type, like a :class:`float` or :class:`int`. The + ``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any +-necessary type-checking and type-conversions to be performed. Many common +-built-in types can be used directly as the value of the ``type`` argument:: ++necessary type-checking and type conversions to be performed. Common built-in ++types and functions can be used directly as the value of the ``type`` argument:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('foo', type=int) +@@ -911,7 +941,7 @@ + Namespace(bar=) + + ``type=`` can take any callable that takes a single string argument and returns +-the type-converted value:: ++the converted value:: + + >>> def perfect_square(string): + ... value = int(string) +@@ -946,11 +976,11 @@ + choices + ^^^^^^^ + +-Some command-line args should be selected from a restricted set of values. ++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') +@@ -1043,6 +1073,17 @@ + optional arguments: + -h, --help show this help message and exit + ++:mod:`argparse` supports silencing the help entry for certain options, by ++setting the ``help`` value to ``argparse.SUPPRESS``:: ++ ++ >>> parser = argparse.ArgumentParser(prog='frobble') ++ >>> parser.add_argument('--foo', help=argparse.SUPPRESS) ++ >>> parser.print_help() ++ usage: frobble [-h] ++ ++ optional arguments: ++ -h, --help show this help message and exit ++ + + metavar + ^^^^^^^ +@@ -1052,8 +1093,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() +@@ -1125,10 +1166,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:: + +@@ -1160,7 +1201,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. + + +@@ -1231,15 +1272,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') +@@ -1272,7 +1313,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:: +@@ -1304,7 +1345,7 @@ + Beyond ``sys.argv`` + ^^^^^^^^^^^^^^^^^^^ + +-Sometimes it may be useful to have an ArgumentParser parse args other than those ++Sometimes it may be useful to have an ArgumentParser parse arguments other than those + of :data:`sys.argv`. This can be accomplished by passing a list of strings to + :meth:`~ArgumentParser.parse_args`. This is useful for testing at the + interactive prompt:: +@@ -1325,11 +1366,14 @@ + The Namespace object + ^^^^^^^^^^^^^^^^^^^^ + +-By default, :meth:`~ArgumentParser.parse_args` will return a new object of type +-:class:`Namespace` where the necessary attributes have been set. This class is +-deliberately simple, just an :class:`object` subclass with a readable string +-representation. If you prefer to have dict-like view of the attributes, you +-can use the standard Python idiom via :func:`vars`:: ++.. class:: Namespace ++ ++ Simple class used by default by :meth:`~ArgumentParser.parse_args` to create ++ an object holding attributes and return it. ++ ++This class is deliberately simple, just an :class:`object` subclass with a ++readable string representation. If you prefer to have dict-like view of the ++attributes, you can use the standard Python idiom, :func:`vars`:: + + >>> parser = argparse.ArgumentParser() + >>> parser.add_argument('--foo') +@@ -1387,7 +1431,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']) +@@ -1396,8 +1440,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 +@@ -1519,7 +1563,7 @@ + + The :class:`FileType` factory creates objects that can be passed to the type + argument of :meth:`ArgumentParser.add_argument`. Arguments that have +- :class:`FileType` objects as their type will open command-line args as files ++ :class:`FileType` objects as their type will open command-line arguments as files + with the requested modes and buffer sizes: + + >>> parser = argparse.ArgumentParser() +@@ -1633,7 +1677,7 @@ + .. method:: ArgumentParser.set_defaults(**kwargs) + + Most of the time, the attributes of the object returned by :meth:`parse_args` +- will be fully determined by inspecting the command-line args and the argument ++ will be fully determined by inspecting the command-line arguments and the argument + actions. :meth:`set_defaults` allows some additional + attributes that are determined without any inspection of the command line to + be added:: +@@ -1757,7 +1801,7 @@ + .. method:: ArgumentParser.error(message) + + This method prints a usage message including the *message* to the +- standard output and terminates the program with a status code of 2. ++ standard error and terminates the program with a status code of 2. + + + .. _argparse-from-optparse: +diff -r 8527427914a2 Doc/library/array.rst +--- a/Doc/library/array.rst ++++ b/Doc/library/array.rst +@@ -107,7 +107,7 @@ + memory buffer in bytes can be computed as ``array.buffer_info()[1] * + array.itemsize``. This is occasionally useful when working with low-level (and + inherently unsafe) I/O interfaces that require memory addresses, such as certain +- :cfunc:`ioctl` operations. The returned numbers are valid as long as the array ++ :c:func:`ioctl` operations. The returned numbers are valid as long as the array + exists and no length-changing operations are applied to it. + + .. note:: +diff -r 8527427914a2 Doc/library/ast.rst +--- a/Doc/library/ast.rst ++++ b/Doc/library/ast.rst +@@ -1,7 +1,5 @@ +-.. _ast: +- +-Abstract Syntax Trees +-===================== ++:mod:`ast` --- Abstract Syntax Trees ++==================================== + + .. module:: ast + :synopsis: Abstract Syntax Tree classes and manipulation. +@@ -15,6 +13,9 @@ + .. versionadded:: 2.6 + The high-level ``ast`` module containing all helpers. + ++**Source code:** :source:`Lib/ast.py` ++ ++-------------- + + The :mod:`ast` module helps Python applications to process trees of the Python + abstract syntax grammar. The abstract syntax itself might change with each +@@ -28,11 +29,6 @@ + compiled into a Python code object using the built-in :func:`compile` function. + + +-.. seealso:: +- +- Latest version of the `ast module Python source code +- `_ +- + Node classes + ------------ + +diff -r 8527427914a2 Doc/library/asynchat.rst +--- a/Doc/library/asynchat.rst ++++ b/Doc/library/asynchat.rst +@@ -1,4 +1,3 @@ +- + :mod:`asynchat` --- Asynchronous socket command/response handler + ================================================================ + +@@ -7,6 +6,9 @@ + .. moduleauthor:: Sam Rushing + .. sectionauthor:: Steve Holden + ++**Source code:** :source:`Lib/asynchat.py` ++ ++-------------- + + This module builds on the :mod:`asyncore` infrastructure, simplifying + asynchronous clients and servers and making it easier to handle protocols +@@ -32,7 +34,7 @@ + + Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of + events that are generated by an analysis of socket conditions after a +- :cfunc:`select` call. Once the polling loop has been started the ++ :c:func:`select` call. Once the polling loop has been started the + :class:`async_chat` object's methods are called by the event-processing + framework with no action on the part of the programmer. + +diff -r 8527427914a2 Doc/library/asyncore.rst +--- a/Doc/library/asyncore.rst ++++ b/Doc/library/asyncore.rst +@@ -1,4 +1,3 @@ +- + :mod:`asyncore` --- Asynchronous socket handler + =============================================== + +@@ -10,6 +9,9 @@ + .. sectionauthor:: Steve Holden + .. heavily adapted from original documentation by Sam Rushing + ++**Source code:** :source:`Lib/asyncore.py` ++ ++-------------- + + This module provides the basic infrastructure for writing asynchronous socket + service clients and servers. +@@ -23,7 +25,7 @@ + are probably what you really need. Network servers are rarely processor + bound, however. + +-If your operating system supports the :cfunc:`select` system call in its I/O ++If your operating system supports the :c:func:`select` system call in its I/O + library (and nearly all do), then you can use it to juggle multiple + communication channels at once; doing other work while your I/O is taking + place in the "background." Although this strategy can seem strange and +@@ -93,8 +95,8 @@ + + During asynchronous processing, each mapped channel's :meth:`readable` and + :meth:`writable` methods are used to determine whether the channel's socket +- should be added to the list of channels :cfunc:`select`\ ed or +- :cfunc:`poll`\ ed for read and write events. ++ should be added to the list of channels :c:func:`select`\ ed or ++ :c:func:`poll`\ ed for read and write events. + + Thus, the set of channel events is larger than the basic socket events. The + full set of methods that can be overridden in your subclass follows: +@@ -236,9 +238,9 @@ + .. class:: file_dispatcher() + + A file_dispatcher takes a file descriptor or file object along with an +- optional map argument and wraps it for use with the :cfunc:`poll` or +- :cfunc:`loop` functions. If provided a file object or anything with a +- :cfunc:`fileno` method, that method will be called and passed to the ++ optional map argument and wraps it for use with the :c:func:`poll` or ++ :c:func:`loop` functions. If provided a file object or anything with a ++ :c:func:`fileno` method, that method will be called and passed to the + :class:`file_wrapper` constructor. Availability: UNIX. + + .. class:: file_wrapper() +diff -r 8527427914a2 Doc/library/atexit.rst +--- a/Doc/library/atexit.rst ++++ b/Doc/library/atexit.rst +@@ -1,4 +1,3 @@ +- + :mod:`atexit` --- Exit handlers + =============================== + +@@ -10,14 +9,15 @@ + + .. versionadded:: 2.0 + ++**Source code:** :source:`Lib/atexit.py` ++ ++-------------- ++ + The :mod:`atexit` module defines a single function to register cleanup + functions. Functions thus registered are automatically executed upon normal +-interpreter termination. +- +-.. seealso:: +- +- Latest version of the `atexit Python source code +- `_ ++interpreter termination. The order in which the functions are called is not ++defined; if you have cleanup operations that depend on each other, you should ++wrap them in a function and register that one. This keeps :mod:`atexit` simple. + + Note: the functions registered via this module are not called when the program + is killed by a signal not handled by Python, when a Python fatal internal error +@@ -26,7 +26,7 @@ + .. index:: single: exitfunc (in sys) + + This is an alternate interface to the functionality provided by the +-``sys.exitfunc`` variable. ++:func:`sys.exitfunc` variable. + + Note: This module is unlikely to work correctly when used with other code that + sets ``sys.exitfunc``. In particular, other core Python modules are free to use +@@ -40,7 +40,8 @@ + + Register *func* as a function to be executed at termination. Any optional + arguments that are to be passed to *func* must be passed as arguments to +- :func:`register`. ++ :func:`register`. It is possible to register the same function and arguments ++ more than once. + + At normal program termination (for instance, if :func:`sys.exit` is called or + the main module's execution completes), all functions registered are called in +@@ -54,8 +55,8 @@ + be raised is re-raised. + + .. versionchanged:: 2.6 +- This function now returns *func* which makes it possible to use it as a +- decorator without binding the original name to ``None``. ++ This function now returns *func*, which makes it possible to use it as a ++ decorator. + + + .. seealso:: +@@ -109,5 +110,4 @@ + def goodbye(): + print "You are now leaving the Python sector." + +-This obviously only works with functions that don't take arguments. +- ++This only works with functions that can be called without arguments. +diff -r 8527427914a2 Doc/library/basehttpserver.rst +--- a/Doc/library/basehttpserver.rst ++++ b/Doc/library/basehttpserver.rst +@@ -18,6 +18,10 @@ + module: SimpleHTTPServer + module: CGIHTTPServer + ++**Source code:** :source:`Lib/BaseHTTPServer.py` ++ ++-------------- ++ + This module defines two classes for implementing HTTP servers (Web servers). + Usually, this module isn't used directly, but is used as a basis for building + functioning Web servers. See the :mod:`SimpleHTTPServer` and +diff -r 8527427914a2 Doc/library/bdb.rst +--- a/Doc/library/bdb.rst ++++ b/Doc/library/bdb.rst +@@ -4,6 +4,10 @@ + .. module:: bdb + :synopsis: Debugger framework. + ++**Source code:** :source:`Lib/bdb.py` ++ ++-------------- ++ + The :mod:`bdb` module handles basic debugger functions, like setting breakpoints + or managing execution via the debugger. + +diff -r 8527427914a2 Doc/library/bisect.rst +--- a/Doc/library/bisect.rst ++++ b/Doc/library/bisect.rst +@@ -7,6 +7,12 @@ + .. sectionauthor:: Raymond Hettinger + .. example based on the PyModules FAQ entry by Aaron Watters + ++.. versionadded:: 2.1 ++ ++**Source code:** :source:`Lib/bisect.py` ++ ++-------------- ++ + This module provides support for maintaining a list in sorted order without + having to sort the list after each insertion. For long lists of items with + expensive comparison operations, this can be an improvement over the more common +@@ -14,13 +20,6 @@ + algorithm to do its work. The source code may be most useful as a working + example of the algorithm (the boundary conditions are already right!). + +-.. versionadded:: 2.1 +- +-.. seealso:: +- +- Latest version of the `bisect module Python source code +- `_ +- + The following functions are provided: + + +diff -r 8527427914a2 Doc/library/bsddb.rst +--- a/Doc/library/bsddb.rst ++++ b/Doc/library/bsddb.rst +@@ -54,7 +54,7 @@ + optional *flag* identifies the mode used to open the file. It may be ``'r'`` + (read only), ``'w'`` (read-write) , ``'c'`` (read-write - create if necessary; + the default) or ``'n'`` (read-write - truncate to zero length). The other +- arguments are rarely used and are just passed to the low-level :cfunc:`dbopen` ++ arguments are rarely used and are just passed to the low-level :c:func:`dbopen` + function. Consult the Berkeley DB documentation for their use and + interpretation. + +diff -r 8527427914a2 Doc/library/bz2.rst +--- a/Doc/library/bz2.rst ++++ b/Doc/library/bz2.rst +@@ -67,6 +67,18 @@ + Support for the :keyword:`with` statement was added. + + ++ .. note:: ++ ++ This class does not support input files containing multiple streams (such ++ as those produced by the :program:`pbzip2` tool). When reading such an ++ input file, only the first stream will be accessible. If you require ++ support for multi-stream files, consider using the third-party ++ :mod:`bz2file` module (available from ++ `PyPI `_). This module provides a ++ backport of Python 3.3's :class:`BZ2File` class, which does support ++ multi-stream files. ++ ++ + .. method:: close() + + Close the file. Sets data attribute :attr:`closed` to true. A closed file +diff -r 8527427914a2 Doc/library/calendar.rst +--- a/Doc/library/calendar.rst ++++ b/Doc/library/calendar.rst +@@ -1,4 +1,3 @@ +- + :mod:`calendar` --- General calendar-related functions + ====================================================== + +@@ -7,6 +6,9 @@ + program. + .. sectionauthor:: Drew Csillag + ++**Source code:** :source:`Lib/calendar.py` ++ ++-------------- + + This module allows you to output calendars like the Unix :program:`cal` program, + and provides additional useful functions related to the calendar. By default, +@@ -22,10 +24,6 @@ + calendar in Dershowitz and Reingold's book "Calendrical Calculations", where + it's the base calendar for all computations. + +-.. seealso:: +- +- Latest version of the `calendar module Python source code +- `_ + + .. class:: Calendar([firstweekday]) + +diff -r 8527427914a2 Doc/library/carbon.rst +--- a/Doc/library/carbon.rst ++++ b/Doc/library/carbon.rst +@@ -14,7 +14,7 @@ + in Python (input and output buffers, especially). All methods and functions + have a :attr:`__doc__` string describing their arguments and return values, and + for additional description you are referred to `Inside Macintosh +-`_ or similar works. ++`_ or similar works. + + These modules all live in a package called :mod:`Carbon`. Despite that name they + are not all part of the Carbon framework: CF is really in the CoreFoundation +@@ -515,7 +515,7 @@ + + .. seealso:: + +- `Scrap Manager `_ ++ `Scrap Manager `_ + Apple's documentation for the Scrap Manager gives a lot of useful information + about using the Scrap Manager in applications. + +diff -r 8527427914a2 Doc/library/cgi.rst +--- a/Doc/library/cgi.rst ++++ b/Doc/library/cgi.rst +@@ -13,6 +13,10 @@ + single: URL + single: Common Gateway Interface + ++**Source code:** :source:`Lib/cgi.py` ++ ++-------------- ++ + Support module for Common Gateway Interface (CGI) scripts. + + This module defines a number of utilities for use by CGI scripts written in +diff -r 8527427914a2 Doc/library/cmd.rst +--- a/Doc/library/cmd.rst ++++ b/Doc/library/cmd.rst +@@ -1,4 +1,3 @@ +- + :mod:`cmd` --- Support for line-oriented command interpreters + ============================================================= + +@@ -6,17 +5,15 @@ + :synopsis: Build line-oriented command interpreters. + .. sectionauthor:: Eric S. Raymond + ++**Source code:** :source:`Lib/cmd.py` ++ ++-------------- + + The :class:`Cmd` class provides a simple framework for writing line-oriented + command interpreters. These are often useful for test harnesses, administrative + tools, and prototypes that will later be wrapped in a more sophisticated + interface. + +-.. seealso:: +- +- Latest version of the `cmd module Python source code +- `_ +- + .. class:: Cmd([completekey[, stdin[, stdout]]]) + + A :class:`Cmd` instance or subclass instance is a line-oriented interpreter +@@ -56,7 +53,7 @@ + the line as argument. + + The optional argument is a banner or intro string to be issued before the first +- prompt (this overrides the :attr:`intro` class member). ++ prompt (this overrides the :attr:`intro` class attribute). + + If the :mod:`readline` module is loaded, input will automatically inherit + :program:`bash`\ -like history-list editing (e.g. :kbd:`Control-P` scrolls back +diff -r 8527427914a2 Doc/library/codecs.rst +--- a/Doc/library/codecs.rst ++++ b/Doc/library/codecs.rst +@@ -759,9 +759,9 @@ + --------------------- + + Unicode strings are stored internally as sequences of codepoints (to be precise +-as :ctype:`Py_UNICODE` arrays). Depending on the way Python is compiled (either ++as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either + via ``--enable-unicode=ucs2`` or ``--enable-unicode=ucs4``, with the +-former being the default) :ctype:`Py_UNICODE` is either a 16-bit or 32-bit data ++former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data + type. Once a Unicode object is used outside of CPU and memory, CPU endianness + and how these arrays are stored as bytes become an issue. Transforming a + unicode object into a sequence of bytes is called encoding and recreating the +@@ -782,27 +782,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 Unicode string; as a ``ZERO WIDTH + NO-BREAK SPACE`` it's a normal character that will be decoded like any other. +@@ -810,8 +811,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): + +@@ -824,12 +825,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. +@@ -854,13 +850,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 8527427914a2 Doc/library/collections.rst +--- a/Doc/library/collections.rst ++++ b/Doc/library/collections.rst +@@ -1,4 +1,3 @@ +- + :mod:`collections` --- High-performance container datatypes + =========================================================== + +@@ -15,6 +14,10 @@ + import itertools + __name__ = '' + ++**Source code:** :source:`Lib/collections.py` and :source:`Lib/_abcoll.py` ++ ++-------------- ++ + This module implements specialized container datatypes providing alternatives to + Python's general purpose built-in containers, :class:`dict`, :class:`list`, + :class:`set`, and :class:`tuple`. +@@ -28,13 +31,10 @@ + ===================== ==================================================================== =========================== + + In addition to the concrete container classes, the collections module provides +-:ref:`abstract-base-classes` that can be used to test whether a class provides a +-particular interface, for example, whether it is hashable or a mapping. ++:ref:`abstract base classes ` that can be ++used to test whether a class provides a particular interface, for example, ++whether it is hashable or a mapping. + +-.. seealso:: +- +- Latest version of the `collections module Python source code +- `_ + + :class:`Counter` objects + ------------------------ +@@ -188,7 +188,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. +@@ -202,14 +202,14 @@ + * `Bag class `_ + in Smalltalk. + +- * Wikipedia entry for `Multisets `_\. ++ * Wikipedia entry for `Multisets `_. + + * `C++ multisets `_ + tutorial with examples. + + * For mathematical operations on multisets and their use cases, see + *Knuth, Donald. The Art of Computer Programming Volume II, +- Section 4.6.3, Exercise 19*\. ++ Section 4.6.3, Exercise 19*. + + * To enumerate all distinct multisets of a given size over a given set of + elements, see :func:`itertools.combinations_with_replacement`. +@@ -453,8 +453,7 @@ + :class:`defaultdict` objects support the following method in addition to the + standard :class:`dict` operations: + +- +- .. method:: defaultdict.__missing__(key) ++ .. method:: __missing__(key) + + If the :attr:`default_factory` attribute is ``None``, this raises a + :exc:`KeyError` exception with the *key* as argument. +@@ -470,11 +469,16 @@ + :class:`dict` class when the requested key is not found; whatever it + returns or raises is then returned or raised by :meth:`__getitem__`. + ++ Note that :meth:`__missing__` is *not* called for any operations besides ++ :meth:`__getitem__`. This means that :meth:`get` will, like normal ++ dictionaries, return ``None`` as a default rather than using ++ :attr:`default_factory`. ++ + + :class:`defaultdict` objects support the following instance variable: + + +- .. attribute:: defaultdict.default_factory ++ .. attribute:: default_factory + + This attribute is used by the :meth:`__missing__` method; it is + initialized from the first argument to the constructor, if present, or to +@@ -623,7 +627,9 @@ + 'Return a new OrderedDict which maps field names to their values' + return OrderedDict(zip(self._fields, self)) + +- def _replace(_self, **kwds): ++ __dict__ = property(_asdict) ++ ++ def _replace(_self, **kwds): + 'Return a new Point object replacing specified fields with new values' + result = _self._make(map(kwds.pop, ('x', 'y'), _self)) + if kwds: +@@ -849,14 +855,14 @@ + original insertion position is changed and moved to the end:: + + class LastUpdatedOrderedDict(OrderedDict): ++ 'Store items in the order the keys were last added' + +- 'Store items in the order the keys were last added' + def __setitem__(self, key, value): + if key in self: + 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): +@@ -869,10 +875,10 @@ + return self.__class__, (OrderedDict(self),) + + +-.. _abstract-base-classes: ++.. _collections-abstract-base-classes: + +-ABCs - abstract base classes +----------------------------- ++Collections Abstract Base Classes ++--------------------------------- + + The collections module offers the following :term:`ABCs `: + +@@ -886,7 +892,7 @@ + :class:`Sized` ``__len__`` + :class:`Callable` ``__call__`` + +-:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``. ``__iter__``, ``__reversed__``, ++:class:`Sequence` :class:`Sized`, ``__getitem__`` ``__contains__``, ``__iter__``, ``__reversed__``, + :class:`Iterable`, ``index``, and ``count`` + :class:`Container` + +@@ -1021,9 +1027,6 @@ + + .. seealso:: + +- * Latest version of the `Python source code for the collections abstract base classes +- `_ +- + * `OrderedSet recipe `_ for an + example built on :class:`MutableSet`. + +diff -r 8527427914a2 Doc/library/colorsys.rst +--- a/Doc/library/colorsys.rst ++++ b/Doc/library/colorsys.rst +@@ -5,6 +5,9 @@ + :synopsis: Conversion functions between RGB and other color systems. + .. sectionauthor:: David Ascher + ++**Source code:** :source:`Lib/colorsys.py` ++ ++-------------- + + The :mod:`colorsys` module defines bidirectional conversions of color values + between colors expressed in the RGB (Red Green Blue) color space used in +diff -r 8527427914a2 Doc/library/commands.rst +--- a/Doc/library/commands.rst ++++ b/Doc/library/commands.rst +@@ -38,7 +38,7 @@ + ``(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 :cfunc:`wait`. ++ according to the rules for the C function :c:func:`wait`. + + + .. function:: getoutput(cmd) +diff -r 8527427914a2 Doc/library/constants.rst +--- a/Doc/library/constants.rst ++++ b/Doc/library/constants.rst +@@ -1,3 +1,5 @@ ++.. _built-in-consts: ++ + Built-in Constants + ================== + +diff -r 8527427914a2 Doc/library/contextlib.rst +--- a/Doc/library/contextlib.rst ++++ b/Doc/library/contextlib.rst +@@ -7,15 +7,14 @@ + + .. versionadded:: 2.5 + ++**Source code:** :source:`Lib/contextlib.py` ++ ++-------------- ++ + This module provides utilities for common tasks involving the :keyword:`with` + statement. For more information see also :ref:`typecontextmanager` and + :ref:`context-managers`. + +-.. seealso:: +- +- Latest version of the `contextlib Python source code +- `_ +- + Functions provided: + + +diff -r 8527427914a2 Doc/library/cookie.rst +--- a/Doc/library/cookie.rst ++++ b/Doc/library/cookie.rst +@@ -11,6 +11,9 @@ + 3.0. The :term:`2to3` tool will automatically adapt imports when converting + your sources to 3.0. + ++**Source code:** :source:`Lib/Cookie.py` ++ ++-------------- + + The :mod:`Cookie` module defines classes for abstracting the concept of + cookies, an HTTP state management mechanism. It supports both simple string-only +@@ -191,7 +194,7 @@ + + .. method:: Morsel.set(key, value, coded_value) + +- Set the *key*, *value* and *coded_value* members. ++ Set the *key*, *value* and *coded_value* attributes. + + + .. method:: Morsel.isReservedKey(K) +diff -r 8527427914a2 Doc/library/cookielib.rst +--- a/Doc/library/cookielib.rst ++++ b/Doc/library/cookielib.rst +@@ -11,10 +11,11 @@ + Python 3.0. The :term:`2to3` tool will automatically adapt imports when + converting your sources to 3.0. + +- + .. versionadded:: 2.4 + ++**Source code:** :source:`Lib/cookielib.py` + ++-------------- + + The :mod:`cookielib` module defines classes for automatic handling of HTTP + cookies. It is useful for accessing web sites that require small pieces of data +diff -r 8527427914a2 Doc/library/copy.rst +--- a/Doc/library/copy.rst ++++ b/Doc/library/copy.rst +@@ -4,7 +4,11 @@ + .. module:: copy + :synopsis: Shallow and deep copy operations. + +-This module provides generic (shallow and deep) copying operations. ++Assignment statements in Python do not copy objects, they create bindings ++between a target and an object. For collections that are mutable or contain ++mutable items, a copy is sometimes needed so one can change one copy without ++changing the other. This module provides generic shallow and deep copy ++operations (explained below). + + + Interface summary: +diff -r 8527427914a2 Doc/library/crypto.rst +--- a/Doc/library/crypto.rst ++++ b/Doc/library/crypto.rst +@@ -27,5 +27,5 @@ + A.M. Kuchling of further interest; the package contains modules for various + encryption algorithms, most notably AES. These modules are not distributed with + Python but available separately. See the URL +-http://www.amk.ca/python/code/crypto.html for more information. ++http://www.pycrypto.org for more information. + +diff -r 8527427914a2 Doc/library/ctypes.rst +--- a/Doc/library/ctypes.rst ++++ b/Doc/library/ctypes.rst +@@ -40,7 +40,7 @@ + loads libraries which export functions using the standard ``cdecl`` calling + convention, while *windll* libraries call functions using the ``stdcall`` + calling convention. *oledll* also uses the ``stdcall`` calling convention, and +-assumes the functions return a Windows :ctype:`HRESULT` error code. The error ++assumes the functions return a Windows :c:type:`HRESULT` error code. The error + code is used to automatically raise a :class:`WindowsError` exception when the + function call fails. + +@@ -201,9 +201,9 @@ + ``None``, integers, longs, byte strings and unicode strings are the only native + Python objects that can directly be used as parameters in these function calls. + ``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are +-passed as pointer to the memory block that contains their data (:ctype:`char *` +-or :ctype:`wchar_t *`). Python integers and Python longs are passed as the +-platforms default C :ctype:`int` type, their value is masked to fit into the C ++passed as pointer to the memory block that contains their data (:c:type:`char *` ++or :c:type:`wchar_t *`). Python integers and Python longs are passed as the ++platforms default C :c:type:`int` type, their value is masked to fit into the C + type. + + Before we move on calling functions with other parameter types, we have to learn +@@ -217,48 +217,48 @@ + + :mod:`ctypes` defines a number of primitive C compatible data types : + +-+----------------------+----------------------------------------+----------------------------+ +-| ctypes type | C type | Python type | +-+======================+========================================+============================+ +-| :class:`c_bool` | :ctype:`_Bool` | bool (1) | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_char` | :ctype:`char` | 1-character string | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_wchar` | :ctype:`wchar_t` | 1-character unicode string | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_byte` | :ctype:`char` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_ubyte` | :ctype:`unsigned char` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_short` | :ctype:`short` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_ushort` | :ctype:`unsigned short` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_int` | :ctype:`int` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_uint` | :ctype:`unsigned int` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_long` | :ctype:`long` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_ulong` | :ctype:`unsigned long` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_longlong` | :ctype:`__int64` or :ctype:`long long` | int/long | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_ulonglong` | :ctype:`unsigned __int64` or | int/long | +-| | :ctype:`unsigned long long` | | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_float` | :ctype:`float` | float | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_double` | :ctype:`double` | float | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_longdouble`| :ctype:`long double` | float | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_char_p` | :ctype:`char *` (NUL terminated) | string or ``None`` | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_wchar_p` | :ctype:`wchar_t *` (NUL terminated) | unicode or ``None`` | +-+----------------------+----------------------------------------+----------------------------+ +-| :class:`c_void_p` | :ctype:`void *` | int/long or ``None`` | +-+----------------------+----------------------------------------+----------------------------+ +++----------------------+------------------------------------------+----------------------------+ ++| ctypes type | C type | Python type | +++======================+==========================================+============================+ ++| :class:`c_bool` | :c:type:`_Bool` | bool (1) | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_char` | :c:type:`char` | 1-character string | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_wchar` | :c:type:`wchar_t` | 1-character unicode string | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_byte` | :c:type:`char` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_ubyte` | :c:type:`unsigned char` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_short` | :c:type:`short` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_ushort` | :c:type:`unsigned short` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_int` | :c:type:`int` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_uint` | :c:type:`unsigned int` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_long` | :c:type:`long` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_ulong` | :c:type:`unsigned long` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int/long | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int/long | ++| | :c:type:`unsigned long long` | | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_float` | :c:type:`float` | float | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_double` | :c:type:`double` | float | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_longdouble`| :c:type:`long double` | float | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | string or ``None`` | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | unicode or ``None`` | +++----------------------+------------------------------------------+----------------------------+ ++| :class:`c_void_p` | :c:type:`void *` | int/long or ``None`` | +++----------------------+------------------------------------------+----------------------------+ + + (1) + The constructor accepts any object with a truth value. +@@ -329,7 +329,7 @@ + The :func:`create_string_buffer` function replaces the :func:`c_buffer` function + (which is still available as an alias), as well as the :func:`c_string` function + from earlier ctypes releases. To create a mutable memory block containing +-unicode characters of the C type :ctype:`wchar_t` use the ++unicode characters of the C type :c:type:`wchar_t` use the + :func:`create_unicode_buffer` function. + + +@@ -440,7 +440,7 @@ + Return types + ^^^^^^^^^^^^ + +-By default functions are assumed to return the C :ctype:`int` type. Other ++By default functions are assumed to return the C :c:type:`int` type. Other + return types can be specified by setting the :attr:`restype` attribute of the + function object. + +@@ -869,10 +869,10 @@ + + struct cell; /* forward declaration */ + +- struct { ++ struct cell { + char *name; + struct cell *next; +- } cell; ++ }; + + The straightforward translation into ctypes code would be this, but it does not + work:: +@@ -1338,7 +1338,7 @@ + + Instances of this class represent loaded shared libraries. Functions in these + libraries use the standard C calling convention, and are assumed to return +- :ctype:`int`. ++ :c:type:`int`. + + + .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False) +@@ -1355,7 +1355,7 @@ + + Windows only: Instances of this class represent loaded shared libraries, + functions in these libraries use the ``stdcall`` calling convention, and are +- assumed to return :ctype:`int` by default. ++ assumed to return :c:type:`int` by default. + + On Windows CE only the standard calling convention is used, for convenience the + :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this +@@ -1500,7 +1500,7 @@ + + An instance of :class:`PyDLL` that exposes Python C API functions as + attributes. Note that all these functions are assumed to return C +- :ctype:`int`, which is of course not always the truth, so you have to assign ++ :c:type:`int`, which is of course not always the truth, so you have to assign + the correct :attr:`restype` attribute to use these functions. + + +@@ -1530,10 +1530,10 @@ + .. attribute:: restype + + Assign a ctypes type to specify the result type of the foreign function. +- Use ``None`` for :ctype:`void`, a function not returning anything. ++ Use ``None`` for :c:type:`void`, a function not returning anything. + + It is possible to assign a callable Python object that is not a ctypes +- type, in this case the function is assumed to return a C :ctype:`int`, and ++ type, in this case the function is assumed to return a C :c:type:`int`, and + the callable will be called with this integer, allowing to do further + processing or error checking. Using this is deprecated, for more flexible + post processing or error checking use a ctypes data type as +@@ -2000,7 +2000,7 @@ + + .. function:: string_at(address[, size]) + +- This function returns the string starting at memory address address. If size ++ This function returns the string starting at memory address *address*. If size + is specified, it is used as size, otherwise the string is assumed to be + zero-terminated. + +@@ -2159,21 +2159,21 @@ + + .. class:: c_byte + +- Represents the C :ctype:`signed char` datatype, and interprets the value as ++ Represents the C :c:type:`signed char` datatype, and interprets the value as + small integer. The constructor accepts an optional integer initializer; no + overflow checking is done. + + + .. class:: c_char + +- Represents the C :ctype:`char` datatype, and interprets the value as a single ++ Represents the C :c:type:`char` datatype, and interprets the value as a single + character. The constructor accepts an optional string initializer, the + length of the string must be exactly one character. + + + .. class:: c_char_p + +- Represents the C :ctype:`char *` datatype when it points to a zero-terminated ++ Represents the C :c:type:`char *` datatype when it points to a zero-terminated + string. For a general character pointer that may also point to binary data, + ``POINTER(c_char)`` must be used. The constructor accepts an integer + address, or a string. +@@ -2181,13 +2181,13 @@ + + .. class:: c_double + +- Represents the C :ctype:`double` datatype. The constructor accepts an ++ Represents the C :c:type:`double` datatype. The constructor accepts an + optional float initializer. + + + .. class:: c_longdouble + +- Represents the C :ctype:`long double` datatype. The constructor accepts an ++ Represents the C :c:type:`long double` datatype. The constructor accepts an + optional float initializer. On platforms where ``sizeof(long double) == + sizeof(double)`` it is an alias to :class:`c_double`. + +@@ -2195,150 +2195,150 @@ + + .. class:: c_float + +- Represents the C :ctype:`float` datatype. The constructor accepts an ++ Represents the C :c:type:`float` datatype. The constructor accepts an + optional float initializer. + + + .. class:: c_int + +- Represents the C :ctype:`signed int` datatype. The constructor accepts an ++ Represents the C :c:type:`signed int` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. On platforms + where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`. + + + .. class:: c_int8 + +- Represents the C 8-bit :ctype:`signed int` datatype. Usually an alias for ++ Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_byte`. + + + .. class:: c_int16 + +- Represents the C 16-bit :ctype:`signed int` datatype. Usually an alias for ++ Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_short`. + + + .. class:: c_int32 + +- Represents the C 32-bit :ctype:`signed int` datatype. Usually an alias for ++ Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_int`. + + + .. class:: c_int64 + +- Represents the C 64-bit :ctype:`signed int` datatype. Usually an alias for ++ Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for + :class:`c_longlong`. + + + .. class:: c_long + +- Represents the C :ctype:`signed long` datatype. The constructor accepts an ++ Represents the C :c:type:`signed long` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. + + + .. class:: c_longlong + +- Represents the C :ctype:`signed long long` datatype. The constructor accepts ++ Represents the C :c:type:`signed long long` datatype. The constructor accepts + an optional integer initializer; no overflow checking is done. + + + .. class:: c_short + +- Represents the C :ctype:`signed short` datatype. The constructor accepts an ++ Represents the C :c:type:`signed short` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. + + + .. class:: c_size_t + +- Represents the C :ctype:`size_t` datatype. ++ Represents the C :c:type:`size_t` datatype. + + + .. class:: c_ssize_t + +- Represents the C :ctype:`ssize_t` datatype. ++ Represents the C :c:type:`ssize_t` datatype. + + .. versionadded:: 2.7 + + + .. class:: c_ubyte + +- Represents the C :ctype:`unsigned char` datatype, it interprets the value as ++ Represents the C :c:type:`unsigned char` datatype, it interprets the value as + small integer. The constructor accepts an optional integer initializer; no + overflow checking is done. + + + .. class:: c_uint + +- Represents the C :ctype:`unsigned int` datatype. The constructor accepts an ++ Represents the C :c:type:`unsigned int` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. On platforms + where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`. + + + .. class:: c_uint8 + +- Represents the C 8-bit :ctype:`unsigned int` datatype. Usually an alias for ++ Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_ubyte`. + + + .. class:: c_uint16 + +- Represents the C 16-bit :ctype:`unsigned int` datatype. Usually an alias for ++ Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_ushort`. + + + .. class:: c_uint32 + +- Represents the C 32-bit :ctype:`unsigned int` datatype. Usually an alias for ++ Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_uint`. + + + .. class:: c_uint64 + +- Represents the C 64-bit :ctype:`unsigned int` datatype. Usually an alias for ++ Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for + :class:`c_ulonglong`. + + + .. class:: c_ulong + +- Represents the C :ctype:`unsigned long` datatype. The constructor accepts an ++ Represents the C :c:type:`unsigned long` datatype. The constructor accepts an + optional integer initializer; no overflow checking is done. + + + .. class:: c_ulonglong + +- Represents the C :ctype:`unsigned long long` datatype. The constructor ++ Represents the C :c:type:`unsigned long long` datatype. The constructor + accepts an optional integer initializer; no overflow checking is done. + + + .. class:: c_ushort + +- Represents the C :ctype:`unsigned short` datatype. The constructor accepts ++ Represents the C :c:type:`unsigned short` datatype. The constructor accepts + an optional integer initializer; no overflow checking is done. + + + .. class:: c_void_p + +- Represents the C :ctype:`void *` type. The value is represented as integer. ++ Represents the C :c:type:`void *` type. The value is represented as integer. + The constructor accepts an optional integer initializer. + + + .. class:: c_wchar + +- Represents the C :ctype:`wchar_t` datatype, and interprets the value as a ++ Represents the C :c:type:`wchar_t` datatype, and interprets the value as a + single character unicode string. The constructor accepts an optional string + initializer, the length of the string must be exactly one character. + + + .. class:: c_wchar_p + +- Represents the C :ctype:`wchar_t *` datatype, which must be a pointer to a ++ Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a + zero-terminated wide character string. The constructor accepts an integer + address, or a string. + + + .. class:: c_bool + +- Represent the C :ctype:`bool` datatype (more accurately, :ctype:`_Bool` from ++ Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from + C99). Its value can be True or False, and the constructor accepts any object + that has a truth value. + +@@ -2347,18 +2347,18 @@ + + .. class:: HRESULT + +- Windows only: Represents a :ctype:`HRESULT` value, which contains success or ++ Windows only: Represents a :c:type:`HRESULT` value, which contains success or + error information for a function or method call. + + + .. class:: py_object + +- Represents the C :ctype:`PyObject *` datatype. Calling this without an +- argument creates a ``NULL`` :ctype:`PyObject *` pointer. ++ Represents the C :c:type:`PyObject *` datatype. Calling this without an ++ argument creates a ``NULL`` :c:type:`PyObject *` pointer. + + The :mod:`ctypes.wintypes` module provides quite some other Windows specific +-data types, for example :ctype:`HWND`, :ctype:`WPARAM`, or :ctype:`DWORD`. Some +-useful structures like :ctype:`MSG` or :ctype:`RECT` are also defined. ++data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some ++useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined. + + + .. _ctypes-structured-data-types: +diff -r 8527427914a2 Doc/library/curses.rst +--- a/Doc/library/curses.rst ++++ b/Doc/library/curses.rst +@@ -44,10 +44,6 @@ + Module :mod:`curses.textpad` + Editable text widget for curses supporting :program:`Emacs`\ -like bindings. + +- Module :mod:`curses.wrapper` +- Convenience function to ensure proper terminal setup and resetting on +- application entry and exit. +- + :ref:`curses-howto` + Tutorial material on using curses with Python, by Andrew Kuchling and Eric + Raymond. +@@ -79,7 +75,7 @@ + + .. function:: baudrate() + +- Returns the output speed of the terminal in bits per second. On software ++ Return the output speed of the terminal in bits per second. On software + terminal emulators it will have a fixed high value. Included for historical + reasons; in former times, it was used to write output loops for time delays and + occasionally to change interfaces depending on the line speed. +@@ -92,7 +88,7 @@ + + .. function:: can_change_color() + +- Returns true or false, depending on whether the programmer can change the colors ++ Return ``True`` or ``False``, depending on whether the programmer can change the colors + displayed by the terminal. + + +@@ -107,7 +103,7 @@ + + .. function:: color_content(color_number) + +- Returns the intensity of the red, green, and blue (RGB) components in the color ++ Return the intensity of the red, green, and blue (RGB) components in the color + *color_number*, which must be between ``0`` and :const:`COLORS`. A 3-tuple is + returned, containing the R,G,B values for the given color, which will be between + ``0`` (no component) and ``1000`` (maximum amount of component). +@@ -115,7 +111,7 @@ + + .. function:: color_pair(color_number) + +- Returns the attribute value for displaying text in the specified color. This ++ Return the attribute value for displaying text in the specified color. This + attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`, + and the other :const:`A_\*` attributes. :func:`pair_number` is the counterpart + to this function. +@@ -123,7 +119,7 @@ + + .. function:: curs_set(visibility) + +- Sets the cursor state. *visibility* can be set to 0, 1, or 2, for invisible, ++ Set the cursor state. *visibility* can be set to 0, 1, or 2, for invisible, + normal, or very visible. If the terminal supports the visibility requested, the + previous cursor state is returned; otherwise, an exception is raised. On many + terminals, the "visible" mode is an underline cursor and the "very visible" mode +@@ -132,7 +128,7 @@ + + .. function:: def_prog_mode() + +- Saves the current terminal mode as the "program" mode, the mode when the running ++ Save the current terminal mode as the "program" mode, the mode when the running + program is using curses. (Its counterpart is the "shell" mode, for when the + program is not in curses.) Subsequent calls to :func:`reset_prog_mode` will + restore this mode. +@@ -140,7 +136,7 @@ + + .. function:: def_shell_mode() + +- Saves the current terminal mode as the "shell" mode, the mode when the running ++ Save the current terminal mode as the "shell" mode, the mode when the running + program is not using curses. (Its counterpart is the "program" mode, when the + program is using curses capabilities.) Subsequent calls to + :func:`reset_shell_mode` will restore this mode. +@@ -148,7 +144,7 @@ + + .. function:: delay_output(ms) + +- Inserts an *ms* millisecond pause in output. ++ Insert an *ms* millisecond pause in output. + + + .. function:: doupdate() +@@ -179,7 +175,7 @@ + + .. function:: erasechar() + +- Returns the user's current erase character. Under Unix operating systems this ++ Return the user's current erase character. Under Unix operating systems this + is a property of the controlling tty of the curses program, and is not set by + the curses library itself. + +@@ -187,7 +183,7 @@ + .. function:: filter() + + The :func:`.filter` routine, if used, must be called before :func:`initscr` is +- called. The effect is that, during those calls, LINES is set to 1; the ++ called. The effect is that, during those calls, :envvar:`LINES` is set to 1; the + capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home + string is set to the value of cr. The effect is that the cursor is confined to + the current line, and so are screen updates. This may be used for enabling +@@ -213,7 +209,7 @@ + method should be call to retrieve the queued mouse event, represented as a + 5-tuple ``(id, x, y, z, bstate)``. *id* is an ID value used to distinguish + multiple devices, and *x*, *y*, *z* are the event's coordinates. (*z* is +- currently unused.). *bstate* is an integer value whose bits will be set to ++ currently unused.) *bstate* is an integer value whose bits will be set to + indicate the type of event, and will be the bitwise OR of one or more of the + following constants, where *n* is the button number from 1 to 4: + :const:`BUTTONn_PRESSED`, :const:`BUTTONn_RELEASED`, :const:`BUTTONn_CLICKED`, +@@ -223,32 +219,32 @@ + + .. function:: getsyx() + +- Returns the current coordinates of the virtual screen cursor in y and x. If ++ Return the current coordinates of the virtual screen cursor in y and x. If + leaveok is currently true, then -1,-1 is returned. + + + .. function:: getwin(file) + +- Reads window related data stored in the file by an earlier :func:`putwin` call. ++ Read window related data stored in the file by an earlier :func:`putwin` call. + The routine then creates and initializes a new window using that data, returning + the new window object. + + + .. function:: has_colors() + +- Returns true if the terminal can display colors; otherwise, it returns false. ++ Return ``True`` if the terminal can display colors; otherwise, return ``False``. + + + .. function:: has_ic() + +- Returns true if the terminal has insert- and delete- character capabilities. ++ Return ``True`` if the terminal has insert- and delete-character capabilities. + This function is included for historical reasons only, as all modern software + terminal emulators have such capabilities. + + + .. function:: has_il() + +- Returns true if the terminal has insert- and delete-line capabilities, or can ++ Return ``True`` if the terminal has insert- and delete-line capabilities, or can + simulate them using scrolling regions. This function is included for + historical reasons only, as all modern software terminal emulators have such + capabilities. +@@ -256,7 +252,7 @@ + + .. function:: has_key(ch) + +- Takes a key value *ch*, and returns true if the current terminal type recognizes ++ Take a key value *ch*, and return ``True`` if the current terminal type recognizes + a key with that value. + + +@@ -265,13 +261,13 @@ + Used for half-delay mode, which is similar to cbreak mode in that characters + typed by the user are immediately available to the program. However, after + blocking for *tenths* tenths of seconds, an exception is raised if nothing has +- been typed. The value of *tenths* must be a number between 1 and 255. Use ++ been typed. The value of *tenths* must be a number between ``1`` and ``255``. Use + :func:`nocbreak` to leave half-delay mode. + + + .. function:: init_color(color_number, r, g, b) + +- Changes the definition of a color, taking the number of the color to be changed ++ Change the definition of a color, taking the number of the color to be changed + followed by three RGB values (for the amounts of red, green, and blue + components). The value of *color_number* must be between ``0`` and + :const:`COLORS`. Each of *r*, *g*, *b*, must be a value between ``0`` and +@@ -282,7 +278,7 @@ + + .. function:: init_pair(pair_number, fg, bg) + +- Changes the definition of a color-pair. It takes three arguments: the number of ++ Change the definition of a color-pair. It takes three arguments: the number of + the color-pair to be changed, the foreground color number, and the background + color number. The value of *pair_number* must be between ``1`` and + ``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot +@@ -294,7 +290,7 @@ + + .. function:: initscr() + +- Initialize the library. Returns a :class:`WindowObject` which represents the ++ Initialize the library. Return a :class:`WindowObject` which represents the + whole screen. + + .. note:: +@@ -303,9 +299,15 @@ + cause the interpreter to exit. + + ++.. function:: is_term_resized(nlines, ncols) ++ ++ Return ``True`` if :func:`resize_term` would modify the window structure, ++ ``False`` otherwise. ++ ++ + .. function:: isendwin() + +- Returns true if :func:`endwin` has been called (that is, the curses library has ++ Return ``True`` if :func:`endwin` has been called (that is, the curses library has + been deinitialized). + + +@@ -321,14 +323,14 @@ + + .. function:: killchar() + +- Returns the user's current line kill character. Under Unix operating systems ++ Return the user's current line kill character. Under Unix operating systems + this is a property of the controlling tty of the curses program, and is not set + by the curses library itself. + + + .. function:: longname() + +- Returns a string containing the terminfo long name field describing the current ++ Return a string containing the terminfo long name field describing the current + terminal. The maximum length of a verbose description is 128 characters. It is + defined only after the call to :func:`initscr`. + +@@ -341,14 +343,14 @@ + + .. function:: mouseinterval(interval) + +- Sets the maximum time in milliseconds that can elapse between press and release +- events in order for them to be recognized as a click, and returns the previous ++ Set the maximum time in milliseconds that can elapse between press and release ++ events in order for them to be recognized as a click, and return the previous + interval value. The default value is 200 msec, or one fifth of a second. + + + .. function:: mousemask(mousemask) + +- Sets the mouse events to be reported, and returns a tuple ``(availmask, ++ Set the mouse events to be reported, and return a tuple ``(availmask, + oldmask)``. *availmask* indicates which of the specified mouse events can be + reported; on complete failure it returns 0. *oldmask* is the previous value of + the given window's mouse event mask. If this function is never called, no mouse +@@ -362,7 +364,7 @@ + + .. function:: newpad(nlines, ncols) + +- Creates and returns a pointer to a new pad data structure with the given number ++ Create and return a pointer to a new pad data structure with the given number + of lines and columns. A pad is returned as a window object. + + A pad is like a window, except that it is not restricted by the screen size, and +@@ -372,9 +374,9 @@ + echoing of input) do not occur. The :meth:`refresh` and :meth:`noutrefresh` + methods of a pad require 6 arguments to specify the part of the pad to be + displayed and the location on the screen to be used for the display. The +- arguments are pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol; the p ++ arguments are *pminrow*, *pmincol*, *sminrow*, *smincol*, *smaxrow*, *smaxcol*; the *p* + arguments refer to the upper left corner of the pad region to be displayed and +- the s arguments define a clipping box on the screen within which the pad region ++ the *s* arguments define a clipping box on the screen within which the pad region + is to be displayed. + + +@@ -416,7 +418,7 @@ + + .. function:: noqiflush() + +- When the noqiflush routine is used, normal flush of input and output queues ++ When the :func:`noqiflush` routine is used, normal flush of input and output queues + associated with the INTR, QUIT and SUSP characters will not be done. You may + want to call :func:`noqiflush` in a signal handler if you want output to + continue as though the interrupt had not occurred, after the handler exits. +@@ -429,27 +431,27 @@ + + .. function:: pair_content(pair_number) + +- Returns a tuple ``(fg, bg)`` containing the colors for the requested color pair. ++ Return a tuple ``(fg, bg)`` containing the colors for the requested color pair. + The value of *pair_number* must be between ``1`` and ``COLOR_PAIRS - 1``. + + + .. function:: pair_number(attr) + +- Returns the number of the color-pair set by the attribute value *attr*. ++ Return the number of the color-pair set by the attribute value *attr*. + :func:`color_pair` is the counterpart to this function. + + + .. function:: putp(string) + +- Equivalent to ``tputs(str, 1, putchar)``; emits the value of a specified +- terminfo capability for the current terminal. Note that the output of putp ++ Equivalent to ``tputs(str, 1, putchar)``; emit the value of a specified ++ terminfo capability for the current terminal. Note that the output of :func:`putp` + always goes to standard output. + + + .. function:: qiflush( [flag] ) + +- If *flag* is false, the effect is the same as calling :func:`noqiflush`. If +- *flag* is true, or no argument is provided, the queues will be flushed when ++ If *flag* is ``False``, the effect is the same as calling :func:`noqiflush`. If ++ *flag* is ``True``, or no argument is provided, the queues will be flushed when + these control characters are read. + + +@@ -462,26 +464,55 @@ + + .. function:: reset_prog_mode() + +- Restores the terminal to "program" mode, as previously saved by ++ Restore the terminal to "program" mode, as previously saved by + :func:`def_prog_mode`. + + + .. function:: reset_shell_mode() + +- Restores the terminal to "shell" mode, as previously saved by ++ Restore the terminal to "shell" mode, as previously saved by + :func:`def_shell_mode`. + + ++.. function:: resetty() ++ ++ Restore the state of the terminal modes to what it was at the last call to ++ :func:`savetty`. ++ ++ ++.. function:: resize_term(nlines, ncols) ++ ++ Backend function used by :func:`resizeterm`, performing most of the work; ++ when resizing the windows, :func:`resize_term` blank-fills the areas that are ++ extended. The calling application should fill in these areas with ++ appropriate data. The :func:`resize_term` function attempts to resize all ++ windows. However, due to the calling convention of pads, it is not possible ++ to resize these without additional interaction with the application. ++ ++ ++.. function:: resizeterm(nlines, ncols) ++ ++ Resize the standard and current windows to the specified dimensions, and ++ adjusts other bookkeeping data used by the curses library that record the ++ window dimensions (in particular the SIGWINCH handler). ++ ++ ++.. function:: savetty() ++ ++ Save the current state of the terminal modes in a buffer, usable by ++ :func:`resetty`. ++ ++ + .. function:: setsyx(y, x) + +- Sets the virtual screen cursor to *y*, *x*. If *y* and *x* are both -1, then ++ Set the virtual screen cursor to *y*, *x*. If *y* and *x* are both -1, then + leaveok is set. + + + .. function:: setupterm([termstr, fd]) + +- Initializes the terminal. *termstr* is a string giving the terminal name; if +- omitted, the value of the TERM environment variable will be used. *fd* is the ++ Initialize the terminal. *termstr* is a string giving the terminal name; if ++ omitted, the value of the :envvar:`TERM` environment variable will be used. *fd* is the + file descriptor to which any initialization sequences will be sent; if not + supplied, the file descriptor for ``sys.stdout`` will be used. + +@@ -501,19 +532,19 @@ + + .. function:: termattrs() + +- Returns a logical OR of all video attributes supported by the terminal. This ++ Return a logical OR of all video attributes supported by the terminal. This + information is useful when a curses program needs complete control over the + appearance of the screen. + + + .. function:: termname() + +- Returns the value of the environment variable TERM, truncated to 14 characters. ++ Return the value of the environment variable :envvar:`TERM`, truncated to 14 characters. + + + .. function:: tigetflag(capname) + +- Returns the value of the Boolean capability corresponding to the terminfo ++ Return the value of the Boolean capability corresponding to the terminfo + capability name *capname*. The value ``-1`` is returned if *capname* is not a + Boolean capability, or ``0`` if it is canceled or absent from the terminal + description. +@@ -521,7 +552,7 @@ + + .. function:: tigetnum(capname) + +- Returns the value of the numeric capability corresponding to the terminfo ++ Return the value of the numeric capability corresponding to the terminfo + capability name *capname*. The value ``-2`` is returned if *capname* is not a + numeric capability, or ``-1`` if it is canceled or absent from the terminal + description. +@@ -529,22 +560,22 @@ + + .. function:: tigetstr(capname) + +- Returns the value of the string capability corresponding to the terminfo ++ Return the value of the string capability corresponding to the terminfo + capability name *capname*. ``None`` is returned if *capname* is not a string + capability, or is canceled or absent from the terminal description. + + + .. function:: tparm(str[,...]) + +- Instantiates 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 ++ 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 + result depending on terminal type. + + + .. function:: typeahead(fd) + +- Specifies that the file descriptor *fd* be used for typeahead checking. If *fd* ++ Specify that the file descriptor *fd* be used for typeahead checking. If *fd* + is ``-1``, then no typeahead checking is done. + + The curses library does "line-breakout optimization" by looking for typeahead +@@ -556,7 +587,7 @@ + + .. function:: unctrl(ch) + +- Returns a string which is a printable representation of the character *ch*. ++ Return a string which is a printable representation of the character *ch*. + Control characters are displayed as a caret followed by the character, for + example as ``^C``. Printing characters are left as they are. + +@@ -579,7 +610,7 @@ + .. function:: use_env(flag) + + If used, this function should be called before :func:`initscr` or newterm are +- called. When *flag* is false, the values of lines and columns specified in the ++ called. When *flag* is ``False``, the values of lines and columns specified in the + terminfo database will be used, even if environment variables :envvar:`LINES` + and :envvar:`COLUMNS` (used by default) are set, or if curses is running in a + window (in which case default behavior would be to use the window size if +@@ -595,6 +626,19 @@ + foreground color on the default background. + + ++.. function:: wrapper(func, ...) ++ ++ Initialize curses and call another callable object, *func*, which should be the ++ rest of your curses-using application. If the application raises an exception, ++ this function will restore the terminal to a sane state before re-raising the ++ exception and generating a traceback. The callable object *func* is then passed ++ the main window 'stdscr' as its first argument, followed by any other arguments ++ passed to :func:`wrapper`. Before calling *func*, :func:`wrapper` turns on ++ cbreak mode, turns off echo, enables the terminal keypad, and initializes colors ++ if the terminal has color support. On exit (whether normally or by exception) ++ it restores cooked mode, turns on echo, and disables the terminal keypad. ++ ++ + .. _curses-window-objects: + + Window Objects +@@ -608,7 +652,7 @@ + + .. note:: + +- A *character* means a C character (an ASCII code), rather then a Python ++ A *character* means a C character (an ASCII code), rather than a Python + character (a string of length 1). (This note is true whenever the + documentation mentions a character.) The built-in :func:`ord` is handy for + conveying strings to codes. +@@ -650,7 +694,7 @@ + + .. method:: window.bkgd(ch[, attr]) + +- Sets the background property of the window to the character *ch*, with ++ Set the background property of the window to the character *ch*, with + attributes *attr*. The change is then applied to every character position in + that window: + +@@ -663,7 +707,7 @@ + + .. method:: window.bkgdset(ch[, attr]) + +- Sets the window's background. A window's background consists of a character and ++ Set the window's background. A window's background consists of a character and + any combination of attributes. The attribute part of the background is combined + (OR'ed) with all non-blank characters that are written into the window. Both + the character and attribute parts of the background are combined with the blank +@@ -708,12 +752,12 @@ + .. method:: window.box([vertch, horch]) + + Similar to :meth:`border`, but both *ls* and *rs* are *vertch* and both *ts* and +- bs are *horch*. The default corner characters are always used by this function. ++ *bs* are *horch*. The default corner characters are always used by this function. + + + .. method:: window.chgat([y, x, ] [num,] attr) + +- Sets the attributes of *num* characters at the current cursor position, or at ++ Set the attributes of *num* characters at the current cursor position, or at + position ``(y, x)`` if supplied. If no value of *num* is given or *num* = -1, + the attribute will be set on all the characters to the end of the line. This + function does not move the cursor. The changed line will be touched using the +@@ -723,7 +767,7 @@ + + .. method:: window.clear() + +- Like :meth:`erase`, but also causes the whole window to be repainted upon next ++ Like :meth:`erase`, but also cause the whole window to be repainted upon next + call to :meth:`refresh`. + + +@@ -746,7 +790,7 @@ + + .. method:: window.cursyncup() + +- Updates the current cursor position of all the ancestors of the window to ++ Update the current cursor position of all the ancestors of the window to + reflect the current cursor position of the window. + + +@@ -757,14 +801,14 @@ + + .. method:: window.deleteln() + +- Delete the line under the cursor. All following lines are moved up by 1 line. ++ Delete the line under the cursor. All following lines are moved up by one line. + + + .. method:: window.derwin([nlines, ncols,] begin_y, begin_x) + + An abbreviation for "derive window", :meth:`derwin` is the same as calling + :meth:`subwin`, except that *begin_y* and *begin_x* are relative to the origin +- of the window, rather than relative to the entire screen. Returns a window ++ of the window, rather than relative to the entire screen. Return a window + object for the derived window. + + +@@ -776,8 +820,8 @@ + + .. method:: window.enclose(y, x) + +- Tests whether the given pair of screen-relative character-cell coordinates are +- enclosed by the given window, returning true or false. It is useful for ++ Test whether the given pair of screen-relative character-cell coordinates are ++ enclosed by the given window, returning ``True`` or ``False``. It is useful for + determining what subset of the screen windows enclose the location of a mouse + event. + +@@ -792,6 +836,11 @@ + Return a tuple ``(y, x)`` of co-ordinates of upper-left corner. + + ++.. method:: window.getbkgd() ++ ++ Return the given window's current background character/attribute pair. ++ ++ + .. method:: window.getch([y, x]) + + Get a character. Note that the integer returned does *not* have to be in ASCII +@@ -814,8 +863,8 @@ + + .. method:: window.getparyx() + +- Returns the beginning coordinates of this window relative to its parent window +- into two integer variables y and x. Returns ``-1,-1`` if this window has no ++ Return the beginning coordinates of this window relative to its parent window ++ into two integer variables y and x. Return ``-1, -1`` if this window has no + parent. + + +@@ -838,8 +887,8 @@ + + .. method:: window.idcok(flag) + +- If *flag* is false, curses no longer considers using the hardware insert/delete +- character feature of the terminal; if *flag* is true, use of character insertion ++ If *flag* is ``False``, curses no longer considers using the hardware insert/delete ++ character feature of the terminal; if *flag* is ``True``, use of character insertion + and deletion is enabled. When curses is first initialized, use of character + insert/delete is enabled by default. + +@@ -852,7 +901,7 @@ + + .. method:: window.immedok(flag) + +- If *flag* is true, any change in the window image automatically causes the ++ If *flag* is ``True``, any change in the window image automatically causes the + window to be refreshed; you no longer have to call :meth:`refresh` yourself. + However, it may degrade performance considerably, due to repeated calls to + wrefresh. This option is disabled by default. +@@ -872,7 +921,7 @@ + + .. method:: window.insdelln(nlines) + +- Inserts *nlines* lines into the specified window above the current line. The ++ Insert *nlines* lines into the specified window above the current line. The + *nlines* bottom lines are lost. For negative *nlines*, delete *nlines* lines + starting with the one under the cursor, and move the remaining lines up. The + bottom *nlines* lines are cleared. The current cursor position remains the +@@ -881,7 +930,7 @@ + + .. method:: window.insertln() + +- Insert a blank line under the cursor. All following lines are moved down by 1 ++ Insert a blank line under the cursor. All following lines are moved down by one + line. + + +@@ -904,23 +953,23 @@ + + .. method:: window.instr([y, x] [, n]) + +- Returns a string of characters, extracted from the window starting at the ++ Return a string of characters, extracted from the window starting at the + current cursor position, or at *y*, *x* if specified. Attributes are stripped +- from the characters. If *n* is specified, :meth:`instr` returns return a string ++ from the characters. If *n* is specified, :meth:`instr` returns a string + at most *n* characters long (exclusive of the trailing NUL). + + + .. method:: window.is_linetouched(line) + +- Returns true if the specified line was modified since the last call to +- :meth:`refresh`; otherwise returns false. Raises a :exc:`curses.error` ++ Return ``True`` if the specified line was modified since the last call to ++ :meth:`refresh`; otherwise return ``False``. Raise a :exc:`curses.error` + exception if *line* is not valid for the given window. + + + .. method:: window.is_wintouched() + +- Returns true if the specified window was modified since the last call to +- :meth:`refresh`; otherwise returns false. ++ Return ``True`` if the specified window was modified since the last call to ++ :meth:`refresh`; otherwise return ``False``. + + + .. method:: window.keypad(yes) +@@ -946,7 +995,7 @@ + + .. method:: window.mvderwin(y, x) + +- Moves the window inside its parent window. The screen-relative parameters of ++ Move the window inside its parent window. The screen-relative parameters of + the window are not changed. This routine is used to display different parts of + the parent window at the same physical position on the screen. + +@@ -1004,19 +1053,19 @@ + + .. method:: window.putwin(file) + +- Writes all data associated with the window into the provided file object. This ++ Write all data associated with the window into the provided file object. This + information can be later retrieved using the :func:`getwin` function. + + + .. method:: window.redrawln(beg, num) + +- Indicates that the *num* screen lines, starting at line *beg*, are corrupted and ++ Indicate that the *num* screen lines, starting at line *beg*, are corrupted and + should be completely redrawn on the next :meth:`refresh` call. + + + .. method:: window.redrawwin() + +- Touches the entire window, causing it to be completely redrawn on the next ++ Touch the entire window, causing it to be completely redrawn on the next + :meth:`refresh` call. + + +@@ -1037,6 +1086,14 @@ + *sminrow*, or *smincol* are treated as if they were zero. + + ++.. method:: window.resize(nlines, ncols) ++ ++ Reallocate storage for a curses window to adjust its dimensions to the ++ specified values. If either dimension is larger than the current values, the ++ window's data is filled with blanks that have the current background ++ rendition (as set by :meth:`bkgdset`) merged into them. ++ ++ + .. method:: window.scroll([lines=1]) + + Scroll the screen or scrolling region upward by *lines* lines. +@@ -1044,7 +1101,7 @@ + + .. method:: window.scrollok(flag) + +- Controls what happens when the cursor of a window is moved off the edge of the ++ Control what happens when the cursor of a window is moved off the edge of the + window or scrolling region, either as a result of a newline action on the bottom + line, or typing the last character of the last line. If *flag* is false, the + cursor is left on the bottom line. If *flag* is true, the window is scrolled up +@@ -1086,26 +1143,26 @@ + + .. method:: window.syncdown() + +- Touches each location in the window that has been touched in any of its ancestor ++ Touch each location in the window that has been touched in any of its ancestor + windows. This routine is called by :meth:`refresh`, so it should almost never + be necessary to call it manually. + + + .. method:: window.syncok(flag) + +- If called with *flag* set to true, then :meth:`syncup` is called automatically ++ If called with *flag* set to ``True``, then :meth:`syncup` is called automatically + whenever there is a change in the window. + + + .. method:: window.syncup() + +- Touches all locations in ancestors of the window that have been changed in the ++ Touch all locations in ancestors of the window that have been changed in the + window. + + + .. method:: window.timeout(delay) + +- Sets blocking or non-blocking read behavior for the window. If *delay* is ++ Set blocking or non-blocking read behavior for the window. If *delay* is + negative, blocking read is used (which will wait indefinitely for input). If + *delay* is zero, then non-blocking read is used, and -1 will be returned by + :meth:`getch` if no input is waiting. If *delay* is positive, then +@@ -1128,7 +1185,7 @@ + + .. method:: window.untouchwin() + +- Marks all lines in the window as unchanged since the last call to ++ Mark all lines in the window as unchanged since the last call to + :meth:`refresh`. + + +@@ -1587,7 +1644,7 @@ + each keystroke entered with the keystroke as a parameter; command dispatch + is done on the result. This method returns the window contents as a + string; whether blanks in the window are included is affected by the +- :attr:`stripspaces` member. ++ :attr:`stripspaces` attribute. + + + .. method:: do_command(ch) +@@ -1653,45 +1710,15 @@ + + .. method:: gather() + +- This method returns the window contents as a string; whether blanks in the ++ Return the window contents as a string; whether blanks in the + window are included is affected by the :attr:`stripspaces` member. + + + .. attribute:: stripspaces + +- This data member is a flag which controls the interpretation of blanks in ++ This attribute is a flag which controls the interpretation of blanks in + the window. When it is on, trailing blanks on each line are ignored; any + cursor motion that would land the cursor on a trailing blank goes to the + end of that line instead, and trailing blanks are stripped when the window + contents are gathered. + +- +-:mod:`curses.wrapper` --- Terminal handler for curses programs +-============================================================== +- +-.. module:: curses.wrapper +- :synopsis: Terminal configuration wrapper for curses programs. +-.. moduleauthor:: Eric Raymond +-.. sectionauthor:: Eric Raymond +- +- +-.. versionadded:: 1.6 +- +-This module supplies one function, :func:`wrapper`, which runs another function +-which should be the rest of your curses-using application. If the application +-raises an exception, :func:`wrapper` will restore the terminal to a sane state +-before re-raising the exception and generating a traceback. +- +- +-.. function:: wrapper(func, ...) +- +- Wrapper function that initializes curses and calls another function, *func*, +- restoring normal keyboard/screen behavior on error. The callable object *func* +- is then passed the main window 'stdscr' as its first argument, followed by any +- other arguments passed to :func:`wrapper`. +- +-Before calling the hook function, :func:`wrapper` turns on cbreak mode, turns +-off echo, enables the terminal keypad, and initializes colors if the terminal +-has color support. On exit (whether normally or by exception) it restores +-cooked mode, turns on echo, and disables the terminal keypad. +- +diff -r 8527427914a2 Doc/library/datetime.rst +--- a/Doc/library/datetime.rst ++++ b/Doc/library/datetime.rst +@@ -13,7 +13,7 @@ + + The :mod:`datetime` module supplies classes for manipulating dates and times in + both simple and complex ways. While date and time arithmetic is supported, the +-focus of the implementation is on efficient member extraction for output ++focus of the implementation is on efficient attribute extraction for output + formatting and manipulation. For related + functionality, see also the :mod:`time` and :mod:`calendar` modules. + +@@ -27,8 +27,8 @@ + work with, at the cost of ignoring some aspects of reality. + + For applications requiring more, :class:`datetime` and :class:`time` objects +-have an optional time zone information member, :attr:`tzinfo`, that can contain +-an instance of a subclass of the abstract :class:`tzinfo` class. These ++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 no + concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module. +@@ -360,7 +360,7 @@ + + Return the local date corresponding to the POSIX timestamp, such as is returned + by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out +- of the range of values supported by the platform C :cfunc:`localtime` function. ++ of the range of values supported by the platform C :c:func:`localtime` function. + It's common for this to be restricted to years from 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`. +@@ -463,9 +463,9 @@ + + .. method:: date.replace(year, month, day) + +- Return a date with the same value, except for those members given new values by +- whichever keyword arguments are specified. For example, if ``d == date(2002, +- 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``. ++ Return a date with the same value, except for those parameters given new ++ values by whichever keyword arguments are specified. For example, if ``d == ++ date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``. + + + .. method:: date.timetuple() +@@ -534,7 +534,7 @@ + Return a string representing the date, for example ``date(2002, 12, + 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to + ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C +- :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which ++ :c:func:`ctime` function (which :func:`time.ctime` invokes, but which + :meth:`date.ctime` does not invoke) conforms to the C standard. + + +@@ -641,7 +641,7 @@ + or not specified, this is like :meth:`today`, but, if possible, supplies more + precision than can be gotten from going through a :func:`time.time` timestamp + (for example, this may be possible on platforms supplying the C +- :cfunc:`gettimeofday` function). ++ :c:func:`gettimeofday` function). + + Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the + current date and time are converted to *tz*'s time zone. In this case the +@@ -669,8 +669,8 @@ + ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``. + + :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of +- the range of values supported by the platform C :cfunc:`localtime` or +- :cfunc:`gmtime` functions. It's common for this to be restricted to years in ++ the range of values supported by the platform C :c:func:`localtime` or ++ :c:func:`gmtime` functions. It's common for this to be restricted to years in + 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 +@@ -681,7 +681,7 @@ + + 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 :cfunc:`gmtime` function. ++ 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 + :meth:`fromtimestamp`. + +@@ -696,11 +696,13 @@ + + .. classmethod:: datetime.combine(date, time) + +- Return a new :class:`datetime` object whose date members are equal to the given +- :class:`date` object's, and whose time and :attr:`tzinfo` members 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 and :attr:`tzinfo` members are ignored. ++ 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*, ++ ``d == datetime.combine(d.date(), d.timetz())``. If date is a ++ :class:`datetime` object, its time components and :attr:`tzinfo` attributes ++ are ignored. + + + .. classmethod:: datetime.strptime(date_string, format) +@@ -795,43 +797,44 @@ + (1) + datetime2 is a duration of timedelta removed from datetime1, moving forward in + time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The +- result has the same :attr:`tzinfo` member as the input datetime, and datetime2 - +- datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year +- would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note +- that no time zone adjustments are done even if the input is an aware object. ++ result has the same :attr:`tzinfo` attribute as the input datetime, and ++ datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if ++ datetime2.year would be smaller than :const:`MINYEAR` or larger than ++ :const:`MAXYEAR`. Note that no time zone adjustments are done even if the ++ input is an aware object. + + (2) + Computes the datetime2 such that datetime2 + timedelta == datetime1. As for +- addition, the result has the same :attr:`tzinfo` member as the input datetime, +- and no time zone adjustments are done even if the input is aware. This isn't +- quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation +- can overflow in cases where datetime1 - timedelta does not. ++ addition, the result has the same :attr:`tzinfo` attribute as the input ++ datetime, and no time zone adjustments are done even if the input is aware. ++ This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta ++ 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 + both operands are naive, or if both are aware. If one is aware and the other is + naive, :exc:`TypeError` is raised. + +- If both are naive, or both are aware and have the same :attr:`tzinfo` member, +- the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta` ++ If both are naive, or both are aware and have the same :attr:`tzinfo` attribute, ++ the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta` + object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments + are done in this case. + +- If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if +- *a* and *b* were first converted to naive UTC datetimes first. The result is +- ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - +- b.utcoffset())`` except that the implementation never overflows. ++ If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts ++ as if *a* and *b* were first converted to naive UTC datetimes first. The ++ result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) ++ - b.utcoffset())`` except that the implementation never overflows. + + (4) + *datetime1* is considered less than *datetime2* when *datetime1* precedes + *datetime2* 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` member, the +- common :attr:`tzinfo` member is ignored and the base datetimes are compared. If +- both comparands are aware and have different :attr:`tzinfo` members, the +- comparands are first adjusted by subtracting their UTC offsets (obtained from +- ``self.utcoffset()``). ++ If both comparands are aware, and have the same :attr:`tzinfo` attribute, the ++ common :attr:`tzinfo` attribute is ignored and the base datetimes are ++ compared. If both comparands are aware and have different :attr:`tzinfo` ++ attributes, the comparands are first adjusted by subtracting their UTC ++ offsets (obtained from ``self.utcoffset()``). + + .. note:: + +@@ -864,22 +867,22 @@ + .. method:: datetime.timetz() + + Return :class:`time` object with same hour, minute, second, microsecond, and +- tzinfo members. See also method :meth:`time`. ++ tzinfo attributes. See also method :meth:`time`. + + + .. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) + +- Return a datetime with the same members, except for those members given new +- values by whichever keyword arguments are specified. Note that ``tzinfo=None`` +- can be specified to create a naive datetime from an aware datetime with no +- conversion of date and time members. ++ Return a datetime with the same attributes, except for those attributes given ++ new values by whichever keyword arguments are specified. Note that ++ ``tzinfo=None`` can be specified to create a naive datetime from an aware ++ datetime with no conversion of date and time data. + + + .. method:: datetime.astimezone(tz) + +- Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting +- the date and time members so the result is the same UTC time as *self*, but in +- *tz*'s local time. ++ 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. + + *tz* must be an instance of a :class:`tzinfo` subclass, and its + :meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must +@@ -887,18 +890,18 @@ + not return ``None``). + + If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no +- adjustment of date or time members is performed. Else the result is local time +- in time zone *tz*, representing the same UTC time as *self*: after ``astz = +- dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date +- and time members as ``dt - dt.utcoffset()``. The discussion of class +- :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries +- where this cannot be achieved (an issue only if *tz* models both standard and +- daylight time). ++ adjustment of date or time data is performed. Else the result is local ++ time in time zone *tz*, representing the same UTC time as *self*: after ++ ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have ++ the same date and time data as ``dt - dt.utcoffset()``. The discussion ++ of class :class:`tzinfo` explains the cases at Daylight Saving Time transition ++ boundaries where this cannot be achieved (an issue only if *tz* models both ++ standard and daylight time). + + If you merely want to attach a time zone object *tz* to a datetime *dt* without +- adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you ++ adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you + merely want to remove the time zone object from an aware datetime *dt* without +- conversion of date and time members, use ``dt.replace(tzinfo=None)``. ++ conversion of date and time data, use ``dt.replace(tzinfo=None)``. + + Note that the default :meth:`tzinfo.fromutc` method can be overridden in a + :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`. +@@ -1021,7 +1024,7 @@ + Return a string representing the date and time, for example ``datetime(2002, 12, + 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is + equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the +- native C :cfunc:`ctime` function (which :func:`time.ctime` invokes, but which ++ native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which + :meth:`datetime.ctime` does not invoke) conforms to the C standard. + + +@@ -1161,19 +1164,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): +@@ -1200,7 +1203,7 @@ + + .. 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. + + +@@ -1209,14 +1212,14 @@ + * 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` member, the common :attr:`tzinfo` member is ignored and +- the base times are compared. If both comparands are aware and have different +- :attr:`tzinfo` members, 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 different type, +- :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The +- latter cases return :const:`False` or :const:`True`, respectively. ++ the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is ++ ignored and the base times are compared. If both comparands are aware and ++ 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 ++ different type, :exc:`TypeError` is raised unless the comparison is ``==`` or ++ ``!=``. The latter cases return :const:`False` or :const:`True`, respectively. + + * hash, use as dict key + +@@ -1231,10 +1234,10 @@ + + .. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]) + +- Return a :class:`time` with the same value, except for those members 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 members. ++ 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. + + + .. method:: time.isoformat() +@@ -1317,7 +1320,7 @@ + + 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 +-view their members as being in local time, and the :class:`tzinfo` object ++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. + +@@ -1362,9 +1365,9 @@ + already been added to the UTC offset returned by :meth:`utcoffset`, so there's + no need to consult :meth:`dst` unless you're interested in obtaining DST info + separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo` +- member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be +- set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes +- when crossing time zones. ++ attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag ++ should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for ++ DST changes when crossing time zones. + + An instance *tz* of a :class:`tzinfo` subclass that models both standard and + daylight times must be consistent in this sense: +@@ -1382,13 +1385,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 +@@ -1439,11 +1442,11 @@ + + .. method:: tzinfo.fromutc(self, dt) + +- This is called from the default :class:`datetime.astimezone()` implementation. +- When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members +- are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to +- adjust the date and time members, returning an equivalent datetime in *self*'s +- local time. ++ This is called from the default :class:`datetime.astimezone()` ++ implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s ++ date and time data are to be viewed as expressing a UTC time. The purpose ++ of :meth:`fromutc` is to adjust the date and time data, returning an ++ equivalent datetime in *self*'s local time. + + Most :class:`tzinfo` subclasses should be able to inherit the default + :meth:`fromutc` implementation without problems. It's strong enough to handle +diff -r 8527427914a2 Doc/library/decimal.rst +--- a/Doc/library/decimal.rst ++++ b/Doc/library/decimal.rst +@@ -35,7 +35,7 @@ + people learn at school." -- excerpt from the decimal arithmetic specification. + + * Decimal numbers can be represented exactly. In contrast, numbers like +- :const:`1.1` and :const:`2.2` do not have an exact representations in binary ++ :const:`1.1` and :const:`2.2` do not have exact representations in binary + floating point. End users typically would not expect ``1.1 + 2.2`` to display + as :const:`3.3000000000000003` as it does with binary floating point. + +@@ -742,7 +742,7 @@ + + Normalize the number by stripping the rightmost trailing zeros and + converting any result equal to :const:`Decimal('0')` to +- :const:`Decimal('0e0')`. Used for producing canonical values for members ++ :const:`Decimal('0e0')`. Used for producing canonical values for attributes + of an equivalence class. For example, ``Decimal('32.100')`` and + ``Decimal('0.321000e+2')`` both normalize to the equivalent value + ``Decimal('32.1')``. +diff -r 8527427914a2 Doc/library/dis.rst +--- a/Doc/library/dis.rst ++++ b/Doc/library/dis.rst +@@ -1,21 +1,18 @@ +- + :mod:`dis` --- Disassembler for Python bytecode + =============================================== + + .. module:: dis + :synopsis: Disassembler for Python bytecode. + ++**Source code:** :source:`Lib/dis.py` ++ ++-------------- + + The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by + disassembling it. The CPython bytecode which this module takes as an + input is defined in the file :file:`Include/opcode.h` and used by the compiler + and the interpreter. + +-.. seealso:: +- +- Latest version of the `dis module Python source code +- `_ +- + .. impl-detail:: + + Bytecode is an implementation detail of the CPython interpreter! No +diff -r 8527427914a2 Doc/library/dl.rst +--- a/Doc/library/dl.rst ++++ b/Doc/library/dl.rst +@@ -13,7 +13,7 @@ + + .. sectionauthor:: Moshe Zadka + +-The :mod:`dl` module defines an interface to the :cfunc:`dlopen` function, which ++The :mod:`dl` module defines an interface to the :c:func:`dlopen` function, which + is the most common interface on Unix platforms for handling dynamically linked + libraries. It allows the program to call arbitrary functions in such a library. + +@@ -105,10 +105,10 @@ + Call the function named *name* in the referenced shared object. The arguments + must be either Python integers, which will be passed as is, Python strings, to + which a pointer will be passed, or ``None``, which will be passed as *NULL*. +- Note that strings should only be passed to functions as :ctype:`const char\*`, ++ Note that strings should only be passed to functions as :c:type:`const char\*`, + as Python will not like its string mutated. + + There must be at most 10 arguments, and arguments not given will be treated as +- ``None``. The function's return value must be a C :ctype:`long`, which is a ++ ``None``. The function's return value must be a C :c:type:`long`, which is a + Python integer. + +diff -r 8527427914a2 Doc/library/doctest.rst +--- a/Doc/library/doctest.rst ++++ b/Doc/library/doctest.rst +@@ -1199,12 +1199,11 @@ + .. class:: DocTest(examples, globs, name, filename, lineno, docstring) + + A collection of doctest examples that should be run in a single namespace. The +- constructor arguments are used to initialize the member variables of the same +- names. ++ constructor arguments are used to initialize the attributes of the same names. + + .. versionadded:: 2.4 + +- :class:`DocTest` defines the following member variables. They are initialized by ++ :class:`DocTest` defines the following attributes. They are initialized by + the constructor, and should not be modified directly. + + +@@ -1257,12 +1256,12 @@ + .. class:: Example(source, want[, exc_msg][, lineno][, indent][, options]) + + A single interactive example, consisting of a Python statement and its expected +- output. The constructor arguments are used to initialize the member variables +- of the same names. ++ output. The constructor arguments are used to initialize the attributes of the ++ same names. + + .. versionadded:: 2.4 + +- :class:`Example` defines the following member variables. They are initialized by ++ :class:`Example` defines the following attributes. They are initialized by + the constructor, and should not be modified directly. + + +@@ -1770,9 +1769,9 @@ + + An exception raised by :class:`DocTestRunner` to signal that a doctest example's + actual output did not match its expected output. The constructor arguments are +- used to initialize the member variables of the same names. +- +-:exc:`DocTestFailure` defines the following member variables: ++ used to initialize the attributes of the same names. ++ ++:exc:`DocTestFailure` defines the following attributes: + + + .. attribute:: DocTestFailure.test +@@ -1794,9 +1793,9 @@ + + An exception raised by :class:`DocTestRunner` to signal that a doctest + example raised an unexpected exception. The constructor arguments are used +- to initialize the member variables of the same names. +- +-:exc:`UnexpectedException` defines the following member variables: ++ to initialize the attributes of the same names. ++ ++:exc:`UnexpectedException` defines the following attributes: + + + .. attribute:: UnexpectedException.test +diff -r 8527427914a2 Doc/library/dummy_thread.rst +--- a/Doc/library/dummy_thread.rst ++++ b/Doc/library/dummy_thread.rst +@@ -10,6 +10,9 @@ + converting your sources to 3.0; however, you should consider using the + high-lever :mod:`dummy_threading` module instead. + ++**Source code:** :source:`Lib/dummy_thread.py` ++ ++-------------- + + This module provides a duplicate interface to the :mod:`thread` module. It is + meant to be imported when the :mod:`thread` module is not provided on a +diff -r 8527427914a2 Doc/library/dummy_threading.rst +--- a/Doc/library/dummy_threading.rst ++++ b/Doc/library/dummy_threading.rst +@@ -1,10 +1,12 @@ +- + :mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module + ============================================================================== + + .. module:: dummy_threading + :synopsis: Drop-in replacement for the threading module. + ++**Source code:** :source:`Lib/dummy_threading.py` ++ ++-------------- + + This module provides a duplicate interface to the :mod:`threading` module. It + is meant to be imported when the :mod:`thread` module is not provided on a +diff -r 8527427914a2 Doc/library/easydialogs.rst +--- a/Doc/library/easydialogs.rst ++++ b/Doc/library/easydialogs.rst +@@ -143,7 +143,7 @@ + + .. seealso:: + +- `Navigation Services Reference `_ ++ `Navigation Services Reference `_ + Programmer's reference documentation for the Navigation Services, a part of the + Carbon framework. + +diff -r 8527427914a2 Doc/library/email.message.rst +--- a/Doc/library/email.message.rst ++++ b/Doc/library/email.message.rst +@@ -295,7 +295,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 8527427914a2 Doc/library/email.mime.rst +--- a/Doc/library/email.mime.rst ++++ b/Doc/library/email.mime.rst +@@ -196,6 +196,6 @@ + + .. versionchanged:: 2.4 + The previously deprecated *_encoding* argument has been removed. Content +- Transfer Encoding now happens happens implicitly based on the *_charset* ++ Transfer Encoding now happens implicitly based on the *_charset* + argument. + +diff -r 8527427914a2 Doc/library/email.parser.rst +--- a/Doc/library/email.parser.rst ++++ b/Doc/library/email.parser.rst +@@ -135,7 +135,9 @@ + data or by a blank line. Following the header block is the body of the + message (which may contain MIME-encoded subparts). + +- Optional *headersonly* is as with the :meth:`parse` method. ++ Optional *headersonly* is a flag specifying whether to stop parsing after ++ reading the headers or not. The default is ``False``, meaning it parses ++ the entire contents of the file. + + .. versionchanged:: 2.2.2 + The *headersonly* flag was added. +@@ -148,9 +150,7 @@ + equivalent to wrapping *text* in a :class:`StringIO` instance first and + calling :meth:`parse`. + +- Optional *headersonly* is a flag specifying whether to stop parsing after +- reading the headers or not. The default is ``False``, meaning it parses +- the entire contents of the file. ++ Optional *headersonly* is as with the :meth:`parse` method. + + .. versionchanged:: 2.2.2 + The *headersonly* flag was added. +diff -r 8527427914a2 Doc/library/exceptions.rst +--- a/Doc/library/exceptions.rst ++++ b/Doc/library/exceptions.rst +@@ -220,7 +220,7 @@ + Raised when an operation runs out of memory but the situation may still be + rescued (by deleting some objects). The associated value is a string indicating + what kind of (internal) operation ran out of memory. Note that because of the +- underlying memory management architecture (C's :cfunc:`malloc` function), the ++ underlying memory management architecture (C's :c:func:`malloc` function), the + interpreter may not always be able to completely recover from this situation; it + nevertheless raises an exception so that a stack traceback can be printed, in + case a run-away program was the cause. +@@ -249,8 +249,8 @@ + This exception is derived from :exc:`EnvironmentError`. It is raised when a + function returns a system-related error (not for illegal argument types or + other incidental errors). The :attr:`errno` attribute is a numeric error +- code from :cdata:`errno`, and the :attr:`strerror` attribute is the +- corresponding string, as would be printed by the C function :cfunc:`perror`. ++ code from :c:data:`errno`, and the :attr:`strerror` attribute is the ++ corresponding string, as would be printed by the C function :c:func:`perror`. + See the module :mod:`errno`, which contains names for the error codes defined + by the underlying operating system. + +@@ -342,7 +342,7 @@ + This exception is raised by the :func:`sys.exit` function. When it is not + handled, the Python interpreter exits; no stack traceback is printed. If the + associated value is a plain integer, it specifies the system exit status (passed +- to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if ++ to C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if + it has another type (such as a string), the object's value is printed and the + exit status is one. + +@@ -429,16 +429,16 @@ + .. exception:: WindowsError + + Raised when a Windows-specific error occurs or when the error number does not +- correspond to an :cdata:`errno` value. The :attr:`winerror` and ++ correspond to an :c:data:`errno` value. The :attr:`winerror` and + :attr:`strerror` values are created from the return values of the +- :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows ++ :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows + Platform API. The :attr:`errno` value maps the :attr:`winerror` value to + corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`. + + .. versionadded:: 2.0 + + .. versionchanged:: 2.5 +- Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`. ++ Previous versions put the :c:func:`GetLastError` codes into :attr:`errno`. + + + .. exception:: ZeroDivisionError +diff -r 8527427914a2 Doc/library/fcntl.rst +--- a/Doc/library/fcntl.rst ++++ b/Doc/library/fcntl.rst +@@ -13,7 +13,7 @@ + pair: UNIX; I/O control + + This module performs file control and I/O control on file descriptors. It is an +-interface to the :cfunc:`fcntl` and :cfunc:`ioctl` Unix routines. ++interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines. + + All functions in this module take a file descriptor *fd* as their first + argument. This can be an integer file descriptor, such as returned by +@@ -31,17 +31,17 @@ + :mod:`fcntl` module. The argument *arg* is optional, and defaults to the integer + value ``0``. When present, it can either be an integer value, or a string. + With the argument missing or an integer value, the return value of this function +- is the integer return value of the C :cfunc:`fcntl` call. When the argument is ++ is the integer return value of the C :c:func:`fcntl` call. When the argument is + a string it represents a binary structure, e.g. created by :func:`struct.pack`. + The binary data is copied to a buffer whose address is passed to the C +- :cfunc:`fcntl` call. The return value after a successful call is the contents ++ :c:func:`fcntl` call. The return value after a successful call is the contents + of the buffer, converted to a string object. The length of the returned string + will be the same as the length of the *arg* argument. This is limited to 1024 + bytes. If the information returned in the buffer by the operating system is + larger than 1024 bytes, this is most likely to result in a segmentation + violation or a more subtle data corruption. + +- If the :cfunc:`fcntl` fails, an :exc:`IOError` is raised. ++ If the :c:func:`fcntl` fails, an :exc:`IOError` is raised. + + + .. function:: ioctl(fd, op[, arg[, mutate_flag]]) +@@ -97,7 +97,7 @@ + Perform the lock operation *op* on file descriptor *fd* (file objects providing + a :meth:`fileno` method are accepted as well). See the Unix manual + :manpage:`flock(2)` for details. (On some systems, this function is emulated +- using :cfunc:`fcntl`.) ++ using :c:func:`fcntl`.) + + + .. function:: lockf(fd, operation, [length, [start, [whence]]]) +diff -r 8527427914a2 Doc/library/filecmp.rst +--- a/Doc/library/filecmp.rst ++++ b/Doc/library/filecmp.rst +@@ -1,4 +1,3 @@ +- + :mod:`filecmp` --- File and Directory Comparisons + ================================================= + +@@ -6,16 +5,14 @@ + :synopsis: Compare files efficiently. + .. sectionauthor:: Moshe Zadka + ++**Source code:** :source:`Lib/filecmp.py` ++ ++-------------- + + The :mod:`filecmp` module defines functions to compare files and directories, + with various optional time/correctness trade-offs. For comparing files, + see also the :mod:`difflib` module. + +-.. seealso:: +- +- Latest version of the `filecmp Python source code +- `_ +- + The :mod:`filecmp` module defines the following functions: + + +diff -r 8527427914a2 Doc/library/fileinput.rst +--- a/Doc/library/fileinput.rst ++++ b/Doc/library/fileinput.rst +@@ -6,6 +6,9 @@ + .. moduleauthor:: Guido van Rossum + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/fileinput.py` ++ ++-------------- + + This module implements a helper class and functions to quickly write a + loop over standard input or a list of files. If you just want to read or +@@ -44,11 +47,6 @@ + returns an accordingly opened file-like object. Two useful hooks are already + provided by this module. + +-.. seealso:: +- +- Latest version of the `fileinput Python source code +- `_ +- + The following function is the primary interface of this module: + + +diff -r 8527427914a2 Doc/library/fl.rst +--- a/Doc/library/fl.rst ++++ b/Doc/library/fl.rst +@@ -29,8 +29,8 @@ + the 'current form' maintained by the library to which new FORMS objects are + added, all functions that add a FORMS object to a form are methods of the Python + object representing the form. Consequently, there are no Python equivalents for +-the C functions :cfunc:`fl_addto_form` and :cfunc:`fl_end_form`, and the +-equivalent of :cfunc:`fl_bgn_form` is called :func:`fl.make_form`. ++the C functions :c:func:`fl_addto_form` and :c:func:`fl_end_form`, and the ++equivalent of :c:func:`fl_bgn_form` is called :func:`fl.make_form`. + + Watch out for the somewhat confusing terminology: FORMS uses the word + :dfn:`object` for the buttons, sliders etc. that you can place in a form. In +@@ -44,7 +44,7 @@ + event handling is available, though, so you can mix FORMS with pure GL windows. + + **Please note:** importing :mod:`fl` implies a call to the GL function +-:cfunc:`foreground` and to the FORMS routine :cfunc:`fl_init`. ++:c:func:`foreground` and to the FORMS routine :c:func:`fl_init`. + + + .. _fl-functions: +@@ -88,7 +88,7 @@ + .. function:: get_rgbmode() + + Return the current rgb mode. This is the value of the C global variable +- :cdata:`fl_rgbmode`. ++ :c:data:`fl_rgbmode`. + + + .. function:: show_message(str1, str2, str3) +@@ -153,8 +153,8 @@ + mapcolor() + getmcolor() + +- See the description in the FORMS documentation of :cfunc:`fl_color`, +- :cfunc:`fl_mapcolor` and :cfunc:`fl_getmcolor`. ++ See the description in the FORMS documentation of :c:func:`fl_color`, ++ :c:func:`fl_mapcolor` and :c:func:`fl_getmcolor`. + + + .. _form-objects: +diff -r 8527427914a2 Doc/library/fm.rst +--- a/Doc/library/fm.rst ++++ b/Doc/library/fm.rst +@@ -30,7 +30,7 @@ + + .. function:: init() + +- Initialization function. Calls :cfunc:`fminit`. It is normally not necessary to ++ Initialization function. Calls :c:func:`fminit`. It is normally not necessary to + call this function, since it is called automatically the first time the + :mod:`fm` module is imported. + +@@ -43,7 +43,7 @@ + .. function:: enumerate() + + Returns a list of available font names. This is an interface to +- :cfunc:`fmenumerate`. ++ :c:func:`fmenumerate`. + + + .. function:: prstr(string) +diff -r 8527427914a2 Doc/library/fnmatch.rst +--- a/Doc/library/fnmatch.rst ++++ b/Doc/library/fnmatch.rst +@@ -1,4 +1,3 @@ +- + :mod:`fnmatch` --- Unix filename pattern matching + ================================================= + +@@ -10,6 +9,10 @@ + + .. index:: module: re + ++**Source code:** :source:`Lib/fnmatch.py` ++ ++-------------- ++ + This module provides support for Unix shell-style wildcards, which are *not* the + same as regular expressions (which are documented in the :mod:`re` module). The + special characters used in shell-style wildcards are: +@@ -34,10 +37,6 @@ + a period are not special for this module, and are matched by the ``*`` and ``?`` + patterns. + +-.. seealso:: +- +- Latest version of the `fnmatch Python source code +- `_ + + .. function:: fnmatch(filename, pattern) + +@@ -95,4 +94,3 @@ + + Module :mod:`glob` + Unix shell-style path expansion. +- +diff -r 8527427914a2 Doc/library/fractions.rst +--- a/Doc/library/fractions.rst ++++ b/Doc/library/fractions.rst +@@ -1,4 +1,3 @@ +- + :mod:`fractions` --- Rational numbers + ===================================== + +@@ -8,6 +7,9 @@ + .. sectionauthor:: Jeffrey Yasskin + .. versionadded:: 2.6 + ++**Source code:** :source:`Lib/fractions.py` ++ ++-------------- + + The :mod:`fractions` module provides support for rational number arithmetic. + +diff -r 8527427914a2 Doc/library/ftplib.rst +--- a/Doc/library/ftplib.rst ++++ b/Doc/library/ftplib.rst +@@ -9,6 +9,10 @@ + pair: FTP; protocol + single: FTP; ftplib (standard module) + ++**Source code:** :source:`Lib/ftplib.py` ++ ++-------------- ++ + This module defines the class :class:`FTP` and a few related items. The + :class:`FTP` class implements the client side of the FTP protocol. You can use + this to write Python programs that perform a variety of automated FTP jobs, such +diff -r 8527427914a2 Doc/library/functions.rst +--- a/Doc/library/functions.rst ++++ b/Doc/library/functions.rst +@@ -123,6 +123,8 @@ + + Without an argument, an array of size 0 is created. + ++ .. versionadded:: 2.6 ++ + + .. function:: callable(object) + +@@ -298,19 +300,18 @@ + The resulting list is sorted alphabetically. For example: + + >>> import struct +- >>> dir() # doctest: +SKIP ++ >>> dir() # show the names in the module namespace + ['__builtins__', '__doc__', '__name__', 'struct'] +- >>> dir(struct) # doctest: +NORMALIZE_WHITESPACE ++ >>> dir(struct) # show the names in the struct module + ['Struct', '__builtins__', '__doc__', '__file__', '__name__', + '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', + 'unpack', 'unpack_from'] +- >>> class Foo(object): +- ... def __dir__(self): +- ... return ["kan", "ga", "roo"] +- ... +- >>> f = Foo() +- >>> dir(f) +- ['ga', 'kan', 'roo'] ++ >>> class Shape(object): ++ def __dir__(self): ++ return ['area', 'perimeter', 'location'] ++ >>> s = Shape() ++ >>> dir(s) ++ ['area', 'perimeter', 'location'] + + .. note:: + +@@ -342,20 +343,25 @@ + :term:`iterator`, or some other object which supports iteration. The + :meth:`!next` method of the iterator returned by :func:`enumerate` returns a + tuple containing a count (from *start* which defaults to 0) and the +- corresponding value obtained from iterating over *iterable*. +- :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``, +- ``(1, seq[1])``, ``(2, seq[2])``, .... For example: ++ values obtained from iterating over *sequence*:: + +- >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): +- ... print i, season +- 0 Spring +- 1 Summer +- 2 Fall +- 3 Winter ++ >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] ++ >>> list(enumerate(seasons)) ++ [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] ++ >>> list(enumerate(seasons, start=1)) ++ [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] ++ ++ Equivalent to:: ++ ++ def enumerate(sequence, start=0): ++ n = start ++ for elem in sequence: ++ yield n, elem ++ n += 1 + + .. versionadded:: 2.3 +- .. versionadded:: 2.6 +- The *start* parameter. ++ .. versionchanged:: 2.6 ++ The *start* parameter was added. + + + .. function:: eval(expression[, globals[, locals]]) +@@ -579,20 +585,16 @@ + Two objects with non-overlapping lifetimes may have the same :func:`id` + value. + +- .. impl-detail:: This is the address of the object. ++ .. impl-detail:: This is the address of the object in memory. + + + .. function:: input([prompt]) + + Equivalent to ``eval(raw_input(prompt))``. + +- .. warning:: +- +- This function is not safe from user errors! It expects a valid Python +- expression as input; if the input is not syntactically valid, a +- :exc:`SyntaxError` will be raised. Other exceptions may be raised if there is an +- error during evaluation. (On the other hand, sometimes this is exactly what you +- need when writing a quick script for expert use.) ++ This function does not catch user errors. If the input is not syntactically ++ valid, a :exc:`SyntaxError` will be raised. Other exceptions may be raised if ++ there is an error during evaluation. + + If the :mod:`readline` module was loaded, then :func:`input` will use it to + provide elaborate line editing and history features. +@@ -621,9 +623,11 @@ + .. 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. Also return true if *classinfo* ++ or of a (direct, indirect or :term:`virtual `) subclass ++ thereof. Also return true if *classinfo* + is a type object (new-style class) and *object* is an object of that type or of +- a (direct or indirect) subclass thereof. If *object* is not a class instance or ++ a (direct, indirect or :term:`virtual `) subclass ++ thereof. If *object* is not a class instance or + an object of the given type, the function always returns false. If *classinfo* + is neither a class object nor a type object, it may be a tuple of class or type + objects, or may recursively contain other such tuples (other sequence types are +@@ -636,7 +640,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. +@@ -660,10 +665,10 @@ + + One useful application of the second form of :func:`iter` is to read lines of + a file until a certain line is reached. The following example reads a file +- until ``"STOP"`` is reached: :: ++ until the :meth:`readline` method returns an empty string:: + +- with open("mydata.txt") as fp: +- for line in iter(fp.readline, "STOP"): ++ with open('mydata.txt') as fp: ++ for line in iter(fp.readline, ''): + process_line(line) + + .. versionadded:: 2.2 +@@ -793,15 +798,15 @@ + Formerly only returned an unsigned literal. + + +-.. function:: open(filename[, mode[, bufsize]]) ++.. function:: open(name[, mode[, buffering]]) + + Open a file, returning an object of the :class:`file` type described in + section :ref:`bltin-file-objects`. If the file cannot be opened, + :exc:`IOError` is raised. When opening a file, it's preferable to use + :func:`open` instead of invoking the :class:`file` constructor directly. + +- The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`: +- *filename* is the file name to be opened, and *mode* is a string indicating how ++ The first two arguments are the same as for ``stdio``'s :c:func:`fopen`: ++ *name* is the file name to be opened, and *mode* is a string indicating how + the file is to be opened. + + The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for +@@ -822,9 +827,9 @@ + single: buffer size, I/O + single: I/O control; buffering + +- The optional *bufsize* argument specifies the file's desired buffer size: 0 ++ The optional *buffering* argument specifies the file's desired buffer size: 0 + means unbuffered, 1 means line buffered, any other positive value means use a +- buffer of (approximately) that size. A negative *bufsize* means to use the ++ buffer of (approximately) that size. A negative *buffering* means to use the + system default, which is usually line buffered for tty devices and fully + buffered for other files. If omitted, the system default is used. [#]_ + +@@ -833,7 +838,7 @@ + binary mode, on systems that differentiate between binary and text files; on + systems that don't have this distinction, adding the ``'b'`` has no effect. + +- In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or ++ In addition to the standard :c:func:`fopen` values *mode* may be ``'U'`` or + ``'rU'``. Python is usually built with universal newline support; supplying + ``'U'`` opens the file as a text file, but lines may be terminated by any of the + following: the Unix end-of-line convention ``'\n'``, the Macintosh convention +@@ -902,7 +907,9 @@ + *end*. + + The *file* argument must be an object with a ``write(string)`` method; if it +- is not present or ``None``, :data:`sys.stdout` will be used. ++ is not present or ``None``, :data:`sys.stdout` will be used. Output buffering ++ is determined by *file*. Use ``file.flush()`` to ensure, for instance, ++ immediate appearance on a screen. + + .. note:: + +@@ -1048,7 +1055,19 @@ + it is placed before the items of the iterable in the calculation, and serves as + a default when the iterable is empty. If *initializer* is not given and + *iterable* contains only one item, the first item is returned. ++ Roughly equivalent to:: + ++ def reduce(function, iterable, initializer=None): ++ it = iter(iterable) ++ if initializer is None: ++ try: ++ initializer = next(it) ++ except StopIteration: ++ raise TypeError('reduce() of empty sequence with no initial value') ++ accum_value = initializer ++ for x in iterable: ++ accum_value = function(accum_value, x) ++ return accum_value + + .. function:: reload(module) + +@@ -1241,8 +1260,9 @@ + It can be called either on the class (such as ``C.f()``) or on an instance (such + as ``C().f()``). The instance is ignored except for its class. + +- Static methods in Python are similar to those found in Java or C++. For a more +- advanced concept, see :func:`classmethod` in this section. ++ Static methods in Python are similar to those found in Java or C++. Also see ++ :func:`classmethod` for a variant that is useful for creating alternate ++ class constructors. + + For more information on static methods, consult the documentation on the + standard type hierarchy in :ref:`types`. +@@ -1335,6 +1355,10 @@ + argument form specifies the arguments exactly and makes the appropriate + references. + ++ For practical suggestions on how to design cooperative classes using ++ :func:`super`, see `guide to using super() ++ `_. ++ + .. versionadded:: 2.2 + + +@@ -1434,15 +1458,17 @@ + + .. function:: vars([object]) + +- Without an argument, act like :func:`locals`. ++ Return the :attr:`__dict__` attribute for a module, class, instance, ++ or any other object with a :attr:`__dict__` attribute. + +- With a module, class or class instance object as argument (or anything else that +- has a :attr:`__dict__` attribute), return that attribute. ++ Objects such as modules and instances have an updateable :attr:`__dict__` ++ attribute; however, other objects may have write restrictions on their ++ :attr:`__dict__` attributes (for example, new-style classes use a ++ dictproxy to prevent direct dictionary updates). + +- .. note:: +- +- The returned dictionary should not be modified: +- the effects on the corresponding symbol table are undefined. [#]_ ++ Without an argument, :func:`vars` acts like :func:`locals`. Note, the ++ locals dictionary is only useful for reads since updates to the locals ++ dictionary are ignored. + + + .. function:: xrange([start,] stop[, step]) +@@ -1645,8 +1671,8 @@ + .. [#] It is used relatively rarely so does not warrant being made into a statement. + + .. [#] Specifying a buffer size currently has no effect on systems that don't have +- :cfunc:`setvbuf`. The interface to specify the buffer size is not done using a +- method that calls :cfunc:`setvbuf`, because that may dump core when called after ++ :c:func:`setvbuf`. The interface to specify the buffer size is not done using a ++ method that calls :c:func:`setvbuf`, because that may dump core when called after + any I/O has been performed, and there's no reliable way to determine whether + this is the case. + +diff -r 8527427914a2 Doc/library/functools.rst +--- a/Doc/library/functools.rst ++++ b/Doc/library/functools.rst +@@ -1,37 +1,35 @@ +-:mod:`functools` --- Higher order functions and operations on callable objects ++:mod:`functools` --- Higher-order functions and operations on callable objects + ============================================================================== + + .. module:: functools +- :synopsis: Higher order functions and operations on callable objects. ++ :synopsis: Higher-order functions and operations on callable objects. + .. moduleauthor:: Peter Harris + .. moduleauthor:: Raymond Hettinger + .. moduleauthor:: Nick Coghlan + .. sectionauthor:: Peter Harris + ++.. versionadded:: 2.5 + +-.. versionadded:: 2.5 ++**Source code:** :source:`Lib/functools.py` ++ ++-------------- + + The :mod:`functools` module is for higher-order functions: functions that act on + or return other functions. In general, any callable object can be treated as a + function for the purposes of this module. + +-.. seealso:: +- +- Latest version of the `functools Python source code +- `_ +- + The :mod:`functools` module defines the following functions: + + .. function:: cmp_to_key(func) + +- Transform an old-style comparison function to a key-function. Used with ++ Transform an old-style comparison function to a key function. Used with + tools that accept key functions (such as :func:`sorted`, :func:`min`, + :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`, + :func:`itertools.groupby`). This function is primarily used as a transition +- tool for programs being converted to Py3.x where comparison functions are no +- longer supported. ++ tool for programs being converted to Python 3 where comparison functions are ++ no longer supported. + +- A compare function is any callable that accept two arguments, compares them, ++ A comparison function is any callable that accept two arguments, compares them, + and returns a negative number for less-than, zero for equality, or a positive + number for greater-than. A key function is a callable that accepts one + argument and returns another value that indicates the position in the desired +diff -r 8527427914a2 Doc/library/getopt.rst +--- a/Doc/library/getopt.rst ++++ b/Doc/library/getopt.rst +@@ -1,4 +1,3 @@ +- + :mod:`getopt` --- C-style parser for command line options + ========================================================= + +@@ -6,22 +5,23 @@ + :synopsis: Portable parser for command line options; support both short and long option + names. + ++**Source code:** :source:`Lib/getopt.py` ++ ++-------------- ++ + .. note:: + The :mod:`getopt` module is a parser for command line options whose API is +- designed to be familiar to users of the C :cfunc:`getopt` function. Users who +- are unfamiliar with the C :cfunc:`getopt` function or who would like to write ++ designed to be familiar to users of the C :c:func:`getopt` function. Users who ++ are unfamiliar with the C :c:func:`getopt` function or who would like to write + less code and get better help and error messages should consider using the + :mod:`argparse` module instead. + + This module helps scripts to parse the command line arguments in ``sys.argv``. +-It supports the same conventions as the Unix :cfunc:`getopt` function (including ++It supports the same conventions as the Unix :c:func:`getopt` function (including + the special meanings of arguments of the form '``-``' and '``--``'). Long + options similar to those supported by GNU software may be used as well via an + optional third argument. + +-A more convenient, flexible, and powerful alternative is the +-:mod:`optparse` module. +- + This module provides two functions and an + exception: + +@@ -32,11 +32,11 @@ + be parsed, without the leading reference to the running program. Typically, this + means ``sys.argv[1:]``. *options* is the string of option letters that the + script wants to recognize, with options that require an argument followed by a +- colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses). ++ colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses). + + .. note:: + +- Unlike GNU :cfunc:`getopt`, after a non-option argument, all further ++ Unlike GNU :c:func:`getopt`, after a non-option argument, all further + arguments are considered also non-options. This is similar to the way + non-GNU Unix systems work. + +diff -r 8527427914a2 Doc/library/gettext.rst +--- a/Doc/library/gettext.rst ++++ b/Doc/library/gettext.rst +@@ -1,4 +1,3 @@ +- + :mod:`gettext` --- Multilingual internationalization services + ============================================================= + +@@ -7,6 +6,9 @@ + .. moduleauthor:: Barry A. Warsaw + .. sectionauthor:: Barry A. Warsaw + ++**Source code:** :source:`Lib/gettext.py` ++ ++-------------- + + The :mod:`gettext` module provides internationalization (I18N) and localization + (L10N) services for your Python modules and applications. It supports both the +@@ -298,7 +300,7 @@ + + .. method:: lngettext(singular, plural, n) + +- If a fallback has been set, forward :meth:`ngettext` to the ++ If a fallback has been set, forward :meth:`lngettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. + +@@ -754,8 +756,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 8527427914a2 Doc/library/glob.rst +--- a/Doc/library/glob.rst ++++ b/Doc/library/glob.rst +@@ -1,4 +1,3 @@ +- + :mod:`glob` --- Unix style pathname pattern expansion + ===================================================== + +@@ -8,6 +7,10 @@ + + .. index:: single: filenames; pathname expansion + ++**Source code:** :source:`Lib/glob.py` ++ ++-------------- ++ + The :mod:`glob` module finds all the pathnames matching a specified pattern + according to the rules used by the Unix shell. No tilde expansion is done, but + ``*``, ``?``, and character ranges expressed with ``[]`` will be correctly +@@ -16,10 +19,6 @@ + subshell. (For tilde and shell variable expansion, use + :func:`os.path.expanduser` and :func:`os.path.expandvars`.) + +-.. seealso:: +- +- Latest version of the `glob module Python source code +- `_ + + .. function:: glob(pathname) + +diff -r 8527427914a2 Doc/library/gzip.rst +--- a/Doc/library/gzip.rst ++++ b/Doc/library/gzip.rst +@@ -4,6 +4,10 @@ + .. module:: gzip + :synopsis: Interfaces for gzip compression and decompression using file objects. + ++**Source code:** :source:`Lib/gzip.py` ++ ++-------------- ++ + This module provides a simple interface to compress and decompress files just + like the GNU programs :program:`gzip` and :program:`gunzip` would. + +@@ -58,7 +62,7 @@ + time is used. This module ignores the timestamp when decompressing; + however, some programs, such as :program:`gunzip`\ , make use of it. + The format of the timestamp is the same as that of the return value of +- ``time.time()`` and of the ``st_mtime`` member of the object returned ++ ``time.time()`` and of the ``st_mtime`` attribute of the object returned + by ``os.stat()``. + + Calling a :class:`GzipFile` object's :meth:`close` method does not close +diff -r 8527427914a2 Doc/library/hashlib.rst +--- a/Doc/library/hashlib.rst ++++ b/Doc/library/hashlib.rst +@@ -1,4 +1,3 @@ +- + :mod:`hashlib` --- Secure hashes and message digests + ==================================================== + +@@ -14,6 +13,10 @@ + single: message digest, MD5 + single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512 + ++**Source code:** :source:`Lib/hashlib.py` ++ ++-------------- ++ + This module implements a common interface to many different secure hash and + message digest algorithms. Included are the FIPS secure hash algorithms SHA1, + SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 +diff -r 8527427914a2 Doc/library/heapq.rst +--- a/Doc/library/heapq.rst ++++ b/Doc/library/heapq.rst +@@ -10,14 +10,13 @@ + + .. versionadded:: 2.3 + ++**Source code:** :source:`Lib/heapq.py` ++ ++-------------- ++ + This module provides an implementation of the heap queue algorithm, also known + as the priority queue algorithm. + +-.. seealso:: +- +- Latest version of the `heapq Python source code +- `_ +- + Heaps are binary trees for which every parent node has a value less than or + equal to any of its children. This implementation uses arrays for which + ``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting +@@ -188,36 +187,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 ++existing 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 8527427914a2 Doc/library/hmac.rst +--- a/Doc/library/hmac.rst ++++ b/Doc/library/hmac.rst +@@ -1,4 +1,3 @@ +- + :mod:`hmac` --- Keyed-Hashing for Message Authentication + ======================================================== + +@@ -10,6 +9,10 @@ + + .. versionadded:: 2.2 + ++**Source code:** :source:`Lib/hmac.py` ++ ++-------------- ++ + This module implements the HMAC algorithm as described by :rfc:`2104`. + + +@@ -22,29 +25,28 @@ + + An HMAC object has the following methods: + +- +-.. method:: hmac.update(msg) ++.. method:: HMAC.update(msg) + + Update the hmac object with the string *msg*. Repeated calls are equivalent to + a single call with the concatenation of all the arguments: ``m.update(a); + m.update(b)`` is equivalent to ``m.update(a + b)``. + + +-.. method:: hmac.digest() ++.. method:: HMAC.digest() + + Return the digest of the strings passed to the :meth:`update` method so far. + This string will be the same length as the *digest_size* of the digest given to + the constructor. It may contain non-ASCII characters, including NUL bytes. + + +-.. method:: hmac.hexdigest() ++.. method:: HMAC.hexdigest() + + Like :meth:`digest` except the digest is returned as a string twice the length + containing only hexadecimal digits. This may be used to exchange the value + safely in email or other non-binary environments. + + +-.. method:: hmac.copy() ++.. method:: HMAC.copy() + + Return a copy ("clone") of the hmac object. This can be used to efficiently + compute the digests of strings that share a common initial substring. +diff -r 8527427914a2 Doc/library/htmllib.rst +--- a/Doc/library/htmllib.rst ++++ b/Doc/library/htmllib.rst +@@ -165,10 +165,13 @@ + Python 3.0. The :term:`2to3` tool will automatically adapt imports when + converting your sources to 3.0. + ++**Source code:** :source:`Lib/htmlentitydefs.py` ++ ++-------------- + + This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``, + and ``entitydefs``. ``entitydefs`` is used by the :mod:`htmllib` module to +-provide the :attr:`entitydefs` member of the :class:`HTMLParser` class. The ++provide the :attr:`entitydefs` attribute of the :class:`HTMLParser` class. The + definition provided here contains all the entities defined by XHTML 1.0 that + can be handled using simple textual substitution in the Latin-1 character set + (ISO-8859-1). +diff -r 8527427914a2 Doc/library/htmlparser.rst +--- a/Doc/library/htmlparser.rst ++++ b/Doc/library/htmlparser.rst +@@ -8,8 +8,8 @@ + .. note:: + + The :mod:`HTMLParser` module has been renamed to :mod:`html.parser` in Python +- 3.0. The :term:`2to3` tool will automatically adapt imports when converting +- your sources to 3.0. ++ 3. The :term:`2to3` tool will automatically adapt imports when converting ++ your sources to Python 3. + + + .. versionadded:: 2.2 +@@ -18,6 +18,10 @@ + single: HTML + single: XHTML + ++**Source code:** :source:`Lib/HTMLParser.py` ++ ++-------------- ++ + This module defines a class :class:`HTMLParser` which serves as the basis for + parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML. + Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser +@@ -60,7 +64,8 @@ + + Feed some text to the parser. It is processed insofar as it consists of + complete elements; incomplete data is buffered until more data is fed or +- :meth:`close` is called. ++ :meth:`close` is called. *data* can be either :class:`unicode` or ++ :class:`str`, but passing :class:`unicode` is advised. + + + .. method:: HTMLParser.close() +@@ -105,9 +110,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) +@@ -119,7 +124,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. + + +@@ -182,16 +188,21 @@ + 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 HTMLParser 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 + +- def handle_starttag(self, tag, attrs): +- print "Encountered the beginning of a %s tag" % tag + +- def handle_endtag(self, tag): +- print "Encountered the end of a %s tag" % tag +- ++ parser = MyHTMLParser() ++ parser.feed('Test' ++ '

Parse me!

') +diff -r 8527427914a2 Doc/library/httplib.rst +--- a/Doc/library/httplib.rst ++++ b/Doc/library/httplib.rst +@@ -16,6 +16,10 @@ + + .. index:: module: urllib + ++**Source code:** :source:`Lib/httplib.py` ++ ++-------------- ++ + This module defines classes which implement the client side of the HTTP and + HTTPS protocols. It is normally not used directly --- the module :mod:`urllib` + uses it to handle URLs that use HTTP and HTTPS. +@@ -448,7 +452,7 @@ + Set the host and the port for HTTP Connect Tunnelling. Normally used when + it is required to do HTTPS Conection 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 send + with the CONNECT request. + + .. versionadded:: 2.7 +@@ -488,9 +492,16 @@ + 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. ++ ++ .. versionchanged:: 2.7 ++ *message_body* was added. + + + .. method:: HTTPConnection.send(data) +@@ -588,14 +599,16 @@ + Here is an example session that shows how to ``POST`` requests:: + + >>> import httplib, urllib +- >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) ++ >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) + >>> headers = {"Content-type": "application/x-www-form-urlencoded", + ... "Accept": "text/plain"} +- >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") +- >>> conn.request("POST", "/cgi-bin/query", params, headers) ++ >>> conn = httplib.HTTPConnection("bugs.python.org") ++ >>> conn.request("POST", "", params, headers) + >>> response = conn.getresponse() + >>> print response.status, response.reason +- 200 OK ++ 302 Found + >>> data = response.read() ++ >>> data ++ 'Redirecting to http://bugs.python.org/issue12524' + >>> conn.close() + +diff -r 8527427914a2 Doc/library/imaplib.rst +--- a/Doc/library/imaplib.rst ++++ b/Doc/library/imaplib.rst +@@ -16,6 +16,10 @@ + pair: IMAP4_SSL; protocol + pair: IMAP4_stream; protocol + ++**Source code:** :source:`Lib/imaplib.py` ++ ++-------------- ++ + This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and + :class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and + implement a large subset of the IMAP4rev1 client protocol as defined in +diff -r 8527427914a2 Doc/library/imghdr.rst +--- a/Doc/library/imghdr.rst ++++ b/Doc/library/imghdr.rst +@@ -1,10 +1,12 @@ +- + :mod:`imghdr` --- Determine the type of an image + ================================================ + + .. module:: imghdr + :synopsis: Determine the type of image contained in a file or byte stream. + ++**Source code:** :source:`Lib/imghdr.py` ++ ++-------------- + + The :mod:`imghdr` module determines the type of image contained in a file or + byte stream. +diff -r 8527427914a2 Doc/library/inspect.rst +--- a/Doc/library/inspect.rst ++++ b/Doc/library/inspect.rst +@@ -1,4 +1,3 @@ +- + :mod:`inspect` --- Inspect live objects + ======================================= + +@@ -10,6 +9,10 @@ + + .. versionadded:: 2.1 + ++**Source code:** :source:`Lib/inspect.py` ++ ++-------------- ++ + The :mod:`inspect` module provides several useful functions to help get + information about live objects such as modules, classes, methods, functions, + tracebacks, frame objects, and code objects. For example, it can help you +@@ -363,7 +366,7 @@ + .. impl-detail:: + + getsets are attributes defined in extension modules via +- :ctype:`PyGetSetDef` structures. For Python implementations without such ++ :c:type:`PyGetSetDef` structures. For Python implementations without such + types, this method will always return ``False``. + + .. versionadded:: 2.5 +@@ -376,7 +379,7 @@ + .. impl-detail:: + + Member descriptors are attributes defined in extension modules via +- :ctype:`PyMemberDef` structures. For Python implementations without such ++ :c:type:`PyMemberDef` structures. For Python implementations without such + types, this method will always return ``False``. + + .. versionadded:: 2.5 +diff -r 8527427914a2 Doc/library/io.rst +--- a/Doc/library/io.rst ++++ b/Doc/library/io.rst +@@ -233,7 +233,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 :class:`bytes`), or a text stream (yielding +- :class:`unicode` strings). See :meth:`readline` below. ++ :class:`unicode` 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 +@@ -407,8 +407,8 @@ + :class:`RawIOBase` implementation, but wrap one, like + :class:`BufferedWriter` and :class:`BufferedReader` do. + +- :class:`BufferedIOBase` provides or overrides these members in addition to +- those from :class:`IOBase`: ++ :class:`BufferedIOBase` provides or overrides these methods and attribute in ++ addition to those from :class:`IOBase`: + + .. attribute:: raw + +@@ -604,25 +604,6 @@ + if the buffer needs to be written out but the raw stream blocks. + + +-.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE) +- +- A buffered I/O object giving a combined, higher-level access to two +- sequential :class:`RawIOBase` objects: one readable, the other writeable. +- It is useful for pairs of unidirectional communication channels +- (pipes, for instance). It inherits :class:`BufferedIOBase`. +- +- *reader* and *writer* are :class:`RawIOBase` objects that are readable and +- writeable respectively. If the *buffer_size* is omitted it defaults to +- :data:`DEFAULT_BUFFER_SIZE`. +- +- A fourth argument, *max_buffer_size*, is supported, but unused and +- deprecated. +- +- :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods +- except for :meth:`~BufferedIOBase.detach`, which raises +- :exc:`UnsupportedOperation`. +- +- + .. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE) + + A buffered interface to random access streams. It inherits +@@ -639,6 +620,29 @@ + :class:`BufferedWriter` can do. + + ++.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE) ++ ++ A buffered I/O object combining two unidirectional :class:`RawIOBase` ++ objects -- one readable, the other writeable -- into a single bidirectional ++ endpoint. It inherits :class:`BufferedIOBase`. ++ ++ *reader* and *writer* are :class:`RawIOBase` objects that are readable and ++ writeable respectively. If the *buffer_size* is omitted it defaults to ++ :data:`DEFAULT_BUFFER_SIZE`. ++ ++ A fourth argument, *max_buffer_size*, is supported, but unused and ++ deprecated. ++ ++ :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods ++ except for :meth:`~BufferedIOBase.detach`, which raises ++ :exc:`UnsupportedOperation`. ++ ++ .. warning:: ++ :class:`BufferedRWPair` does not attempt to synchronize accesses to ++ its underlying raw streams. You should not pass it the same object ++ as reader and writer; use :class:`BufferedRandom` instead. ++ ++ + Text I/O + -------- + +@@ -697,6 +701,32 @@ + Read until newline or EOF and return a single ``unicode``. If the + stream is already at EOF, an empty string is returned. + ++ .. method:: seek(offset, whence=SEEK_SET) ++ ++ Change the stream position to the given *offset*. Behaviour depends ++ on the *whence* parameter: ++ ++ * :data:`SEEK_SET` or ``0``: seek from the start of the stream ++ (the default); *offset* must either be a number returned by ++ :meth:`TextIOBase.tell`, or zero. Any other *offset* value ++ produces undefined behaviour. ++ * :data:`SEEK_CUR` or ``1``: "seek" to the current position; ++ *offset* must be zero, which is a no-operation (all other values ++ are unsupported). ++ * :data:`SEEK_END` or ``2``: seek to the end of the stream; ++ *offset* must be zero (all other values are unsupported). ++ ++ Return the new absolute position as an opaque number. ++ ++ .. versionadded:: 2.7 ++ The ``SEEK_*`` constants. ++ ++ .. method:: tell() ++ ++ Return the current stream position as an opaque number. The number ++ does not usually represent a number of bytes in the underlying ++ binary storage. ++ + .. method:: write(s) + + Write the :class:`unicode` string *s* to the stream and return the +diff -r 8527427914a2 Doc/library/itertools.rst +--- a/Doc/library/itertools.rst ++++ b/Doc/library/itertools.rst +@@ -433,9 +433,9 @@ + + def izip(*iterables): + # izip('ABCD', 'xy') --> Ax By +- iterables = map(iter, iterables) +- while iterables: +- yield tuple(map(next, iterables)) ++ iterators = map(iter, iterables) ++ while iterators: ++ yield tuple(map(next, iterators)) + + .. versionchanged:: 2.4 + When no iterables are specified, returns a zero length iterator instead of +@@ -456,17 +456,24 @@ + iterables are of uneven length, missing values are filled-in with *fillvalue*. + Iteration continues until the longest iterable is exhausted. Equivalent to:: + ++ class ZipExhausted(Exception): ++ pass ++ + def izip_longest(*args, **kwds): + # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- + fillvalue = kwds.get('fillvalue') +- def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): +- yield counter() # yields the fillvalue, or raises IndexError ++ counter = [len(args) - 1] ++ def sentinel(): ++ if not counter[0]: ++ raise ZipExhausted ++ counter[0] -= 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 izip(*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 +@@ -583,6 +590,11 @@ + for i in xrange(times): + yield object + ++ A common use for *repeat* is to supply a stream of constant values to *imap* ++ or *zip*:: ++ ++ >>> list(imap(pow, xrange(10), repeat(2))) ++ [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + + .. function:: starmap(function, iterable) + +diff -r 8527427914a2 Doc/library/keyword.rst +--- a/Doc/library/keyword.rst ++++ b/Doc/library/keyword.rst +@@ -1,10 +1,12 @@ +- + :mod:`keyword` --- Testing for Python keywords + ============================================== + + .. module:: keyword + :synopsis: Test whether a string is a keyword in Python. + ++**Source code:** :source:`Lib/keyword.py` ++ ++-------------- + + This module allows a Python program to determine if a string is a keyword. + +@@ -19,9 +21,3 @@ + Sequence containing all the keywords defined for the interpreter. If any + keywords are defined to only be active when particular :mod:`__future__` + statements are in effect, these will be included as well. +- +- +-.. seealso:: +- +- Latest version of the `keyword module Python source code +- `_ +diff -r 8527427914a2 Doc/library/linecache.rst +--- a/Doc/library/linecache.rst ++++ b/Doc/library/linecache.rst +@@ -6,17 +6,15 @@ + :synopsis: This module provides random access to individual lines from text files. + .. sectionauthor:: Moshe Zadka + ++**Source code:** :source:`Lib/linecache.py` ++ ++-------------- + + The :mod:`linecache` module allows one to get any line from any file, while + attempting to optimize internally, using a cache, the common case where many + lines are read from a single file. This is used by the :mod:`traceback` module + to retrieve source lines for inclusion in the formatted traceback. + +-.. seealso:: +- +- Latest version of the `linecache module Python source code +- `_ +- + The :mod:`linecache` module defines the following functions: + + +diff -r 8527427914a2 Doc/library/locale.rst +--- a/Doc/library/locale.rst ++++ b/Doc/library/locale.rst +@@ -23,19 +23,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]) + +- 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. +@@ -51,7 +51,7 @@ + changed thereafter, using multithreading should not cause problems. + + .. versionchanged:: 2.0 +- Added support for tuple values of the *locale* parameter. ++ Added support for iterable values of the *locale* parameter. + + + .. function:: localeconv() +@@ -219,7 +219,7 @@ + + .. note:: + +- The expression is in the syntax suitable for the :cfunc:`regex` function ++ The expression is in the syntax suitable for the :c:func:`regex` function + from the C library, which might differ from the syntax used in :mod:`re`. + + .. data:: NOEXPR +@@ -560,7 +560,7 @@ + Python applications should normally find no need to invoke these functions, and + should use :mod:`gettext` instead. A known exception to this rule are + applications that link with additional C libraries which internally invoke +-:cfunc:`gettext` or :func:`dcgettext`. For these applications, it may be ++:c:func:`gettext` or :func:`dcgettext`. For these applications, it may be + necessary to bind the text domain, so that the libraries can properly locate + their message catalogs. + +diff -r 8527427914a2 Doc/library/logging.config.rst +--- a/Doc/library/logging.config.rst ++++ b/Doc/library/logging.config.rst +@@ -516,6 +516,31 @@ + to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that + fails. + ++ ++.. _logging-import-resolution: ++ ++Import resolution and custom importers ++"""""""""""""""""""""""""""""""""""""" ++ ++Import resolution, by default, uses the builtin :func:`__import__` function ++to do its importing. You may want to replace this with your own importing ++mechanism: if so, you can replace the :attr:`importer` attribute of the ++:class:`DictConfigurator` or its superclass, the ++:class:`BaseConfigurator` class. However, you need to be ++careful because of the way functions are accessed from classes via ++descriptors. If you are using a Python callable to do your imports, and you ++want to define it at class level rather than instance level, you need to wrap ++it with :func:`staticmethod`. For example:: ++ ++ from importlib import import_module ++ from logging.config import BaseConfigurator ++ ++ BaseConfigurator.importer = staticmethod(import_module) ++ ++You don't need to wrap with :func:`staticmethod` if you're setting the import ++callable on a configurator *instance*. ++ ++ + .. _logging-config-fileformat: + + Configuration file format +diff -r 8527427914a2 Doc/library/logging.handlers.rst +--- a/Doc/library/logging.handlers.rst ++++ b/Doc/library/logging.handlers.rst +@@ -262,10 +262,7 @@ + :meth:`emit`. + + .. versionchanged:: 2.6 +- *delay* was added. +- +- .. versionchanged:: 2.7 +- *utc* was added. ++ *delay* and *utc* were added. + + + .. method:: doRollover() +@@ -613,8 +610,14 @@ + port, use the (host, port) tuple format for the *mailhost* argument. If you + use a string, the standard SMTP port is used. If your SMTP server requires + authentication, you can specify a (username, password) tuple for the +- *credentials* argument. If *secure* is True, then the handler will attempt +- to use TLS for the email transmission. ++ *credentials* argument. ++ ++ To specify the use of a secure protocol (TLS), pass in a tuple to the ++ *secure* argument. This will only be used when authentication credentials are ++ supplied. The tuple should be either an empty tuple, or a single-value tuple ++ with the name of a keyfile, or a 2-value tuple with the names of the keyfile ++ and certificate file. (This tuple is passed to the ++ :meth:`smtplib.SMTP.starttls` method.) + + .. versionchanged:: 2.6 + *credentials* was added. +diff -r 8527427914a2 Doc/library/logging.rst +--- a/Doc/library/logging.rst ++++ b/Doc/library/logging.rst +@@ -59,9 +59,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 ``True``. + + + .. method:: Logger.setLevel(lvl) +@@ -416,6 +422,13 @@ + record. Otherwise, the ISO8601 format is used. The resulting string is + returned. + ++ This function uses a user-configurable function to convert the creation ++ time to a tuple. By default, :func:`time.localtime` is used; to change ++ this for a particular formatter instance, set the ``converter`` attribute ++ to a function with the same signature as :func:`time.localtime` or ++ :func:`time.gmtime`. To change it for all formatters, for example if you ++ want all logging times to be shown in GMT, set the ``converter`` ++ attribute in the ``Formatter`` class. + + .. method:: formatException(exc_info) + +@@ -491,6 +504,9 @@ + :param name: The name of the logger used to log the event represented by + this LogRecord. + :param level: The numeric level of the logging event (one of DEBUG, INFO etc.) ++ Note that this is converted to *two* attributes of the LogRecord: ++ ``levelno`` for the numeric value and ``levelname`` for the ++ corresponding level name. + :param pathname: The full pathname of the source file where the logging call + was made. + :param lineno: The line number in the source file where the logging call was +diff -r 8527427914a2 Doc/library/macos.rst +--- a/Doc/library/macos.rst ++++ b/Doc/library/macos.rst +@@ -41,7 +41,7 @@ + + This exception is raised on MacOS generated errors, either from functions in + this module or from other mac-specific modules like the toolbox interfaces. The +- arguments are the integer error code (the :cdata:`OSErr` value) and a textual ++ arguments are the integer error code (the :c:data:`OSErr` value) and a textual + description of the error code. Symbolic names for all known error codes are + defined in the standard module :mod:`macerrors`. + +diff -r 8527427914a2 Doc/library/mailbox.rst +--- a/Doc/library/mailbox.rst ++++ b/Doc/library/mailbox.rst +@@ -459,7 +459,7 @@ + unlock() + + Three locking mechanisms are used---dot locking and, if available, the +- :cfunc:`flock` and :cfunc:`lockf` system calls. ++ :c:func:`flock` and :c:func:`lockf` system calls. + + + .. seealso:: +@@ -573,7 +573,7 @@ + unlock() + + Three locking mechanisms are used---dot locking and, if available, the +- :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking ++ :c:func:`flock` and :c:func:`lockf` system calls. For MH mailboxes, locking + the mailbox means locking the :file:`.mh_sequences` file and, only for the + duration of any operations that affect them, locking individual message + files. +@@ -671,7 +671,7 @@ + unlock() + + Three locking mechanisms are used---dot locking and, if available, the +- :cfunc:`flock` and :cfunc:`lockf` system calls. ++ :c:func:`flock` and :c:func:`lockf` system calls. + + + .. seealso:: +@@ -722,7 +722,7 @@ + unlock() + + Three locking mechanisms are used---dot locking and, if available, the +- :cfunc:`flock` and :cfunc:`lockf` system calls. ++ :c:func:`flock` and :c:func:`lockf` system calls. + + + .. seealso:: +@@ -765,7 +765,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 8527427914a2 Doc/library/mailcap.rst +--- a/Doc/library/mailcap.rst ++++ b/Doc/library/mailcap.rst +@@ -4,7 +4,9 @@ + .. module:: mailcap + :synopsis: Mailcap file handling. + ++**Source code:** :source:`Lib/mailcap.py` + ++-------------- + + Mailcap files are used to configure how MIME-aware applications such as mail + readers and Web browsers react to files with different MIME types. (The name +diff -r 8527427914a2 Doc/library/mimetypes.rst +--- a/Doc/library/mimetypes.rst ++++ b/Doc/library/mimetypes.rst +@@ -1,4 +1,3 @@ +- + :mod:`mimetypes` --- Map filenames to MIME types + ================================================ + +@@ -9,6 +8,10 @@ + + .. index:: pair: MIME; content type + ++**Source code:** :source:`Lib/mimetypes.py` ++ ++-------------- ++ + The :mod:`mimetypes` module converts between a filename or URL and the MIME type + associated with the filename extension. Conversions are provided from filename + to MIME type and from MIME type to filename extension; encodings are not +@@ -23,31 +26,31 @@ + the information :func:`init` sets up. + + +-.. function:: guess_type(filename[, strict]) ++.. function:: guess_type(url, strict=True) + + .. index:: pair: MIME; headers + +- Guess the type of a file based on its filename or URL, given by *filename*. The ++ Guess the type of a file based on its filename or URL, given by *url*. The + return value is a tuple ``(type, encoding)`` where *type* is ``None`` if the + type can't be guessed (missing or unknown suffix) or a string of the form + ``'type/subtype'``, usable for a MIME :mailheader:`content-type` header. + + *encoding* is ``None`` for no encoding or the name of the program used to encode + (e.g. :program:`compress` or :program:`gzip`). The encoding is suitable for use +- as a :mailheader:`Content-Encoding` header, *not* as a ++ as a :mailheader:`Content-Encoding` header, **not** as a + :mailheader:`Content-Transfer-Encoding` header. The mappings are table driven. + Encoding suffixes are case sensitive; type suffixes are first tried case + sensitively, then case insensitively. + +- Optional *strict* is a flag specifying whether the list of known MIME types ++ The optional *strict* argument is a flag specifying whether the list of known MIME types + is limited to only the official types `registered with IANA +- `_ are recognized. +- When *strict* is true (the default), only the IANA types are supported; when +- *strict* is false, some additional non-standard but commonly used MIME types ++ `_. ++ When *strict* is ``True`` (the default), only the IANA types are supported; when ++ *strict* is ``False``, some additional non-standard but commonly used MIME types + are also recognized. + + +-.. function:: guess_all_extensions(type[, strict]) ++.. function:: guess_all_extensions(type, strict=True) + + Guess the extensions for a file based on its MIME type, given by *type*. The + return value is a list of strings giving all possible filename extensions, +@@ -55,25 +58,25 @@ + been associated with any particular data stream, but would be mapped to the MIME + type *type* by :func:`guess_type`. + +- Optional *strict* has the same meaning as with the :func:`guess_type` function. ++ The optional *strict* argument has the same meaning as with the :func:`guess_type` function. + + +-.. function:: guess_extension(type[, strict]) ++.. function:: guess_extension(type, strict=True) + + Guess the extension for a file based on its MIME type, given by *type*. The + return value is a string giving a filename extension, including the leading dot + (``'.'``). The extension is not guaranteed to have been associated with any +- particular data stream, but would be mapped to the MIME type *type* by ++ particular data stream, but would be mapped to the MIME type *type* by + :func:`guess_type`. If no extension can be guessed for *type*, ``None`` is + returned. + +- Optional *strict* has the same meaning as with the :func:`guess_type` function. ++ The optional *strict* argument has the same meaning as with the :func:`guess_type` function. + + Some additional functions and data items are available for controlling the + behavior of the module. + + +-.. function:: init([files]) ++.. function:: init(files=None) + + Initialize the internal data structures. If given, *files* must be a sequence + of file names which should be used to augment the default type map. If omitted, +@@ -88,26 +91,26 @@ + + .. function:: read_mime_types(filename) + +- Load the type map given in the file *filename*, if it exists. The type map is ++ Load the type map given in the file *filename*, if it exists. The type map is + returned as a dictionary mapping filename extensions, including the leading dot + (``'.'``), to strings of the form ``'type/subtype'``. If the file *filename* + does not exist or cannot be read, ``None`` is returned. + + +-.. function:: add_type(type, ext[, strict]) ++.. function:: add_type(type, ext, strict=True) + +- Add a mapping from the mimetype *type* to the extension *ext*. When the ++ Add a mapping from the MIME type *type* to the extension *ext*. When the + extension is already known, the new type will replace the old one. When the type + is already known the extension will be added to the list of known extensions. + +- When *strict* is True (the default), the mapping will added to the official MIME ++ When *strict* is ``True`` (the default), the mapping will added to the official MIME + types, otherwise to the non-standard ones. + + + .. data:: inited + + Flag indicating whether or not the global data structures have been initialized. +- This is set to true by :func:`init`. ++ This is set to ``True`` by :func:`init`. + + + .. data:: knownfiles +@@ -142,23 +145,6 @@ + Dictionary mapping filename extensions to non-standard, but commonly found MIME + types. + +-The :class:`MimeTypes` class may be useful for applications which may want more +-than one MIME-type database: +- +- +-.. class:: MimeTypes([filenames]) +- +- This class represents a MIME-types database. By default, it provides access to +- the same database as the rest of this module. The initial database is a copy of +- that provided by the module, and may be extended by loading additional +- :file:`mime.types`\ -style files into the database using the :meth:`read` or +- :meth:`readfp` methods. The mapping dictionaries may also be cleared before +- loading additional data if the default data is not desired. +- +- The optional *filenames* parameter can be used to cause additional files to be +- loaded "on top" of the default database. +- +- .. versionadded:: 2.2 + + An example usage of the module:: + +@@ -179,70 +165,96 @@ + MimeTypes Objects + ----------------- + +-:class:`MimeTypes` instances provide an interface which is very like that of the ++The :class:`MimeTypes` class may be useful for applications which may want more ++than one MIME-type database; it provides an interface similar to the one of the + :mod:`mimetypes` module. + + ++.. class:: MimeTypes(filenames=(), strict=True) ++ ++ This class represents a MIME-types database. By default, it provides access to ++ the same database as the rest of this module. The initial database is a copy of ++ that provided by the module, and may be extended by loading additional ++ :file:`mime.types`\ -style files into the database using the :meth:`read` or ++ :meth:`readfp` methods. The mapping dictionaries may also be cleared before ++ loading additional data if the default data is not desired. ++ ++ The optional *filenames* parameter can be used to cause additional files to be ++ loaded "on top" of the default database. ++ ++ + .. attribute:: MimeTypes.suffix_map + + Dictionary mapping suffixes to suffixes. This is used to allow recognition of + encoded files for which the encoding and the type are indicated by the same + extension. For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz` + to allow the encoding and type to be recognized separately. This is initially a +- copy of the global ``suffix_map`` defined in the module. ++ copy of the global :data:`suffix_map` defined in the module. + + + .. attribute:: MimeTypes.encodings_map + + Dictionary mapping filename extensions to encoding types. This is initially a +- copy of the global ``encodings_map`` defined in the module. ++ copy of the global :data:`encodings_map` defined in the module. + + + .. attribute:: MimeTypes.types_map + +- Dictionary mapping filename extensions to MIME types. This is initially a copy +- of the global ``types_map`` defined in the module. ++ Tuple containing two dictionaries, mapping filename extensions to MIME types: ++ the first dictionary is for the non-standards types and the second one is for ++ the standard types. They are initialized by :data:`common_types` and ++ :data:`types_map`. + + +-.. attribute:: MimeTypes.common_types ++.. attribute:: MimeTypes.types_map_inv + +- Dictionary mapping filename extensions to non-standard, but commonly found MIME +- types. This is initially a copy of the global ``common_types`` defined in the +- module. ++ Tuple containing two dictionaries, mapping MIME types to a list of filename ++ extensions: the first dictionary is for the non-standards types and the ++ second one is for the standard types. They are initialized by ++ :data:`common_types` and :data:`types_map`. + + +-.. method:: MimeTypes.guess_extension(type[, strict]) ++.. method:: MimeTypes.guess_extension(type, strict=True) + + Similar to the :func:`guess_extension` function, using the tables stored as part + of the object. + + +-.. method:: MimeTypes.guess_all_extensions(type[, strict]) +- +- Similar to the :func:`guess_all_extensions` function, using the tables stored as part +- of the object. +- +- +-.. method:: MimeTypes.guess_type(url[, strict]) ++.. method:: MimeTypes.guess_type(url, strict=True) + + Similar to the :func:`guess_type` function, using the tables stored as part of + the object. + + +-.. method:: MimeTypes.read(path) ++.. method:: MimeTypes.guess_all_extensions(type, strict=True) + +- Load MIME information from a file named *path*. This uses :meth:`readfp` to ++ Similar to the :func:`guess_all_extensions` function, using the tables stored ++ as part of the object. ++ ++ ++.. method:: MimeTypes.read(filename, strict=True) ++ ++ Load MIME information from a file named *filename*. This uses :meth:`readfp` to + parse the file. + ++ If *strict* is ``True``, information will be added to list of standard types, ++ else to the list of non-standard types. + +-.. method:: MimeTypes.readfp(file) + +- Load MIME type information from an open file. The file must have the format of ++.. method:: MimeTypes.readfp(fp, strict=True) ++ ++ Load MIME type information from an open file *fp*. The file must have the format of + the standard :file:`mime.types` files. + ++ If *strict* is ``True``, information will be added to the list of standard ++ types, else to the list of non-standard types. + +-.. method:: MimeTypes.read_windows_registry() ++ ++.. method:: MimeTypes.read_windows_registry(strict=True) + + Load MIME type information from the Windows registry. Availability: Windows. + ++ If *strict* is ``True``, information will be added to the list of standard ++ types, else to the list of non-standard types. ++ + .. versionadded:: 2.7 +diff -r 8527427914a2 Doc/library/mmap.rst +--- a/Doc/library/mmap.rst ++++ b/Doc/library/mmap.rst +@@ -23,6 +23,12 @@ + :func:`os.open` function, which returns a file descriptor directly (the file + still needs to be closed when done). + ++.. note:: ++ If you want to create a memory-mapping for a writable, buffered file, you ++ should :func:`~io.IOBase.flush` the file first. This is necessary to ensure ++ that local modifications to the buffers are actually available to the ++ mapping. ++ + For both the Unix and Windows versions of the constructor, *access* may be + specified as an optional keyword parameter. *access* accepts one of three + values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY` +diff -r 8527427914a2 Doc/library/modulefinder.rst +--- a/Doc/library/modulefinder.rst ++++ b/Doc/library/modulefinder.rst +@@ -1,15 +1,16 @@ +- + :mod:`modulefinder` --- Find modules used by a script + ===================================================== + ++.. module:: modulefinder ++ :synopsis: Find modules used by a script. + .. sectionauthor:: A.M. Kuchling + + +-.. module:: modulefinder +- :synopsis: Find modules used by a script. ++.. versionadded:: 2.3 + ++**Source code:** :source:`Lib/modulefinder.py` + +-.. versionadded:: 2.3 ++-------------- + + This module provides a :class:`ModuleFinder` class that can be used to determine + the set of modules imported by a script. ``modulefinder.py`` can also be run as +diff -r 8527427914a2 Doc/library/msilib.rst +--- a/Doc/library/msilib.rst ++++ b/Doc/library/msilib.rst +@@ -44,7 +44,7 @@ + .. function:: UuidCreate() + + Return the string representation of a new unique identifier. This wraps the +- Windows API functions :cfunc:`UuidCreate` and :cfunc:`UuidToString`. ++ Windows API functions :c:func:`UuidCreate` and :c:func:`UuidToString`. + + + .. function:: OpenDatabase(path, persist) +@@ -60,7 +60,7 @@ + + .. function:: CreateRecord(count) + +- Return a new record object by calling :cfunc:`MSICreateRecord`. *count* is the ++ Return a new record object by calling :c:func:`MSICreateRecord`. *count* is the + number of fields of the record. + + +@@ -135,20 +135,20 @@ + + .. method:: Database.OpenView(sql) + +- Return a view object, by calling :cfunc:`MSIDatabaseOpenView`. *sql* is the SQL ++ Return a view object, by calling :c:func:`MSIDatabaseOpenView`. *sql* is the SQL + statement to execute. + + + .. method:: Database.Commit() + + Commit the changes pending in the current transaction, by calling +- :cfunc:`MSIDatabaseCommit`. ++ :c:func:`MSIDatabaseCommit`. + + + .. method:: Database.GetSummaryInformation(count) + + Return a new summary information object, by calling +- :cfunc:`MsiGetSummaryInformation`. *count* is the maximum number of updated ++ :c:func:`MsiGetSummaryInformation`. *count* is the maximum number of updated + values. + + +@@ -166,7 +166,7 @@ + + .. method:: View.Execute(params) + +- Execute the SQL query of the view, through :cfunc:`MSIViewExecute`. If ++ Execute the SQL query of the view, through :c:func:`MSIViewExecute`. If + *params* is not ``None``, it is a record describing actual values of the + parameter tokens in the query. + +@@ -174,18 +174,18 @@ + .. method:: View.GetColumnInfo(kind) + + Return a record describing the columns of the view, through calling +- :cfunc:`MsiViewGetColumnInfo`. *kind* can be either ``MSICOLINFO_NAMES`` or ++ :c:func:`MsiViewGetColumnInfo`. *kind* can be either ``MSICOLINFO_NAMES`` or + ``MSICOLINFO_TYPES``. + + + .. method:: View.Fetch() + +- Return a result record of the query, through calling :cfunc:`MsiViewFetch`. ++ Return a result record of the query, through calling :c:func:`MsiViewFetch`. + + + .. method:: View.Modify(kind, data) + +- Modify the view, by calling :cfunc:`MsiViewModify`. *kind* can be one of ++ Modify the view, by calling :c:func:`MsiViewModify`. *kind* can be one of + ``MSIMODIFY_SEEK``, ``MSIMODIFY_REFRESH``, ``MSIMODIFY_INSERT``, + ``MSIMODIFY_UPDATE``, ``MSIMODIFY_ASSIGN``, ``MSIMODIFY_REPLACE``, + ``MSIMODIFY_MERGE``, ``MSIMODIFY_DELETE``, ``MSIMODIFY_INSERT_TEMPORARY``, +@@ -197,7 +197,7 @@ + + .. method:: View.Close() + +- Close the view, through :cfunc:`MsiViewClose`. ++ Close the view, through :c:func:`MsiViewClose`. + + + .. seealso:: +@@ -216,7 +216,7 @@ + + .. method:: SummaryInformation.GetProperty(field) + +- Return a property of the summary, through :cfunc:`MsiSummaryInfoGetProperty`. ++ Return a property of the summary, through :c:func:`MsiSummaryInfoGetProperty`. + *field* is the name of the property, and can be one of the constants + ``PID_CODEPAGE``, ``PID_TITLE``, ``PID_SUBJECT``, ``PID_AUTHOR``, + ``PID_KEYWORDS``, ``PID_COMMENTS``, ``PID_TEMPLATE``, ``PID_LASTAUTHOR``, +@@ -228,12 +228,12 @@ + .. method:: SummaryInformation.GetPropertyCount() + + Return the number of summary properties, through +- :cfunc:`MsiSummaryInfoGetPropertyCount`. ++ :c:func:`MsiSummaryInfoGetPropertyCount`. + + + .. method:: SummaryInformation.SetProperty(field, value) + +- Set a property through :cfunc:`MsiSummaryInfoSetProperty`. *field* can have the ++ Set a property through :c:func:`MsiSummaryInfoSetProperty`. *field* can have the + same values as in :meth:`GetProperty`, *value* is the new value of the property. + Possible value types are integer and string. + +@@ -241,7 +241,7 @@ + .. method:: SummaryInformation.Persist() + + Write the modified properties to the summary information stream, using +- :cfunc:`MsiSummaryInfoPersist`. ++ :c:func:`MsiSummaryInfoPersist`. + + + .. seealso:: +@@ -260,7 +260,7 @@ + .. method:: Record.GetFieldCount() + + Return the number of fields of the record, through +- :cfunc:`MsiRecordGetFieldCount`. ++ :c:func:`MsiRecordGetFieldCount`. + + + .. method:: Record.GetInteger(field) +@@ -277,25 +277,25 @@ + + .. method:: Record.SetString(field, value) + +- Set *field* to *value* through :cfunc:`MsiRecordSetString`. *field* must be an ++ Set *field* to *value* through :c:func:`MsiRecordSetString`. *field* must be an + integer; *value* a string. + + + .. method:: Record.SetStream(field, value) + + Set *field* to the contents of the file named *value*, through +- :cfunc:`MsiRecordSetStream`. *field* must be an integer; *value* a string. ++ :c:func:`MsiRecordSetStream`. *field* must be an integer; *value* a string. + + + .. method:: Record.SetInteger(field, value) + +- Set *field* to *value* through :cfunc:`MsiRecordSetInteger`. Both *field* and ++ Set *field* to *value* through :c:func:`MsiRecordSetInteger`. Both *field* and + *value* must be an integer. + + + .. method:: Record.ClearData() + +- Set all fields of the record to 0, through :cfunc:`MsiRecordClearData`. ++ Set all fields of the record to 0, through :c:func:`MsiRecordClearData`. + + + .. seealso:: +diff -r 8527427914a2 Doc/library/msvcrt.rst +--- a/Doc/library/msvcrt.rst ++++ b/Doc/library/msvcrt.rst +@@ -152,5 +152,5 @@ + + .. function:: heapmin() + +- Force the :cfunc:`malloc` heap to clean itself up and return unused blocks to ++ Force the :c:func:`malloc` heap to clean itself up and return unused blocks to + the operating system. On failure, this raises :exc:`IOError`. +diff -r 8527427914a2 Doc/library/multiprocessing.rst +--- a/Doc/library/multiprocessing.rst ++++ b/Doc/library/multiprocessing.rst +@@ -282,7 +282,7 @@ + + if __name__ == '__main__': + pool = Pool(processes=4) # start 4 worker processes +- result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously ++ result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously + print result.get(timeout=1) # prints "100" unless your computer is *very* slow + print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" + +@@ -408,7 +408,7 @@ + .. method:: terminate() + + Terminate the process. On Unix this is done using the ``SIGTERM`` signal; +- on Windows :cfunc:`TerminateProcess` is used. Note that exit handlers and ++ on Windows :c:func:`TerminateProcess` is used. Note that exit handlers and + finally clauses, etc., will not be executed. + + Note that descendant processes of the process will *not* be terminated -- +@@ -464,7 +464,7 @@ + For passing messages one can use :func:`Pipe` (for a connection between two + processes) or a queue (which allows multiple producers and consumers). + +-The :class:`Queue` and :class:`JoinableQueue` types are multi-producer, ++The :class:`Queue`, :class:`multiprocessing.queues.SimpleQueue` and :class:`JoinableQueue` types are multi-producer, + multi-consumer FIFO queues modelled on the :class:`Queue.Queue` class in the + standard library. They differ in that :class:`Queue` lacks the + :meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join` methods introduced +@@ -472,7 +472,7 @@ + + If you use :class:`JoinableQueue` then you **must** call + :meth:`JoinableQueue.task_done` for each task removed from the queue or else the +-semaphore used to count the number of unfinished tasks may eventually overflow ++semaphore used to count the number of unfinished tasks may eventually overflow, + raising an exception. + + Note that one can also create a shared queue by using a manager object -- see +@@ -490,7 +490,7 @@ + + If a process is killed using :meth:`Process.terminate` or :func:`os.kill` + while it is trying to use a :class:`Queue`, then the data in the queue is +- likely to become corrupted. This may cause any other processes to get an ++ likely to become corrupted. This may cause any other process to get an + exception when it tries to use the queue later on. + + .. warning:: +@@ -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]]) + +@@ -610,6 +610,23 @@ + exits -- see :meth:`join_thread`. + + ++.. class:: multiprocessing.queues.SimpleQueue() ++ ++ It is a simplified :class:`Queue` type, very close to a locked :class:`Pipe`. ++ ++ .. method:: empty() ++ ++ Return ``True`` if the queue is empty, ``False`` otherwise. ++ ++ .. method:: get() ++ ++ Remove and return an item from the queue. ++ ++ .. method:: put(item) ++ ++ Put *item* into the queue. ++ ++ + .. class:: JoinableQueue([maxsize]) + + :class:`JoinableQueue`, a :class:`Queue` subclass, is a queue which +@@ -692,7 +709,7 @@ + (By default :data:`sys.executable` is used). Embedders will probably need to + do some thing like :: + +- setExecutable(os.path.join(sys.exec_prefix, 'pythonw.exe')) ++ set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe')) + + before they can create child processes. (Windows only) + +@@ -711,7 +728,7 @@ + Connection objects allow the sending and receiving of picklable objects or + strings. They can be thought of as message oriented connected sockets. + +-Connection objects usually created using :func:`Pipe` -- see also ++Connection objects are usually created using :func:`Pipe` -- see also + :ref:`multiprocessing-listeners-clients`. + + .. class:: Connection +@@ -722,17 +739,18 @@ + using :meth:`recv`. + + The object must be picklable. Very large pickles (approximately 32 MB+, +- though it depends on the OS) may raise a ValueError exception. ++ though it depends on the OS) may raise a :exc:`ValueError` exception. + + .. method:: recv() + + Return an object sent from the other end of the connection using +- :meth:`send`. Raises :exc:`EOFError` if there is nothing left to receive ++ :meth:`send`. Blocks until there its something to receive. Raises ++ :exc:`EOFError` if there is nothing left to receive + and the other end was closed. + + .. method:: fileno() + +- Returns the file descriptor or handle used by the connection. ++ Return the file descriptor or handle used by the connection. + + .. method:: close() + +@@ -756,12 +774,13 @@ + If *offset* is given then data is read from that position in *buffer*. If + *size* is given then that many bytes will be read from buffer. Very large + buffers (approximately 32 MB+, though it depends on the OS) may raise a +- ValueError exception ++ :exc:`ValueError` exception + + .. method:: recv_bytes([maxlength]) + + Return a complete message of byte data sent from the other end of the +- connection as a string. Raises :exc:`EOFError` if there is nothing left ++ connection as a string. Blocks until there is something to receive. ++ Raises :exc:`EOFError` if there is nothing left + to receive and the other end has closed. + + If *maxlength* is specified and the message is longer than *maxlength* +@@ -771,7 +790,8 @@ + .. method:: recv_bytes_into(buffer[, offset]) + + Read into *buffer* a complete message of byte data sent from the other end +- of the connection and return the number of bytes in the message. Raises ++ of the connection and return the number of bytes in the message. Blocks ++ until there is something to receive. Raises + :exc:`EOFError` if there is nothing left to receive and the other end was + closed. + +@@ -1329,7 +1349,7 @@ + >>>>>>>>>>>>>>>>>>> + + To create one's own manager, one creates a subclass of :class:`BaseManager` and +-use the :meth:`~BaseManager.register` classmethod to register new types or ++uses the :meth:`~BaseManager.register` classmethod to register new types or + callables with the manager class. For example:: + + from multiprocessing.managers import BaseManager +@@ -1494,7 +1514,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`. +@@ -1579,10 +1599,10 @@ + + .. method:: apply(func[, args[, kwds]]) + +- Equivalent of the :func:`apply` built-in function. It blocks till the +- result is ready. Given this blocks, :meth:`apply_async` is better suited +- for performing work in parallel. Additionally, the passed +- in function is only executed in one of the workers of the pool. ++ Equivalent of the :func:`apply` built-in function. It blocks until the ++ result is ready, so :meth:`apply_async` is better suited for performing ++ work in parallel. Additionally, *func* is only executed in one of the ++ workers of the pool. + + .. method:: apply_async(func[, args[, kwds[, callback]]]) + +@@ -1596,7 +1616,7 @@ + .. method:: map(func, iterable[, chunksize]) + + A parallel equivalent of the :func:`map` built-in function (it supports only +- one *iterable* argument though). It blocks till the result is ready. ++ one *iterable* argument though). It blocks until the result is ready. + + This method chops the iterable into a number of chunks which it submits to + the process pool as separate tasks. The (approximate) size of these +@@ -1617,7 +1637,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 +@@ -2046,7 +2066,7 @@ + On Windows many types from :mod:`multiprocessing` need to be picklable so + that child processes can use them. However, one should generally avoid + sending shared objects to other processes using pipes or queues. Instead +- you should arrange the program so that a process which need access to a ++ you should arrange the program so that a process which needs access to a + shared resource created elsewhere can inherit it from an ancestor process. + + Avoid terminating processes +@@ -2125,7 +2145,7 @@ + for i in range(10): + Process(target=f, args=(lock,)).start() + +-Beware replacing sys.stdin with a "file like object" ++Beware of replacing :data:`sys.stdin` with a "file like object" + + :mod:`multiprocessing` originally unconditionally called:: + +@@ -2243,7 +2263,7 @@ + + + An example showing how to use queues to feed tasks to a collection of worker +-process and collect the results: ++processes and collect the results: + + .. literalinclude:: ../includes/mp_workers.py + +diff -r 8527427914a2 Doc/library/netrc.rst +--- a/Doc/library/netrc.rst ++++ b/Doc/library/netrc.rst +@@ -10,6 +10,10 @@ + + .. versionadded:: 1.5.2 + ++**Source code:** :source:`Lib/netrc.py` ++ ++-------------- ++ + The :class:`netrc` class parses and encapsulates the netrc file format used by + the Unix :program:`ftp` program and other FTP clients. + +diff -r 8527427914a2 Doc/library/new.rst +--- a/Doc/library/new.rst ++++ b/Doc/library/new.rst +@@ -48,7 +48,7 @@ + + .. function:: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab) + +- This function is an interface to the :cfunc:`PyCode_New` C function. ++ This function is an interface to the :c:func:`PyCode_New` C function. + + .. XXX This is still undocumented! + +diff -r 8527427914a2 Doc/library/nntplib.rst +--- a/Doc/library/nntplib.rst ++++ b/Doc/library/nntplib.rst +@@ -10,6 +10,10 @@ + pair: NNTP; protocol + single: Network News Transfer Protocol + ++**Source code:** :source:`Lib/nntplib.py` ++ ++-------------- ++ + This module defines the class :class:`NNTP` which implements the client side of + the NNTP protocol. It can be used to implement a news reader or poster, or + automated news processors. For more information on NNTP (Network News Transfer +diff -r 8527427914a2 Doc/library/numbers.rst +--- a/Doc/library/numbers.rst ++++ b/Doc/library/numbers.rst +@@ -7,9 +7,9 @@ + .. versionadded:: 2.6 + + +-The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric abstract +-base classes which progressively define more operations. None of the types +-defined in this module can be instantiated. ++The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric ++:term:`abstract base classes ` which progressively define ++more operations. None of the types defined in this module can be instantiated. + + + .. class:: Number +diff -r 8527427914a2 Doc/library/operator.rst +--- a/Doc/library/operator.rst ++++ b/Doc/library/operator.rst +@@ -12,11 +12,11 @@ + from operator import itemgetter + + +-The :mod:`operator` module exports a set of functions implemented in C +-corresponding to the intrinsic operators of Python. For example, +-``operator.add(x, y)`` is equivalent to the expression ``x+y``. The function +-names are those used for special class methods; variants without leading and +-trailing ``__`` are also provided for convenience. ++The :mod:`operator` module exports a set of efficient functions corresponding to ++the intrinsic operators of Python. For example, ``operator.add(x, y)`` is ++equivalent to the expression ``x+y``. The function names are those used for ++special class methods; variants without leading and trailing ``__`` are also ++provided for convenience. + + The functions fall into categories that perform object comparisons, logical + operations, mathematical operations, sequence operations, and abstract type +diff -r 8527427914a2 Doc/library/optparse.rst +--- a/Doc/library/optparse.rst ++++ b/Doc/library/optparse.rst +@@ -4,17 +4,18 @@ + .. module:: optparse + :synopsis: Command-line option parsing library. + :deprecated: ++.. moduleauthor:: Greg Ward ++.. sectionauthor:: Greg Ward ++ ++.. versionadded:: 2.3 + + .. deprecated:: 2.7 + The :mod:`optparse` module is deprecated and will not be developed further; + development will continue with the :mod:`argparse` module. + +-.. moduleauthor:: Greg Ward +- +-.. versionadded:: 2.3 +- +-.. sectionauthor:: Greg Ward +- ++**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 +@@ -609,8 +610,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. " +@@ -657,8 +658,9 @@ + + .. method:: OptionParser.get_option_group(opt_str) + +- Return, if defined, the :class:`OptionGroup` that has the title or the long +- description equals to *opt_str* ++ Return the :class:`OptionGroup` to which the short or long option ++ string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If ++ there's no such :class:`OptionGroup`, return ``None``. + + .. _optparse-printing-version-string: + +diff -r 8527427914a2 Doc/library/os.path.rst +--- a/Doc/library/os.path.rst ++++ b/Doc/library/os.path.rst +@@ -196,10 +196,11 @@ + path, all previous components (on Windows, including the previous drive letter, + if there was one) are thrown away, and joining continues. The return value is + the concatenation of *path1*, and optionally *path2*, etc., with exactly one +- directory separator (``os.sep``) inserted between components, unless *path2* is +- empty. Note that on Windows, since there is a current directory for each drive, +- ``os.path.join("c:", "foo")`` represents a path relative to the current +- directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. ++ directory separator (``os.sep``) following each non-empty part except the last. ++ (This means that an empty last part will result in a path that ends with a ++ separator.) Note that on Windows, since there is a current directory for ++ each drive, ``os.path.join("c:", "foo")`` represents a path relative to the ++ current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. + + + .. function:: normcase(path) +diff -r 8527427914a2 Doc/library/os.rst +--- a/Doc/library/os.rst ++++ b/Doc/library/os.rst +@@ -53,6 +53,13 @@ + names have currently been registered: ``'posix'``, ``'nt'``, + ``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``. + ++ .. seealso:: ++ :attr:`sys.platform` has a finer granularity. :func:`os.uname` gives ++ system-dependent version information. ++ ++ The :mod:`platform` module provides detailed checks for the ++ system's identity. ++ + + .. _os-procinfo: + +@@ -87,7 +94,7 @@ + + On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may + cause memory leaks. Refer to the system documentation for +- :cfunc:`putenv`. ++ :c:func:`putenv`. + + If :func:`putenv` is not provided, a modified copy of this mapping may be + passed to the appropriate process-creation functions to cause child processes +@@ -302,7 +309,7 @@ + + .. function:: setpgrp() + +- Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on ++ Call the system call :c:func:`setpgrp` or :c:func:`setpgrp(0, 0)` depending on + which version is implemented (if any). See the Unix manual for the semantics. + + Availability: Unix. +@@ -310,7 +317,7 @@ + + .. function:: setpgid(pid, pgrp) + +- Call the system call :cfunc:`setpgid` to set the process group id of the ++ Call the system call :c:func:`setpgid` to set the process group id of the + process with id *pid* to the process group with id *pgrp*. See the Unix manual + for the semantics. + +@@ -351,7 +358,7 @@ + + .. function:: getsid(pid) + +- Call the system call :cfunc:`getsid`. See the Unix manual for the semantics. ++ Call the system call :c:func:`getsid`. See the Unix manual for the semantics. + + Availability: Unix. + +@@ -360,7 +367,7 @@ + + .. function:: setsid() + +- Call the system call :cfunc:`setsid`. See the Unix manual for the semantics. ++ Call the system call :c:func:`setsid`. See the Unix manual for the semantics. + + Availability: Unix. + +@@ -378,7 +385,7 @@ + .. function:: strerror(code) + + Return the error message corresponding to the error code in *code*. +- On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown ++ On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown + error number, :exc:`ValueError` is raised. + + Availability: Unix, Windows. +@@ -447,7 +454,7 @@ + + .. versionchanged:: 2.5 + On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is +- set on the file descriptor (which the :cfunc:`fdopen` implementation already ++ set on the file descriptor (which the :c:func:`fdopen` implementation already + does on most platforms). + + +@@ -470,7 +477,7 @@ + + .. versionchanged:: 2.0 + This function worked unreliably under Windows in earlier versions of Python. +- This was due to the use of the :cfunc:`_popen` function from the libraries ++ This was due to the use of the :c:func:`_popen` function from the libraries + provided with Windows. Newer versions of Python do not use the broken + implementation from the Windows libraries. + +@@ -690,7 +697,7 @@ + .. function:: fsync(fd) + + Force write of file with filedescriptor *fd* to disk. On Unix, this calls the +- native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function. ++ native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function. + + If you're starting with a Python file object *f*, first do ``f.flush()``, and + then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated +@@ -929,7 +936,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 +@@ -1014,6 +1021,8 @@ + * :data:`stat.UF_APPEND` + * :data:`stat.UF_OPAQUE` + * :data:`stat.UF_NOUNLINK` ++ * :data:`stat.UF_COMPRESSED` ++ * :data:`stat.UF_HIDDEN` + * :data:`stat.SF_ARCHIVED` + * :data:`stat.SF_IMMUTABLE` + * :data:`stat.SF_APPEND` +@@ -1133,7 +1142,7 @@ + + .. function:: lstat(path) + +- Perform the equivalent of an :cfunc:`lstat` system call on the given path. ++ Perform the equivalent of an :c:func:`lstat` system call on the given path. + Similar to :func:`~os.stat`, but does not follow symbolic links. On + platforms that do not support symbolic links, this is an alias for + :func:`~os.stat`. +@@ -1171,7 +1180,7 @@ + .. function:: major(device) + + Extract the device major number from a raw device number (usually the +- :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). ++ :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`). + + .. versionadded:: 2.3 + +@@ -1179,7 +1188,7 @@ + .. function:: minor(device) + + Extract the device minor number from a raw device number (usually the +- :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). ++ :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`). + + .. versionadded:: 2.3 + +@@ -1334,11 +1343,11 @@ + + .. function:: stat(path) + +- Perform the equivalent of a :cfunc:`stat` system call on the given path. ++ Perform the equivalent of a :c:func:`stat` system call on the given path. + (This function follows symlinks; to stat a symlink use :func:`lstat`.) + + The return value is an object whose attributes correspond to the members +- of the :ctype:`stat` structure, namely: ++ of the :c:type:`stat` structure, namely: + + * :attr:`st_mode` - protection bits, + * :attr:`st_ino` - inode number, +@@ -1386,15 +1395,16 @@ + + .. note:: + +- The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and +- :attr:`st_ctime` members depends on the operating system and the file system. +- For example, on Windows systems using the FAT or FAT32 file systems, +- :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day +- resolution. See your operating system documentation for details. ++ The exact meaning and resolution of the :attr:`st_atime`, ++ :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating ++ system and the file system. For example, on Windows systems using the FAT ++ or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and ++ :attr:`st_atime` has only 1-day resolution. See your operating system ++ documentation for details. + + For backward compatibility, the return value of :func:`~os.stat` is also accessible + as a tuple of at least 10 integers giving the most important (and portable) +- members of the :ctype:`stat` structure, in the order :attr:`st_mode`, ++ members of the :c:type:`stat` structure, in the order :attr:`st_mode`, + :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`, + :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`, + :attr:`st_ctime`. More items may be added at the end by some implementations. +@@ -1402,7 +1412,7 @@ + .. index:: module: stat + + The standard module :mod:`stat` defines functions and constants that are useful +- for extracting information from a :ctype:`stat` structure. (On Windows, some ++ for extracting information from a :c:type:`stat` structure. (On Windows, some + items are filled with dummy values.) + + Example:: +@@ -1451,9 +1461,9 @@ + + .. function:: statvfs(path) + +- Perform a :cfunc:`statvfs` system call on the given path. The return value is ++ Perform a :c:func:`statvfs` system call on the given path. The return value is + an object whose attributes describe the filesystem on the given path, and +- correspond to the members of the :ctype:`statvfs` structure, namely: ++ correspond to the members of the :c:type:`statvfs` structure, namely: + :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`, + :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`, + :attr:`f_flag`, :attr:`f_namemax`. +@@ -1463,7 +1473,7 @@ + For backward compatibility, the return value is also accessible as a tuple whose + values correspond to the attributes, in the order given above. The standard + module :mod:`statvfs` defines constants that are useful for extracting +- information from a :ctype:`statvfs` structure when accessing it as a sequence; ++ information from a :c:type:`statvfs` structure when accessing it as a sequence; + this remains useful when writing code that needs to work with versions of Python + that don't support accessing the fields as attributes. + +@@ -1588,7 +1598,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 +@@ -1654,7 +1664,7 @@ + program loaded into the process. In each case, the first of these arguments is + passed to the new program as its own name rather than as an argument a user may + have typed on a command line. For the C programmer, this is the ``argv[0]`` +-passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo', ++passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo', + ['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem + to be ignored. + +@@ -1663,8 +1673,9 @@ + + Generate a :const:`SIGABRT` signal to the current process. On Unix, the default + behavior is to produce a core dump; on Windows, the process immediately returns +- an exit code of ``3``. Be aware that programs which use :func:`signal.signal` +- to register a handler for :const:`SIGABRT` will behave differently. ++ an exit code of ``3``. Be aware that calling this function will not call the ++ Python signal handler registered for :const:`SIGABRT` with ++ :func:`signal.signal`. + + Availability: Unix, Windows. + +@@ -2041,7 +2052,9 @@ + os.spawnvpe(os.P_WAIT, 'cp', L, os.environ) + + Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp` +- and :func:`spawnvpe` are not available on Windows. ++ and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and ++ :func:`spawnve` are not thread-safe on Windows; we advise you to use the ++ :mod:`subprocess` module instead. + + .. versionadded:: 1.6 + +@@ -2104,7 +2117,7 @@ + There is no option to wait for the application to close, and no way to retrieve + the application's exit status. The *path* parameter is relative to the current + directory. If you want to use an absolute path, make sure the first character +- is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function ++ is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function + doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that + the path is properly encoded for Win32. + +@@ -2119,13 +2132,13 @@ + .. function:: system(command) + + Execute the command (a string) in a subshell. This is implemented by calling +- the Standard C function :cfunc:`system`, and has the same limitations. ++ the Standard C function :c:func:`system`, and has the same limitations. + Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the + executed command. + + On Unix, the return value is the exit status of the process encoded in the + format specified for :func:`wait`. Note that POSIX does not specify the meaning +- of the return value of the C :cfunc:`system` function, so the return value of ++ of the return value of the C :c:func:`system` function, so the return value of + the Python function is system-dependent. + + On Windows, the return value is that returned by the system shell after running +diff -r 8527427914a2 Doc/library/ossaudiodev.rst +--- a/Doc/library/ossaudiodev.rst ++++ b/Doc/library/ossaudiodev.rst +@@ -17,7 +17,7 @@ + ALSA is in the standard kernel as of 2.5.x. Presumably if you + use ALSA, you'll have to make sure its OSS compatibility layer + is active to use ossaudiodev, but you're gonna need it for the vast +- majority of Linux audio apps anyways. ++ majority of Linux audio apps anyway. + + Sounds like things are also complicated for other BSDs. In response + to my python-dev query, Thomas Wouters said: +@@ -59,7 +59,7 @@ + what went wrong. + + (If :mod:`ossaudiodev` receives an error from a system call such as +- :cfunc:`open`, :cfunc:`write`, or :cfunc:`ioctl`, it raises :exc:`IOError`. ++ :c:func:`open`, :c:func:`write`, or :c:func:`ioctl`, it raises :exc:`IOError`. + Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.) + + (For backwards compatibility, the exception class is also available as +diff -r 8527427914a2 Doc/library/othergui.rst +--- a/Doc/library/othergui.rst ++++ b/Doc/library/othergui.rst +@@ -3,34 +3,8 @@ + Other Graphical User Interface Packages + ======================================= + +-There are an number of extension widget sets to :mod:`Tkinter`. +- +-.. seealso:: +- +- `Python megawidgets `_ +- is a toolkit for building high-level compound widgets in Python using the +- :mod:`Tkinter` module. 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. +- +- 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: ++Major cross-platform (Windows, Mac OS X, Unix-like) GUI toolkits are ++available for Python: + + .. seealso:: + +diff -r 8527427914a2 Doc/library/pickle.rst +--- a/Doc/library/pickle.rst ++++ b/Doc/library/pickle.rst +@@ -364,7 +364,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. [#]_ +diff -r 8527427914a2 Doc/library/pickletools.rst +--- a/Doc/library/pickletools.rst ++++ b/Doc/library/pickletools.rst +@@ -8,6 +8,10 @@ + + .. versionadded:: 2.3 + ++**Source code:** :source:`Lib/pickletools.py` ++ ++-------------- ++ + This module contains various constants relating to the intimate details of the + :mod:`pickle` module, some lengthy comments about the implementation, and a few + useful functions for analyzing pickled data. The contents of this module are +diff -r 8527427914a2 Doc/library/pipes.rst +--- a/Doc/library/pipes.rst ++++ b/Doc/library/pipes.rst +@@ -1,4 +1,3 @@ +- + :mod:`pipes` --- Interface to shell pipelines + ============================================= + +@@ -7,6 +6,9 @@ + :synopsis: A Python interface to Unix shell pipelines. + .. sectionauthor:: Moshe Zadka + ++**Source code:** :source:`Lib/pipes.py` ++ ++-------------- + + The :mod:`pipes` module defines a class to abstract the concept of a *pipeline* + --- a sequence of converters from one file to another. +diff -r 8527427914a2 Doc/library/pkgutil.rst +--- a/Doc/library/pkgutil.rst ++++ b/Doc/library/pkgutil.rst +@@ -1,15 +1,18 @@ +- + :mod:`pkgutil` --- Package extension utility + ============================================ + + .. module:: pkgutil + :synopsis: Utilities for the import system. + ++.. versionadded:: 2.3 ++ ++**Source code:** :source:`Lib/pkgutil.py` ++ ++-------------- ++ + This module provides utilities for the import system, in particular package + support. + +-.. versionadded:: 2.3 +- + + .. function:: extend_path(path, name) + +@@ -187,3 +190,5 @@ + + If the package cannot be located or loaded, or it uses a :pep:`302` loader + which does not support :func:`get_data`, then ``None`` is returned. ++ ++ .. versionadded:: 2.6 +diff -r 8527427914a2 Doc/library/platform.rst +--- a/Doc/library/platform.rst ++++ b/Doc/library/platform.rst +@@ -9,6 +9,10 @@ + + .. versionadded:: 2.3 + ++**Source code:** :source:`Lib/platform.py` ++ ++-------------- ++ + .. note:: + + Specific platforms listed alphabetically, with Linux included in the Unix +@@ -29,8 +33,8 @@ + returned as strings. + + Values that cannot be determined are returned as given by the parameter presets. +- If bits is given as ``''``, the :cfunc:`sizeof(pointer)` (or +- :cfunc:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the ++ If bits is given as ``''``, the :c:func:`sizeof(pointer)` (or ++ :c:func:`sizeof(long)` on Python version < 1.5.2) is used as indicator for the + supported pointer size. + + The function relies on the system's :file:`file` command to do the actual work. +@@ -193,8 +197,8 @@ + .. function:: win32_ver(release='', version='', csd='', ptype='') + + Get additional version information from the Windows Registry and return a tuple +- ``(version, csd, ptype)`` referring to version number, CSD level and OS type +- (multi/single processor). ++ ``(version, csd, ptype)`` referring to version number, CSD level ++ (service pack) and OS type (multi/single processor). + + As a hint: *ptype* is ``'Uniprocessor Free'`` on single processor NT machines + and ``'Multiprocessor Free'`` on multi processor machines. The *'Free'* refers +@@ -233,9 +237,6 @@ + Entries which cannot be determined are set to ``''``. All tuple entries are + strings. + +- Documentation for the underlying :cfunc:`gestalt` API is available online at +- http://www.rgaros.nl/gestalt/. +- + + Unix Platforms + -------------- +diff -r 8527427914a2 Doc/library/plistlib.rst +--- a/Doc/library/plistlib.rst ++++ b/Doc/library/plistlib.rst +@@ -15,6 +15,10 @@ + pair: plist; file + single: property list + ++**Source code:** :source:`Lib/plistlib.py` ++ ++-------------- ++ + This module provides an interface for reading and writing the "property list" + XML files used mainly by Mac OS X. + +diff -r 8527427914a2 Doc/library/popen2.rst +--- a/Doc/library/popen2.rst ++++ b/Doc/library/popen2.rst +@@ -104,7 +104,7 @@ + + Waits for and returns the status code of the child process. The status code + encodes both the return code of the process and information about whether it +- exited using the :cfunc:`exit` system call or died due to a signal. Functions ++ exited using the :c:func:`exit` system call or died due to a signal. Functions + to help interpret the status code are defined in the :mod:`os` module; see + section :ref:`os-process` for the :func:`W\*` family of functions. + +diff -r 8527427914a2 Doc/library/poplib.rst +--- a/Doc/library/poplib.rst ++++ b/Doc/library/poplib.rst +@@ -1,4 +1,3 @@ +- + :mod:`poplib` --- POP3 protocol client + ====================================== + +@@ -9,6 +8,10 @@ + + .. index:: pair: POP3; protocol + ++**Source code:** :source:`Lib/poplib.py` ++ ++-------------- ++ + This module defines a class, :class:`POP3`, which encapsulates a connection to a + POP3 server and implements the protocol as defined in :rfc:`1725`. The + :class:`POP3` class supports both the minimal and optional command sets. +diff -r 8527427914a2 Doc/library/posix.rst +--- a/Doc/library/posix.rst ++++ b/Doc/library/posix.rst +@@ -38,13 +38,13 @@ + + Several operating systems (including AIX, HP-UX, Irix and Solaris) provide + support for files that are larger than 2 GB from a C programming model where +-:ctype:`int` and :ctype:`long` are 32-bit values. This is typically accomplished ++:c:type:`int` and :c:type:`long` are 32-bit values. This is typically accomplished + by defining the relevant size and offset types as 64-bit values. Such files are + sometimes referred to as :dfn:`large files`. + +-Large file support is enabled in Python when the size of an :ctype:`off_t` is +-larger than a :ctype:`long` and the :ctype:`long long` type is available and is +-at least as large as an :ctype:`off_t`. Python longs are then used to represent ++Large file support is enabled in Python when the size of an :c:type:`off_t` is ++larger than a :c:type:`long` and the :c:type:`long long` type is available and is ++at least as large as an :c:type:`off_t`. Python longs are then used to represent + file sizes, offsets and other values that can exceed the range of a Python int. + It may be necessary to configure and compile Python with certain compiler flags + to enable this mode. For example, it is enabled by default with recent versions +diff -r 8527427914a2 Doc/library/pprint.rst +--- a/Doc/library/pprint.rst ++++ b/Doc/library/pprint.rst +@@ -1,4 +1,3 @@ +- + :mod:`pprint` --- Data pretty printer + ===================================== + +@@ -7,6 +6,9 @@ + .. moduleauthor:: Fred L. Drake, Jr. + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/pprint.py` ++ ++-------------- + + The :mod:`pprint` module provides a capability to "pretty-print" arbitrary + Python data structures in a form which can be used as input to the interpreter. +@@ -28,10 +30,6 @@ + .. versionchanged:: 2.6 + Added support for :class:`set` and :class:`frozenset`. + +-.. seealso:: +- +- Latest version of the `pprint module Python source code +- `_ + + The :mod:`pprint` module defines one class: + +diff -r 8527427914a2 Doc/library/profile.rst +--- a/Doc/library/profile.rst ++++ b/Doc/library/profile.rst +@@ -1,4 +1,3 @@ +- + .. _profile: + + ******************** +@@ -10,29 +9,9 @@ + .. module:: profile + :synopsis: Python source profiler. + +-.. index:: single: InfoSeek Corporation ++**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py` + +-Copyright © 1994, by InfoSeek Corporation, all rights reserved. +- +-Written by James Roskind. [#]_ +- +-Permission to use, copy, modify, and distribute this Python software and its +-associated documentation for any purpose (subject to the restriction in the +-following sentence) 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 +-InfoSeek not be used in advertising or publicity pertaining to distribution of +-the software without specific, written prior permission. This permission is +-explicitly restricted to the copying and modification of the software to remain +-in Python, compiled Python, or other languages (such as C) wherein the modified +-or derived code is exclusively imported into a Python module. +- +-INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT +-SHALL INFOSEEK CORPORATION 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. ++-------------- + + .. _profiler-introduction: + +@@ -65,7 +44,6 @@ + :mod:`cProfile`. Adds significant overhead to profiled programs. + If you're trying to extend + the profiler in some way, the task might be easier with this module. +- Copyright © 1994, by InfoSeek Corporation. + + .. versionchanged:: 2.4 + Now also reports the time spent in calls to built-in functions and methods. +diff -r 8527427914a2 Doc/library/py_compile.rst +--- a/Doc/library/py_compile.rst ++++ b/Doc/library/py_compile.rst +@@ -8,6 +8,10 @@ + + .. index:: pair: file; byte-code + ++**Source code:** :source:`Lib/py_compile.py` ++ ++-------------- ++ + The :mod:`py_compile` module provides a function to generate a byte-code file + from a source file, and another function used when the module source file is + invoked as a script. +diff -r 8527427914a2 Doc/library/pyclbr.rst +--- a/Doc/library/pyclbr.rst ++++ b/Doc/library/pyclbr.rst +@@ -1,4 +1,3 @@ +- + :mod:`pyclbr` --- Python class browser support + ============================================== + +@@ -6,6 +5,9 @@ + :synopsis: Supports information extraction for a Python class browser. + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/pyclbr.py` ++ ++-------------- + + The :mod:`pyclbr` module can be used to determine some limited information + about the classes, methods and top-level functions defined in a module. The +@@ -43,7 +45,7 @@ + + The :class:`Class` objects used as values in the dictionary returned by + :func:`readmodule` and :func:`readmodule_ex` provide the following data +-members: ++attributes: + + + .. attribute:: Class.module +@@ -87,7 +89,7 @@ + ---------------- + + The :class:`Function` objects used as values in the dictionary returned by +-:func:`readmodule_ex` provide the following data members: ++:func:`readmodule_ex` provide the following attributes: + + + .. attribute:: Function.module +diff -r 8527427914a2 Doc/library/pydoc.rst +--- a/Doc/library/pydoc.rst ++++ b/Doc/library/pydoc.rst +@@ -1,4 +1,3 @@ +- + :mod:`pydoc` --- Documentation generator and online help system + =============================================================== + +@@ -15,6 +14,10 @@ + single: documentation; online + single: help; online + ++**Source code:** :source:`Lib/pydoc.py` ++ ++-------------- ++ + The :mod:`pydoc` module automatically generates documentation from Python + modules. The documentation can be presented as pages of text on the console, + served to a Web browser, or saved to HTML files. +diff -r 8527427914a2 Doc/library/queue.rst +--- a/Doc/library/queue.rst ++++ b/Doc/library/queue.rst +@@ -1,4 +1,4 @@ +-:mod:`queue` --- A synchronized queue class ++:mod:`Queue` --- A synchronized queue class + =========================================== + + .. module:: Queue +@@ -9,6 +9,9 @@ + :term:`2to3` tool will automatically adapt imports when converting your + sources to 3.0. + ++**Source code:** :source:`Lib/Queue.py` ++ ++-------------- + + The :mod:`Queue` module implements multi-producer, multi-consumer queues. + It is especially useful in threaded programming when information must be +@@ -24,11 +27,6 @@ + the entries are kept sorted (using the :mod:`heapq` module) and the + lowest valued entry is retrieved first. + +-.. seealso:: +- +- Latest version of the `queue module Python source code +- `_. +- + The :mod:`Queue` module defines the following classes and exceptions: + + .. class:: Queue(maxsize=0) +diff -r 8527427914a2 Doc/library/quopri.rst +--- a/Doc/library/quopri.rst ++++ b/Doc/library/quopri.rst +@@ -1,4 +1,3 @@ +- + :mod:`quopri` --- Encode and decode MIME quoted-printable data + ============================================================== + +@@ -10,6 +9,10 @@ + pair: quoted-printable; encoding + single: MIME; quoted-printable encoding + ++**Source code:** :source:`Lib/quopri.py` ++ ++-------------- ++ + This module performs quoted-printable transport encoding and decoding, as + defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One: + Mechanisms for Specifying and Describing the Format of Internet Message Bodies". +@@ -18,11 +21,6 @@ + :mod:`base64` module is more compact if there are many such characters, as when + sending a graphics file. + +-.. seealso:: +- +- Latest version of the `quopri module Python source code +- `_ +- + .. function:: decode(input, output[,header]) + + Decode the contents of the *input* file and write the resulting decoded binary +diff -r 8527427914a2 Doc/library/random.rst +--- a/Doc/library/random.rst ++++ b/Doc/library/random.rst +@@ -1,19 +1,16 @@ +- + :mod:`random` --- Generate pseudo-random numbers + ================================================ + + .. module:: random + :synopsis: Generate pseudo-random numbers with various common distributions. + ++**Source code:** :source:`Lib/random.py` ++ ++-------------- + + This module implements pseudo-random number generators for various + distributions. + +-.. seealso:: +- +- Latest version of the `random module Python source code +- `_ +- + For integers, uniform selection from a range. For sequences, uniform selection + of a random element, a function to generate a random permutation of a list + in-place, and a function for random sampling without replacement. +@@ -199,6 +196,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 +@@ -229,6 +227,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 8527427914a2 Doc/library/re.rst +--- a/Doc/library/re.rst ++++ b/Doc/library/re.rst +@@ -156,30 +156,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:`LOCALE` +- or :const:`UNICODE` 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:`LOCALE` or :const:`UNICODE` 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 +@@ -425,7 +431,7 @@ + form. + + +-.. function:: compile(pattern[, flags]) ++.. function:: compile(pattern, flags=0) + + Compile a regular expression pattern into a regular expression object, which + can be used for matching using its :func:`match` and :func:`search` methods, +@@ -456,6 +462,11 @@ + about compiling regular expressions. + + ++.. data:: DEBUG ++ ++ Display debug information about compiled expression. ++ ++ + .. data:: I + IGNORECASE + +@@ -515,7 +526,7 @@ + b = re.compile(r"\d+\.\d*") + + +-.. function:: search(pattern, string[, flags]) ++.. function:: search(pattern, string, flags=0) + + Scan through *string* looking for a location where the regular expression + *pattern* produces a match, and return a corresponding :class:`MatchObject` +@@ -524,7 +535,7 @@ + string. + + +-.. function:: match(pattern, string[, flags]) ++.. function:: match(pattern, string, flags=0) + + If zero or more characters at the beginning of *string* match the regular + expression *pattern*, return a corresponding :class:`MatchObject` instance. +@@ -537,7 +548,7 @@ + instead. + + +-.. function:: split(pattern, string[, maxsplit=0, flags=0]) ++.. function:: split(pattern, string, maxsplit=0, flags=0) + + Split *string* by the occurrences of *pattern*. If capturing parentheses are + used in *pattern*, then the text of all groups in the pattern are also returned +@@ -578,7 +589,7 @@ + Added the optional flags argument. + + +-.. function:: findall(pattern, string[, flags]) ++.. function:: findall(pattern, string, flags=0) + + Return all non-overlapping matches of *pattern* in *string*, as a list of + strings. The *string* is scanned left-to-right, and matches are returned in +@@ -593,7 +604,7 @@ + Added the optional flags argument. + + +-.. function:: finditer(pattern, string[, flags]) ++.. function:: finditer(pattern, string, flags=0) + + Return an :term:`iterator` yielding :class:`MatchObject` instances over all + non-overlapping matches for the RE *pattern* in *string*. The *string* is +@@ -607,13 +618,13 @@ + Added the optional flags argument. + + +-.. function:: sub(pattern, repl, string[, count, flags]) ++.. function:: sub(pattern, repl, string, count=0, flags=0) + + Return the string obtained by replacing the leftmost non-overlapping occurrences + of *pattern* in *string* by the replacement *repl*. If the pattern isn't found, + *string* is returned unchanged. *repl* can be a string or a function; if it is + a string, any backslash escapes in it are processed. That is, ``\n`` is +- converted to a single newline character, ``\r`` is converted to a linefeed, and ++ converted to a single newline character, ``\r`` is converted to a carriage return, and + so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such + as ``\6``, are replaced with the substring matched by group 6 in the pattern. + For example: +@@ -656,7 +667,7 @@ + Added the optional flags argument. + + +-.. function:: subn(pattern, repl, string[, count, flags]) ++.. function:: subn(pattern, repl, string, count=0, flags=0) + + Perform the same operation as :func:`sub`, but return a tuple ``(new_string, + number_of_subs_made)``. +@@ -741,7 +752,7 @@ + <_sre.SRE_Match object at ...> + + +- .. method:: RegexObject.split(string[, maxsplit=0]) ++ .. method:: RegexObject.split(string, maxsplit=0) + + Identical to the :func:`split` function, using the compiled pattern. + +@@ -760,12 +771,12 @@ + region like for :meth:`match`. + + +- .. method:: RegexObject.sub(repl, string[, count=0]) ++ .. method:: RegexObject.sub(repl, string, count=0) + + Identical to the :func:`sub` function, using the compiled pattern. + + +- .. method:: RegexObject.subn(repl, string[, count=0]) ++ .. method:: RegexObject.subn(repl, string, count=0) + + Identical to the :func:`subn` function, using the compiled pattern. + +@@ -994,16 +1005,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. + "" + +@@ -1042,14 +1053,14 @@ + + .. index:: single: scanf() + +-Python does not currently have an equivalent to :cfunc:`scanf`. Regular ++Python does not currently have an equivalent to :c:func:`scanf`. Regular + expressions are generally more powerful, though also more verbose, than +-:cfunc:`scanf` format strings. The table below offers some more-or-less +-equivalent mappings between :cfunc:`scanf` format tokens and regular ++:c:func:`scanf` format strings. The table below offers some more-or-less ++equivalent mappings between :c:func:`scanf` format tokens and regular + expressions. + + +--------------------------------+---------------------------------------------+ +-| :cfunc:`scanf` Token | Regular Expression | ++| :c:func:`scanf` Token | Regular Expression | + +================================+=============================================+ + | ``%c`` | ``.`` | + +--------------------------------+---------------------------------------------+ +@@ -1074,7 +1085,7 @@ + + /usr/sbin/sendmail - 0 errors, 4 warnings + +-you would use a :cfunc:`scanf` format like :: ++you would use a :c:func:`scanf` format like :: + + %s - %d errors, %d warnings + +diff -r 8527427914a2 Doc/library/repr.rst +--- a/Doc/library/repr.rst ++++ b/Doc/library/repr.rst +@@ -1,4 +1,3 @@ +- + :mod:`repr` --- Alternate :func:`repr` implementation + ===================================================== + +@@ -11,15 +10,14 @@ + :term:`2to3` tool will automatically adapt imports when converting your + sources to 3.0. + ++**Source code:** :source:`Lib/repr.py` ++ ++-------------- ++ + The :mod:`repr` module provides a means for producing object representations + with limits on the size of the resulting strings. This is used in the Python + debugger and may be useful in other contexts as well. + +-.. seealso:: +- +- Latest version of the `repr module Python source code +- `_ +- + This module provides a class, an instance, and a function: + + +@@ -49,7 +47,7 @@ + Repr Objects + ------------ + +-:class:`Repr` instances provide several members which can be used to provide ++:class:`Repr` instances provide several attributes which can be used to provide + size limits for the representations of different object types, and methods + which format specific object types. + +diff -r 8527427914a2 Doc/library/restricted.rst +--- a/Doc/library/restricted.rst ++++ b/Doc/library/restricted.rst +@@ -31,7 +31,7 @@ + might be deemed "safe" for untrusted code to read any file within a specified + directory, but never to write a file. In this case, the supervisor may redefine + the built-in :func:`open` function so that it raises an exception whenever the +-*mode* parameter is ``'w'``. It might also perform a :cfunc:`chroot`\ -like ++*mode* parameter is ``'w'``. It might also perform a :c:func:`chroot`\ -like + operation on the *filename* parameter, such that root is always relative to some + safe "sandbox" area of the filesystem. In this case, the untrusted code would + still see an built-in :func:`open` function in its environment, with the same +diff -r 8527427914a2 Doc/library/rfc822.rst +--- a/Doc/library/rfc822.rst ++++ b/Doc/library/rfc822.rst +@@ -42,8 +42,8 @@ + from a buffered stream. + + The optional *seekable* argument is provided as a workaround for certain stdio +- libraries in which :cfunc:`tell` discards buffered data before discovering that +- the :cfunc:`lseek` system call doesn't work. For maximum portability, you ++ libraries in which :c:func:`tell` discards buffered data before discovering that ++ the :c:func:`lseek` system call doesn't work. For maximum portability, you + should set the seekable argument to zero to prevent that initial :meth:`tell` + when passing in an unseekable object such as a file object created from a socket + object. +diff -r 8527427914a2 Doc/library/rlcompleter.rst +--- a/Doc/library/rlcompleter.rst ++++ b/Doc/library/rlcompleter.rst +@@ -1,4 +1,3 @@ +- + :mod:`rlcompleter` --- Completion function for GNU readline + =========================================================== + +@@ -6,6 +5,9 @@ + :synopsis: Python identifier completion, suitable for the GNU readline library. + .. sectionauthor:: Moshe Zadka + ++**Source code:** :source:`Lib/rlcompleter.py` ++ ++-------------- + + The :mod:`rlcompleter` module defines a completion function suitable for the + :mod:`readline` module by completing valid Python identifiers and keywords. +diff -r 8527427914a2 Doc/library/runpy.rst +--- a/Doc/library/runpy.rst ++++ b/Doc/library/runpy.rst +@@ -8,6 +8,10 @@ + + .. versionadded:: 2.5 + ++**Source code:** :source:`Lib/runpy.py` ++ ++-------------- ++ + The :mod:`runpy` module is used to locate and run Python modules without + importing them first. Its main use is to implement the :option:`-m` command + line switch that allows scripts to be located using the Python module +diff -r 8527427914a2 Doc/library/sched.rst +--- a/Doc/library/sched.rst ++++ b/Doc/library/sched.rst +@@ -7,14 +7,13 @@ + + .. index:: single: event scheduling + ++**Source code:** :source:`Lib/sched.py` ++ ++-------------- ++ + The :mod:`sched` module defines a class which implements a general purpose event + scheduler: + +-.. seealso:: +- +- Latest version of the `sched module Python source code +- `_ +- + .. class:: scheduler(timefunc, delayfunc) + + The :class:`scheduler` class defines a generic interface to scheduling events. +@@ -96,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 8527427914a2 Doc/library/select.rst +--- a/Doc/library/select.rst ++++ b/Doc/library/select.rst +@@ -6,9 +6,9 @@ + :synopsis: Wait for I/O completion on multiple streams. + + +-This module provides access to the :cfunc:`select` and :cfunc:`poll` functions +-available in most operating systems, :cfunc:`epoll` available on Linux 2.5+ and +-:cfunc:`kqueue` available on most BSD. ++This module provides access to the :c:func:`select` and :c:func:`poll` functions ++available in most operating systems, :c:func:`epoll` available on Linux 2.5+ and ++:c:func:`kqueue` available on most BSD. + Note that on Windows, it only works for sockets; on other operating systems, + it also works for other file types (in particular, on Unix, it works on pipes). + It cannot be used on regular files to determine whether a file has grown since +@@ -20,8 +20,8 @@ + .. exception:: error + + The exception raised when an error occurs. The accompanying value is a pair +- containing the numeric error code from :cdata:`errno` and the corresponding +- string, as would be printed by the C function :cfunc:`perror`. ++ containing the numeric error code from :c:data:`errno` and the corresponding ++ string, as would be printed by the C function :c:func:`perror`. + + + .. function:: epoll([sizehint=-1]) +@@ -60,7 +60,7 @@ + + .. function:: select(rlist, wlist, xlist[, timeout]) + +- This is a straightforward interface to the Unix :cfunc:`select` system call. ++ This is a straightforward interface to the Unix :c:func:`select` system call. + The first three arguments are sequences of 'waitable objects': either + integers representing file descriptors or objects with a parameterless method + named :meth:`fileno` returning such an integer: +@@ -96,7 +96,7 @@ + .. index:: single: WinSock + + File objects on Windows are not acceptable, but sockets are. On Windows, +- the underlying :cfunc:`select` function is provided by the WinSock ++ the underlying :c:func:`select` function is provided by the WinSock + library, and does not handle file descriptors that don't originate from + WinSock. + +@@ -195,13 +195,13 @@ + Polling Objects + --------------- + +-The :cfunc:`poll` system call, supported on most Unix systems, provides better ++The :c:func:`poll` system call, supported on most Unix systems, provides better + scalability for network servers that service many, many clients at the same +-time. :cfunc:`poll` scales better because the system call only requires listing +-the file descriptors of interest, while :cfunc:`select` builds a bitmap, turns ++time. :c:func:`poll` scales better because the system call only requires listing ++the file descriptors of interest, while :c:func:`select` builds a bitmap, turns + on bits for the fds of interest, and then afterward the whole bitmap has to be +-linearly scanned again. :cfunc:`select` is O(highest file descriptor), while +-:cfunc:`poll` is O(number of file descriptors). ++linearly scanned again. :c:func:`select` is O(highest file descriptor), while ++:c:func:`poll` is O(number of file descriptors). + + + .. method:: poll.register(fd[, eventmask]) +diff -r 8527427914a2 Doc/library/shelve.rst +--- a/Doc/library/shelve.rst ++++ b/Doc/library/shelve.rst +@@ -7,16 +7,16 @@ + + .. index:: module: pickle + ++**Source code:** :source:`Lib/shelve.py` ++ ++-------------- ++ + A "shelf" is a persistent, dictionary-like object. The difference with "dbm" + databases is that the values (not the keys!) in a shelf can be essentially + arbitrary Python objects --- anything that the :mod:`pickle` module can handle. + This includes most class instances, recursive data types, and objects containing + lots of shared sub-objects. The keys are ordinary strings. + +-.. seealso:: +- +- Latest version of the `shelve module Python source code +- `_ + + .. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]]) + +@@ -44,17 +44,12 @@ + determine which accessed entries are mutable, nor which ones were actually + mutated). + +- .. note:: ++ Like file objects, shelve objects should be closed explicitly to ensure ++ that the persistent data is flushed to disk. + +- Do not rely on the shelf being closed automatically; always call +- :meth:`close` explicitly when you don't need it any more, or use a +- :keyword:`with` statement with :func:`contextlib.closing`. +- +-.. warning:: +- +- Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure +- to load a shelf from an untrusted source. Like with pickle, loading a shelf +- can execute arbitrary code. ++ Since the :mod:`shelve` module stores objects using :mod:`pickle`, the same ++ security precautions apply. Accordingly, you should avoid loading a shelf ++ from an untrusted source. + + Shelf objects support all methods supported by dictionaries. This eases the + transition from dictionary based scripts to those requiring persistent storage. +diff -r 8527427914a2 Doc/library/shlex.rst +--- a/Doc/library/shlex.rst ++++ b/Doc/library/shlex.rst +@@ -1,4 +1,3 @@ +- + :mod:`shlex` --- Simple lexical analysis + ======================================== + +@@ -12,14 +11,17 @@ + + .. versionadded:: 1.5.2 + ++**Source code:** :source:`Lib/shlex.py` ++ ++-------------- ++ ++ + The :class:`shlex` class makes it easy to write lexical analyzers for simple + syntaxes resembling that of the Unix shell. This will often be useful for + writing minilanguages, (for example, in run control files for Python + applications) or for parsing quoted strings. + +-.. note:: +- +- The :mod:`shlex` module currently does not support Unicode input. ++Prior to Python 2.7.3, this module did not support Unicode input. + + The :mod:`shlex` module defines the following functions: + +@@ -28,8 +30,8 @@ + + Split the string *s* using shell-like syntax. If *comments* is :const:`False` + (the default), the parsing of comments in the given string will be disabled +- (setting the :attr:`commenters` member of the :class:`shlex` instance to the +- empty string). This function operates in POSIX mode by default, but uses ++ (setting the :attr:`commenters` attribute of the :class:`shlex` instance to ++ the empty string). This function operates in POSIX mode by default, but uses + non-POSIX mode if the *posix* argument is false. + + .. versionadded:: 2.3 +@@ -53,7 +55,7 @@ + :meth:`readline` methods, or a string (strings are accepted since Python 2.3). + If no argument is given, input will be taken from ``sys.stdin``. The second + optional argument is a filename string, which sets the initial value of the +- :attr:`infile` member. If the *instream* argument is omitted or equal to ++ :attr:`infile` attribute. If the *instream* argument is omitted or equal to + ``sys.stdin``, this second argument defaults to "stdin". The *posix* argument + was introduced in Python 2.3, and defines the operational mode. When *posix* is + not true (default), the :class:`shlex` instance will operate in compatibility +@@ -221,8 +223,8 @@ + + .. attribute:: shlex.source + +- This member is ``None`` by default. If you assign a string to it, that string +- will be recognized as a lexical-level inclusion request similar to the ++ This attribute is ``None`` by default. If you assign a string to it, that ++ string will be recognized as a lexical-level inclusion request similar to the + ``source`` keyword in various shells. That is, the immediately following token + will opened as a filename and input taken from that stream until EOF, at which + point the :meth:`close` method of that stream will be called and the input +@@ -232,7 +234,7 @@ + + .. attribute:: shlex.debug + +- If this member is numeric and ``1`` or more, a :class:`shlex` instance will ++ If this attribute is numeric and ``1`` or more, a :class:`shlex` instance will + print verbose progress output on its behavior. If you need to use this, you can + read the module source code to learn the details. + +diff -r 8527427914a2 Doc/library/shutil.rst +--- a/Doc/library/shutil.rst ++++ b/Doc/library/shutil.rst +@@ -1,4 +1,3 @@ +- + :mod:`shutil` --- High-level file operations + ============================================ + +@@ -11,20 +10,19 @@ + single: file; copying + single: copying files + ++**Source code:** :source:`Lib/shutil.py` ++ ++-------------- ++ + The :mod:`shutil` module offers a number of high-level operations on files and + collections of files. In particular, functions are provided which support file + copying and removal. For operations on individual files, see also the + :mod:`os` module. + +-.. seealso:: +- +- Latest version of the `shutil module Python source code +- `_ +- + .. warning:: + +- Even the higher-level file copying functions (:func:`copy`, :func:`copy2`) +- can't copy all file metadata. ++ Even the higher-level file copying functions (:func:`shutil.copy`, ++ :func:`shutil.copy2`) can't copy all file metadata. + + On POSIX platforms, this means that file owner and group are lost as well + as ACLs. On Mac OS, the resource fork and other metadata are not used. +@@ -49,10 +47,10 @@ + + .. function:: copyfile(src, dst) + +- Copy the contents (no metadata) of the file named *src* to a file named *dst*. +- *dst* must be the complete target file name; look at :func:`copy` for a copy that +- accepts a target directory path. If *src* and *dst* are the same files, +- :exc:`Error` is raised. ++ Copy the contents (no metadata) of the file named *src* to a file named ++ *dst*. *dst* must be the complete target file name; look at ++ :func:`shutil.copy` for a copy that accepts a target directory path. If ++ *src* and *dst* are the same files, :exc:`Error` is raised. + The destination location must be writable; otherwise, an :exc:`IOError` exception + will be raised. If *dst* already exists, it will be replaced. Special files + such as character or block devices and pipes cannot be copied with this +@@ -82,9 +80,9 @@ + + .. function:: copy2(src, dst) + +- Similar to :func:`copy`, but metadata is copied as well -- in fact, this is just +- :func:`copy` followed by :func:`copystat`. This is similar to the +- Unix command :program:`cp -p`. ++ Similar to :func:`shutil.copy`, but metadata is copied as well -- in fact, ++ this is just :func:`shutil.copy` followed by :func:`copystat`. This is ++ similar to the Unix command :program:`cp -p`. + + + .. function:: ignore_patterns(\*patterns) +@@ -99,14 +97,15 @@ + .. function:: copytree(src, dst[, symlinks=False[, ignore=None]]) + + Recursively copy an entire directory tree rooted at *src*. The destination +- directory, named by *dst*, must not already exist; it will be created as well +- as missing parent directories. Permissions and times of directories are +- copied with :func:`copystat`, individual files are copied using +- :func:`copy2`. ++ directory, named by *dst*, must not already exist; it will be created as ++ well as missing parent directories. Permissions and times of directories ++ are copied with :func:`copystat`, individual files are copied using ++ :func:`shutil.copy2`. + + If *symlinks* is true, symbolic links in the source tree are represented as +- symbolic links in the new tree; if false or omitted, the contents of the +- linked files are copied to the new tree. ++ symbolic links in the new tree, but the metadata of the original links is NOT ++ copied; if false or omitted, the contents and metadata of the linked files ++ are copied to the new tree. + + If *ignore* is given, it must be a callable that will receive as its + arguments the directory being visited by :func:`copytree`, and a list of its +@@ -161,22 +160,31 @@ + + .. function:: move(src, dst) + +- Recursively move a file or directory to another location. ++ Recursively move a file or directory (*src*) to another location (*dst*). + +- If the destination is on the current filesystem, then simply use rename. +- Otherwise, copy src (with :func:`copy2`) to the dst and then remove src. ++ If the destination is a directory or a symlink to a directory, then *src* is ++ moved inside that directory. ++ ++ The destination directory must not already exist. If the destination already ++ exists but is not a directory, it may be overwritten depending on ++ :func:`os.rename` semantics. ++ ++ If the destination is on the current filesystem, then :func:`os.rename` is ++ used. Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and ++ then removed. + + .. versionadded:: 2.3 + + + .. exception:: Error + +- This exception collects exceptions that raised during a multi-file operation. For +- :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*, +- *dstname*, *exception*). ++ This exception collects exceptions that are raised during a multi-file ++ operation. For :func:`copytree`, the exception argument is a list of 3-tuples ++ (*srcname*, *dstname*, *exception*). + + .. versionadded:: 2.3 + ++ + .. _shutil-example: + + copytree example +@@ -270,12 +278,14 @@ + *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`. ++ + .. versionadded:: 2.7 + + + .. function:: get_archive_formats() + +- Returns a list of supported formats for archiving. ++ Return a list of supported formats for archiving. + Each element of the returned sequence is a tuple ``(name, description)`` + + By default :mod:`shutil` provides these formats: +@@ -293,7 +303,7 @@ + + .. function:: register_archive_format(name, function, [extra_args, [description]]) + +- Registers an archiver for the format *name*. *function* is a callable that ++ Register an archiver for the format *name*. *function* is a callable that + will be used to invoke the archiver. + + If given, *extra_args* is a sequence of ``(name, value)`` that will be +diff -r 8527427914a2 Doc/library/signal.rst +--- a/Doc/library/signal.rst ++++ b/Doc/library/signal.rst +@@ -69,7 +69,7 @@ + All the signal numbers are defined symbolically. For example, the hangup signal + is defined as :const:`signal.SIGHUP`; the variable names are identical to the + names used in C programs, as found in ````. The Unix man page for +- ':cfunc:`signal`' lists the existing signals (on some systems this is ++ ':c:func:`signal`' lists the existing signals (on some systems this is + :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that + not all systems define the same set of signal names; only those names defined by + the system are defined by this module. +@@ -216,7 +216,7 @@ + + Note that installing a signal handler with :func:`signal` will reset the + restart behaviour to interruptible by implicitly calling +- :cfunc:`siginterrupt` with a true *flag* value for the given signal. ++ :c:func:`siginterrupt` with a true *flag* value for the given signal. + + .. versionadded:: 2.6 + +diff -r 8527427914a2 Doc/library/simplexmlrpcserver.rst +--- a/Doc/library/simplexmlrpcserver.rst ++++ b/Doc/library/simplexmlrpcserver.rst +@@ -14,6 +14,10 @@ + + .. versionadded:: 2.2 + ++**Source code:** :source:`Lib/SimpleXMLRPCServer.py` ++ ++-------------- ++ + The :mod:`SimpleXMLRPCServer` module provides a basic server framework for + XML-RPC servers written in Python. Servers can either be free standing, using + :class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using +diff -r 8527427914a2 Doc/library/site.rst +--- a/Doc/library/site.rst ++++ b/Doc/library/site.rst +@@ -1,17 +1,22 @@ +- + :mod:`site` --- Site-specific configuration hook + ================================================ + + .. module:: site +- :synopsis: A standard way to reference site-specific modules. ++ :synopsis: Module responsible for site-specific configuration. + ++**Source code:** :source:`Lib/site.py` ++ ++-------------- ++ ++.. highlightlang:: none + + **This module is automatically imported during initialization.** The automatic + import can be suppressed using the interpreter's :option:`-S` option. + + .. index:: triple: module; search; path + +-Importing this module will append site-specific paths to the module search path. ++Importing this module will append site-specific paths to the module search path ++and add a few builtins. + + .. index:: + pair: site-python; directory +@@ -26,11 +31,11 @@ + if it refers to an existing directory, and if so, adds it to ``sys.path`` and + also inspects the newly added path for configuration files. + +-A path configuration file is a file whose name has the form :file:`package.pth` ++A path configuration file is a file whose name has the form :file:`{name}.pth` + and exists in one of the four directories mentioned above; its contents are + additional items (one per line) to be added to ``sys.path``. Non-existing items +-are never added to ``sys.path``, but no check is made that the item refers to a +-directory (rather than a file). No item is added to ``sys.path`` more than ++are never added to ``sys.path``, and no check is made that the item refers to a ++directory rather than a file. No item is added to ``sys.path`` more than + once. Blank lines and lines beginning with ``#`` are skipped. Lines starting + with ``import`` (followed by space or tab) are executed. + +@@ -43,8 +48,7 @@ + + For example, suppose ``sys.prefix`` and ``sys.exec_prefix`` are set to + :file:`/usr/local`. The Python X.Y library is then installed in +-:file:`/usr/local/lib/python{X.Y}` (where only the first three characters of +-``sys.version`` are used to form the installation path name). Suppose this has ++:file:`/usr/local/lib/python{X.Y}`. Suppose this has + a subdirectory :file:`/usr/local/lib/python{X.Y}/site-packages` with three + subsubdirectories, :file:`foo`, :file:`bar` and :file:`spam`, and two path + configuration files, :file:`foo.pth` and :file:`bar.pth`. Assume +@@ -77,86 +81,132 @@ + + After these path manipulations, an attempt is made to import a module named + :mod:`sitecustomize`, which can perform arbitrary site-specific customizations. +-If this import fails with an :exc:`ImportError` exception, it is silently +-ignored. ++It is typically created by a system administrator in the site-packages ++directory. If this import fails with an :exc:`ImportError` exception, it is ++silently ignored. + +-.. index:: module: sitecustomize ++.. index:: module: usercustomize ++ ++After this, an attempt is made to import a module named :mod:`usercustomize`, ++which can perform arbitrary user-specific customizations, if ++:data:`ENABLE_USER_SITE` is true. This file is intended to be created in the ++user site-packages directory (see below), which is part of ``sys.path`` unless ++disabled by :option:`-s`. An :exc:`ImportError` will be silently ignored. + + Note that for some non-Unix systems, ``sys.prefix`` and ``sys.exec_prefix`` are + empty, and the path manipulations are skipped; however the import of +-:mod:`sitecustomize` is still attempted. ++:mod:`sitecustomize` and :mod:`usercustomize` is still attempted. + + + .. data:: PREFIXES + +- A list of prefixes for site package directories ++ A list of prefixes for site-packages directories. + + .. versionadded:: 2.6 + + + .. data:: ENABLE_USER_SITE + +- Flag showing the status of the user site directory. True means the +- user site directory is enabled and added to sys.path. When the flag +- is None the user site directory is disabled for security reasons. ++ Flag showing the status of the user site-packages directory. ``True`` means ++ that it is enabled and was added to ``sys.path``. ``False`` means that it ++ was disabled by user request (with :option:`-s` or ++ :envvar:`PYTHONNOUSERSITE`). ``None`` means it was disabled for security ++ reasons (mismatch between user or group id and effective id) or by an ++ administrator. + + .. versionadded:: 2.6 + + + .. data:: USER_SITE + +- Path to the user site directory for the current Python version or None ++ Path to the user site-packages for the running Python. Can be ``None`` if ++ :func:`getusersitepackages` hasn't been called yet. Default value is ++ :file:`~/.local/lib/python{X.Y}/site-packages` for UNIX and non-framework Mac ++ OS X builds, :file:`~/Library/Python/{X.Y}/lib/python/site-packages` for Mac ++ framework builds, and :file:`{%APPDATA%}\\Python\\Python{XY}\\site-packages` ++ on Windows. This directory is a site directory, which means that ++ :file:`.pth` files in it will be processed. + + .. versionadded:: 2.6 + + + .. data:: USER_BASE + +- Path to the base directory for user site directories ++ Path to the base directory for the user site-packages. Can be ``None`` if ++ :func:`getuserbase` hasn't been called yet. Default value is ++ :file:`~/.local` for UNIX and Mac OS X non-framework builds, ++ :file:`~/Library/Python/{X.Y}` for Mac framework builds, and ++ :file:`{%APPDATA%}\\Python` for Windows. This value is used by Distutils to ++ compute the installation directories for scripts, data files, Python modules, ++ etc. for the :ref:`user installation scheme `. See ++ also :envvar:`PYTHONUSERBASE`. + + .. versionadded:: 2.6 + + +-.. envvar:: PYTHONNOUSERSITE +- +- .. versionadded:: 2.6 +- +- +-.. envvar:: PYTHONUSERBASE +- +- .. versionadded:: 2.6 +- +- + .. function:: addsitedir(sitedir, known_paths=None) + +- Adds a directory to sys.path and processes its pth files. ++ Add a directory to sys.path and process its :file:`.pth` files. Typically ++ used in :mod:`sitecustomize` or :mod:`usercustomize` (see above). ++ + + .. function:: getsitepackages() + +- Returns a list containing all global site-packages directories +- (and possibly site-python). ++ Return a list containing all global site-packages directories (and possibly ++ site-python). + + .. versionadded:: 2.7 + ++ + .. function:: getuserbase() + +- Returns the "user base" directory path. +- +- The "user base" directory can be used to store data. If the global +- variable ``USER_BASE`` is not initialized yet, this function will also set +- it. ++ Return the path of the user base directory, :data:`USER_BASE`. If it is not ++ initialized yet, this function will also set it, respecting ++ :envvar:`PYTHONUSERBASE`. + + .. versionadded:: 2.7 + ++ + .. function:: getusersitepackages() + +- Returns the user-specific site-packages directory path. +- +- If the global variable ``USER_SITE`` is not initialized yet, this +- function will also set it. ++ Return the path of the user-specific site-packages directory, ++ :data:`USER_SITE`. If it is not initialized yet, this function will also set ++ it, respecting :envvar:`PYTHONNOUSERSITE` and :data:`USER_BASE`. + + .. versionadded:: 2.7 + +-.. XXX Update documentation +-.. XXX document python -m site --user-base --user-site + ++The :mod:`site` module also provides a way to get the user directories from the ++command line: ++ ++.. code-block:: sh ++ ++ $ python3 -m site --user-site ++ /home/user/.local/lib/python3.3/site-packages ++ ++.. program:: site ++ ++If it is called without arguments, it will print the contents of ++:data:`sys.path` on the standard output, followed by the value of ++:data:`USER_BASE` and whether the directory exists, then the same thing for ++:data:`USER_SITE`, and finally the value of :data:`ENABLE_USER_SITE`. ++ ++.. cmdoption:: --user-base ++ ++ Print the path to the user base directory. ++ ++.. cmdoption:: --user-site ++ ++ Print the path to the user site-packages directory. ++ ++If both options are given, user base and user site will be printed (always in ++this order), separated by :data:`os.pathsep`. ++ ++If any option is given, the script will exit with one of these values: ``O`` if ++the user site-packages directory is enabled, ``1`` if it was disabled by the ++user, ``2`` if it is disabled for security reasons or by an administrator, and a ++value greater than 2 if there is an error. ++ ++.. seealso:: ++ ++ :pep:`370` -- Per user site-packages directory +diff -r 8527427914a2 Doc/library/smtpd.rst +--- a/Doc/library/smtpd.rst ++++ b/Doc/library/smtpd.rst +@@ -7,8 +7,9 @@ + .. moduleauthor:: Barry Warsaw + .. sectionauthor:: Moshe Zadka + ++**Source code:** :source:`Lib/smtpd.py` + +- ++-------------- + + This module offers several classes to implement SMTP servers. One is a generic + do-nothing implementation, which can be overridden, while the other two offer +diff -r 8527427914a2 Doc/library/smtplib.rst +--- a/Doc/library/smtplib.rst ++++ b/Doc/library/smtplib.rst +@@ -1,4 +1,3 @@ +- + :mod:`smtplib` --- SMTP protocol client + ======================================= + +@@ -11,6 +10,10 @@ + pair: SMTP; protocol + single: Simple Mail Transfer Protocol + ++**Source code:** :source:`Lib/smtplib.py` ++ ++-------------- ++ + The :mod:`smtplib` module defines an SMTP client session object that can be used + to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For + details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer +diff -r 8527427914a2 Doc/library/sndhdr.rst +--- a/Doc/library/sndhdr.rst ++++ b/Doc/library/sndhdr.rst +@@ -1,4 +1,3 @@ +- + :mod:`sndhdr` --- Determine type of sound file + ============================================== + +@@ -11,6 +10,10 @@ + single: A-LAW + single: u-LAW + ++**Source code:** :source:`Lib/sndhdr.py` ++ ++-------------- ++ + The :mod:`sndhdr` provides utility functions which attempt to determine the type + of sound data which is in a file. When these functions are able to determine + what type of sound data is stored in a file, they return a tuple ``(type, +diff -r 8527427914a2 Doc/library/socket.rst +--- a/Doc/library/socket.rst ++++ b/Doc/library/socket.rst +@@ -119,7 +119,7 @@ + + The accompanying value is a pair ``(h_errno, string)`` representing an error + returned by a library call. *string* represents the description of *h_errno*, as +- returned by the :cfunc:`hstrerror` C function. ++ returned by the :c:func:`hstrerror` C function. + + + .. exception:: gaierror +@@ -127,7 +127,7 @@ + This exception is raised for address-related errors, for :func:`getaddrinfo` and + :func:`getnameinfo`. The accompanying value is a pair ``(error, string)`` + representing an error returned by a library call. *string* represents the +- description of *error*, as returned by the :cfunc:`gai_strerror` C function. The ++ description of *error*, as returned by the :c:func:`gai_strerror` C function. The + *error* value will match one of the :const:`EAI_\*` constants defined in this + module. + +@@ -207,10 +207,17 @@ + + .. function:: create_connection(address[, timeout[, source_address]]) + +- Convenience function. Connect to *address* (a 2-tuple ``(host, port)``), +- and return the socket object. Passing the optional *timeout* parameter will +- set the timeout on the socket instance before attempting to connect. If no +- *timeout* is supplied, the global default timeout setting returned by ++ Connect to a TCP service listening on the Internet *address* (a 2-tuple ++ ``(host, port)``), and return the socket object. This is a higher-level ++ function than :meth:`socket.connect`: if *host* is a non-numeric hostname, ++ it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`, ++ and then try to connect to all possible addresses in turn until a ++ connection succeeds. This makes it easy to write clients that are ++ compatible to both IPv4 and IPv6. ++ ++ Passing the optional *timeout* parameter will set the timeout on the ++ socket instance before attempting to connect. If no *timeout* is ++ supplied, the global default timeout setting returned by + :func:`getdefaulttimeout` is used. + + If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the +@@ -423,7 +430,7 @@ + Convert an IPv4 address from dotted-quad string format (for example, + '123.45.67.89') to 32-bit packed binary format, as a string four characters in + length. This is useful when conversing with a program that uses the standard C +- library and needs objects of type :ctype:`struct in_addr`, which is the C type ++ library and needs objects of type :c:type:`struct in_addr`, which is the C type + for the 32-bit packed binary this function returns. + + :func:`inet_aton` also accepts strings with less than three dots; see the +@@ -431,7 +438,7 @@ + + If the IPv4 address string passed to this function is invalid, + :exc:`socket.error` will be raised. Note that exactly what is valid depends on +- the underlying C implementation of :cfunc:`inet_aton`. ++ the underlying C implementation of :c:func:`inet_aton`. + + :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used + instead for IPv4/v6 dual stack support. +@@ -442,7 +449,7 @@ + Convert a 32-bit packed IPv4 address (a string four characters in length) to its + standard dotted-quad string representation (for example, '123.45.67.89'). This + is useful when conversing with a program that uses the standard C library and +- needs objects of type :ctype:`struct in_addr`, which is the C type for the ++ needs objects of type :c:type:`struct in_addr`, which is the C type for the + 32-bit packed binary data this function takes as an argument. + + If the string passed to this function is not exactly 4 bytes in length, +@@ -454,14 +461,14 @@ + + Convert an IP address from its family-specific string format to a packed, binary + format. :func:`inet_pton` is useful when a library or network protocol calls for +- an object of type :ctype:`struct in_addr` (similar to :func:`inet_aton`) or +- :ctype:`struct in6_addr`. ++ an object of type :c:type:`struct in_addr` (similar to :func:`inet_aton`) or ++ :c:type:`struct in6_addr`. + + Supported values for *address_family* are currently :const:`AF_INET` and + :const:`AF_INET6`. If the IP address string *ip_string* is invalid, + :exc:`socket.error` will be raised. Note that exactly what is valid depends on + both the value of *address_family* and the underlying implementation of +- :cfunc:`inet_pton`. ++ :c:func:`inet_pton`. + + Availability: Unix (maybe not all platforms). + +@@ -473,8 +480,8 @@ + Convert a packed IP address (a string of some number of characters) to its + standard, family-specific string representation (for example, ``'7.10.0.5'`` or + ``'5aef:2b::8'``) :func:`inet_ntop` is useful when a library or network protocol +- returns an object of type :ctype:`struct in_addr` (similar to :func:`inet_ntoa`) +- or :ctype:`struct in6_addr`. ++ returns an object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`) ++ or :c:type:`struct in6_addr`. + + Supported values for *address_family* are currently :const:`AF_INET` and + :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the +@@ -488,7 +495,7 @@ + + .. function:: getdefaulttimeout() + +- Return the default timeout in floating seconds for new socket objects. A value ++ Return the default timeout in seconds (float) for new socket objects. A value + of ``None`` indicates that new socket objects have no timeout. When the socket + module is first imported, the default is ``None``. + +@@ -497,7 +504,7 @@ + + .. function:: setdefaulttimeout(timeout) + +- Set the default timeout in floating seconds for new socket objects. A value of ++ Set the default timeout in seconds (float) for new socket objects. A value of + ``None`` indicates that new socket objects have no timeout. When the socket + module is first imported, the default is ``None``. + +@@ -576,10 +583,10 @@ + .. method:: socket.connect_ex(address) + + Like ``connect(address)``, but return an error indicator instead of raising an +- exception for errors returned by the C-level :cfunc:`connect` call (other ++ exception for errors returned by the C-level :c:func:`connect` call (other + problems, such as "host not found," can still raise exceptions). The error + indicator is ``0`` if the operation succeeded, otherwise the value of the +- :cdata:`errno` variable. This is useful to support, for example, asynchronous ++ :c:data:`errno` variable. This is useful to support, for example, asynchronous + connects. + + .. note:: +@@ -654,7 +661,7 @@ + + Return a :dfn:`file object` associated with the socket. (File objects are + described in :ref:`bltin-file-objects`.) The file object +- references a :cfunc:`dup`\ ped version of the socket file descriptor, so the ++ references a :c:func:`dup`\ ped version of the socket file descriptor, so the + file object and socket object may be closed or garbage-collected independently. + The socket must be in blocking mode (it can not have a timeout). The optional + *mode* and *bufsize* arguments are interpreted the same way as by the built-in +@@ -718,7 +725,8 @@ + optional *flags* argument has the same meaning as for :meth:`recv` above. + Returns the number of bytes sent. Applications are responsible for checking that + all data has been sent; if only some of the data was transmitted, the +- application needs to attempt delivery of the remaining data. ++ application needs to attempt delivery of the remaining data. For further ++ information on this concept, consult the :ref:`socket-howto`. + + + .. method:: socket.sendall(string[, flags]) +@@ -766,7 +774,7 @@ + + .. method:: socket.gettimeout() + +- Return the timeout in floating seconds associated with socket operations, or ++ Return the timeout in seconds (float) associated with socket operations, or + ``None`` if no timeout is set. This reflects the last call to + :meth:`setblocking` or :meth:`settimeout`. + +@@ -856,8 +864,8 @@ + :meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly + repeating the :meth:`~socket.accept` to service more than one client), while a + client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also +-note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the +-socket it is listening on but on the new socket returned by ++note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on ++the socket it is listening on but on the new socket returned by + :meth:`~socket.accept`. + + The first two examples support IPv4 only. :: +@@ -875,7 +883,7 @@ + while 1: + data = conn.recv(1024) + if not data: break +- conn.send(data) ++ conn.sendall(data) + conn.close() + + :: +@@ -887,7 +895,7 @@ + PORT = 50007 # The same port as used by the server + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((HOST, PORT)) +- s.send('Hello, world') ++ s.sendall('Hello, world') + data = s.recv(1024) + s.close() + print 'Received', repr(data) +@@ -959,7 +967,7 @@ + if s is None: + print 'could not open socket' + sys.exit(1) +- s.send('Hello, world') ++ s.sendall('Hello, world') + data = s.recv(1024) + s.close() + print 'Received', repr(data) +@@ -989,3 +997,22 @@ + + # disabled promiscuous mode + s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) ++ ++ ++Running an example several times with too small delay between executions, could ++lead to this error:: ++ ++ socket.error: [Errno 98] Address already in use ++ ++This is because the previous execution has left the socket in a ``TIME_WAIT`` ++state, and can't be immediately reused. ++ ++There is a :mod:`socket` flag to set, in order to prevent this, ++:data:`socket.SO_REUSEADDR`:: ++ ++ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ++ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ++ s.bind((HOST, PORT)) ++ ++the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in ++``TIME_WAIT`` state, without waiting for its natural timeout to expire. +diff -r 8527427914a2 Doc/library/socketserver.rst +--- a/Doc/library/socketserver.rst ++++ b/Doc/library/socketserver.rst +@@ -1,4 +1,3 @@ +- + :mod:`SocketServer` --- A framework for network servers + ======================================================= + +@@ -11,6 +10,9 @@ + Python 3.0. The :term:`2to3` tool will automatically adapt imports when + converting your sources to 3.0. + ++**Source code:** :source:`Lib/SocketServer.py` ++ ++-------------- + + The :mod:`SocketServer` module simplifies the task of writing network servers. + +@@ -85,7 +87,7 @@ + class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass + + The mix-in class must come first, since it overrides a method defined in +-:class:`UDPServer`. Setting the various member variables also changes the ++:class:`UDPServer`. Setting the various attributes also change the + behavior of the underlying server mechanism. + + To implement a service, you must derive a class from :class:`BaseRequestHandler` +@@ -156,13 +158,14 @@ + + .. method:: BaseServer.serve_forever(poll_interval=0.5) + +- Handle requests until an explicit :meth:`shutdown` request. Polls for +- shutdown every *poll_interval* seconds. ++ Handle requests until an explicit :meth:`shutdown` request. ++ Poll for shutdown every *poll_interval* seconds. Ignores :attr:`self.timeout`. ++ If you need to do periodic tasks, do them in another thread. + + + .. method:: BaseServer.shutdown() + +- Tells the :meth:`serve_forever` loop to stop and waits until it does. ++ Tell the :meth:`serve_forever` loop to stop and wait until it does. + + .. versionadded:: 2.6 + +@@ -223,6 +226,7 @@ + desired. If :meth:`handle_request` receives no incoming requests within the + timeout period, the :meth:`handle_timeout` method is called. + ++ + There are various server methods that can be overridden by subclasses of base + server classes like :class:`TCPServer`; these methods aren't useful to external + users of the server object. +@@ -353,10 +357,10 @@ + 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()) ++ self.request.sendall(self.data.upper()) + + if __name__ == "__main__": + HOST, PORT = "localhost", 9999 +@@ -377,7 +381,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 +@@ -386,7 +390,7 @@ + The difference is that the ``readline()`` call in the second handler will call + ``recv()`` multiple times until it encounters a newline character, while the + single ``recv()`` call in the first handler will just return what has been sent +-from the client in one ``send()`` call. ++from the client in one ``sendall()`` call. + + + This is the client side:: +@@ -400,16 +404,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(data + "\n") ++ try: ++ # Connect to server and send data ++ sock.connect((HOST, PORT)) ++ sock.sendall(data + "\n") + +- # Receive data from the server and shut down +- received = sock.recv(1024) +- sock.close() ++ # Receive data from the server and shut down ++ received = sock.recv(1024) ++ 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: +@@ -450,7 +456,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) + +@@ -475,8 +481,8 @@ + sock.sendto(data + "\n", (HOST, PORT)) + received = sock.recv(1024) + +- 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. + +@@ -497,9 +503,9 @@ + + def handle(self): + data = self.request.recv(1024) +- cur_thread = threading.currentThread() +- response = "%s: %s" % (cur_thread.getName(), data) +- self.request.send(response) ++ cur_thread = threading.current_thread() ++ response = "{}: {}".format(cur_thread.name, data) ++ self.request.sendall(response) + + class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): + pass +@@ -507,10 +513,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.sendall(message) ++ response = sock.recv(1024) ++ print "Received: {}".format(response) ++ finally: ++ sock.close() + + if __name__ == "__main__": + # Port 0 means to select an arbitrary unused port +@@ -523,9 +531,9 @@ + # 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.getName() ++ print "Server loop running in thread:", server_thread.name + + client(ip, port, "Hello World 1") + client(ip, port, "Hello World 2") +@@ -533,6 +541,7 @@ + + server.shutdown() + ++ + The output of the example should look something like this:: + + $ python ThreadedTCPServer.py +diff -r 8527427914a2 Doc/library/sqlite3.rst +--- a/Doc/library/sqlite3.rst ++++ b/Doc/library/sqlite3.rst +@@ -22,6 +22,7 @@ + represents the database. Here the data will be stored in the + :file:`/tmp/example` file:: + ++ import sqlite3 + conn = sqlite3.connect('/tmp/example') + + You can also supply the special name ``:memory:`` to create a database in RAM. +@@ -58,7 +59,7 @@ + + # Never do this -- insecure! + symbol = 'IBM' +- c.execute("... where symbol = '%s'" % symbol) ++ c.execute("select * from stocks where symbol = '%s'" % symbol) + + # Do this instead + t = (symbol,) +@@ -66,7 +67,7 @@ + + # Larger example + for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), +- ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ++ ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), + ('2006-04-06', 'SELL', 'IBM', 500, 53.00), + ]: + c.execute('insert into stocks values (?,?,?,?,?)', t) +@@ -86,7 +87,7 @@ + (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14) + (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0) + (u'2006-04-06', u'SELL', u'IBM', 500, 53.0) +- (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0) ++ (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0) + >>> + + +@@ -240,7 +241,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. + +@@ -378,6 +379,8 @@ + + .. literalinclude:: ../includes/sqlite3/load_extension.py + ++ Loadable extensions are disabled by default. See [#f1]_ ++ + .. method:: Connection.load_extension(path) + + .. versionadded:: 2.7 +@@ -386,6 +389,8 @@ + enable extension loading with :meth:`enable_load_extension` before you can + use this routine. + ++ Loadable extensions are disabled by default. See [#f1]_ ++ + .. attribute:: Connection.row_factory + + You can change this attribute to a callable that accepts the cursor and the +@@ -600,42 +605,42 @@ + + Let's assume we initialize a table as in the example given above:: + +- conn = sqlite3.connect(":memory:") +- c = conn.cursor() +- c.execute('''create table stocks +- (date text, trans text, symbol text, +- qty real, price real)''') +- c.execute("""insert into stocks +- values ('2006-01-05','BUY','RHAT',100,35.14)""") +- conn.commit() +- c.close() ++ conn = sqlite3.connect(":memory:") ++ c = conn.cursor() ++ c.execute('''create table stocks ++ (date text, trans text, symbol text, ++ qty real, price real)''') ++ c.execute("""insert into stocks ++ values ('2006-01-05','BUY','RHAT',100,35.14)""") ++ conn.commit() ++ c.close() + + Now we plug :class:`Row` in:: + +- >>> conn.row_factory = sqlite3.Row +- >>> c = conn.cursor() +- >>> c.execute('select * from stocks') +- +- >>> r = c.fetchone() +- >>> type(r) +- +- >>> r +- (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14) +- >>> len(r) +- 5 +- >>> r[2] +- u'RHAT' +- >>> r.keys() +- ['date', 'trans', 'symbol', 'qty', 'price'] +- >>> r['qty'] +- 100.0 +- >>> for member in r: print member +- ... +- 2006-01-05 +- BUY +- RHAT +- 100.0 +- 35.14 ++ >>> conn.row_factory = sqlite3.Row ++ >>> c = conn.cursor() ++ >>> c.execute('select * from stocks') ++ ++ >>> r = c.fetchone() ++ >>> type(r) ++ ++ >>> r ++ (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14) ++ >>> len(r) ++ 5 ++ >>> r[2] ++ u'RHAT' ++ >>> r.keys() ++ ['date', 'trans', 'symbol', 'qty', 'price'] ++ >>> r['qty'] ++ 100.0 ++ >>> for member in r: print member ++ ... ++ 2006-01-05 ++ BUY ++ RHAT ++ 100.0 ++ 35.14 + + + .. _sqlite3-types: +@@ -893,3 +898,12 @@ + + The only exception is calling the :meth:`~Connection.interrupt` method, which + only makes sense to call from a different thread. ++ ++.. rubric:: Footnotes ++ ++.. [#f1] The sqlite3 module is not built with loadable extension support by ++ default, because some platforms (notably Mac OS X) have SQLite libraries ++ which are compiled without this feature. To get loadable extension support, ++ you must modify setup.py and remove the line that sets ++ SQLITE_OMIT_LOAD_EXTENSION. ++ +diff -r 8527427914a2 Doc/library/ssl.rst +--- a/Doc/library/ssl.rst ++++ b/Doc/library/ssl.rst +@@ -5,9 +5,6 @@ + :synopsis: TLS/SSL wrapper for socket objects + + .. moduleauthor:: Bill Janssen +- +-.. versionadded:: 2.6 +- + .. sectionauthor:: Bill Janssen + + +@@ -15,6 +12,12 @@ + + .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer + ++.. versionadded:: 2.6 ++ ++**Source code:** :source:`Lib/ssl.py` ++ ++-------------- ++ + This module provides access to Transport Layer Security (often known as "Secure + Sockets Layer") encryption and peer authentication facilities for network + sockets, both client-side and server-side. This module uses the OpenSSL +@@ -100,9 +103,8 @@ + The parameter ``ssl_version`` specifies which version of the SSL protocol to + use. Typically, the server chooses a particular protocol version, and the + client must adapt to the server's choice. Most of the versions are not +- interoperable with the other versions. If not specified, for client-side +- operation, the default SSL version is SSLv3; for server-side operation, +- SSLv23. These version selections provide the most compatibility with other ++ interoperable with the other versions. If not specified, the default is ++ :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other + versions. + + Here's a table showing which versions in a client (down the side) can connect +@@ -114,7 +116,7 @@ + *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** + ------------------------ --------- --------- ---------- --------- + *SSLv2* yes no yes no +- *SSLv3* yes yes yes no ++ *SSLv3* no yes yes no + *SSLv23* yes no yes no + *TLSv1* no no yes yes + ======================== ========= ========= ========== ========= +@@ -619,8 +621,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 8527427914a2 Doc/library/stat.rst +--- a/Doc/library/stat.rst ++++ b/Doc/library/stat.rst +@@ -1,4 +1,3 @@ +- + :mod:`stat` --- Interpreting :func:`stat` results + ================================================= + +@@ -6,11 +5,14 @@ + :synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat(). + .. sectionauthor:: Skip Montanaro + ++**Source code:** :source:`Lib/stat.py` ++ ++-------------- + + The :mod:`stat` module defines constants and functions for interpreting the + results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they +-exist). For complete details about the :cfunc:`stat`, :cfunc:`fstat` and +-:cfunc:`lstat` calls, consult the documentation for your system. ++exist). For complete details about the :c:func:`stat`, :c:func:`fstat` and ++:c:func:`lstat` calls, consult the documentation for your system. + + The :mod:`stat` module defines the following functions to test for specific file + types: +@@ -68,7 +70,7 @@ + + Normally, you would use the :func:`os.path.is\*` functions for testing the type + of a file; the functions here are useful when you are doing multiple tests of +-the same file and wish to avoid the overhead of the :cfunc:`stat` system call ++the same file and wish to avoid the overhead of the :c:func:`stat` system call + for each test. These are also useful when checking for information about a file + that isn't handled by :mod:`os.path`, like the tests for block and character + devices. +@@ -84,7 +86,7 @@ + + for f in os.listdir(top): + pathname = os.path.join(top, f) +- mode = os.stat(pathname)[ST_MODE] ++ mode = os.stat(pathname).st_mode + if S_ISDIR(mode): + # It's a directory, recurse into it + walktree(pathname, callback) +@@ -306,11 +308,19 @@ + + .. data:: UF_OPAQUE + +- The file may not be renamed or deleted. ++ The directory is opaque when viewed through a union stack. + + .. data:: UF_NOUNLINK + +- The directory is opaque when viewed through a union stack. ++ The file may not be renamed or deleted. ++ ++.. data:: UF_COMPRESSED ++ ++ The file is stored compressed (Mac OS X 10.6+). ++ ++.. data:: UF_HIDDEN ++ ++ The file should not be displayed in a GUI (Mac OS X 10.5+). + + .. data:: SF_ARCHIVED + +diff -r 8527427914a2 Doc/library/statvfs.rst +--- a/Doc/library/statvfs.rst ++++ b/Doc/library/statvfs.rst +@@ -61,7 +61,7 @@ + + .. data:: F_FLAG + +- Flags. System dependent: see :cfunc:`statvfs` man page. ++ Flags. System dependent: see :c:func:`statvfs` man page. + + + .. data:: F_NAMEMAX +diff -r 8527427914a2 Doc/library/stdtypes.rst +--- a/Doc/library/stdtypes.rst ++++ b/Doc/library/stdtypes.rst +@@ -63,7 +63,7 @@ + + * instances of user-defined classes, if the class defines a :meth:`__nonzero__` + or :meth:`__len__` method, when that method returns the integer zero or +- :class:`bool` value ``False``. [#]_ ++ :class:`bool` value ``False``. [1]_ + + .. index:: single: true + +@@ -226,11 +226,11 @@ + There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long + integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In + addition, Booleans are a subtype of plain integers. Plain integers (also just +-called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives ++called :dfn:`integers`) are implemented using :c:type:`long` in C, which gives + them at least 32 bits of precision (``sys.maxint`` is always set to the maximum + plain integer value for the current platform, the minimum value is + ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point +-numbers are usually implemented using :ctype:`double` in C; information about ++numbers are usually implemented using :c:type:`double` in C; information about + the precision and internal representation of floating point numbers for the + machine on which your program is running is available in + :data:`sys.float_info`. Complex numbers have a real and imaginary part, which +@@ -277,7 +277,7 @@ + operands of different numeric types, the operand with the "narrower" type is + widened to that of the other, where plain integer is narrower than long integer + is narrower than floating point is narrower than complex. Comparisons between +-numbers of mixed type use the same rule. [#]_ The constructors :func:`int`, ++numbers of mixed type use the same rule. [2]_ The constructors :func:`int`, + :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers + of a specific type. + +@@ -401,12 +401,12 @@ + + .. _bitstring-ops: + +-Bit-string Operations on Integer Types ++Bitwise Operations on Integer Types + -------------------------------------- + + .. index:: + triple: operations on; integer; types +- pair: bit-string; operations ++ pair: bitwise; operations + pair: shifting; operations + pair: masking; operations + operator: ^ +@@ -414,16 +414,16 @@ + operator: << + operator: >> + +-Plain and long integer types support additional operations that make sense only +-for bit-strings. Negative numbers are treated as their 2's complement value +-(for long integers, this assumes a sufficiently large number of bits that no +-overflow occurs during the operation). ++Bitwise operations only make sense for integers. Negative numbers are treated ++as their 2's complement value (this assumes a sufficiently large number of bits ++that no overflow occurs during the operation). + + The priorities of the binary bitwise operations are all lower than the numeric + operations and higher than the comparisons; the unary operation ``~`` has the + same priority as the other unary numeric operations (``+`` and ``-``). + +-This table lists the bit-string operations sorted in ascending priority: ++This table lists the bitwise operations sorted in ascending priority ++(operations in the same box have the same priority): + + +------------+--------------------------------+----------+ + | Operation | Result | Notes | +@@ -709,7 +709,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* +@@ -730,7 +730,7 @@ + | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) | + | | concatenated | | + +------------------+--------------------------------+----------+ +-| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) | ++| ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) | + +------------------+--------------------------------+----------+ + | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | + +------------------+--------------------------------+----------+ +@@ -1007,7 +1007,7 @@ + + .. method:: str.islower() + +- Return true if all cased characters in the string are lowercase and there is at ++ Return true if all cased characters [4]_ in the string are lowercase and there is at + least one cased character, false otherwise. + + For 8-bit strings, this method is locale-dependent. +@@ -1032,7 +1032,7 @@ + + .. method:: str.isupper() + +- Return true if all cased characters in the string are uppercase and there is at ++ Return true if all cased characters [4]_ in the string are uppercase and there is at + least one cased character, false otherwise. + + For 8-bit strings, this method is locale-dependent. +@@ -1049,7 +1049,7 @@ + + Return the string left justified in a string of length *width*. Padding is done + using the specified *fillchar* (default is a space). The original string is +- returned if *width* is less than ``len(s)``. ++ returned if *width* is less than or equal to ``len(s)``. + + .. versionchanged:: 2.4 + Support for the *fillchar* argument. +@@ -1057,7 +1057,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. + + For 8-bit strings, this method is locale-dependent. + +@@ -1112,7 +1113,7 @@ + + Return the string right justified in a string of length *width*. Padding is done + using the specified *fillchar* (default is a space). The original string is +- returned if *width* is less than ``len(s)``. ++ returned if *width* is less than or equal to ``len(s)``. + + .. versionchanged:: 2.4 + Support for the *fillchar* argument. +@@ -1280,7 +1281,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). + + For 8-bit strings, this method is locale-dependent. + +@@ -1289,7 +1293,7 @@ + + Return the numeric string left filled with zeros in a string of length + *width*. A sign prefix is handled correctly. The original string is +- returned if *width* is less than ``len(s)``. ++ returned if *width* is less than or equal to ``len(s)``. + + + .. versionadded:: 2.2.2 +@@ -1307,7 +1311,7 @@ + + Return ``True`` if there are only decimal characters in S, ``False`` + otherwise. Decimal characters include 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. + + +@@ -1331,12 +1335,12 @@ + *interpolation* operator. Given ``format % values`` (where *format* is a string + or Unicode object), ``%`` conversion specifications in *format* are replaced + with zero or more elements of *values*. The effect is similar to the using +-:cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any ++:c:func:`sprintf` in the C language. If *format* is a Unicode object, or if any + of the objects being converted using the ``%s`` conversion are Unicode objects, + the result will also be a Unicode object. + + 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). + +@@ -2327,7 +2331,7 @@ + + .. method:: file.flush() + +- Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a ++ Flush the internal buffer, like ``stdio``'s :c:func:`fflush`. This may be a + no-op on some file-like objects. + + .. note:: +@@ -2368,12 +2372,12 @@ + A file object is its own iterator, for example ``iter(f)`` returns *f* (unless + *f* is closed). When a file is used as an iterator, typically in a + :keyword:`for` loop (for example, ``for line in f: print line``), the +- :meth:`.next` method is called repeatedly. This method returns the next input ++ :meth:`~file.next` method is called repeatedly. This method returns the next input + line, or raises :exc:`StopIteration` when EOF is hit when the file is open for + reading (behavior is undefined when the file is open for writing). In order to + make a :keyword:`for` loop the most efficient way of looping over the lines of a +- file (a very common operation), the :meth:`next` method uses a hidden read-ahead +- buffer. As a consequence of using a read-ahead buffer, combining :meth:`.next` ++ file (a very common operation), the :meth:`~file.next` method uses a hidden read-ahead ++ buffer. As a consequence of using a read-ahead buffer, combining :meth:`~file.next` + with other file methods (like :meth:`readline`) does not work right. However, + using :meth:`seek` to reposition the file to an absolute position will flush the + read-ahead buffer. +@@ -2388,21 +2392,21 @@ + all data until EOF is reached. The bytes are returned as a string object. An + empty string is returned when EOF is encountered immediately. (For certain + files, like ttys, it makes sense to continue reading after an EOF is hit.) Note +- that this method may call the underlying C function :cfunc:`fread` more than ++ that this method may call the underlying C function :c:func:`fread` more than + once in an effort to acquire as close to *size* bytes as possible. Also note + that when in non-blocking mode, less data than was requested may be + returned, even if no *size* parameter was given. + + .. note:: + This function is simply a wrapper for the underlying +- :cfunc:`fread` C function, and will behave the same in corner cases, ++ :c:func:`fread` C function, and will behave the same in corner cases, + such as whether the EOF value is cached. + + + .. method:: file.readline([size]) + + Read one entire line from the file. A trailing newline character is kept in +- the string (but may be absent when a file ends with an incomplete line). [#]_ ++ the string (but may be absent when a file ends with an incomplete line). [6]_ + If the *size* argument is present and non-negative, it is a maximum byte + count (including the trailing newline) and an incomplete line may be + returned. When *size* is not 0, an empty string is returned *only* when EOF +@@ -2410,7 +2414,7 @@ + + .. note:: + +- Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters ++ Unlike ``stdio``'s :c:func:`fgets`, the returned string contains null characters + (``'\0'``) if they occurred in the input. + + +@@ -2436,7 +2440,7 @@ + + .. method:: file.seek(offset[, whence]) + +- Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence* ++ Set the file's current position, like ``stdio``'s :c:func:`fseek`. The *whence* + argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file + positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the + current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's +@@ -2461,11 +2465,11 @@ + + .. method:: file.tell() + +- Return the file's current position, like ``stdio``'s :cfunc:`ftell`. ++ Return the file's current position, like ``stdio``'s :c:func:`ftell`. + + .. note:: + +- On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`) ++ On Windows, :meth:`tell` can return illegal values (after an :c:func:`fgets`) + when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to + circumvent this problem. + +@@ -2787,7 +2791,7 @@ + foo`` does not require a module object named *foo* to exist, rather it requires + an (external) *definition* for a module named *foo* somewhere.) + +-A special member of every module is :attr:`__dict__`. This is the dictionary ++A special attribute of every module is :attr:`__dict__`. This is the dictionary + containing the module's symbol table. Modifying this dictionary will actually + change the module's symbol table, but direct assignment to the :attr:`__dict__` + attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines +@@ -2930,7 +2934,18 @@ + supports no special operations. There is exactly one ellipsis object, named + :const:`Ellipsis` (a built-in name). + +-It is written as ``Ellipsis``. ++It is written as ``Ellipsis``. When in a subscript, it can also be written as ++``...``, for example ``seq[...]``. ++ ++ ++The NotImplemented Object ++------------------------- ++ ++This object is returned from comparisons and binary operations when they are ++asked to operate on types they don't support. See :ref:`comparisons` for more ++information. ++ ++It is written as ``NotImplemented``. + + + Boolean Values +@@ -2940,9 +2955,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 +@@ -3033,18 +3048,21 @@ + + .. 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. + +-.. [#] The advantage of leaving the newline on is that returning an empty string is ++.. [6] The advantage of leaving the newline on is that returning an empty string is + then an unambiguous EOF indication. It is also possible (in cases where it + might matter, for example, if you want to make an exact copy of a file while + scanning its lines) to tell whether the last line of a file ended in a newline +diff -r 8527427914a2 Doc/library/string.rst +--- a/Doc/library/string.rst ++++ b/Doc/library/string.rst +@@ -7,6 +7,10 @@ + + .. index:: module: re + ++**Source code:** :source:`Lib/string.py` ++ ++-------------- ++ + The :mod:`string` module contains a number of useful constants and + classes, as well as some deprecated legacy functions that are also + available as methods on strings. In addition, Python's built-in string +@@ -17,12 +21,6 @@ + :ref:`string-formatting` section. Also, see the :mod:`re` module for + string functions based on regular expressions. + +-.. seealso:: +- +- Latest version of the `string module Python source code +- `_ +- +- + String constants + ---------------- + +@@ -245,11 +243,13 @@ + + 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) + and the numbers 0, 1, 2, ... will be automatically inserted in that order. ++Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary ++dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string. + The *arg_name* can be followed by any number of index or + attribute expressions. An expression of the form ``'.name'`` selects the named + attribute using :func:`getattr`, while an expression of the form ``'[index]'`` +@@ -602,7 +602,7 @@ + + >>> points = 19.5 + >>> total = 22 +- >>> 'Correct answers: {:.2%}.'.format(points/total) ++ >>> 'Correct answers: {:.2%}'.format(points/total) + 'Correct answers: 88.64%' + + Using type-specific formatting:: +@@ -729,9 +729,9 @@ + to parse template strings. To do this, you can override these class attributes: + + * *delimiter* -- This is the literal string describing a placeholder introducing +- delimiter. The default value ``$``. Note that this should *not* be a regular +- expression, as the implementation will call :meth:`re.escape` on this string as +- needed. ++ delimiter. The default value is ``$``. Note that this should *not* be a ++ regular expression, as the implementation will call :meth:`re.escape` on this ++ string as needed. + + * *idpattern* -- This is the regular expression describing the pattern for + non-braced placeholders (the braces will be added automatically as +diff -r 8527427914a2 Doc/library/stringio.rst +--- a/Doc/library/stringio.rst ++++ b/Doc/library/stringio.rst +@@ -82,10 +82,7 @@ + those cases. + + Unlike the :mod:`StringIO` module, this module is not able to accept Unicode +- strings that cannot be encoded as plain ASCII strings. Calling +- :func:`StringIO` with a Unicode string parameter populates the object with +- the buffer representation of the Unicode string instead of encoding the +- string. ++ strings that cannot be encoded as plain ASCII strings. + + Another difference from the :mod:`StringIO` module is that calling + :func:`StringIO` with a string parameter creates a read-only object. Unlike an +diff -r 8527427914a2 Doc/library/struct.rst +--- a/Doc/library/struct.rst ++++ b/Doc/library/struct.rst +@@ -22,8 +22,8 @@ + alignment is taken into account when unpacking. This behavior is chosen so + that the bytes of a packed struct correspond exactly to the layout in memory + of the corresponding C struct. To handle platform-independent data formats +- or omit implicit pad bytes, use `standard` size and alignment instead of +- `native` size and alignment: see :ref:`struct-alignment` for details. ++ or omit implicit pad bytes, use ``standard`` size and alignment instead of ++ ``native`` size and alignment: see :ref:`struct-alignment` for details. + + Functions and Exceptions + ------------------------ +@@ -162,60 +162,60 @@ + ``'='``. When using native size, the size of the packed value is + platform-dependent. + +-+--------+-------------------------+--------------------+----------------+------------+ +-| Format | C Type | Python type | Standard size | Notes | +-+========+=========================+====================+================+============+ +-| ``x`` | pad byte | no value | | | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``c`` | :ctype:`char` | string of length 1 | 1 | | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``b`` | :ctype:`signed char` | integer | 1 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``B`` | :ctype:`unsigned char` | integer | 1 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``?`` | :ctype:`_Bool` | bool | 1 | \(1) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``h`` | :ctype:`short` | integer | 2 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``H`` | :ctype:`unsigned short` | integer | 2 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``i`` | :ctype:`int` | integer | 4 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``I`` | :ctype:`unsigned int` | integer | 4 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``l`` | :ctype:`long` | integer | 4 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``L`` | :ctype:`unsigned long` | integer | 4 | \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``q`` | :ctype:`long long` | integer | 8 | \(2), \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``Q`` | :ctype:`unsigned long | integer | 8 | \(2), \(3) | +-| | long` | | | | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``f`` | :ctype:`float` | float | 4 | \(4) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``d`` | :ctype:`double` | float | 8 | \(4) | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``s`` | :ctype:`char[]` | string | | | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``p`` | :ctype:`char[]` | string | | | +-+--------+-------------------------+--------------------+----------------+------------+ +-| ``P`` | :ctype:`void \*` | integer | | \(5), \(3) | +-+--------+-------------------------+--------------------+----------------+------------+ +++--------+--------------------------+--------------------+----------------+------------+ ++| Format | C Type | Python type | Standard size | Notes | +++========+==========================+====================+================+============+ ++| ``x`` | pad byte | no value | | | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``c`` | :c:type:`char` | string of length 1 | 1 | | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``b`` | :c:type:`signed char` | integer | 1 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``B`` | :c:type:`unsigned char` | integer | 1 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``?`` | :c:type:`_Bool` | bool | 1 | \(1) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``h`` | :c:type:`short` | integer | 2 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``H`` | :c:type:`unsigned short` | integer | 2 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``i`` | :c:type:`int` | integer | 4 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``I`` | :c:type:`unsigned int` | integer | 4 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``l`` | :c:type:`long` | integer | 4 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``L`` | :c:type:`unsigned long` | integer | 4 | \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``q`` | :c:type:`long long` | integer | 8 | \(2), \(3) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``Q`` | :c:type:`unsigned long | integer | 8 | \(2), \(3) | ++| | long` | | | | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``f`` | :c:type:`float` | float | 4 | \(4) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``d`` | :c:type:`double` | float | 8 | \(4) | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``s`` | :c:type:`char[]` | string | | | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``p`` | :c:type:`char[]` | string | | | +++--------+--------------------------+--------------------+----------------+------------+ ++| ``P`` | :c:type:`void \*` | integer | | \(5), \(3) | +++--------+--------------------------+--------------------+----------------+------------+ + + Notes: + + (1) +- The ``'?'`` conversion code corresponds to the :ctype:`_Bool` type defined by +- C99. If this type is not available, it is simulated using a :ctype:`char`. In ++ The ``'?'`` conversion code corresponds to the :c:type:`_Bool` type defined by ++ C99. If this type is not available, it is simulated using a :c:type:`char`. In + standard mode, it is always represented by one byte. + + .. versionadded:: 2.6 + + (2) + The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if +- the platform C compiler supports C :ctype:`long long`, or, on Windows, +- :ctype:`__int64`. They are always available in standard modes. ++ the platform C compiler supports C :c:type:`long long`, or, on Windows, ++ :c:type:`__int64`. They are always available in standard modes. + + .. versionadded:: 2.2 + +@@ -257,10 +257,11 @@ + For the ``'s'`` format character, the count is interpreted as the size of the + string, not a repeat count like for the other format characters; for example, + ``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters. +-For packing, the string is truncated or padded with null bytes as appropriate to +-make it fit. For unpacking, the resulting string always has exactly the +-specified number of bytes. As a special case, ``'0s'`` means a single, empty +-string (while ``'0c'`` means 0 characters). ++If a count is not given, it defaults to 1. For packing, the string is ++truncated or padded with null bytes as appropriate to make it fit. For ++unpacking, the resulting string always has exactly the specified number of ++bytes. As a special case, ``'0s'`` means a single, empty string (while ++``'0c'`` means 0 characters). + + The ``'p'`` format character encodes a "Pascal string", meaning a short + variable-length string stored in a *fixed number of bytes*, given by the count. +diff -r 8527427914a2 Doc/library/subprocess.rst +--- a/Doc/library/subprocess.rst ++++ b/Doc/library/subprocess.rst +@@ -31,7 +31,215 @@ + 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!"]) ++ '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 ++ ++ 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 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 Constructor ++^^^^^^^^^^^^^^^^^ ++ ++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=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0) +@@ -81,24 +289,6 @@ + + Popen(['/bin/sh', '-c', args[0], args[1], ...]) + +- .. 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. +- + On Windows: the :class:`Popen` class uses CreateProcess() to execute the child + child program, which operates on strings. If *args* is a sequence, it will + be converted to a string in a manner described in +@@ -126,14 +316,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 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. ++ 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. + + If *preexec_fn* is set to a callable object, this object will be called in the + child process just before the child is executed. (Unix only) +@@ -147,6 +338,12 @@ + If *shell* is :const:`True`, the specified command will be executed through the + shell. + ++ .. warning:: ++ ++ Enabling this option can be a security hazard if combined with untrusted ++ input. See the warning under :ref:`frequently-used-arguments` ++ for details. ++ + If *cwd* is not ``None``, the child's current directory will be changed to *cwd* + before it is executed. Note that this directory is not considered when + searching the executable, so you can't specify the program's path relative to +@@ -184,87 +381,6 @@ + :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only) + + +-.. 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 +- +- .. versionadded:: 2.5 +- +- .. 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"]) +- '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) +- 'ls: non_existent_file: No such file or directory\n' +- +- .. versionadded:: 2.7 +- +- + Exceptions + ^^^^^^^^^^ + +@@ -280,16 +396,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 +@@ -353,7 +472,7 @@ + .. method:: Popen.terminate() + + Stop the child. On Posix OSs the method sends SIGTERM to the +- child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called ++ child. On Windows the Win32 API function :c:func:`TerminateProcess` is called + to stop the child. + + .. versionadded:: 2.6 +@@ -428,38 +547,39 @@ + + .. attribute:: dwFlags + +- A bit field that determines whether certain :class:`STARTUPINFO` members +- are used when the process creates a window. :: ++ A bit field that determines whether certain :class:`STARTUPINFO` ++ attributes are used when the process creates a window. :: + + si = subprocess.STARTUPINFO() + si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW + + .. attribute:: hStdInput + +- If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is +- the standard input handle for the process. If :data:`STARTF_USESTDHANDLES` +- is not specified, the default for standard input is the keyboard buffer. ++ If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute ++ is the standard input handle for the process. If ++ :data:`STARTF_USESTDHANDLES` is not specified, the default for standard ++ input is the keyboard buffer. + + .. attribute:: hStdOutput + +- If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is +- the standard output handle for the process. Otherwise, this member is +- ignored and the default for standard output is the console window's ++ If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute ++ is the standard output handle for the process. Otherwise, this attribute ++ is ignored and the default for standard output is the console window's + buffer. + + .. attribute:: hStdError + +- If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is +- the standard error handle for the process. Otherwise, this member is ++ If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute ++ is the standard error handle for the process. Otherwise, this attribute is + ignored and the default for standard error is the console window's buffer. + + .. attribute:: wShowWindow + +- If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this member ++ If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute + can be any of the values that can be specified in the ``nCmdShow`` + parameter for the + `ShowWindow `__ +- function, except for ``SW_SHOWDEFAULT``. Otherwise, this member is ++ function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is + ignored. + + :data:`SW_HIDE` is provided for this attribute. It is used when +@@ -493,12 +613,12 @@ + .. data:: STARTF_USESTDHANDLES + + Specifies that the :attr:`STARTUPINFO.hStdInput`, +- :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` members ++ :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes + contain additional information. + + .. data:: STARTF_USESHOWWINDOW + +- Specifies that the :attr:`STARTUPINFO.wShowWindow` member contains ++ Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains + additional information. + + .. data:: CREATE_NEW_CONSOLE +@@ -522,15 +642,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 +@@ -539,8 +665,8 @@ + :: + + output=`mycmd myarg` +- ==> +- output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] ++ # becomes ++ output = check_output(["mycmd", "myarg"]) + + + Replacing shell pipeline +@@ -549,7 +675,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. +@@ -558,22 +684,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: +@@ -718,6 +849,7 @@ + * popen2 closes all file descriptors by default, but you have to specify + ``close_fds=True`` with :class:`Popen`. + ++ + Notes + ----- + +diff -r 8527427914a2 Doc/library/sunau.rst +--- a/Doc/library/sunau.rst ++++ b/Doc/library/sunau.rst +@@ -1,4 +1,3 @@ +- + :mod:`sunau` --- Read and write Sun AU files + ============================================ + +@@ -6,6 +5,9 @@ + :synopsis: Provide an interface to the Sun AU sound format. + .. sectionauthor:: Moshe Zadka + ++**Source code:** :source:`Lib/sunau.py` ++ ++-------------- + + The :mod:`sunau` module provides a convenient interface to the Sun AU sound + format. Note that this module is interface-compatible with the modules +diff -r 8527427914a2 Doc/library/sunaudio.rst +--- a/Doc/library/sunaudio.rst ++++ b/Doc/library/sunaudio.rst +@@ -93,10 +93,10 @@ + names and meanings of the attributes are described in ```` and in + the :manpage:`audio(7I)` manual page. Member names are slightly different from + their C counterparts: a status object is only a single structure. Members of the +- :cdata:`play` substructure have ``o_`` prepended to their name and members of +- the :cdata:`record` structure have ``i_``. So, the C member +- :cdata:`play.sample_rate` is accessed as :attr:`o_sample_rate`, +- :cdata:`record.gain` as :attr:`i_gain` and :cdata:`monitor_gain` plainly as ++ :c:data:`play` substructure have ``o_`` prepended to their name and members of ++ the :c:data:`record` structure have ``i_``. So, the C member ++ :c:data:`play.sample_rate` is accessed as :attr:`o_sample_rate`, ++ :c:data:`record.gain` as :attr:`i_gain` and :c:data:`monitor_gain` plainly as + :attr:`monitor_gain`. + + +diff -r 8527427914a2 Doc/library/symbol.rst +--- a/Doc/library/symbol.rst ++++ b/Doc/library/symbol.rst +@@ -1,4 +1,3 @@ +- + :mod:`symbol` --- Constants used with Python parse trees + ======================================================== + +@@ -6,6 +5,9 @@ + :synopsis: Constants representing internal nodes of the parse tree. + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/symbol.py` ++ ++-------------- + + This module provides constants which represent the numeric values of internal + nodes of the parse tree. Unlike most Python constants, these use lower-case +@@ -23,10 +25,3 @@ + back to name strings, allowing more human-readable representation of parse trees + to be generated. + +- +-.. seealso:: +- +- Module :mod:`parser` +- The second example for the :mod:`parser` module shows how to use the +- :mod:`symbol` module. +- +diff -r 8527427914a2 Doc/library/sys.rst +--- a/Doc/library/sys.rst ++++ b/Doc/library/sys.rst +@@ -32,20 +32,6 @@ + .. versionadded:: 2.0 + + +-.. data:: subversion +- +- A triple (repo, branch, version) representing the Subversion information of the +- Python interpreter. *repo* is the name of the repository, ``'CPython'``. +- *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or +- ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter +- was built from a Subversion checkout; it contains the revision number (range) +- and possibly a trailing 'M' if there were local modifications. If the tree was +- exported (or svnversion was not available), it is the revision of +- ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``. +- +- .. versionadded:: 2.5 +- +- + .. data:: builtin_module_names + + A tuple of strings giving the names of all modules that are compiled into this +@@ -109,6 +95,17 @@ + customized by assigning another one-argument function to ``sys.displayhook``. + + ++.. 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. ++ ++ .. versionadded:: 2.6 ++ ++ + .. function:: excepthook(type, value, traceback) + + This function prints out a given traceback and exception to ``sys.stderr``. +@@ -210,16 +207,18 @@ + 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 ``2.7``. + + + .. data:: executable + +- A string giving the name of the executable binary for the Python interpreter, on +- systems where this makes sense. ++ A string giving the absolute path of the executable binary for the Python ++ interpreter, on systems where this makes sense. If Python is unable to retrieve ++ the real path to its executable, :data:`sys.executable` will be an empty string ++ or ``None``. + + + .. function:: exit([arg]) +@@ -331,8 +330,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 +@@ -387,7 +390,7 @@ + + .. function:: getdlopenflags() + +- Return the current value of the flags that are used for :cfunc:`dlopen` calls. ++ Return the current value of the flags that are used for :c:func:`dlopen` calls. + The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules. + Availability: Unix. + +@@ -532,8 +535,8 @@ + +---------------------------------------+---------------------------------+ + + +- This function wraps the Win32 :cfunc:`GetVersionEx` function; see the +- Microsoft documentation on :cfunc:`OSVERSIONINFOEX` for more information ++ This function wraps the Win32 :c:func:`GetVersionEx` function; see the ++ Microsoft documentation on :c:func:`OSVERSIONINFOEX` for more information + about these fields. + + Availability: Windows. +@@ -652,7 +655,7 @@ + imported. The :meth:`find_module` method is called at least with the + absolute name of the module being imported. If the module to be imported is + contained in package then the parent package's :attr:`__path__` attribute +- is passed in as a second argument. The method returns :keyword:`None` if ++ is passed in as a second argument. The method returns ``None`` if + the module cannot be found, else returns a :term:`loader`. + + :data:`sys.meta_path` is searched before any implicit default finders or +@@ -711,7 +714,7 @@ + A dictionary acting as a cache for :term:`finder` objects. The keys are + paths that have been passed to :data:`sys.path_hooks` and the values are + the finders that are found. If a path is a valid file system path but no +- explicit finder is found on :data:`sys.path_hooks` then :keyword:`None` is ++ explicit finder is found on :data:`sys.path_hooks` then ``None`` is + stored to represent the implicit default finder should be used. If the path + is not an existing path then :class:`imp.NullImporter` is set. + +@@ -723,23 +726,45 @@ + This string contains a platform identifier that can be used to append + platform-specific components to :data:`sys.path`, for instance. + +- For Unix systems, this is the lowercased OS name as returned by ``uname -s`` +- with the first part of the version as returned by ``uname -r`` appended, +- e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*. ++ For most Unix systems, this is the lowercased OS name as returned by ``uname ++ -s`` with the first part of the version as returned by ``uname -r`` appended, ++ e.g. ``'sunos5'``, *at the time when Python was built*. Unless you want to ++ test for a specific system version, it is therefore recommended to use the ++ following idiom:: ++ ++ if sys.platform.startswith('freebsd'): ++ # FreeBSD-specific code here... ++ elif sys.platform.startswith('linux'): ++ # Linux-specific code here... ++ ++ .. versionchanged:: 2.7.3 ++ Since lots of code check for ``sys.platform == 'linux2'``, and there is ++ no essential change between Linux 2.x and 3.x, ``sys.platform`` is always ++ set to ``'linux2'``, even on Linux 3.x. In Python 3.3 and later, the ++ value will always be set to ``'linux'``, so it is recommended to always ++ use the ``startswith`` idiom presented above. ++ + For other systems, the values are: + +- ================ =========================== +- System :data:`platform` value +- ================ =========================== +- Windows ``'win32'`` +- Windows/Cygwin ``'cygwin'`` +- Mac OS X ``'darwin'`` +- OS/2 ``'os2'`` +- OS/2 EMX ``'os2emx'`` +- RiscOS ``'riscos'`` +- AtheOS ``'atheos'`` +- ================ =========================== ++ ===================== =========================== ++ System :data:`platform` value ++ ===================== =========================== ++ Linux (2.x *and* 3.x) ``'linux2'`` ++ Windows ``'win32'`` ++ Windows/Cygwin ``'cygwin'`` ++ Mac OS X ``'darwin'`` ++ OS/2 ``'os2'`` ++ OS/2 EMX ``'os2emx'`` ++ RiscOS ``'riscos'`` ++ AtheOS ``'atheos'`` ++ ===================== =========================== + ++ .. seealso:: ++ :attr:`os.name` has a coarser granularity. :func:`os.uname` gives ++ system-dependent version information. ++ ++ The :mod:`platform` module provides detailed checks for the ++ system's identity. + + .. data:: prefix + +@@ -747,10 +772,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 ``2.7``. + + + .. data:: ps1 +@@ -778,17 +803,6 @@ + .. versionadded:: 2.6 + + +-.. 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. +- +- .. versionadded:: 2.6 +- +- + .. function:: setcheckinterval(interval) + + Set the interpreter's "check interval". This integer value determines how often +@@ -815,7 +829,7 @@ + + .. function:: setdlopenflags(n) + +- Set the flags used by the interpreter for :cfunc:`dlopen` calls, such as when ++ Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when + the interpreter loads extension modules. Among other things, this will enable a + lazy resolving of symbols when importing a module, if called as + ``sys.setdlopenflags(0)``. To share symbols across extension modules, call as +@@ -980,6 +994,26 @@ + replacing it, and restore the saved object. + + ++.. data:: subversion ++ ++ A triple (repo, branch, version) representing the Subversion information of the ++ Python interpreter. *repo* is the name of the repository, ``'CPython'``. ++ *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or ++ ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter ++ was built from a Subversion checkout; it contains the revision number (range) ++ and possibly a trailing 'M' if there were local modifications. If the tree was ++ exported (or svnversion was not available), it is the revision of ++ ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``. ++ ++ .. versionadded:: 2.5 ++ ++ .. note:: ++ Python is now `developed `_ using ++ Mercurial. In recent Python 2.7 bugfix releases, :data:`subversion` ++ therefore contains placeholder information. It is removed in Python ++ 3.3. ++ ++ + .. data:: tracebacklimit + + When this variable is set to an integer value, it determines the maximum number +diff -r 8527427914a2 Doc/library/sysconfig.rst +--- a/Doc/library/sysconfig.rst ++++ b/Doc/library/sysconfig.rst +@@ -5,10 +5,15 @@ + :synopsis: Python's configuration information + .. moduleauthor:: Tarek Ziade + .. sectionauthor:: Tarek Ziade +-.. versionadded:: 2.7 + .. index:: + single: configuration information + ++.. versionadded:: 2.7 ++ ++**Source code:** :source:`Lib/sysconfig.py` ++ ++-------------- ++ + The :mod:`sysconfig` module provides access to Python's configuration + information like the list of installation paths and the configuration variables + relevant for the current platform. +diff -r 8527427914a2 Doc/library/syslog.rst +--- a/Doc/library/syslog.rst ++++ b/Doc/library/syslog.rst +@@ -30,7 +30,7 @@ + ``openlog()`` will be called with no arguments. + + +-.. function:: openlog([ident[, logopt[, facility]]]) ++.. function:: openlog([ident[, logoption[, facility]]]) + + Logging options of subsequent :func:`syslog` calls can be set by calling + :func:`openlog`. :func:`syslog` will call :func:`openlog` with no arguments +@@ -38,7 +38,7 @@ + + The optional *ident* keyword argument is a string which is prepended to every + message, and defaults to ``sys.argv[0]`` with leading path components +- stripped. The optional *logopt* keyword argument (default is 0) is a bit ++ stripped. The optional *logoption* keyword argument (default is 0) is a bit + field -- see below for possible values to combine. The optional *facility* + keyword argument (default is :const:`LOG_USER`) sets the default facility for + messages which do not have a facility explicitly encoded. +@@ -98,5 +98,5 @@ + logged messages, and write the messages to the destination facility used for + mail logging:: + +- syslog.openlog(logopt=syslog.LOG_PID, facility=syslog.LOG_MAIL) ++ syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL) + syslog.syslog('E-mail processing initiated...') +diff -r 8527427914a2 Doc/library/tabnanny.rst +--- a/Doc/library/tabnanny.rst ++++ b/Doc/library/tabnanny.rst +@@ -9,6 +9,10 @@ + + .. rudimentary documentation based on module comments + ++**Source code:** :source:`Lib/tabnanny.py` ++ ++-------------- ++ + For the time being this module is intended to be called as a script. However it + is possible to import it into an IDE and use the function :func:`check` + described below. +diff -r 8527427914a2 Doc/library/tarfile.rst +--- a/Doc/library/tarfile.rst ++++ b/Doc/library/tarfile.rst +@@ -1,5 +1,3 @@ +-.. _tarfile-mod: +- + :mod:`tarfile` --- Read and write tar archive files + =================================================== + +@@ -12,6 +10,9 @@ + .. moduleauthor:: Lars Gustäbel + .. sectionauthor:: Lars Gustäbel + ++**Source code:** :source:`Lib/tarfile.py` ++ ++-------------- + + The :mod:`tarfile` module makes it possible to read and write tar + archives, including those using gzip or bz2 compression. +diff -r 8527427914a2 Doc/library/telnetlib.rst +--- a/Doc/library/telnetlib.rst ++++ b/Doc/library/telnetlib.rst +@@ -1,4 +1,3 @@ +- + :mod:`telnetlib` --- Telnet client + ================================== + +@@ -9,6 +8,10 @@ + + .. index:: single: protocol; Telnet + ++**Source code:** :source:`Lib/telnetlib.py` ++ ++-------------- ++ + The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the + Telnet protocol. See :rfc:`854` for details about the protocol. In addition, it + provides symbolic constants for the protocol characters (see below), and for the +diff -r 8527427914a2 Doc/library/tempfile.rst +--- a/Doc/library/tempfile.rst ++++ b/Doc/library/tempfile.rst +@@ -1,4 +1,3 @@ +- + :mod:`tempfile` --- Generate temporary files and directories + ============================================================ + +@@ -13,6 +12,10 @@ + pair: temporary; file name + pair: temporary; file + ++**Source code:** :source:`Lib/tempfile.py` ++ ++-------------- ++ + This module generates temporary files and directories. It works on all + supported platforms. + +@@ -61,7 +64,7 @@ + This function operates exactly as :func:`TemporaryFile` does, except that + the file is guaranteed to have a visible name in the file system (on + Unix, the directory entry is not unlinked). That name can be retrieved +- from the :attr:`name` member of the file object. Whether the name can be ++ from the :attr:`name` attribute of the file object. Whether the name can be + used to open the file a second time, while the named temporary file is + still open, varies across platforms (it can be so used on Unix; it cannot + on Windows NT or later). If *delete* is true (the default), the file is +diff -r 8527427914a2 Doc/library/textwrap.rst +--- a/Doc/library/textwrap.rst ++++ b/Doc/library/textwrap.rst +@@ -1,4 +1,3 @@ +- + :mod:`textwrap` --- Text wrapping and filling + ============================================= + +@@ -7,8 +6,11 @@ + .. moduleauthor:: Greg Ward + .. sectionauthor:: Greg Ward + ++.. versionadded:: 2.3 + +-.. versionadded:: 2.3 ++**Source code:** :source:`Lib/textwrap.py` ++ ++-------------- + + The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and + :func:`fill`, as well as :class:`TextWrapper`, the class that does all the work, +@@ -16,11 +18,6 @@ + or two text strings, the convenience functions should be good enough; + otherwise, you should use an instance of :class:`TextWrapper` for efficiency. + +-.. seealso:: +- +- Latest version of the `textwrap module Python source code +- `_ +- + .. function:: wrap(text[, width[, ...]]) + + Wraps the single paragraph in *text* (a string) so every line is at most *width* +diff -r 8527427914a2 Doc/library/threading.rst +--- a/Doc/library/threading.rst ++++ b/Doc/library/threading.rst +@@ -4,6 +4,9 @@ + .. module:: threading + :synopsis: Higher-level threading interface. + ++**Source code:** :source:`Lib/threading.py` ++ ++-------------- + + This module constructs higher-level threading interfaces on top of the lower + level :mod:`thread` module. +@@ -36,11 +39,6 @@ + :mod:`multiprocessing`. However, threading is still an appropriate model + if you want to run multiple I/O-bound tasks simultaneously. + +-.. seealso:: +- +- Latest version of the `threading module Python source code +- `_ +- + + This module defines the following functions and objects: + +@@ -575,20 +573,21 @@ + interface is then used to restore the recursion level when the lock is + reacquired. + +- .. 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. + +diff -r 8527427914a2 Doc/library/time.rst +--- a/Doc/library/time.rst ++++ b/Doc/library/time.rst +@@ -74,8 +74,8 @@ + * On the other hand, the precision of :func:`time` and :func:`sleep` is better + than their Unix equivalents: times are expressed as floating point numbers, + :func:`time` returns the most accurate time available (using Unix +- :cfunc:`gettimeofday` where available), and :func:`sleep` will accept a time +- with a nonzero fraction (Unix :cfunc:`select` is used to implement this, where ++ :c:func:`gettimeofday` where available), and :func:`sleep` will accept a time ++ with a nonzero fraction (Unix :c:func:`select` is used to implement this, where + available). + + * The time value as returned by :func:`gmtime`, :func:`localtime`, and +@@ -156,7 +156,7 @@ + + On Windows, this function returns wall-clock seconds elapsed since the first + call to this function, as a floating point number, based on the Win32 function +- :cfunc:`QueryPerformanceCounter`. The resolution is typically better than one ++ :c:func:`QueryPerformanceCounter`. The resolution is typically better than one + microsecond. + + +@@ -560,6 +560,6 @@ + preferred hour/minute offset is not supported by all ANSI C libraries. Also, a + strict reading of the original 1982 :rfc:`822` standard calls for a two-digit + year (%y rather than %Y), but practice moved to 4-digit years long before the +- year 2000. The 4-digit year has been mandated by :rfc:`2822`, which obsoletes +- :rfc:`822`. ++ year 2000. After that, :rfc:`822` became obsolete and the 4-digit year has ++ been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`. + +diff -r 8527427914a2 Doc/library/timeit.rst +--- a/Doc/library/timeit.rst ++++ b/Doc/library/timeit.rst +@@ -1,4 +1,3 @@ +- + :mod:`timeit` --- Measure execution time of small code snippets + =============================================================== + +@@ -12,6 +11,10 @@ + single: Benchmarking + single: Performance + ++**Source code:** :source:`Lib/timeit.py` ++ ++-------------- ++ + This module provides a simple way to time small bits of Python code. It has both + command line as well as callable interfaces. It avoids a number of common traps + for measuring execution times. See also Tim Peters' introduction to the +@@ -195,13 +198,13 @@ + :keyword:`try`/:keyword:`except` to test for missing and present object + attributes. :: + +- % timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' ++ $ python -m timeit 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' + 100000 loops, best of 3: 15.7 usec per loop +- % timeit.py 'if hasattr(str, "__nonzero__"): pass' ++ $ python -m timeit 'if hasattr(str, "__nonzero__"): pass' + 100000 loops, best of 3: 4.26 usec per loop +- % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' ++ $ python -m timeit 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' + 1000000 loops, best of 3: 1.43 usec per loop +- % timeit.py 'if hasattr(int, "__nonzero__"): pass' ++ $ python -m timeit 'if hasattr(int, "__nonzero__"): pass' + 100000 loops, best of 3: 2.23 usec per loop + + :: +@@ -242,12 +245,12 @@ + ``setup`` parameter which contains an import statement:: + + def test(): +- "Stupid test function" ++ """Stupid test function""" + L = [] + for i in range(100): + L.append(i) + +- if __name__=='__main__': ++ if __name__ == '__main__': + from timeit import Timer + t = Timer("test()", "from __main__ import test") + print t.timeit() +diff -r 8527427914a2 Doc/library/token.rst +--- a/Doc/library/token.rst ++++ b/Doc/library/token.rst +@@ -1,4 +1,3 @@ +- + :mod:`token` --- Constants used with Python parse trees + ======================================================= + +@@ -6,6 +5,9 @@ + :synopsis: Constants representing terminal nodes of the parse tree. + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/token.py` ++ ++-------------- + + This module provides constants which represent the numeric values of leaf nodes + of the parse tree (terminal tokens). Refer to the file :file:`Grammar/Grammar` +diff -r 8527427914a2 Doc/library/tokenize.rst +--- a/Doc/library/tokenize.rst ++++ b/Doc/library/tokenize.rst +@@ -1,4 +1,3 @@ +- + :mod:`tokenize` --- Tokenizer for Python source + =============================================== + +@@ -7,16 +6,20 @@ + .. moduleauthor:: Ka Ping Yee + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/tokenize.py` ++ ++-------------- + + The :mod:`tokenize` module provides a lexical scanner for Python source code, + implemented in Python. The scanner in this module returns comments as tokens as + well, making it useful for implementing "pretty-printers," including colorizers + for on-screen displays. + +-.. seealso:: +- +- Latest version of the `tokenize module Python source code +- `_ ++To simplify token stream handling, all :ref:`operators` and :ref:`delimiters` ++tokens are returned using the generic :data:`token.OP` token type. The exact ++type can be determined by checking the token ``string`` field on the ++:term:`named tuple` returned from :func:`tokenize.tokenize` for the character ++sequence that identifies a specific operator token. + + The primary entry point is a :term:`generator`: + +diff -r 8527427914a2 Doc/library/trace.rst +--- a/Doc/library/trace.rst ++++ b/Doc/library/trace.rst +@@ -1,21 +1,18 @@ +- + :mod:`trace` --- Trace or track Python statement execution + ========================================================== + + .. module:: trace + :synopsis: Trace or track Python statement execution. + ++**Source code:** :source:`Lib/trace.py` ++ ++-------------- + + The :mod:`trace` module allows you to trace program execution, generate + annotated statement coverage listings, print caller/callee relationships and + list functions executed during a program run. It can be used in another program + or from the command line. + +-.. seealso:: +- +- Latest version of the `trace module Python source code +- `_ +- + .. _trace-cli: + + Command-Line Usage +diff -r 8527427914a2 Doc/library/ttk.rst +--- a/Doc/library/ttk.rst ++++ b/Doc/library/ttk.rst +@@ -1243,7 +1243,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):: +@@ -1294,7 +1294,7 @@ + + * sticky=spec + Specifies how the image is placed within the final parcel. spec +- contains zero or more characters “nâ€, “sâ€, “wâ€, or “eâ€. ++ contains zero or more characters "n", "s", "w", or "e". + + * width=width + Specifies a minimum width for the element. If less than zero, the +diff -r 8527427914a2 Doc/library/turtle.rst +--- a/Doc/library/turtle.rst ++++ b/Doc/library/turtle.rst +@@ -18,10 +18,10 @@ + part of the original Logo programming language developed by Wally Feurzig and + Seymour Papert in 1966. + +-Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it the ++Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it the + command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the + direction it is facing, drawing a line as it moves. Give it the command +-``turtle.left(25)``, and it rotates in-place 25 degrees clockwise. ++``turtle.right(25)``, and it rotates in-place 25 degrees clockwise. + + By combining together these and similar commands, intricate shapes and pictures + can easily be drawn. +@@ -157,6 +157,7 @@ + | :func:`onclick` + | :func:`onrelease` + | :func:`ondrag` ++ | :func:`mainloop` | :func:`done` + + Special Turtle methods + | :func:`begin_poly` +@@ -1291,6 +1292,15 @@ + the screen thereby producing handdrawings (if pen is down). + + ++.. function:: mainloop() ++ done() ++ ++ Starts event loop - calling Tkinter's mainloop function. Must be the last ++ statement in a turtle graphics program. ++ ++ >>> turtle.mainloop() ++ ++ + Special Turtle methods + ---------------------- + +diff -r 8527427914a2 Doc/library/types.rst +--- a/Doc/library/types.rst ++++ b/Doc/library/types.rst +@@ -4,6 +4,9 @@ + .. module:: types + :synopsis: Names for built-in types. + ++**Source code:** :source:`Lib/types.py` ++ ++-------------- + + This module defines names for some object types that are used by the standard + Python interpreter, but not for the types defined by various extension modules. +diff -r 8527427914a2 Doc/library/unicodedata.rst +--- a/Doc/library/unicodedata.rst ++++ b/Doc/library/unicodedata.rst +@@ -107,7 +107,7 @@ + based on the definition of canonical equivalence and compatibility equivalence. + In Unicode, several characters can be expressed in various way. For example, the + character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as +- the sequence U+0327 (COMBINING CEDILLA) U+0043 (LATIN CAPITAL LETTER C). ++ the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA). + + For each character, there are two normal forms: normal form C and normal form D. + Normal form D (NFD) is also known as canonical decomposition, and translates +diff -r 8527427914a2 Doc/library/unittest.rst +--- a/Doc/library/unittest.rst ++++ b/Doc/library/unittest.rst +@@ -307,7 +307,7 @@ + + Test discovery loads tests by importing them. Once test discovery has + found all the test files from the start directory you specify it turns the +- paths into package names to import. For example `foo/bar/baz.py` will be ++ paths into package names to import. For example :file:`foo/bar/baz.py` will be + imported as ``foo.bar.baz``. + + If you have a package installed globally and attempt test discovery on +@@ -352,7 +352,7 @@ + widget = Widget('The widget') + self.assertEqual(widget.size(), (50, 50), 'incorrect default size') + +-Note that in order to test something, we use the one of the :meth:`assert\*` ++Note that in order to test something, we use one of the :meth:`assert\*` + methods provided by the :class:`TestCase` base class. If the test fails, an + exception will be raised, and :mod:`unittest` will identify the test case as a + :dfn:`failure`. Any other exceptions will be treated as :dfn:`errors`. This +@@ -840,13 +840,13 @@ + + In addition, if *first* and *second* are the exact same type and one of + list, tuple, dict, set, frozenset or unicode or any type that a subclass +- registers with :meth:`addTypeEqualityFunc` the type specific equality ++ registers with :meth:`addTypeEqualityFunc` the type-specific equality + function will be called in order to generate a more useful default + error message (see also the :ref:`list of type-specific methods + `). + + .. versionchanged:: 2.7 +- Added the automatic calling of type specific equality function. ++ Added the automatic calling of type-specific equality function. + + + .. method:: assertNotEqual(first, second, msg=None) +@@ -895,6 +895,7 @@ + + 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 the exact type, use :func:`assertIs(type(obj), cls) `. + + .. versionadded:: 2.7 + +@@ -905,11 +906,11 @@ + +---------------------------------------------------------+--------------------------------------+------------+ + | 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:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises `exc` | 2.7 | +- | ` | and the message matches `re` | | ++ | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds) | ``fun(*args, **kwds)`` raises *exc* | 2.7 | ++ | ` | and the message matches *re* | | + +---------------------------------------------------------+--------------------------------------+------------+ + + .. method:: assertRaises(exception, callable, *args, **kwds) +@@ -995,7 +996,7 @@ + | ` | works with unhashable objs | | + +---------------------------------------+--------------------------------+--------------+ + | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs | 2.7 | +- | ` | in `a` exist in `b` | | ++ | ` | in *a* exist in *b* | | + +---------------------------------------+--------------------------------+--------------+ + + +diff -r 8527427914a2 Doc/library/urllib.rst +--- a/Doc/library/urllib.rst ++++ b/Doc/library/urllib.rst +@@ -23,7 +23,7 @@ + instead of filenames. Some restrictions apply --- it can only open URLs for + reading, and no seek operations are available. + +-.. warning:: When opening HTTPS URLs, it is not attempted to validate the ++.. warning:: When opening HTTPS URLs, it does not attempt to validate the + server certificate. Use at your own risk! + + +@@ -210,7 +210,7 @@ + + Replace special characters in *string* using the ``%xx`` escape. Letters, + digits, and the characters ``'_.-'`` are never quoted. By default, this +- function is intended for quoting the path section of the URL.The optional ++ function is intended for quoting the path section of the URL. The optional + *safe* parameter specifies additional characters that should not be quoted + --- its default value is ``'/'``. + +@@ -274,10 +274,10 @@ + .. function:: getproxies() + + This helper function returns a dictionary of scheme to proxy server URL +- mappings. It scans the environment for variables named ``_proxy`` +- for all operating systems first, and when it cannot find it, looks for proxy +- information from Mac OSX System Configuration for Mac OS X and Windows +- Systems Registry for Windows. ++ mappings. It scans the environment for variables named ``_proxy``, ++ in case insensitive way, for all operating systems first, and when it cannot ++ find it, looks for proxy information from Mac OSX System Configuration for ++ Mac OS X and Windows Systems Registry for Windows. + + + URL Opener objects +diff -r 8527427914a2 Doc/library/urllib2.rst +--- a/Doc/library/urllib2.rst ++++ b/Doc/library/urllib2.rst +@@ -36,7 +36,7 @@ + :mimetype:`application/x-www-form-urlencoded` format. The + :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and + returns a string in this format. urllib2 module sends HTTP/1.1 requests with +- `Connection:close` header included. ++ ``Connection:close`` header included. + + The optional *timeout* parameter specifies a timeout in seconds for blocking + operations like the connection attempt (if not specified, the global default +@@ -90,7 +90,7 @@ + :class:`HTTPSHandler` will also be added. + + Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its +- :attr:`handler_order` member variable to modify its position in the handlers ++ :attr:`handler_order` attribute to modify its position in the handlers + list. + + The following exceptions are raised as appropriate: +@@ -297,6 +297,11 @@ + A catch-all class to handle unknown URLs. + + ++.. class:: HTTPErrorProcessor() ++ ++ Process HTTP error responses. ++ ++ + .. _request-objects: + + Request Objects +@@ -495,7 +500,7 @@ + + Remove any parents. + +-The following members and methods should only be used by classes derived from ++The following attributes and methods should only be used by classes derived from + :class:`BaseHandler`. + + .. note:: +@@ -881,7 +886,7 @@ + .. versionadded:: 2.4 + + +-.. method:: HTTPErrorProcessor.unknown_open() ++.. method:: HTTPErrorProcessor.http_response() + + Process HTTP error responses. + +@@ -893,6 +898,12 @@ + :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no + other handler handles the error. + ++.. method:: HTTPErrorProcessor.https_response() ++ ++ Process HTTPS error responses. ++ ++ The behavior is same as :meth:`http_response`. ++ + + .. _urllib2-examples: + +diff -r 8527427914a2 Doc/library/urlparse.rst +--- a/Doc/library/urlparse.rst ++++ b/Doc/library/urlparse.rst +@@ -17,6 +17,9 @@ + The :term:`2to3` tool will automatically adapt imports when converting + your sources to 3.0. + ++**Source code:** :source:`Lib/urlparse.py` ++ ++-------------- + + This module defines a standard interface to break Uniform Resource Locator (URL) + strings up in components (addressing scheme, network location, path etc.), to +@@ -33,11 +36,6 @@ + .. versionadded:: 2.5 + Support for the ``sftp`` and ``sips`` schemes. + +-.. seealso:: +- +- Latest version of the `urlparse module Python source code +- `_ +- + The :mod:`urlparse` module defines the following functions: + + +diff -r 8527427914a2 Doc/library/userdict.rst +--- a/Doc/library/userdict.rst ++++ b/Doc/library/userdict.rst +@@ -1,4 +1,3 @@ +- + :mod:`UserDict` --- Class wrapper for dictionary objects + ======================================================== + +@@ -6,6 +5,10 @@ + :synopsis: Class wrapper for dictionary objects. + + ++**Source code:** :source:`Lib/UserDict.py` ++ ++-------------- ++ + The module defines a mixin, :class:`DictMixin`, defining all dictionary methods + for classes that already have a minimum mapping interface. This greatly + simplifies writing classes that need to be substitutable for dictionaries (such +@@ -19,11 +22,6 @@ + sub-classes that obtained new behaviors by overriding existing methods or adding + new ones. + +-.. seealso:: +- +- Latest version of the `UserDict Python source code +- `_ +- + The :mod:`UserDict` module defines the :class:`UserDict` class and + :class:`DictMixin`: + +@@ -85,9 +83,18 @@ + + .. note:: + +- This module is available for backward compatibility only. If you are writing +- code that does not need to work with versions of Python earlier than Python 2.2, +- please consider subclassing directly from the built-in :class:`list` type. ++ When Python 2.2 was released, many of the use cases for this class were ++ subsumed by the ability to subclass :class:`list` directly. However, a ++ handful of use cases remain. ++ ++ This module provides a list-interface around an underlying data store. By ++ default, that data store is a :class:`list`; however, it can be used to wrap ++ a list-like interface around other objects (such as persistent storage). ++ ++ In addition, this class can be mixed-in with built-in classes using multiple ++ inheritance. This can sometimes be useful. For example, you can inherit ++ from :class:`UserList` and :class:`str` at the same time. That would not be ++ possible with both a real :class:`list` and a real :class:`str`. + + This module defines a class that acts as a wrapper around list objects. It is a + useful base class for your own list-like classes, which can inherit from them +diff -r 8527427914a2 Doc/library/uu.rst +--- a/Doc/library/uu.rst ++++ b/Doc/library/uu.rst +@@ -1,4 +1,3 @@ +- + :mod:`uu` --- Encode and decode uuencode files + ============================================== + +@@ -6,6 +5,9 @@ + :synopsis: Encode and decode files in uuencode format. + .. moduleauthor:: Lance Ellinghouse + ++**Source code:** :source:`Lib/uu.py` ++ ++-------------- + + This module encodes and decodes files in uuencode format, allowing arbitrary + binary data to be transferred over ASCII-only connections. Wherever a file +@@ -22,11 +24,6 @@ + + This code was contributed by Lance Ellinghouse, and modified by Jack Jansen. + +-.. seealso:: +- +- Latest version of the `uu module Python source code +- `_ +- + The :mod:`uu` module defines the following functions: + + +@@ -62,4 +59,3 @@ + + Module :mod:`binascii` + Support module containing ASCII-to-binary and binary-to-ASCII conversions. +- +diff -r 8527427914a2 Doc/library/uuid.rst +--- a/Doc/library/uuid.rst ++++ b/Doc/library/uuid.rst +@@ -225,34 +225,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 + '\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 8527427914a2 Doc/library/warnings.rst +--- a/Doc/library/warnings.rst ++++ b/Doc/library/warnings.rst +@@ -9,13 +9,17 @@ + + .. versionadded:: 2.1 + ++**Source code:** :source:`Lib/warnings.py` ++ ++-------------- ++ + Warning messages are typically issued in situations where it is useful to alert + the user of some condition in a program, where that condition (normally) doesn't + warrant raising an exception and terminating the program. For example, one + might want to issue a warning when a program uses an obsolete module. + + Python programmers issue warnings by calling the :func:`warn` function defined +-in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see ++in this module. (C programmers use :c:func:`PyErr_WarnEx`; see + :ref:`exceptionhandling` for details). + + Warning messages are normally written to ``sys.stderr``, but their disposition +@@ -39,6 +43,10 @@ + message by calling :func:`formatwarning`, which is also available for use by + custom implementations. + ++.. seealso:: ++ :func:`logging.captureWarnings` allows you to handle all warnings with ++ the standard logging infrastructure. ++ + + .. _warning-categories: + +diff -r 8527427914a2 Doc/library/wave.rst +--- a/Doc/library/wave.rst ++++ b/Doc/library/wave.rst +@@ -6,6 +6,10 @@ + .. sectionauthor:: Moshe Zadka + .. Documentations stolen from comments in file. + ++**Source code:** :source:`Lib/wave.py` ++ ++-------------- ++ + The :mod:`wave` module provides a convenient interface to the WAV sound format. + It does not support compression/decompression, but it does support mono/stereo. + +diff -r 8527427914a2 Doc/library/weakref.rst +--- a/Doc/library/weakref.rst ++++ b/Doc/library/weakref.rst +@@ -11,6 +11,10 @@ + + .. versionadded:: 2.1 + ++**Source code:** :source:`Lib/weakref.py` ++ ++-------------- ++ + The :mod:`weakref` module allows the Python programmer to create :dfn:`weak + references` to objects. + +diff -r 8527427914a2 Doc/library/webbrowser.rst +--- a/Doc/library/webbrowser.rst ++++ b/Doc/library/webbrowser.rst +@@ -1,4 +1,3 @@ +- + :mod:`webbrowser` --- Convenient Web-browser controller + ======================================================= + +@@ -7,6 +6,9 @@ + .. moduleauthor:: Fred L. Drake, Jr. + .. sectionauthor:: Fred L. Drake, Jr. + ++**Source code:** :source:`Lib/webbrowser.py` ++ ++-------------- + + The :mod:`webbrowser` module provides a high-level interface to allow displaying + Web-based documents to users. Under most circumstances, simply calling the +diff -r 8527427914a2 Doc/library/winsound.rst +--- a/Doc/library/winsound.rst ++++ b/Doc/library/winsound.rst +@@ -27,7 +27,7 @@ + + .. function:: PlaySound(sound, flags) + +- Call the underlying :cfunc:`PlaySound` function from the Platform API. The ++ Call the underlying :c:func:`PlaySound` function from the Platform API. The + *sound* parameter may be a filename, audio data as a string, or ``None``. Its + interpretation depends on the value of *flags*, which can be a bitwise ORed + combination of the constants described below. If the *sound* parameter is +@@ -37,7 +37,7 @@ + + .. function:: MessageBeep([type=MB_OK]) + +- Call the underlying :cfunc:`MessageBeep` function from the Platform API. This ++ Call the underlying :c:func:`MessageBeep` function from the Platform API. This + plays a sound as specified in the registry. The *type* argument specifies which + sound to play; possible values are ``-1``, ``MB_ICONASTERISK``, + ``MB_ICONEXCLAMATION``, ``MB_ICONHAND``, ``MB_ICONQUESTION``, and ``MB_OK``, all +diff -r 8527427914a2 Doc/library/xdrlib.rst +--- a/Doc/library/xdrlib.rst ++++ b/Doc/library/xdrlib.rst +@@ -1,4 +1,3 @@ +- + :mod:`xdrlib` --- Encode and decode XDR data + ============================================ + +@@ -10,6 +9,10 @@ + single: XDR + single: External Data Representation + ++**Source code:** :source:`Lib/xdrlib.py` ++ ++-------------- ++ + The :mod:`xdrlib` module supports the External Data Representation Standard as + described in :rfc:`1014`, written by Sun Microsystems, Inc. June 1987. It + supports most of the data types described in the RFC. +@@ -257,7 +260,7 @@ + + .. exception:: Error + +- The base exception class. :exc:`Error` has a single public data member ++ The base exception class. :exc:`Error` has a single public attribute + :attr:`msg` containing the description of the error. + + +diff -r 8527427914a2 Doc/library/xml.dom.minidom.rst +--- a/Doc/library/xml.dom.minidom.rst ++++ b/Doc/library/xml.dom.minidom.rst +@@ -1,4 +1,3 @@ +- + :mod:`xml.dom.minidom` --- Lightweight DOM implementation + ========================================================= + +@@ -11,6 +10,10 @@ + + .. versionadded:: 2.0 + ++**Source code:** :source:`Lib/xml/dom/minidom.py` ++ ++-------------- ++ + :mod:`xml.dom.minidom` is a light-weight implementation of the Document Object + Model interface. It is intended to be simpler than the full DOM and also + significantly smaller. +diff -r 8527427914a2 Doc/library/xml.dom.pulldom.rst +--- a/Doc/library/xml.dom.pulldom.rst ++++ b/Doc/library/xml.dom.pulldom.rst +@@ -1,4 +1,3 @@ +- + :mod:`xml.dom.pulldom` --- Support for building partial DOM trees + ================================================================= + +@@ -9,6 +8,10 @@ + + .. versionadded:: 2.0 + ++**Source code:** :source:`Lib/xml/dom/pulldom.py` ++ ++-------------- ++ + :mod:`xml.dom.pulldom` allows building only selected portions of a Document + Object Model representation of a document from SAX events. + +diff -r 8527427914a2 Doc/library/xml.etree.elementtree.rst +--- a/Doc/library/xml.etree.elementtree.rst ++++ b/Doc/library/xml.etree.elementtree.rst +@@ -1,4 +1,3 @@ +- + :mod:`xml.etree.ElementTree` --- The ElementTree XML API + ======================================================== + +@@ -9,6 +8,10 @@ + + .. versionadded:: 2.5 + ++**Source code:** :source:`Lib/xml/etree/ElementTree.py` ++ ++-------------- ++ + The :class:`Element` type is a flexible container object, designed to store + hierarchical data structures in memory. The type can be described as a cross + between a list and a dictionary. +@@ -333,6 +336,8 @@ + elements whose tag equals *tag* are returned from the iterator. If the + tree structure is modified during iteration, the result is undefined. + ++ .. versionadded:: 2.7 ++ + + .. method:: iterfind(match) + +diff -r 8527427914a2 Doc/library/xmlrpclib.rst +--- a/Doc/library/xmlrpclib.rst ++++ b/Doc/library/xmlrpclib.rst +@@ -17,6 +17,10 @@ + + .. versionadded:: 2.2 + ++**Source code:** :source:`Lib/xmlrpclib.py` ++ ++-------------- ++ + XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a + transport. With it, a client can call methods with parameters on a remote + server (the server is named by a URI) and get back structured data. This module +@@ -148,7 +152,7 @@ + :class:`Fault` or :class:`ProtocolError` object indicating an error. + + Servers that support the XML introspection API support some common methods +-grouped under the reserved :attr:`system` member: ++grouped under the reserved :attr:`system` attribute: + + + .. method:: ServerProxy.system.listMethods() +@@ -341,7 +345,7 @@ + ------------- + + A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault +-objects have the following members: ++objects have the following attributes: + + + .. attribute:: Fault.faultCode +@@ -390,7 +394,7 @@ + + A :class:`ProtocolError` object describes a protocol error in the underlying + transport layer (such as a 404 'not found' error if the server named by the URI +-does not exist). It has the following members: ++does not exist). It has the following attributes: + + + .. attribute:: ProtocolError.url +@@ -435,8 +439,8 @@ + + .. versionadded:: 2.4 + +-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) +@@ -577,3 +581,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 8527427914a2 Doc/library/zipfile.rst +--- a/Doc/library/zipfile.rst ++++ b/Doc/library/zipfile.rst +@@ -1,4 +1,3 @@ +- + :mod:`zipfile` --- Work with ZIP archives + ========================================= + +@@ -9,6 +8,10 @@ + + .. versionadded:: 1.6 + ++**Source code:** :source:`Lib/zipfile.py` ++ ++-------------- ++ + The ZIP file format is a common archive and compression standard. This module + provides tools to create, read, write, append, and list a ZIP file. Any + advanced use of this module will require an understanding of the format, as +@@ -385,7 +388,7 @@ + +-------+--------------------------+ + | Index | Value | + +=======+==========================+ +- | ``0`` | Year | ++ | ``0`` | Year (>= 1980) | + +-------+--------------------------+ + | ``1`` | Month (one-based) | + +-------+--------------------------+ +@@ -398,6 +401,10 @@ + | ``5`` | Seconds (zero-based) | + +-------+--------------------------+ + ++ .. note:: ++ ++ The ZIP file format does not support timestamps before 1980. ++ + + .. attribute:: ZipInfo.compress_type + +diff -r 8527427914a2 Doc/library/zipimport.rst +--- a/Doc/library/zipimport.rst ++++ b/Doc/library/zipimport.rst +@@ -12,11 +12,11 @@ + This module adds the ability to import Python modules (:file:`\*.py`, + :file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not + needed to use the :mod:`zipimport` module explicitly; it is automatically used +-by the built-in :keyword:`import` mechanism for ``sys.path`` items that are paths ++by the built-in :keyword:`import` mechanism for :data:`sys.path` items that are paths + to ZIP archives. + +-Typically, ``sys.path`` is a list of directory names as strings. This module +-also allows an item of ``sys.path`` to be a string naming a ZIP file archive. ++Typically, :data:`sys.path` is a list of directory names as strings. This module ++also allows an item of :data:`sys.path` to be a string naming a ZIP file archive. + The ZIP archive can contain a subdirectory structure to support package imports, + and a path within the archive can be specified to only import from a + subdirectory. For example, the path :file:`/tmp/example.zip/lib/` would only +diff -r 8527427914a2 Doc/library/zlib.rst +--- a/Doc/library/zlib.rst ++++ b/Doc/library/zlib.rst +@@ -132,7 +132,7 @@ + *bufsize* is the initial size of the buffer used to hold decompressed data. If + more space is required, the buffer size will be increased as needed, so you + don't have to get this value exactly right; tuning it will only save a few calls +- to :cfunc:`malloc`. The default size is 16384. ++ to :c:func:`malloc`. The default size is 16384. + + + .. function:: decompressobj([wbits]) +diff -r 8527427914a2 Doc/license.rst +--- a/Doc/license.rst ++++ b/Doc/license.rst +@@ -132,7 +132,7 @@ + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python |release| alone or in any derivative + version, provided, however, that PSF's License Agreement and PSF's notice of +- copyright, i.e., "Copyright © 2001-2010 Python Software Foundation; All Rights ++ copyright, i.e., "Copyright © 2001-2012 Python Software Foundation; All Rights + Reserved" are retained in Python |release| alone or in any derivative version + prepared by Licensee. + +@@ -536,36 +536,6 @@ + PERFORMANCE OF THIS SOFTWARE. + + +-Profiling +---------- +- +-The :mod:`profile` and :mod:`pstats` modules contain the following notice:: +- +- Copyright 1994, by InfoSeek Corporation, all rights reserved. +- Written by James Roskind +- +- Permission to use, copy, modify, and distribute this Python software +- and its associated documentation for any purpose (subject to the +- restriction in the following sentence) 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 InfoSeek not be used in +- advertising or publicity pertaining to distribution of the software +- without specific, written prior permission. This permission is +- explicitly restricted to the copying and modification of the software +- to remain in Python, compiled Python, or other languages (such as C) +- wherein the modified or derived code is exclusively imported into a +- Python module. +- +- INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +- SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +- FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION 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 + ----------------- + +@@ -889,7 +859,7 @@ + ----- + + The :mod:`pyexpat` extension is built using an included copy of the expat +-sources unless the build is configured :option:`--with-system-expat`:: ++sources unless the build is configured ``--with-system-expat``:: + + Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper +@@ -918,7 +888,7 @@ + ------ + + The :mod:`_ctypes` extension is built using an included copy of the libffi +-sources unless the build is configured :option:`--with-system-libffi`:: ++sources unless the build is configured ``--with-system-libffi``:: + + Copyright (c) 1996-2008 Red Hat, Inc and others. + +@@ -947,7 +917,7 @@ + ---- + + The :mod:`zlib` extension is built using an included copy of the zlib +-sources unless the zlib version found on the system is too old to be ++sources if the zlib version found on the system is too old to be + used for the build:: + + Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler +diff -r 8527427914a2 Doc/reference/compound_stmts.rst +--- a/Doc/reference/compound_stmts.rst ++++ b/Doc/reference/compound_stmts.rst +@@ -470,7 +470,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. +@@ -562,8 +562,9 @@ + + .. rubric:: Footnotes + +-.. [#] The exception is propagated to the invocation stack only if there is no +- :keyword:`finally` clause that negates the exception. ++.. [#] The exception is propagated to the invocation stack unless ++ there is a :keyword:`finally` clause which happens to raise another ++ exception. That new exception causes the old one to be lost. + + .. [#] Currently, control "flows off the end" except in the case of an exception or the + execution of a :keyword:`return`, :keyword:`continue`, or :keyword:`break` +diff -r 8527427914a2 Doc/reference/datamodel.rst +--- a/Doc/reference/datamodel.rst ++++ b/Doc/reference/datamodel.rst +@@ -2308,7 +2308,7 @@ + + * + +- In ``x * y``, if one operator is a sequence that implements sequence ++ In ``x * y``, if one operand is a sequence that implements sequence + repetition, and the other is an integer (:class:`int` or :class:`long`), + sequence repetition is invoked. + +diff -r 8527427914a2 Doc/reference/expressions.rst +--- a/Doc/reference/expressions.rst ++++ b/Doc/reference/expressions.rst +@@ -347,7 +347,7 @@ + quotes: + + .. productionlist:: +- string_conversion: "'" `expression_list` "'" ++ string_conversion: "`" `expression_list` "`" + + A string conversion evaluates the contained expression list and converts the + resulting object into a string according to rules specific to its type. +@@ -719,7 +719,7 @@ + An implementation may provide built-in functions whose positional parameters + do not have names, even if they are 'named' for the purpose of documentation, + and which therefore cannot be supplied by keyword. In CPython, this is the +- case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to ++ case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to + parse their arguments. + + If there are more positional arguments than there are formal parameter slots, a +@@ -735,12 +735,15 @@ + and the argument values as corresponding values), or a (new) empty dictionary if + there were no excess keyword arguments. + ++.. index:: ++ single: *; in function calls ++ + If the syntax ``*expression`` appears in the function call, ``expression`` must +-evaluate to a sequence. Elements from this sequence are treated as if they were +-additional positional arguments; if there are positional arguments *x1*,..., +-*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is +-equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ..., +-*yM*. ++evaluate to an iterable. Elements from this iterable are treated as if they ++were additional positional arguments; if there are positional arguments ++*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this ++is equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ++..., *yM*. + + A consequence of this is that although the ``*expression`` syntax may appear + *after* some keyword arguments, it is processed *before* the keyword arguments +@@ -761,6 +764,9 @@ + It is unusual for both keyword arguments and the ``*expression`` syntax to be + used in the same call, so in practice this confusion does not arise. + ++.. index:: ++ single: **; in function calls ++ + If the syntax ``**expression`` appears in the function call, ``expression`` must + evaluate to a mapping, the contents of which are treated as additional keyword + arguments. In the case of a keyword appearing in both ``expression`` and as an +@@ -1042,9 +1048,9 @@ + + .. _comparisons: + .. _is: +-.. _isnot: ++.. _is not: + .. _in: +-.. _notin: ++.. _not in: + + Comparisons + =========== +diff -r 8527427914a2 Doc/reference/introduction.rst +--- a/Doc/reference/introduction.rst ++++ b/Doc/reference/introduction.rst +@@ -65,7 +65,7 @@ + An alternate Python for .NET. Unlike Python.NET, this is a complete Python + implementation that generates IL, and compiles Python code directly to .NET + assemblies. It was created by Jim Hugunin, the original creator of Jython. For +- more information, see `the IronPython website `_. ++ more information, see `the IronPython website `_. + + PyPy + An implementation of Python written completely in Python. It supports several +diff -r 8527427914a2 Doc/reference/lexical_analysis.rst +--- a/Doc/reference/lexical_analysis.rst ++++ b/Doc/reference/lexical_analysis.rst +@@ -357,11 +357,11 @@ + assign a different object to it. + + .. versionchanged:: 2.5 +- Both :keyword:`as` and :keyword:`with` are only recognized when the +- ``with_statement`` future feature has been enabled. It will always be enabled in +- Python 2.6. See section :ref:`with` for details. Note that using :keyword:`as` +- and :keyword:`with` as identifiers will always issue a warning, even when the +- ``with_statement`` future directive is not in effect. ++ Using :keyword:`as` and :keyword:`with` as identifiers triggers a warning. To ++ use them as keywords, enable the ``with_statement`` future feature . ++ ++.. versionchanged:: 2.6 ++ :keyword:`as` and :keyword:`with` are full keywords. + + + .. _id-classes: +diff -r 8527427914a2 Doc/reference/simple_stmts.rst +--- a/Doc/reference/simple_stmts.rst ++++ b/Doc/reference/simple_stmts.rst +@@ -352,7 +352,7 @@ + del_stmt: "del" `target_list` + + Deletion is recursively defined very similar to the way assignment is defined. +-Rather that spelling it out in full details, here are some hints. ++Rather than spelling it out in full details, here are some hints. + + Deletion of a target list recursively deletes each target, from left to right. + +@@ -706,7 +706,7 @@ + second argument to :meth:`find_module` is given as the value of the + :attr:`__path__` attribute from the parent package (everything up to the last + dot in the name of the module being imported). If a finder can find the module +-it returns a :term:`loader` (discussed later) or returns :keyword:`None`. ++it returns a :term:`loader` (discussed later) or returns ``None``. + + .. index:: + single: sys.path_hooks +@@ -733,11 +733,11 @@ + the list with a single argument of the path, returning a finder or raises + :exc:`ImportError`. If a finder is returned then it is cached in + :data:`sys.path_importer_cache` and then used for that path entry. If no finder +-can be found but the path exists then a value of :keyword:`None` is ++can be found but the path exists then a value of ``None`` is + stored in :data:`sys.path_importer_cache` to signify that an implicit, + file-based finder that handles modules stored as individual files should be + used for that path. If the path does not exist then a finder which always +-returns :keyword:`None` is placed in the cache for the path. ++returns `None`` is placed in the cache for the path. + + .. index:: + single: loader +diff -r 8527427914a2 Doc/tools/sphinxext/indexcontent.html +--- a/Doc/tools/sphinxext/indexcontent.html ++++ b/Doc/tools/sphinxext/indexcontent.html +@@ -24,8 +24,6 @@ + information for installers & sys-admins

+ +- + + +diff -r 8527427914a2 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 8527427914a2 Doc/tools/sphinxext/pyspecific.py +--- a/Doc/tools/sphinxext/pyspecific.py ++++ b/Doc/tools/sphinxext/pyspecific.py +@@ -5,13 +5,15 @@ + + Sphinx extension with Python doc-specific markup. + +- :copyright: 2008, 2009 by Georg Brandl. ++ :copyright: 2008, 2009, 2010 by Georg Brandl. + :license: Python license. + """ + + ISSUE_URI = 'http://bugs.python.org/issue%s' ++SOURCE_URI = 'http://hg.python.org/cpython/file/2.7/%s' + + from docutils import nodes, utils ++from sphinx.util.nodes import split_explicit_title + + # monkey-patch reST parser to disable alphabetic and roman enumerated lists + from docutils.parsers.rst.states import Body +@@ -44,6 +46,16 @@ + return [refnode], [] + + ++# Support for linking to Python source files easily ++ ++def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): ++ has_t, title, target = split_explicit_title(text) ++ title = utils.unescape(title) ++ target = utils.unescape(target) ++ refnode = nodes.reference(title, title, refuri=SOURCE_URI % target) ++ return [refnode], [] ++ ++ + # Support for marking up implementation details + + from sphinx.util.compat import Directive +@@ -72,26 +84,85 @@ + 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 ++from sphinx.util.compat import Directive ++ ++versionlabels['deprecated-removed'] = \ ++ 'Deprecated since version %s, will be removed in version %s' ++ ++class DeprecatedRemoved(Directive): ++ has_content = True ++ required_arguments = 2 ++ optional_arguments = 1 ++ final_argument_whitespace = True ++ option_spec = {} ++ ++ def run(self): ++ node = addnodes.versionmodified() ++ node.document = self.state.document ++ node['type'] = 'deprecated-removed' ++ version = (self.arguments[0], self.arguments[1]) ++ node['version'] = version ++ if len(self.arguments) == 3: ++ inodes, messages = self.state.inline_text(self.arguments[2], ++ self.lineno+1) ++ node.extend(inodes) ++ if self.content: ++ self.state.nested_parse(self.content, self.content_offset, node) ++ ret = [node] + messages ++ else: ++ ret = [node] ++ env = self.state.document.settings.env ++ env.note_versionchange('deprecated', version[0], node, self.lineno) ++ return ret ++ ++ + # Support for building "topic help" for pydoc + + pydoc_topic_labels = [ + 'assert', 'assignment', 'atom-identifiers', 'atom-literals', + 'attribute-access', 'attribute-references', 'augassign', 'binary', + 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object', +- 'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans', +- 'break', 'callable-types', 'calls', 'class', 'coercion-rules', +- 'comparisons', 'compound', 'context-managers', 'continue', 'conversions', +- 'customization', 'debugger', 'del', 'dict', 'dynamic-features', 'else', +- 'exceptions', 'exec', 'execmodel', 'exprlists', 'floating', 'for', +- 'formatstrings', 'function', 'global', 'id-classes', 'identifiers', 'if', +- 'imaginary', 'import', 'in', 'integers', 'lambda', 'lists', 'naming', +- 'numbers', 'numeric-types', 'objects', 'operator-summary', 'pass', 'power', +- 'print', 'raise', 'return', 'sequence-methods', 'sequence-types', +- 'shifting', 'slicings', 'specialattrs', 'specialnames', +- 'string-conversions', 'string-methods', 'strings', 'subscriptions', 'truth', +- 'try', 'types', 'typesfunctions', 'typesmapping', 'typesmethods', +- 'typesmodules', 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', +- 'yield' ++ 'bltin-null-object', 'bltin-type-objects', 'booleans', ++ 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound', ++ 'context-managers', 'continue', 'conversions', 'customization', 'debugger', ++ 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel', ++ 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global', ++ 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers', ++ 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types', ++ 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return', ++ 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames', ++ 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types', ++ 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules', ++ 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield' + ] + + from os import path +@@ -121,16 +192,16 @@ + for label in self.status_iterator(pydoc_topic_labels, + 'building topics... ', + length=len(pydoc_topic_labels)): +- if label not in self.env.labels: ++ if label not in self.env.domaindata['std']['labels']: + self.warn('label %r not in documentation' % label) + continue +- docname, labelid, sectname = self.env.labels[label] ++ docname, labelid, sectname = self.env.domaindata['std']['labels'][label] + doctree = self.env.get_and_resolve_doctree(docname, self) + document = new_document('
') + document.append(doctree.ids[labelid]) + destination = StringOutput(encoding='utf-8') + writer.write(document, destination) +- self.topics[label] = writer.output ++ self.topics[label] = str(writer.output) + + def finish(self): + f = open(path.join(self.outdir, 'topics.py'), 'w') +@@ -149,9 +220,8 @@ + # Support for documenting Opcodes + + import re +-from sphinx import addnodes + +-opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)\s*\((.*)\)') ++opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?') + + def parse_opcode_signature(env, sig, signode): + """Transform an opcode signature into RST nodes.""" +@@ -160,17 +230,48 @@ + raise ValueError + opname, arglist = m.groups() + signode += addnodes.desc_name(opname, opname) +- paramlist = addnodes.desc_parameterlist() +- signode += paramlist +- paramlist += addnodes.desc_parameter(arglist, arglist) ++ if arglist is not None: ++ paramlist = addnodes.desc_parameterlist() ++ signode += paramlist ++ paramlist += addnodes.desc_parameter(arglist, arglist) + return opname.strip() + + ++# Support for documenting pdb commands ++ ++pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)') ++ ++# later... ++#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers ++# [.,:]+ | # punctuation ++# [\[\]()] | # parens ++# \s+ # whitespace ++# ''', re.X) ++ ++def parse_pdb_command(env, sig, signode): ++ """Transform a pdb command signature into RST nodes.""" ++ m = pdbcmd_sig_re.match(sig) ++ if m is None: ++ raise ValueError ++ name, args = m.groups() ++ fullname = name.replace('(', '').replace(')', '') ++ signode += addnodes.desc_name(name, name) ++ if args: ++ signode += addnodes.desc_addname(' '+args, ' '+args) ++ return fullname ++ ++ + def setup(app): + app.add_role('issue', issue_role) ++ app.add_role('source', source_role) + app.add_directive('impl-detail', ImplementationDetail) ++ app.add_directive('deprecated-removed', DeprecatedRemoved) + app.add_builder(PydocTopicsBuilder) + app.add_builder(suspicious.CheckSuspiciousMarkupBuilder) + app.add_description_unit('opcode', 'opcode', '%s (opcode)', + parse_opcode_signature) ++ 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) +diff -r 8527427914a2 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 8527427914a2 Doc/tools/sphinxext/susp-ignored.csv +--- a/Doc/tools/sphinxext/susp-ignored.csv ++++ b/Doc/tools/sphinxext/susp-ignored.csv +@@ -5,7 +5,6 @@ + c-api/sequence,,:i2,o[i1:i2] = v + c-api/sequence,,:i2,del o[i1:i2] + c-api/unicode,,:end,str[start:end] +-distutils/apiref,,:action,http://pypi.python.org/pypi?:action=list_classifiers + distutils/setupscript,,::, + extending/embedding,,:numargs,"if(!PyArg_ParseTuple(args, "":numargs""))" + extending/extending,,:set,"if (PyArg_ParseTuple(args, ""O:set_callback"", &temp)) {" +@@ -165,35 +164,6 @@ + whatsnew/2.5,,:step,[start:stop:step] + whatsnew/2.5,,:stop,[start:stop:step] + distutils/examples,267,`,This is the description of the ``foobar`` package. +-documenting/fromlatex,39,:func,:func:`str(object)` +-documenting/fromlatex,39,`,:func:`str(object)` +-documenting/fromlatex,39,`,``str(object)`` +-documenting/fromlatex,55,.. deprecated:,.. deprecated:: 2.5 +-documenting/fromlatex,66,.. note:,.. note:: +-documenting/fromlatex,76,:samp,":samp:`open({filename}, {mode})`" +-documenting/fromlatex,76,`,":samp:`open({filename}, {mode})`" +-documenting/fromlatex,80,`,``'c'`` +-documenting/fromlatex,80,`,`Title `_ +-documenting/fromlatex,80,`,``code`` +-documenting/fromlatex,80,`,`Title `_ +-documenting/fromlatex,99,:file,:file:`C:\\Temp\\my.tmp` +-documenting/fromlatex,99,`,:file:`C:\\Temp\\my.tmp` +-documenting/fromlatex,99,`,"``open(""C:\Temp\my.tmp"")``" +-documenting/fromlatex,129,.. function:,.. function:: do_foo(bar) +-documenting/fromlatex,141,.. function:,".. function:: open(filename[, mode[, buffering]])" +-documenting/fromlatex,152,.. function:,.. function:: foo_* +-documenting/fromlatex,152,:noindex,:noindex: +-documenting/fromlatex,162,.. describe:,.. describe:: a == b +-documenting/fromlatex,168,.. cmdoption:,.. cmdoption:: -O +-documenting/fromlatex,168,.. envvar:,.. envvar:: PYTHONINSPECT +-documenting/rest,33,`,``text`` +-documenting/rest,47,:rolename,:rolename:`content` +-documenting/rest,47,`,:rolename:`content` +-documenting/rest,103,::,This is a normal text paragraph. The next paragraph is a code sample:: +-documenting/rest,130,`,`Link text `_ +-documenting/rest,187,.. function:,.. function:: foo(x) +-documenting/rest,187,:bar,:bar: no +-documenting/rest,208,.. rubric:,.. rubric:: Footnotes + faq/programming,,:reduce,"print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y," + faq/programming,,:reduce,"Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro," + faq/programming,,:chr,">=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(" +@@ -222,81 +192,7 @@ + whatsnew/2.7,862,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0" + whatsnew/2.7,,::,>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo') + whatsnew/2.7,,::,"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]'," +-documenting/markup,33,.. sectionauthor:,.. sectionauthor:: Guido van Rossum +-documenting/markup,42,:mod,:mod:`parrot` -- Dead parrot access +-documenting/markup,42,`,:mod:`parrot` -- Dead parrot access +-documenting/markup,42,.. module:,.. module:: parrot +-documenting/markup,42,:platform,":platform: Unix, Windows" +-documenting/markup,42,:synopsis,:synopsis: Analyze and reanimate dead parrots. +-documenting/markup,42,.. moduleauthor:,.. moduleauthor:: Eric Cleese +-documenting/markup,42,.. moduleauthor:,.. moduleauthor:: John Idle +-documenting/markup,88,:noindex,:noindex: +-documenting/markup,95,.. function:,.. function:: spam(eggs) +-documenting/markup,95,:noindex,:noindex: +-documenting/markup,101,.. method:,.. method:: FileInput.input(...) +-documenting/markup,121,.. cfunction:,".. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)" +-documenting/markup,131,.. cmember:,.. cmember:: PyObject* PyTypeObject.tp_bases +-documenting/markup,150,.. cvar:,.. cvar:: PyObject* PyClass_Type +-documenting/markup,179,.. function:,".. function:: Timer.repeat([repeat=3[, number=1000000]])" +-documenting/markup,209,.. cmdoption:,.. cmdoption:: -m +-documenting/markup,227,.. describe:,.. describe:: opcode +-documenting/markup,256,.. highlightlang:,.. highlightlang:: c +-documenting/markup,276,.. literalinclude:,.. literalinclude:: example.py +-documenting/markup,291,:rolename,:rolename:`content` +-documenting/markup,291,`,:rolename:`content` +-documenting/markup,296,:role,:role:`title ` +-documenting/markup,296,`,:role:`title ` +-documenting/markup,302,:meth,:meth:`~Queue.Queue.get` +-documenting/markup,302,`,:meth:`~Queue.Queue.get` +-documenting/markup,350,:func,:func:`filter` +-documenting/markup,350,`,:func:`filter` +-documenting/markup,350,:func,:func:`foo.filter` +-documenting/markup,350,`,:func:`foo.filter` +-documenting/markup,356,:func,:func:`open` +-documenting/markup,356,`,:func:`open` +-documenting/markup,356,:func,:func:`.open` +-documenting/markup,356,`,:func:`.open` +-documenting/markup,435,:file,... is installed in :file:`/usr/lib/python2.{x}/site-packages` ... +-documenting/markup,435,`,... is installed in :file:`/usr/lib/python2.{x}/site-packages` ... +-documenting/markup,454,:kbd,:kbd:`C-x C-f` +-documenting/markup,454,`,:kbd:`C-x C-f` +-documenting/markup,454,:kbd,:kbd:`Control-x Control-f` +-documenting/markup,454,`,:kbd:`Control-x Control-f` +-documenting/markup,468,:mailheader,:mailheader:`Content-Type` +-documenting/markup,468,`,:mailheader:`Content-Type` +-documenting/markup,477,:manpage,:manpage:`ls(1)` +-documenting/markup,477,`,:manpage:`ls(1)` +-documenting/markup,493,:menuselection,:menuselection:`Start --> Programs` +-documenting/markup,493,`,:menuselection:`Start --> Programs` +-documenting/markup,508,`,``code`` +-documenting/markup,526,:file,:file: +-documenting/markup,526,`,``code`` +-documenting/markup,561,:ref,:ref:`label-name` +-documenting/markup,561,`,:ref:`label-name` +-documenting/markup,565,:ref,"It refers to the section itself, see :ref:`my-reference-label`." +-documenting/markup,565,`,"It refers to the section itself, see :ref:`my-reference-label`." +-documenting/markup,574,:ref,:ref: +-documenting/markup,595,.. note:,.. note:: +-documenting/markup,622,.. versionadded:,.. versionadded:: 2.5 +-documenting/markup,647,::,.. impl-detail:: +-documenting/markup,647,::,.. impl-detail:: This shortly mentions an implementation detail. +-documenting/markup,667,.. seealso:,.. seealso:: +-documenting/markup,667,:mod,Module :mod:`zipfile` +-documenting/markup,667,`,Module :mod:`zipfile` +-documenting/markup,667,:mod,Documentation of the :mod:`zipfile` standard module. +-documenting/markup,667,`,Documentation of the :mod:`zipfile` standard module. +-documenting/markup,667,`,"`GNU tar manual, Basic Tar Format `_" +-documenting/markup,681,.. centered:,.. centered:: +-documenting/markup,726,.. toctree:,.. toctree:: +-documenting/markup,726,:maxdepth,:maxdepth: 2 +-documenting/markup,742,.. index:,.. index:: +-documenting/markup,772,.. index:,".. index:: BNF, grammar, syntax, notation" +-documenting/markup,803,`,"unaryneg ::= ""-"" `integer`" +-documenting/markup,808,.. productionlist:,.. productionlist:: +-documenting/markup,808,`,"try1_stmt: ""try"" "":"" `suite`" +-documenting/markup,808,`,": (""except"" [`expression` ["","" `target`]] "":"" `suite`)+" +-documenting/markup,808,`,": [""else"" "":"" `suite`]" +-documenting/markup,808,`,": [""finally"" "":"" `suite`]" +-documenting/markup,808,`,"try2_stmt: ""try"" "":"" `suite`" +-documenting/markup,808,`,": ""finally"" "":"" `suite`" ++howto/pyporting,75,::,# make sure to use :: Python *and* :: Python :: 3 so ++howto/pyporting,75,::,"'Programming Language :: Python'," ++howto/pyporting,75,::,'Programming Language :: Python :: 3' + library/urllib2,67,:close,Connection:close +diff -r 8527427914a2 Doc/tutorial/classes.rst +--- a/Doc/tutorial/classes.rst ++++ b/Doc/tutorial/classes.rst +@@ -409,8 +409,8 @@ + self.add(x) + + Methods may reference global names in the same way as ordinary functions. The +-global scope associated with a method is the module containing the class +-definition. (The class itself is never used as a global scope.) While one ++global scope associated with a method is the module containing its ++definition. (A class is never used as a global scope.) While one + rarely encounters a good reason for using global data in a method, there are + many legitimate uses of the global scope: for one thing, functions and modules + imported into the global scope can be used by methods, as well as functions and +@@ -553,6 +553,28 @@ + without regard to the syntactic position of the identifier, as long as it + occurs within the definition of a class. + ++Name mangling is helpful for letting subclasses override methods without ++breaking intraclass method calls. For example:: ++ ++ class Mapping: ++ def __init__(self, iterable): ++ self.items_list = [] ++ self.__update(iterable) ++ ++ def update(self, iterable): ++ for item in iterable: ++ self.items_list.append(item) ++ ++ __update = update # private copy of original update() method ++ ++ class MappingSubclass(Mapping): ++ ++ def update(self, keys, values): ++ # provides new signature for update() ++ # but does not break __init__() ++ for item in zip(keys, values): ++ self.items_list.append(item) ++ + Note that the mangling rules are designed mostly to avoid accidents; it still is + possible to access or modify a variable that is considered private. This can + even be useful in special circumstances, such as in the debugger. +diff -r 8527427914a2 Doc/tutorial/controlflow.rst +--- a/Doc/tutorial/controlflow.rst ++++ b/Doc/tutorial/controlflow.rst +@@ -156,6 +156,9 @@ + 8 equals 2 * 4 + 9 equals 3 * 3 + ++(Yes, this is the correct code. Look closely: the ``else`` clause belongs to ++the :keyword:`for` loop, **not** the :keyword:`if` statement.) ++ + + .. _tut-pass: + +@@ -380,8 +383,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, +@@ -389,26 +392,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 8527427914a2 Doc/tutorial/datastructures.rst +--- a/Doc/tutorial/datastructures.rst ++++ b/Doc/tutorial/datastructures.rst +@@ -170,8 +170,8 @@ + ``filter(function, sequence)`` returns a sequence consisting of those items from + the sequence for which ``function(item)`` is true. If *sequence* is a + :class:`string` or :class:`tuple`, the result will be of the same type; +-otherwise, it is always a :class:`list`. For example, to compute primes up +-to 25:: ++otherwise, it is always a :class:`list`. For example, to compute a sequence of ++numbers not divisible by 2 and 3:: + + >>> def f(x): return x % 2 != 0 and x % 3 != 0 + ... +@@ -235,89 +235,139 @@ + List Comprehensions + ------------------- + +-List comprehensions provide a concise way to create lists without resorting to +-use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list +-definition tends often to be clearer than lists built using those constructs. +-Each list comprehension consists of 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. :: ++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 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:: ++ ++ >>> [(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)] ++ ++and it's equivalent to: ++ ++ >>> 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)] ++ ++Note how the order of the :keyword:`for` and :keyword:`if` statements is the ++same in both these snippets. ++ ++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'] +- >>> vec = [2, 4, 6] +- >>> [3*x for x in vec] +- [6, 12, 18] +- >>> [3*x for x in vec if x > 3] +- [12, 18] +- >>> [3*x for x in vec if x < 2] +- [] +- >>> [[x,x**2] for x in vec] +- [[2, 4], [4, 16], [6, 36]] +- >>> [x, x**2 for x in vec] # error - parens required for tuples +- File "", line 1, in ? +- [x, x**2 for x in vec] ++ >>> # 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 ++ [x, x**2 for x in range(6)] + ^ + SyntaxError: invalid syntax +- >>> [(x, x**2) for x in vec] +- [(2, 4), (4, 16), (6, 36)] +- >>> 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] ++ >>> # 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] + +-List comprehensions are much more flexible than :func:`map` and can be applied +-to complex expressions and nested functions:: ++List comprehensions can contain complex expressions and nested functions:: + +- >>> [str(round(355/113.0, 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], +- 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:: + +- >>> 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 8527427914a2 Doc/tutorial/inputoutput.rst +--- a/Doc/tutorial/inputoutput.rst ++++ b/Doc/tutorial/inputoutput.rst +@@ -207,7 +207,7 @@ + --------------------- + + The ``%`` operator can also be used for string formatting. It interprets the +-left argument much like a :cfunc:`sprintf`\ -style format string to be applied ++left argument much like a :c:func:`sprintf`\ -style format string to be applied + to the right argument, and returns the string resulting from this formatting + operation. For example:: + +diff -r 8527427914a2 Doc/tutorial/interactive.rst +--- a/Doc/tutorial/interactive.rst ++++ b/Doc/tutorial/interactive.rst +@@ -156,17 +156,18 @@ + quotes, etc., would also be useful. + + One alternative enhanced interactive interpreter that has been around for quite +-some time is `IPython`_, which features tab completion, object exploration and ++some time is IPython_, which features tab completion, object exploration and + advanced history management. It can also be thoroughly customized and embedded + into other applications. Another similar enhanced interactive environment is +-`bpython`_. ++bpython_. + + + .. rubric:: Footnotes + + .. [#] Python will execute the contents of a file identified by the + :envvar:`PYTHONSTARTUP` environment variable when you start an interactive +- interpreter. ++ interpreter. To customize Python even for non-interactive mode, see ++ :ref:`tut-customize`. + + + .. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html +diff -r 8527427914a2 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: +@@ -166,6 +165,8 @@ + suppressed. + + ++.. _tut-source-encoding: ++ + Source Code Encoding + -------------------- + +@@ -240,7 +241,29 @@ + execfile(filename) + + ++.. _tut-customize: ++ ++The Customization Modules ++------------------------- ++ ++Python provides two hooks to let you customize it: :mod:`sitecustomize` and ++:mod:`usercustomize`. To see how it works, you need first to find the location ++of your user site-packages directory. Start Python and run this code: ++ ++ >>> import site ++ >>> site.getusersitepackages() ++ '/home/user/.local/lib/python3.2/site-packages' ++ ++Now you can create a file named :file:`usercustomize.py` in that directory and ++put anything you want in it. It will affect every invocation of Python, unless ++it is started with the :option:`-s` option to disable the automatic import. ++ ++:mod:`sitecustomize` works in the same way, but is typically created by an ++administrator of the computer in the global site-packages directory, and is ++imported before :mod:`usercustomize`. See the documentation of the :mod:`site` ++module for more details. ++ ++ + .. rubric:: Footnotes + + .. [#] A problem with the GNU Readline package may prevent this. +- +diff -r 8527427914a2 Doc/tutorial/introduction.rst +--- a/Doc/tutorial/introduction.rst ++++ b/Doc/tutorial/introduction.rst +@@ -240,13 +240,6 @@ + This is a rather long string containing\n\ + several lines of text much as you would do in C. + +-The interpreter prints the result of string operations in the same way as they +-are typed for input: inside quotes, and with quotes and other funny characters +-escaped by backslashes, to show the precise value. The string is enclosed in +-double quotes if the string contains a single quote and no double quotes, else +-it's enclosed in single quotes. (The :keyword:`print` statement, described +-later, can be used to write strings without quotes or escapes.) +- + Strings can be concatenated (glued together) with the ``+`` operator, and + repeated with ``*``:: + +@@ -637,13 +630,13 @@ + and ``!=`` (not equal to). + + * The *body* of the loop is *indented*: indentation is Python's way of grouping +- statements. Python does not (yet!) provide an intelligent input line editing +- facility, so you have to type a tab or space(s) for each indented line. In +- practice you will prepare more complicated input for Python with a text editor; +- most text editors have an auto-indent facility. When a compound statement is +- entered interactively, it must be followed by a blank line to indicate +- completion (since the parser cannot guess when you have typed the last line). +- Note that each line within a basic block must be indented by the same amount. ++ statements. At the interactive prompt, you have to type a tab or space(s) for ++ each indented line. In practice you will prepare more complicated input ++ for Python with a text editor; all decent text editors have an auto-indent ++ facility. When a compound statement is entered interactively, it must be ++ followed by a blank line to indicate completion (since the parser cannot ++ guess when you have typed the last line). Note that each line within a basic ++ block must be indented by the same amount. + + * The :keyword:`print` statement writes the value of the expression(s) it is + given. It differs from just writing the expression you want to write (as we did +diff -r 8527427914a2 Doc/tutorial/modules.rst +--- a/Doc/tutorial/modules.rst ++++ b/Doc/tutorial/modules.rst +@@ -155,23 +155,22 @@ + + .. index:: triple: module; search; path + +-When a module named :mod:`spam` is imported, the interpreter searches for a file +-named :file:`spam.py` in the current directory, and then in the list of +-directories specified by the environment variable :envvar:`PYTHONPATH`. This +-has the same syntax as the shell variable :envvar:`PATH`, that is, a list of +-directory names. When :envvar:`PYTHONPATH` is not set, or when the file is not +-found there, the search continues in an installation-dependent default path; on +-Unix, this is usually :file:`.:/usr/local/lib/python`. ++When a module named :mod:`spam` is imported, the interpreter first searches for ++a built-in module with that name. If not found, it then searches for a file ++named :file:`spam.py` in a list of directories given by the variable ++:data:`sys.path`. :data:`sys.path` is initialized from these locations: + +-Actually, modules are searched in the list of directories given by the variable +-``sys.path`` which is initialized from the directory containing the input script +-(or the current directory), :envvar:`PYTHONPATH` and the installation- dependent +-default. This allows Python programs that know what they're doing to modify or +-replace the module search path. Note that because the directory containing the +-script being run is on the search path, it is important that the script not have +-the same name as a standard module, or Python will attempt to load the script as +-a module when that module is imported. This will generally be an error. See +-section :ref:`tut-standardmodules` for more information. ++* the directory containing the input script (or the current directory). ++* :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the ++ shell variable :envvar:`PATH`). ++* the installation-dependent default. ++ ++After initialization, Python programs can modify :data:`sys.path`. The ++directory containing the script being run is placed at the beginning of the ++search path, ahead of the standard library path. This means that scripts in that ++directory will be loaded instead of modules of the same name in the library ++directory. This is an error unless the replacement is intended. See section ++:ref:`tut-standardmodules` for more information. + + + "Compiled" Python files +diff -r 8527427914a2 Doc/using/cmdline.rst +--- a/Doc/using/cmdline.rst ++++ b/Doc/using/cmdline.rst +@@ -255,7 +255,8 @@ + + .. cmdoption:: -s + +- Don't add user site directory to sys.path ++ Don't add the :data:`user site-packages directory ` to ++ :data:`sys.path`. + + .. versionadded:: 2.6 + +@@ -511,7 +512,7 @@ + .. envvar:: PYTHONCASEOK + + If this is set, Python ignores case in :keyword:`import` statements. This +- only works on Windows. ++ only works on Windows, OS X, OS/2, and RiscOS. + + + .. envvar:: PYTHONDONTWRITEBYTECODE +@@ -532,7 +533,8 @@ + + .. envvar:: PYTHONNOUSERSITE + +- If this is set, Python won't add the user site directory to sys.path ++ If this is set, Python won't add the :data:`user site-packages directory ++ ` to :data:`sys.path`. + + .. versionadded:: 2.6 + +@@ -543,7 +545,10 @@ + + .. envvar:: PYTHONUSERBASE + +- Sets the base directory for the user site directory ++ Defines the :data:`user base directory `, which is used to ++ compute the path of the :data:`user site-packages directory ` ++ and :ref:`Distutils installation paths ` for ``python ++ setup.py install --user``. + + .. versionadded:: 2.6 + +@@ -569,7 +574,7 @@ + ~~~~~~~~~~~~~~~~~~~~ + + Setting these variables only has an effect in a debug build of Python, that is, +-if Python was configured with the :option:`--with-pydebug` build option. ++if Python was configured with the ``--with-pydebug`` build option. + + .. envvar:: PYTHONTHREADDEBUG + +diff -r 8527427914a2 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: + +@@ -26,11 +26,11 @@ + + .. seealso:: + +- http://www.linux.com/articles/60383 ++ http://www.debian.org/doc/manuals/maint-guide/first.en.html + for Debian users + http://linuxmafia.com/pub/linux/suse-linux-internals/chapter35.html + for OpenSuse users +- http://docs.fedoraproject.org/drafts/rpm-guide-en/ch-creating-rpms.html ++ http://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html + for Fedora users + http://www.slackbook.org/html/package-management-making-packages.html + for Slackware users +@@ -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,17 +65,18 @@ + + 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:: +diff -r 8527427914a2 Doc/using/windows.rst +--- a/Doc/using/windows.rst ++++ b/Doc/using/windows.rst +@@ -47,9 +47,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 + +@@ -292,7 +292,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 8527427914a2 Doc/whatsnew/2.2.rst +--- a/Doc/whatsnew/2.2.rst ++++ b/Doc/whatsnew/2.2.rst +@@ -754,7 +754,7 @@ + + * Classes can define methods called :meth:`__truediv__` and :meth:`__floordiv__` + to overload the two division operators. At the C level, there are also slots in +- the :ctype:`PyNumberMethods` structure so extension types can define the two ++ the :c:type:`PyNumberMethods` structure so extension types can define the two + operators. + + * Python 2.2 supports some command-line arguments for testing whether code will +@@ -983,7 +983,7 @@ + Jun-ichiro "itojun" Hagino.) + + * Two new format characters were added to the :mod:`struct` module for 64-bit +- integers on platforms that support the C :ctype:`long long` type. ``q`` is for ++ integers on platforms that support the C :c:type:`long long` type. ``q`` is for + a signed 64-bit integer, and ``Q`` is for an unsigned one. The value is + returned in Python's long integer type. (Contributed by Tim Peters.) + +@@ -1057,16 +1057,16 @@ + at much higher speeds than Python-based functions and should reduce the overhead + of profiling and tracing. This will be of interest to authors of development + environments for Python. Two new C functions were added to Python's API, +- :cfunc:`PyEval_SetProfile` and :cfunc:`PyEval_SetTrace`. The existing ++ :c:func:`PyEval_SetProfile` and :c:func:`PyEval_SetTrace`. The existing + :func:`sys.setprofile` and :func:`sys.settrace` functions still exist, and have + simply been changed to use the new C-level interface. (Contributed by Fred L. + Drake, Jr.) + + * Another low-level API, primarily of interest to implementors of Python +- debuggers and development tools, was added. :cfunc:`PyInterpreterState_Head` and +- :cfunc:`PyInterpreterState_Next` let a caller walk through all the existing +- interpreter objects; :cfunc:`PyInterpreterState_ThreadHead` and +- :cfunc:`PyThreadState_Next` allow looping over all the thread states for a given ++ debuggers and development tools, was added. :c:func:`PyInterpreterState_Head` and ++ :c:func:`PyInterpreterState_Next` let a caller walk through all the existing ++ interpreter objects; :c:func:`PyInterpreterState_ThreadHead` and ++ :c:func:`PyThreadState_Next` allow looping over all the thread states for a given + interpreter. (Contributed by David Beazley.) + + * The C-level interface to the garbage collector has been changed to make it +@@ -1078,19 +1078,19 @@ + + To upgrade an extension module to the new API, perform the following steps: + +-* Rename :cfunc:`Py_TPFLAGS_GC` to :cfunc:`PyTPFLAGS_HAVE_GC`. ++* Rename :c:func:`Py_TPFLAGS_GC` to :c:func:`PyTPFLAGS_HAVE_GC`. + +-* Use :cfunc:`PyObject_GC_New` or :cfunc:`PyObject_GC_NewVar` to allocate +- objects, and :cfunc:`PyObject_GC_Del` to deallocate them. ++* Use :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar` to allocate ++ objects, and :c:func:`PyObject_GC_Del` to deallocate them. + +-* Rename :cfunc:`PyObject_GC_Init` to :cfunc:`PyObject_GC_Track` and +- :cfunc:`PyObject_GC_Fini` to :cfunc:`PyObject_GC_UnTrack`. ++* Rename :c:func:`PyObject_GC_Init` to :c:func:`PyObject_GC_Track` and ++ :c:func:`PyObject_GC_Fini` to :c:func:`PyObject_GC_UnTrack`. + +-* Remove :cfunc:`PyGC_HEAD_SIZE` from object size calculations. ++* Remove :c:func:`PyGC_HEAD_SIZE` from object size calculations. + +-* Remove calls to :cfunc:`PyObject_AS_GC` and :cfunc:`PyObject_FROM_GC`. ++* Remove calls to :c:func:`PyObject_AS_GC` and :c:func:`PyObject_FROM_GC`. + +-* A new ``et`` format sequence was added to :cfunc:`PyArg_ParseTuple`; ``et`` ++* A new ``et`` format sequence was added to :c:func:`PyArg_ParseTuple`; ``et`` + takes both a parameter and an encoding name, and converts the parameter to the + given encoding if the parameter turns out to be a Unicode string, or leaves it + alone if it's an 8-bit string, assuming it to already be in the desired +@@ -1099,10 +1099,10 @@ + specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS + support on Windows described in the following section.) + +-* A different argument parsing function, :cfunc:`PyArg_UnpackTuple`, has been ++* A different argument parsing function, :c:func:`PyArg_UnpackTuple`, has been + added that's simpler and presumably faster. Instead of specifying a format + string, the caller simply gives the minimum and maximum number of arguments +- expected, and a set of pointers to :ctype:`PyObject\*` variables that will be ++ expected, and a set of pointers to :c:type:`PyObject\*` variables that will be + filled in with argument values. + + * Two new flags :const:`METH_NOARGS` and :const:`METH_O` are available in method +@@ -1111,14 +1111,14 @@ + corresponding method that uses :const:`METH_VARARGS`. Also, the old + :const:`METH_OLDARGS` style of writing C methods is now officially deprecated. + +-* Two new wrapper functions, :cfunc:`PyOS_snprintf` and :cfunc:`PyOS_vsnprintf` ++* Two new wrapper functions, :c:func:`PyOS_snprintf` and :c:func:`PyOS_vsnprintf` + were added to provide cross-platform implementations for the relatively new +- :cfunc:`snprintf` and :cfunc:`vsnprintf` C lib APIs. In contrast to the standard +- :cfunc:`sprintf` and :cfunc:`vsprintf` functions, the Python versions check the ++ :c:func:`snprintf` and :c:func:`vsnprintf` C lib APIs. In contrast to the standard ++ :c:func:`sprintf` and :c:func:`vsprintf` functions, the Python versions check the + bounds of the buffer used to protect against buffer overruns. (Contributed by + M.-A. Lemburg.) + +-* The :cfunc:`_PyTuple_Resize` function has lost an unused parameter, so now it ++* The :c:func:`_PyTuple_Resize` function has lost an unused parameter, so now it + takes 2 parameters instead of 3. The third argument was never used, and can + simply be discarded when porting code from earlier versions to Python 2.2. + +@@ -1219,7 +1219,7 @@ + operator, but these features were rarely used and therefore buggy. The + :meth:`tolist` method and the :attr:`start`, :attr:`stop`, and :attr:`step` + attributes are also being deprecated. At the C level, the fourth argument to +- the :cfunc:`PyRange_New` function, ``repeat``, has also been deprecated. ++ the :c:func:`PyRange_New` function, ``repeat``, has also been deprecated. + + * There were a bunch of patches to the dictionary implementation, mostly to fix + potential core dumps if a dictionary contains objects that sneakily changed +@@ -1242,8 +1242,8 @@ + up to display the output. This patch makes it possible to import such scripts, + in case they're also usable as modules. (Implemented by David Bolen.) + +-* On platforms where Python uses the C :cfunc:`dlopen` function to load +- extension modules, it's now possible to set the flags used by :cfunc:`dlopen` ++* On platforms where Python uses the C :c:func:`dlopen` function to load ++ extension modules, it's now possible to set the flags used by :c:func:`dlopen` + using the :func:`sys.getdlopenflags` and :func:`sys.setdlopenflags` functions. + (Contributed by Bram Stolk.) + +diff -r 8527427914a2 Doc/whatsnew/2.3.rst +--- a/Doc/whatsnew/2.3.rst ++++ b/Doc/whatsnew/2.3.rst +@@ -1797,8 +1797,8 @@ + + Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a + feature added to Python 2.1. Pymalloc is intended to be faster than the system +-:cfunc:`malloc` and to have less memory overhead for allocation patterns typical +-of Python programs. The allocator uses C's :cfunc:`malloc` function to get large ++:c:func:`malloc` and to have less memory overhead for allocation patterns typical ++of Python programs. The allocator uses C's :c:func:`malloc` function to get large + pools of memory and then fulfills smaller memory requests from these pools. + + In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by +@@ -1814,13 +1814,13 @@ + + There's one particularly common error that causes problems. There are a number + of memory allocation functions in Python's C API that have previously just been +-aliases for the C library's :cfunc:`malloc` and :cfunc:`free`, meaning that if ++aliases for the C library's :c:func:`malloc` and :c:func:`free`, meaning that if + you accidentally called mismatched functions the error wouldn't be noticeable. + When the object allocator is enabled, these functions aren't aliases of +-:cfunc:`malloc` and :cfunc:`free` any more, and calling the wrong function to ++:c:func:`malloc` and :c:func:`free` any more, and calling the wrong function to + free memory may get you a core dump. For example, if memory was allocated using +-:cfunc:`PyObject_Malloc`, it has to be freed using :cfunc:`PyObject_Free`, not +-:cfunc:`free`. A few modules included with Python fell afoul of this and had to ++:c:func:`PyObject_Malloc`, it has to be freed using :c:func:`PyObject_Free`, not ++:c:func:`free`. A few modules included with Python fell afoul of this and had to + be fixed; doubtless there are more third-party modules that will have the same + problem. + +@@ -1831,14 +1831,14 @@ + specifically for allocating Python objects. + + * To allocate and free an undistinguished chunk of memory use the "raw memory" +- family: :cfunc:`PyMem_Malloc`, :cfunc:`PyMem_Realloc`, and :cfunc:`PyMem_Free`. ++ family: :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc`, and :c:func:`PyMem_Free`. + + * The "object memory" family is the interface to the pymalloc facility described + above and is biased towards a large number of "small" allocations: +- :cfunc:`PyObject_Malloc`, :cfunc:`PyObject_Realloc`, and :cfunc:`PyObject_Free`. ++ :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and :c:func:`PyObject_Free`. + + * To allocate and free Python objects, use the "object" family +- :cfunc:`PyObject_New`, :cfunc:`PyObject_NewVar`, and :cfunc:`PyObject_Del`. ++ :c:func:`PyObject_New`, :c:func:`PyObject_NewVar`, and :c:func:`PyObject_Del`. + + Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging + features to catch memory overwrites and doubled frees in both extension modules +@@ -1877,10 +1877,10 @@ + (:file:`libpython2.3.so`) by supplying :option:`--enable-shared` when running + Python's :program:`configure` script. (Contributed by Ondrej Palkovsky.) + +-* The :cmacro:`DL_EXPORT` and :cmacro:`DL_IMPORT` macros are now deprecated. ++* The :c:macro:`DL_EXPORT` and :c:macro:`DL_IMPORT` macros are now deprecated. + Initialization functions for Python extension modules should now be declared +- using the new macro :cmacro:`PyMODINIT_FUNC`, while the Python core will +- generally use the :cmacro:`PyAPI_FUNC` and :cmacro:`PyAPI_DATA` macros. ++ using the new macro :c:macro:`PyMODINIT_FUNC`, while the Python core will ++ generally use the :c:macro:`PyAPI_FUNC` and :c:macro:`PyAPI_DATA` macros. + + * The interpreter can be compiled without any docstrings for the built-in + functions and modules by supplying :option:`--without-doc-strings` to the +@@ -1888,19 +1888,19 @@ + but will also mean that you can't get help for Python's built-ins. (Contributed + by Gustavo Niemeyer.) + +-* The :cfunc:`PyArg_NoArgs` macro is now deprecated, and code that uses it ++* The :c:func:`PyArg_NoArgs` macro is now deprecated, and code that uses it + should be changed. For Python 2.2 and later, the method definition table can + specify the :const:`METH_NOARGS` flag, signalling that there are no arguments, + and the argument checking can then be removed. If compatibility with pre-2.2 + versions of Python is important, the code could use ``PyArg_ParseTuple(args, + "")`` instead, but this will be slower than using :const:`METH_NOARGS`. + +-* :cfunc:`PyArg_ParseTuple` accepts new format characters for various sizes of +- unsigned integers: ``B`` for :ctype:`unsigned char`, ``H`` for :ctype:`unsigned +- short int`, ``I`` for :ctype:`unsigned int`, and ``K`` for :ctype:`unsigned ++* :c:func:`PyArg_ParseTuple` accepts new format characters for various sizes of ++ unsigned integers: ``B`` for :c:type:`unsigned char`, ``H`` for :c:type:`unsigned ++ short int`, ``I`` for :c:type:`unsigned int`, and ``K`` for :c:type:`unsigned + long long`. + +-* A new function, :cfunc:`PyObject_DelItemString(mapping, char \*key)` was added ++* A new function, :c:func:`PyObject_DelItemString(mapping, char \*key)` was added + as shorthand for ``PyObject_DelItem(mapping, PyString_New(key))``. + + * File objects now manage their internal string buffer differently, increasing +@@ -1910,7 +1910,7 @@ + + * It's now possible to define class and static methods for a C extension type by + setting either the :const:`METH_CLASS` or :const:`METH_STATIC` flags in a +- method's :ctype:`PyMethodDef` structure. ++ method's :c:type:`PyMethodDef` structure. + + * Python now includes a copy of the Expat XML parser's source code, removing any + dependence on a system version or local installation of Expat. +diff -r 8527427914a2 Doc/whatsnew/2.4.rst +--- a/Doc/whatsnew/2.4.rst ++++ b/Doc/whatsnew/2.4.rst +@@ -469,7 +469,7 @@ + ========================== + + Python has always supported floating-point (FP) numbers, based on the underlying +-C :ctype:`double` type, as a data type. However, while most programming ++C :c:type:`double` type, as a data type. However, while most programming + languages provide a floating-point type, many people (even programmers) are + unaware that floating-point numbers don't represent certain decimal fractions + accurately. The new :class:`Decimal` type can represent these fractions +@@ -498,7 +498,7 @@ + 5. + + Modern systems usually provide floating-point support that conforms to a +-standard called IEEE 754. C's :ctype:`double` type is usually implemented as a ++standard called IEEE 754. C's :c:type:`double` type is usually implemented as a + 64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This + means that numbers can only be specified to 52 bits of precision. If you're + trying to represent numbers whose expansion repeats endlessly, the expansion is +@@ -736,7 +736,7 @@ + However, the module was careful to not change the numeric locale because various + functions in Python's implementation required that the numeric locale remain set + to the ``'C'`` locale. Often this was because the code was using the C +-library's :cfunc:`atof` function. ++library's :c:func:`atof` function. + + Not setting the numeric locale caused trouble for extensions that used third- + party C libraries, however, because they wouldn't have the correct locale set. +@@ -746,11 +746,11 @@ + The solution described in the PEP is to add three new functions to the Python + API that perform ASCII-only conversions, ignoring the locale setting: + +-* :cfunc:`PyOS_ascii_strtod(str, ptr)` and :cfunc:`PyOS_ascii_atof(str, ptr)` +- both convert a string to a C :ctype:`double`. ++* :c:func:`PyOS_ascii_strtod(str, ptr)` and :c:func:`PyOS_ascii_atof(str, ptr)` ++ both convert a string to a C :c:type:`double`. + +-* :cfunc:`PyOS_ascii_formatd(buffer, buf_len, format, d)` converts a +- :ctype:`double` to an ASCII string. ++* :c:func:`PyOS_ascii_formatd(buffer, buf_len, format, d)` converts a ++ :c:type:`double` to an ASCII string. + + The code for these functions came from the GLib library + (http://library.gnome.org/devel/glib/stable/), whose developers kindly +@@ -938,7 +938,7 @@ + * The machinery for growing and shrinking lists was optimized for speed and for + space efficiency. Appending and popping from lists now runs faster due to more + efficient code paths and less frequent use of the underlying system +- :cfunc:`realloc`. List comprehensions also benefit. :meth:`list.extend` was ++ :c:func:`realloc`. List comprehensions also benefit. :meth:`list.extend` was + also optimized and no longer converts its argument into a temporary list before + extending the base list. (Contributed by Raymond Hettinger.) + +@@ -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 +@@ -1445,34 +1445,34 @@ + Some of the changes to Python's build process and to the C API are: + + * Three new convenience macros were added for common return values from +- extension functions: :cmacro:`Py_RETURN_NONE`, :cmacro:`Py_RETURN_TRUE`, and +- :cmacro:`Py_RETURN_FALSE`. (Contributed by Brett Cannon.) ++ extension functions: :c:macro:`Py_RETURN_NONE`, :c:macro:`Py_RETURN_TRUE`, and ++ :c:macro:`Py_RETURN_FALSE`. (Contributed by Brett Cannon.) + +-* Another new macro, :cmacro:`Py_CLEAR(obj)`, decreases the reference count of ++* Another new macro, :c:macro:`Py_CLEAR(obj)`, decreases the reference count of + *obj* and sets *obj* to the null pointer. (Contributed by Jim Fulton.) + +-* A new function, :cfunc:`PyTuple_Pack(N, obj1, obj2, ..., objN)`, constructs ++* A new function, :c:func:`PyTuple_Pack(N, obj1, obj2, ..., objN)`, constructs + tuples from a variable length argument list of Python objects. (Contributed by + Raymond Hettinger.) + +-* A new function, :cfunc:`PyDict_Contains(d, k)`, implements fast dictionary ++* A new function, :c:func:`PyDict_Contains(d, k)`, implements fast dictionary + lookups without masking exceptions raised during the look-up process. + (Contributed by Raymond Hettinger.) + +-* The :cmacro:`Py_IS_NAN(X)` macro returns 1 if its float or double argument ++* The :c:macro:`Py_IS_NAN(X)` macro returns 1 if its float or double argument + *X* is a NaN. (Contributed by Tim Peters.) + + * C code can avoid unnecessary locking by using the new +- :cfunc:`PyEval_ThreadsInitialized` function to tell if any thread operations ++ :c:func:`PyEval_ThreadsInitialized` function to tell if any thread operations + have been performed. If this function returns false, no lock operations are + needed. (Contributed by Nick Coghlan.) + +-* A new function, :cfunc:`PyArg_VaParseTupleAndKeywords`, is the same as +- :cfunc:`PyArg_ParseTupleAndKeywords` but takes a :ctype:`va_list` instead of a ++* A new function, :c:func:`PyArg_VaParseTupleAndKeywords`, is the same as ++ :c:func:`PyArg_ParseTupleAndKeywords` but takes a :c:type:`va_list` instead of a + number of arguments. (Contributed by Greg Chapman.) + + * A new method flag, :const:`METH_COEXISTS`, allows a function defined in slots +- to co-exist with a :ctype:`PyCFunction` having the same name. This can halve ++ to co-exist with a :c:type:`PyCFunction` having the same name. This can halve + the access time for a method such as :meth:`set.__contains__`. (Contributed by + Raymond Hettinger.) + +@@ -1486,8 +1486,8 @@ + though that processor architecture doesn't call that register "the TSC + register". (Contributed by Jeremy Hylton.) + +-* The :ctype:`tracebackobject` type has been renamed to +- :ctype:`PyTracebackObject`. ++* The :c:type:`tracebackobject` type has been renamed to ++ :c:type:`PyTracebackObject`. + + .. ====================================================================== + +diff -r 8527427914a2 Doc/whatsnew/2.5.rst +--- a/Doc/whatsnew/2.5.rst ++++ b/Doc/whatsnew/2.5.rst +@@ -870,31 +870,31 @@ + PEP 353: Using ssize_t as the index type + ======================================== + +-A wide-ranging change to Python's C API, using a new :ctype:`Py_ssize_t` type +-definition instead of :ctype:`int`, will permit the interpreter to handle more ++A wide-ranging change to Python's C API, using a new :c:type:`Py_ssize_t` type ++definition instead of :c:type:`int`, will permit the interpreter to handle more + data on 64-bit platforms. This change doesn't affect Python's capacity on 32-bit + platforms. + +-Various pieces of the Python interpreter used C's :ctype:`int` type to store ++Various pieces of the Python interpreter used C's :c:type:`int` type to store + sizes or counts; for example, the number of items in a list or tuple were stored +-in an :ctype:`int`. The C compilers for most 64-bit platforms still define +-:ctype:`int` as a 32-bit type, so that meant that lists could only hold up to ++in an :c:type:`int`. The C compilers for most 64-bit platforms still define ++:c:type:`int` as a 32-bit type, so that meant that lists could only hold up to + ``2**31 - 1`` = 2147483647 items. (There are actually a few different + programming models that 64-bit C compilers can use -- see + http://www.unix.org/version2/whatsnew/lp64_wp.html for a discussion -- but the +-most commonly available model leaves :ctype:`int` as 32 bits.) ++most commonly available model leaves :c:type:`int` as 32 bits.) + + A limit of 2147483647 items doesn't really matter on a 32-bit platform because + you'll run out of memory before hitting the length limit. Each list item + requires space for a pointer, which is 4 bytes, plus space for a +-:ctype:`PyObject` representing the item. 2147483647\*4 is already more bytes ++:c:type:`PyObject` representing the item. 2147483647\*4 is already more bytes + than a 32-bit address space can contain. + + It's possible to address that much memory on a 64-bit platform, however. The + pointers for a list that size would only require 16 GiB of space, so it's not + unreasonable that Python programmers might construct lists that large. + Therefore, the Python interpreter had to be changed to use some type other than +-:ctype:`int`, and this will be a 64-bit type on 64-bit platforms. The change ++:c:type:`int`, and this will be a 64-bit type on 64-bit platforms. The change + will cause incompatibilities on 64-bit machines, so it was deemed worth making + the transition now, while the number of 64-bit users is still relatively small. + (In 5 or 10 years, we may *all* be on 64-bit machines, and the transition would +@@ -902,15 +902,15 @@ + + This change most strongly affects authors of C extension modules. Python + strings and container types such as lists and tuples now use +-:ctype:`Py_ssize_t` to store their size. Functions such as +-:cfunc:`PyList_Size` now return :ctype:`Py_ssize_t`. Code in extension modules +-may therefore need to have some variables changed to :ctype:`Py_ssize_t`. +- +-The :cfunc:`PyArg_ParseTuple` and :cfunc:`Py_BuildValue` functions have a new +-conversion code, ``n``, for :ctype:`Py_ssize_t`. :cfunc:`PyArg_ParseTuple`'s +-``s#`` and ``t#`` still output :ctype:`int` by default, but you can define the +-macro :cmacro:`PY_SSIZE_T_CLEAN` before including :file:`Python.h` to make +-them return :ctype:`Py_ssize_t`. ++:c:type:`Py_ssize_t` to store their size. Functions such as ++:c:func:`PyList_Size` now return :c:type:`Py_ssize_t`. Code in extension modules ++may therefore need to have some variables changed to :c:type:`Py_ssize_t`. ++ ++The :c:func:`PyArg_ParseTuple` and :c:func:`Py_BuildValue` functions have a new ++conversion code, ``n``, for :c:type:`Py_ssize_t`. :c:func:`PyArg_ParseTuple`'s ++``s#`` and ``t#`` still output :c:type:`int` by default, but you can define the ++macro :c:macro:`PY_SSIZE_T_CLEAN` before including :file:`Python.h` to make ++them return :c:type:`Py_ssize_t`. + + :pep:`353` has a section on conversion guidelines that extension authors should + read to learn about supporting 64-bit platforms. +@@ -954,8 +954,8 @@ + :exc:`TypeError` if this requirement isn't met. + + A corresponding :attr:`nb_index` slot was added to the C-level +-:ctype:`PyNumberMethods` structure to let C extensions implement this protocol. +-:cfunc:`PyNumber_Index(obj)` can be used in extension code to call the ++:c:type:`PyNumberMethods` structure to let C extensions implement this protocol. ++:c:func:`PyNumber_Index(obj)` can be used in extension code to call the + :meth:`__index__` function and retrieve its result. + + +@@ -1179,7 +1179,7 @@ + (Contributed by Bob Ippolito at the NeedForSpeed sprint.) + + * The :mod:`re` module got a 1 or 2% speedup by switching to Python's allocator +- functions instead of the system's :cfunc:`malloc` and :cfunc:`free`. ++ functions instead of the system's :c:func:`malloc` and :c:func:`free`. + (Contributed by Jack Diederich at the NeedForSpeed sprint.) + + * The code generator's peephole optimizer now performs simple constant folding +@@ -1203,7 +1203,7 @@ + Sean Reifschneider at the NeedForSpeed sprint.) + + * Importing now caches the paths tried, recording whether they exist or not so +- that the interpreter makes fewer :cfunc:`open` and :cfunc:`stat` calls on ++ that the interpreter makes fewer :c:func:`open` and :c:func:`stat` calls on + startup. (Contributed by Martin von Löwis and Georg Brandl.) + + .. Patch 921466 +@@ -1459,7 +1459,7 @@ + + On FreeBSD, the :func:`os.stat` function now returns times with nanosecond + resolution, and the returned object now has :attr:`st_gen` and +- :attr:`st_birthtime`. The :attr:`st_flags` member is also available, if the ++ :attr:`st_birthtime`. The :attr:`st_flags` attribute is also available, if the + platform supports it. (Contributed by Antti Louko and Diego Pettenò.) + + .. (Patch 1180695, 1212117) +@@ -1568,7 +1568,7 @@ + reporting ``('CPython', 'trunk', '45313:45315')``. + + This information is also available to C extensions via the +- :cfunc:`Py_GetBuildInfo` function that returns a string of build information ++ :c:func:`Py_GetBuildInfo` function that returns a string of build information + like this: ``"trunk:45355:45356M, Apr 13 2006, 07:42:19"``. (Contributed by + Barry Warsaw.) + +@@ -1690,7 +1690,7 @@ + result = libc.printf("Line of output\n") + + Type constructors for the various C types are provided: :func:`c_int`, +-:func:`c_float`, :func:`c_double`, :func:`c_char_p` (equivalent to :ctype:`char ++:func:`c_float`, :func:`c_double`, :func:`c_char_p` (equivalent to :c:type:`char + \*`), and so forth. Unlike Python's types, the C versions are all mutable; you + can assign to their :attr:`value` attribute to change the wrapped value. Python + integers and strings will be automatically converted to the corresponding C +@@ -1720,7 +1720,7 @@ + ``ctypes.pythonapi`` object. This object does *not* release the global + interpreter lock before calling a function, because the lock must be held when + calling into the interpreter's code. There's a :class:`py_object()` type +-constructor that will create a :ctype:`PyObject \*` pointer. A simple usage:: ++constructor that will create a :c:type:`PyObject \*` pointer. A simple usage:: + + import ctypes + +@@ -2087,8 +2087,8 @@ + http://scan.coverity.com for the statistics. + + * The largest change to the C API came from :pep:`353`, which modifies the +- interpreter to use a :ctype:`Py_ssize_t` type definition instead of +- :ctype:`int`. See the earlier section :ref:`pep-353` for a discussion of this ++ interpreter to use a :c:type:`Py_ssize_t` type definition instead of ++ :c:type:`int`. See the earlier section :ref:`pep-353` for a discussion of this + change. + + * The design of the bytecode compiler has changed a great deal, no longer +@@ -2113,10 +2113,10 @@ + discusses the design. To start learning about the code, read the definition of + the various AST nodes in :file:`Parser/Python.asdl`. A Python script reads this + file and generates a set of C structure definitions in +- :file:`Include/Python-ast.h`. The :cfunc:`PyParser_ASTFromString` and +- :cfunc:`PyParser_ASTFromFile`, defined in :file:`Include/pythonrun.h`, take ++ :file:`Include/Python-ast.h`. The :c:func:`PyParser_ASTFromString` and ++ :c:func:`PyParser_ASTFromFile`, defined in :file:`Include/pythonrun.h`, take + Python source as input and return the root of an AST representing the contents. +- This AST can then be turned into a code object by :cfunc:`PyAST_Compile`. For ++ This AST can then be turned into a code object by :c:func:`PyAST_Compile`. For + more information, read the source code, and then ask questions on python-dev. + + The AST code was developed under Jeremy Hylton's management, and implemented by +@@ -2138,55 +2138,55 @@ + + Note that this change means extension modules must be more careful when + allocating memory. Python's API has many different functions for allocating +- memory that are grouped into families. For example, :cfunc:`PyMem_Malloc`, +- :cfunc:`PyMem_Realloc`, and :cfunc:`PyMem_Free` are one family that allocates +- raw memory, while :cfunc:`PyObject_Malloc`, :cfunc:`PyObject_Realloc`, and +- :cfunc:`PyObject_Free` are another family that's supposed to be used for ++ memory that are grouped into families. For example, :c:func:`PyMem_Malloc`, ++ :c:func:`PyMem_Realloc`, and :c:func:`PyMem_Free` are one family that allocates ++ raw memory, while :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and ++ :c:func:`PyObject_Free` are another family that's supposed to be used for + creating Python objects. + + Previously these different families all reduced to the platform's +- :cfunc:`malloc` and :cfunc:`free` functions. This meant it didn't matter if +- you got things wrong and allocated memory with the :cfunc:`PyMem` function but +- freed it with the :cfunc:`PyObject` function. With 2.5's changes to obmalloc, ++ :c:func:`malloc` and :c:func:`free` functions. This meant it didn't matter if ++ you got things wrong and allocated memory with the :c:func:`PyMem` function but ++ freed it with the :c:func:`PyObject` function. With 2.5's changes to obmalloc, + these families now do different things and mismatches will probably result in a + segfault. You should carefully test your C extension modules with Python 2.5. + +-* The built-in set types now have an official C API. Call :cfunc:`PySet_New` +- and :cfunc:`PyFrozenSet_New` to create a new set, :cfunc:`PySet_Add` and +- :cfunc:`PySet_Discard` to add and remove elements, and :cfunc:`PySet_Contains` +- and :cfunc:`PySet_Size` to examine the set's state. (Contributed by Raymond ++* The built-in set types now have an official C API. Call :c:func:`PySet_New` ++ and :c:func:`PyFrozenSet_New` to create a new set, :c:func:`PySet_Add` and ++ :c:func:`PySet_Discard` to add and remove elements, and :c:func:`PySet_Contains` ++ and :c:func:`PySet_Size` to examine the set's state. (Contributed by Raymond + Hettinger.) + + * C code can now obtain information about the exact revision of the Python +- interpreter by calling the :cfunc:`Py_GetBuildInfo` function that returns a ++ interpreter by calling the :c:func:`Py_GetBuildInfo` function that returns a + string of build information like this: ``"trunk:45355:45356M, Apr 13 2006, + 07:42:19"``. (Contributed by Barry Warsaw.) + + * Two new macros can be used to indicate C functions that are local to the + current file so that a faster calling convention can be used. +- :cfunc:`Py_LOCAL(type)` declares the function as returning a value of the ++ :c:func:`Py_LOCAL(type)` declares the function as returning a value of the + specified *type* and uses a fast-calling qualifier. +- :cfunc:`Py_LOCAL_INLINE(type)` does the same thing and also requests the +- function be inlined. If :cfunc:`PY_LOCAL_AGGRESSIVE` is defined before ++ :c:func:`Py_LOCAL_INLINE(type)` does the same thing and also requests the ++ function be inlined. If :c:func:`PY_LOCAL_AGGRESSIVE` is defined before + :file:`python.h` is included, a set of more aggressive optimizations are enabled + for the module; you should benchmark the results to find out if these + optimizations actually make the code faster. (Contributed by Fredrik Lundh at + the NeedForSpeed sprint.) + +-* :cfunc:`PyErr_NewException(name, base, dict)` can now accept a tuple of base ++* :c:func:`PyErr_NewException(name, base, dict)` can now accept a tuple of base + classes as its *base* argument. (Contributed by Georg Brandl.) + +-* The :cfunc:`PyErr_Warn` function for issuing warnings is now deprecated in +- favour of :cfunc:`PyErr_WarnEx(category, message, stacklevel)` which lets you ++* The :c:func:`PyErr_Warn` function for issuing warnings is now deprecated in ++ favour of :c:func:`PyErr_WarnEx(category, message, stacklevel)` which lets you + specify the number of stack frames separating this function and the caller. A +- *stacklevel* of 1 is the function calling :cfunc:`PyErr_WarnEx`, 2 is the ++ *stacklevel* of 1 is the function calling :c:func:`PyErr_WarnEx`, 2 is the + function above that, and so forth. (Added by Neal Norwitz.) + + * The CPython interpreter is still written in C, but the code can now be + compiled with a C++ compiler without errors. (Implemented by Anthony Baxter, + Martin von Löwis, Skip Montanaro.) + +-* The :cfunc:`PyRange_New` function was removed. It was never documented, never ++* The :c:func:`PyRange_New` function was removed. It was never documented, never + used in the core code, and had dangerously lax error checking. In the unlikely + case that your extensions were using it, you can replace it by something like + the following:: +@@ -2203,7 +2203,7 @@ + --------------------- + + * MacOS X (10.3 and higher): dynamic loading of modules now uses the +- :cfunc:`dlopen` function instead of MacOS-specific functions. ++ :c:func:`dlopen` function instead of MacOS-specific functions. + + * MacOS X: an :option:`--enable-universalsdk` switch was added to the + :program:`configure` script that compiles the interpreter as a universal binary +@@ -2259,15 +2259,15 @@ + Setting :attr:`rpc_paths` to ``None`` or an empty tuple disables this path + checking. + +-* C API: Many functions now use :ctype:`Py_ssize_t` instead of :ctype:`int` to ++* C API: Many functions now use :c:type:`Py_ssize_t` instead of :c:type:`int` to + allow processing more data on 64-bit machines. Extension code may need to make + the same change to avoid warnings and to support 64-bit machines. See the + earlier section :ref:`pep-353` for a discussion of this change. + + * C API: The obmalloc changes mean that you must be careful to not mix usage +- of the :cfunc:`PyMem_\*` and :cfunc:`PyObject_\*` families of functions. Memory +- allocated with one family's :cfunc:`\*_Malloc` must be freed with the +- corresponding family's :cfunc:`\*_Free` function. ++ of the :c:func:`PyMem_\*` and :c:func:`PyObject_\*` families of functions. Memory ++ allocated with one family's :c:func:`\*_Malloc` must be freed with the ++ corresponding family's :c:func:`\*_Free` function. + + .. ====================================================================== + +diff -r 8527427914a2 Doc/whatsnew/2.6.rst +--- a/Doc/whatsnew/2.6.rst ++++ b/Doc/whatsnew/2.6.rst +@@ -121,7 +121,7 @@ + with this switch to see how much work will be necessary to port + code to 3.0. The value of this switch is available + to Python code as the boolean variable :data:`sys.py3kwarning`, +-and to C extension code as :cdata:`Py_Py3kWarningFlag`. ++and to C extension code as :c:data:`Py_Py3kWarningFlag`. + + .. seealso:: + +@@ -232,7 +232,7 @@ + + .. seealso:: + +- :ref:`documenting-index` ++ `Documenting Python `__ + Describes how to write for Python's documentation. + + `Sphinx `__ +@@ -611,8 +611,8 @@ + result = queue.get() + print 'Factorial', N, '=', result + +-A :class:`Queue` is used to communicate the input parameter *N* and +-the result. The :class:`Queue` object is stored in a global variable. ++A :class:`Queue` is used to communicate the result of the factorial. ++The :class:`Queue` object is stored in a global variable. + The child process will use the value of the variable when the child + was created; because it's a :class:`Queue`, parent and child can use + the object to communicate. (If the parent were to change the value of +@@ -975,10 +975,10 @@ + print len(s) # 12 Unicode characters + + At the C level, Python 3.0 will rename the existing 8-bit +-string type, called :ctype:`PyStringObject` in Python 2.x, +-to :ctype:`PyBytesObject`. Python 2.6 uses ``#define`` +-to support using the names :cfunc:`PyBytesObject`, +-:cfunc:`PyBytes_Check`, :cfunc:`PyBytes_FromStringAndSize`, ++string type, called :c:type:`PyStringObject` in Python 2.x, ++to :c:type:`PyBytesObject`. Python 2.6 uses ``#define`` ++to support using the names :c:func:`PyBytesObject`, ++:c:func:`PyBytes_Check`, :c:func:`PyBytes_FromStringAndSize`, + and all the other functions and macros used with strings. + + Instances of the :class:`bytes` type are immutable just +@@ -1010,8 +1010,8 @@ + bytearray(b'ABCde') + + There's also a corresponding C API, with +-:cfunc:`PyByteArray_FromObject`, +-:cfunc:`PyByteArray_FromStringAndSize`, ++:c:func:`PyByteArray_FromObject`, ++:c:func:`PyByteArray_FromStringAndSize`, + and various other functions. + + .. seealso:: +@@ -1130,7 +1130,7 @@ + + .. XXX PyObject_GetBuffer not documented in c-api + +-The *flags* argument to :cfunc:`PyObject_GetBuffer` specifies ++The *flags* argument to :c:func:`PyObject_GetBuffer` specifies + constraints upon the memory returned. Some examples are: + + * :const:`PyBUF_WRITABLE` indicates that the memory must be writable. +@@ -1141,7 +1141,7 @@ + requests a C-contiguous (last dimension varies the fastest) or + Fortran-contiguous (first dimension varies the fastest) array layout. + +-Two new argument codes for :cfunc:`PyArg_ParseTuple`, ++Two new argument codes for :c:func:`PyArg_ParseTuple`, + ``s*`` and ``z*``, return locked buffer objects for a parameter. + + .. seealso:: +@@ -1635,7 +1635,7 @@ + :meth:`__hash__` method inherited from a parent class, so + assigning ``None`` was implemented as an override. At the + C level, extensions can set ``tp_hash`` to +- :cfunc:`PyObject_HashNotImplemented`. ++ :c:func:`PyObject_HashNotImplemented`. + (Fixed by Nick Coghlan and Amaury Forgeot d'Arc; :issue:`2235`.) + + * The :exc:`GeneratorExit` exception now subclasses +@@ -1705,7 +1705,7 @@ + By default, this change is only applied to types that are included with + the Python core. Extension modules may not necessarily be compatible with + this cache, +- so they must explicitly add :cmacro:`Py_TPFLAGS_HAVE_VERSION_TAG` ++ so they must explicitly add :c:macro:`Py_TPFLAGS_HAVE_VERSION_TAG` + to the module's ``tp_flags`` field to enable the method cache. + (To be compatible with the method cache, the extension module's code + must not directly access and modify the ``tp_dict`` member of +@@ -2284,7 +2284,7 @@ + (Contributed by Raymond Hettinger; :issue:`1861`.) + + * The :mod:`select` module now has wrapper functions +- for the Linux :cfunc:`epoll` and BSD :cfunc:`kqueue` system calls. ++ for the Linux :c:func:`epoll` and BSD :c:func:`kqueue` system calls. + :meth:`modify` method was added to the existing :class:`poll` + objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor + or file object and an event mask, modifying the recorded event mask +@@ -2317,13 +2317,13 @@ + Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor + to be used; when a signal is received, a byte is written to that + file descriptor. There's also a C-level function, +- :cfunc:`PySignal_SetWakeupFd`, for setting the descriptor. ++ :c:func:`PySignal_SetWakeupFd`, for setting the descriptor. + + Event loops will use this by opening a pipe to create two descriptors, + one for reading and one for writing. The writable descriptor + will be passed to :func:`set_wakeup_fd`, and the readable descriptor + will be added to the list of descriptors monitored by the event loop via +- :cfunc:`select` or :cfunc:`poll`. ++ :c:func:`select` or :c:func:`poll`. + On receiving a signal, a byte will be written and the main event loop + will be woken up, avoiding the need to poll. + +@@ -2384,7 +2384,7 @@ + has been updated from version 2.3.2 in Python 2.5 to + version 2.4.1. + +-* The :mod:`struct` module now supports the C99 :ctype:`_Bool` type, ++* The :mod:`struct` module now supports the C99 :c:type:`_Bool` type, + using the format character ``'?'``. + (Contributed by David Remahl.) + +@@ -2392,7 +2392,7 @@ + now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods. + On Windows, :meth:`send_signal` only supports the :const:`SIGTERM` + signal, and all these methods are aliases for the Win32 API function +- :cfunc:`TerminateProcess`. ++ :c:func:`TerminateProcess`. + (Contributed by Christian Heimes.) + + * A new variable in the :mod:`sys` module, :attr:`float_info`, is an +@@ -2977,7 +2977,7 @@ + + * Python now must be compiled with C89 compilers (after 19 + years!). This means that the Python source tree has dropped its +- own implementations of :cfunc:`memmove` and :cfunc:`strerror`, which ++ own implementations of :c:func:`memmove` and :c:func:`strerror`, which + are in the C89 standard library. + + * Python 2.6 can be built with Microsoft Visual Studio 2008 (version +@@ -2999,7 +2999,7 @@ + + * The new buffer interface, previously described in + `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__, +- adds :cfunc:`PyObject_GetBuffer` and :cfunc:`PyBuffer_Release`, ++ adds :c:func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release`, + as well as a few other functions. + + * Python's use of the C stdio library is now thread-safe, or at least +@@ -3007,27 +3007,27 @@ + bug occurred if one thread closed a file object while another thread + was reading from or writing to the object. In 2.6 file objects + have a reference count, manipulated by the +- :cfunc:`PyFile_IncUseCount` and :cfunc:`PyFile_DecUseCount` ++ :c:func:`PyFile_IncUseCount` and :c:func:`PyFile_DecUseCount` + functions. File objects can't be closed unless the reference count +- is zero. :cfunc:`PyFile_IncUseCount` should be called while the GIL ++ is zero. :c:func:`PyFile_IncUseCount` should be called while the GIL + is still held, before carrying out an I/O operation using the +- ``FILE *`` pointer, and :cfunc:`PyFile_DecUseCount` should be called ++ ``FILE *`` pointer, and :c:func:`PyFile_DecUseCount` should be called + immediately after the GIL is re-acquired. + (Contributed by Antoine Pitrou and Gregory P. Smith.) + + * Importing modules simultaneously in two different threads no longer + deadlocks; it will now raise an :exc:`ImportError`. A new API +- function, :cfunc:`PyImport_ImportModuleNoBlock`, will look for a ++ function, :c:func:`PyImport_ImportModuleNoBlock`, will look for a + module in ``sys.modules`` first, then try to import it after + acquiring an import lock. If the import lock is held by another + thread, an :exc:`ImportError` is raised. + (Contributed by Christian Heimes.) + + * Several functions return information about the platform's +- floating-point support. :cfunc:`PyFloat_GetMax` returns ++ floating-point support. :c:func:`PyFloat_GetMax` returns + the maximum representable floating point value, +- and :cfunc:`PyFloat_GetMin` returns the minimum +- positive value. :cfunc:`PyFloat_GetInfo` returns an object ++ and :c:func:`PyFloat_GetMin` returns the minimum ++ positive value. :c:func:`PyFloat_GetInfo` returns an object + containing more information from the :file:`float.h` file, such as + ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"`` + (smallest difference between 1.0 and the next largest value +@@ -3035,7 +3035,7 @@ + (Contributed by Christian Heimes; :issue:`1534`.) + + * C functions and methods that use +- :cfunc:`PyComplex_AsCComplex` will now accept arguments that ++ :c:func:`PyComplex_AsCComplex` will now accept arguments that + have a :meth:`__complex__` method. In particular, the functions in the + :mod:`cmath` module will now accept objects with this method. + This is a backport of a Python 3.0 change. +@@ -3049,15 +3049,15 @@ + * Many C extensions define their own little macro for adding + integers and strings to the module's dictionary in the + ``init*`` function. Python 2.6 finally defines standard macros +- for adding values to a module, :cmacro:`PyModule_AddStringMacro` +- and :cmacro:`PyModule_AddIntMacro()`. (Contributed by ++ for adding values to a module, :c:macro:`PyModule_AddStringMacro` ++ and :c:macro:`PyModule_AddIntMacro()`. (Contributed by + Christian Heimes.) + + * Some macros were renamed in both 3.0 and 2.6 to make it clearer that + they are macros, +- not functions. :cmacro:`Py_Size()` became :cmacro:`Py_SIZE()`, +- :cmacro:`Py_Type()` became :cmacro:`Py_TYPE()`, and +- :cmacro:`Py_Refcnt()` became :cmacro:`Py_REFCNT()`. ++ not functions. :c:macro:`Py_Size()` became :c:macro:`Py_SIZE()`, ++ :c:macro:`Py_Type()` became :c:macro:`Py_TYPE()`, and ++ :c:macro:`Py_Refcnt()` became :c:macro:`Py_REFCNT()`. + The mixed-case macros are still available + in Python 2.6 for backward compatibility. + (:issue:`1629`) +@@ -3115,7 +3115,7 @@ + + * The :mod:`socket` module's socket objects now have an + :meth:`ioctl` method that provides a limited interface to the +- :cfunc:`WSAIoctl` system interface. ++ :c:func:`WSAIoctl` system interface. + + * The :mod:`_winreg` module now has a function, + :func:`ExpandEnvironmentStrings`, +@@ -3261,13 +3261,13 @@ + the implementation now explicitly checks for this case and raises + an :exc:`ImportError`. + +-* C API: the :cfunc:`PyImport_Import` and :cfunc:`PyImport_ImportModule` ++* C API: the :c:func:`PyImport_Import` and :c:func:`PyImport_ImportModule` + functions now default to absolute imports, not relative imports. + This will affect C extensions that import other modules. + + * C API: extension data types that shouldn't be hashable + should define their ``tp_hash`` slot to +- :cfunc:`PyObject_HashNotImplemented`. ++ :c:func:`PyObject_HashNotImplemented`. + + * The :mod:`socket` module exception :exc:`socket.error` now inherits + from :exc:`IOError`. Previously it wasn't a subclass of +diff -r 8527427914a2 Doc/whatsnew/2.7.rst +--- a/Doc/whatsnew/2.7.rst ++++ b/Doc/whatsnew/2.7.rst +@@ -147,8 +147,8 @@ + ``float(repr(x))`` recovers ``x``. + * Float-to-string and string-to-float conversions are correctly rounded. + The :func:`round` function is also now correctly rounded. +-* The :ctype:`PyCapsule` type, used to provide a C API for extension modules. +-* The :cfunc:`PyLong_AsLongAndOverflow` C API function. ++* The :c:type:`PyCapsule` type, used to provide a C API for extension modules. ++* The :c:func:`PyLong_AsLongAndOverflow` C API function. + + Other new Python3-mode warnings include: + +@@ -311,7 +311,7 @@ + This means Python now supports three different modules for parsing + command-line arguments: :mod:`getopt`, :mod:`optparse`, and + :mod:`argparse`. The :mod:`getopt` module closely resembles the C +-library's :cfunc:`getopt` function, so it remains useful if you're writing a ++library's :c:func:`getopt` function, so it remains useful if you're writing a + Python prototype that will eventually be rewritten in C. + :mod:`optparse` becomes redundant, but there are no plans to remove it + because there are many scripts still using it, and there's no +@@ -783,8 +783,8 @@ + + (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.) + +-* The :keyword:`import` statement will no longer try a relative import +- if an absolute import (e.g. ``from .os import sep``) fails. This ++* The :keyword:`import` statement will no longer try an absolute import ++ if a relative import (e.g. ``from .os import sep``) fails. This + fixes a bug, but could possibly break certain :keyword:`import` + statements that were only working by accident. (Fixed by Meador Inge; + :issue:`7902`.) +@@ -1478,7 +1478,7 @@ + * The :mod:`ssl` module's :class:`~ssl.SSLSocket` objects now support the + buffer API, which fixed a test suite failure (fix by Antoine Pitrou; + :issue:`7133`) and automatically set +- OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error ++ OpenSSL's :c:macro:`SSL_MODE_AUTO_RETRY`, which will prevent an error + code being returned from :meth:`recv` operations that trigger an SSL + renegotiation (fix by Antoine Pitrou; :issue:`8222`). + +@@ -1946,7 +1946,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') +@@ -1958,8 +1958,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 +@@ -1972,11 +1972,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:: +@@ -1992,13 +1993,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(""" +@@ -2047,49 +2050,49 @@ + debugged doesn't hold the GIL; the macro now acquires it before printing. + (Contributed by Victor Stinner; :issue:`3632`.) + +-* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any ++* :c:func:`Py_AddPendingCall` is now thread-safe, letting any + worker thread submit notifications to the main Python thread. This + is particularly useful for asynchronous IO operations. + (Contributed by Kristján Valur Jónsson; :issue:`4293`.) + +-* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object; ++* New function: :c:func:`PyCode_NewEmpty` creates an empty code object; + only the filename, function name, and first line number are required. + This is useful for extension modules that are attempting to + construct a more useful traceback stack. Previously such +- extensions needed to call :cfunc:`PyCode_New`, which had many ++ extensions needed to call :c:func:`PyCode_New`, which had many + more arguments. (Added by Jeffrey Yasskin.) + +-* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new +- exception class, just as the existing :cfunc:`PyErr_NewException` does, ++* New function: :c:func:`PyErr_NewExceptionWithDoc` creates a new ++ exception class, just as the existing :c:func:`PyErr_NewException` does, + but takes an extra ``char *`` argument containing the docstring for the + new exception class. (Added by 'lekma' on the Python bug tracker; + :issue:`7033`.) + +-* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object ++* New function: :c:func:`PyFrame_GetLineNumber` takes a frame object + and returns the line number that the frame is currently executing. + Previously code would need to get the index of the bytecode + instruction currently executing, and then look up the line number + corresponding to that address. (Added by Jeffrey Yasskin.) + +-* New functions: :cfunc:`PyLong_AsLongAndOverflow` and +- :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long +- integer as a C :ctype:`long` or :ctype:`long long`. ++* New functions: :c:func:`PyLong_AsLongAndOverflow` and ++ :c:func:`PyLong_AsLongLongAndOverflow` approximates a Python long ++ integer as a C :c:type:`long` or :c:type:`long long`. + If the number is too large to fit into + the output type, an *overflow* flag is set and returned to the caller. + (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.) + + * New function: stemming from the rewrite of string-to-float conversion, +- a new :cfunc:`PyOS_string_to_double` function was added. The old +- :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions ++ a new :c:func:`PyOS_string_to_double` function was added. The old ++ :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions + are now deprecated. + +-* New function: :cfunc:`PySys_SetArgvEx` sets the value of ++* New function: :c:func:`PySys_SetArgvEx` sets the value of + ``sys.argv`` and can optionally update ``sys.path`` to include the + directory containing the script named by ``sys.argv[0]`` depending + on the value of an *updatepath* parameter. + + This function was added to close a security hole for applications +- that embed Python. The old function, :cfunc:`PySys_SetArgv`, would ++ that embed Python. The old function, :c:func:`PySys_SetArgv`, would + always update ``sys.path``, and sometimes it would add the current + directory. This meant that, if you ran an application embedding + Python in a directory controlled by someone else, attackers could +@@ -2097,8 +2100,8 @@ + :file:`os.py`) that your application would then import and run. + + If you maintain a C/C++ application that embeds Python, check +- whether you're calling :cfunc:`PySys_SetArgv` and carefully consider +- whether the application should be using :cfunc:`PySys_SetArgvEx` ++ whether you're calling :c:func:`PySys_SetArgv` and carefully consider ++ whether the application should be using :c:func:`PySys_SetArgvEx` + with *updatepath* set to false. + + Security issue reported as `CVE-2008-5983 +@@ -2106,14 +2109,14 @@ + discussed in :issue:`5753`, and fixed by Antoine Pitrou. + + * New macros: the Python header files now define the following macros: +- :cmacro:`Py_ISALNUM`, +- :cmacro:`Py_ISALPHA`, +- :cmacro:`Py_ISDIGIT`, +- :cmacro:`Py_ISLOWER`, +- :cmacro:`Py_ISSPACE`, +- :cmacro:`Py_ISUPPER`, +- :cmacro:`Py_ISXDIGIT`, +- :cmacro:`Py_TOLOWER`, and :cmacro:`Py_TOUPPER`. ++ :c:macro:`Py_ISALNUM`, ++ :c:macro:`Py_ISALPHA`, ++ :c:macro:`Py_ISDIGIT`, ++ :c:macro:`Py_ISLOWER`, ++ :c:macro:`Py_ISSPACE`, ++ :c:macro:`Py_ISUPPER`, ++ :c:macro:`Py_ISXDIGIT`, ++ :c:macro:`Py_TOLOWER`, and :c:macro:`Py_TOUPPER`. + All of these functions are analogous to the C + standard macros for classifying characters, but ignore the current + locale setting, because in +@@ -2123,15 +2126,15 @@ + + .. XXX these macros don't seem to be described in the c-api docs. + +-* Removed function: :cmacro:`PyEval_CallObject` is now only available ++* Removed function: :c:macro:`PyEval_CallObject` is now only available + as a macro. A function version was being kept around to preserve + ABI linking compatibility, but that was in 1997; it can certainly be + deleted by now. (Removed by Antoine Pitrou; :issue:`8276`.) + +-* New format codes: the :cfunc:`PyFormat_FromString`, +- :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` functions now ++* New format codes: the :c:func:`PyFormat_FromString`, ++ :c:func:`PyFormat_FromStringV`, and :c:func:`PyErr_Format` functions now + accept ``%lld`` and ``%llu`` format codes for displaying +- C's :ctype:`long long` types. ++ C's :c:type:`long long` types. + (Contributed by Mark Dickinson; :issue:`7228`.) + + * The complicated interaction between threads and process forking has +@@ -2147,17 +2150,17 @@ + Python 2.7 acquires the import lock before performing an + :func:`os.fork`, and will also clean up any locks created using the + :mod:`threading` module. C extension modules that have internal +- locks, or that call :cfunc:`fork()` themselves, will not benefit ++ locks, or that call :c:func:`fork()` themselves, will not benefit + from this clean-up. + + (Fixed by Thomas Wouters; :issue:`1590864`.) + +-* The :cfunc:`Py_Finalize` function now calls the internal ++* The :c:func:`Py_Finalize` function now calls the internal + :func:`threading._shutdown` function; this prevents some exceptions from + being raised when an interpreter shuts down. + (Patch by Adam Olsen; :issue:`1722344`.) + +-* When using the :ctype:`PyMemberDef` structure to define attributes ++* When using the :c:type:`PyMemberDef` structure to define attributes + of a type, Python will no longer let you try to delete or set a + :const:`T_STRING_INPLACE` attribute. + +@@ -2184,7 +2187,7 @@ + :issue:`6491`.) + + * The :program:`configure` script now checks for floating-point rounding bugs +- on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING` ++ on certain 32-bit Intel chips and defines a :c:macro:`X87_DOUBLE_ROUNDING` + preprocessor definition. No code currently uses this definition, + but it's available if anyone wishes to use it. + (Added by Mark Dickinson; :issue:`2937`.) +@@ -2205,7 +2208,7 @@ + Capsules + ------------------- + +-Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a ++Python 3.1 adds a new C datatype, :c:type:`PyCapsule`, for providing a + C API to an extension module. A capsule is essentially the holder of + a C ``void *`` pointer, and is made available as a module attribute; for + example, the :mod:`socket` module's API is exposed as ``socket.CAPI``, +@@ -2215,10 +2218,10 @@ + to an array of pointers to the module's various API functions. + + There is an existing data type already used for this, +-:ctype:`PyCObject`, but it doesn't provide type safety. Evil code ++:c:type:`PyCObject`, but it doesn't provide type safety. Evil code + written in pure Python could cause a segmentation fault by taking a +-:ctype:`PyCObject` from module A and somehow substituting it for the +-:ctype:`PyCObject` in module B. Capsules know their own name, ++:c:type:`PyCObject` from module A and somehow substituting it for the ++:c:type:`PyCObject` in module B. Capsules know their own name, + and getting the pointer requires providing the name:: + + void *vtable; +@@ -2231,15 +2234,15 @@ + vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI"); + + You are assured that ``vtable`` points to whatever you're expecting. +-If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would ++If a different capsule was passed in, :c:func:`PyCapsule_IsValid` would + detect the mismatched name and return false. Refer to + :ref:`using-capsules` for more information on using these objects. + + Python 2.7 now uses capsules internally to provide various +-extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was ++extension-module APIs, but the :c:func:`PyCObject_AsVoidPtr` was + modified to handle capsules, preserving compile-time compatibility +-with the :ctype:`CObject` interface. Use of +-:cfunc:`PyCObject_AsVoidPtr` will signal a ++with the :c:type:`CObject` interface. Use of ++:c:func:`PyCObject_AsVoidPtr` will signal a + :exc:`PendingDeprecationWarning`, which is silent by default. + + Implemented in Python 3.1 and backported to 2.7 by Larry Hastings; +@@ -2266,7 +2269,7 @@ + were also tested and documented. + (Implemented by Brian Curtin: :issue:`7347`.) + +-* The new :cfunc:`_beginthreadex` API is used to start threads, and ++* The new :c:func:`_beginthreadex` API is used to start threads, and + the native thread-local storage functions are now used. + (Contributed by Kristján Valur Jónsson; :issue:`3582`.) + +@@ -2274,7 +2277,7 @@ + can be the constants :const:`CTRL_C_EVENT`, + :const:`CTRL_BREAK_EVENT`, or any integer. The first two constants + will send Control-C and Control-Break keystroke events to +- subprocesses; any other value will use the :cfunc:`TerminateProcess` ++ subprocesses; any other value will use the :c:func:`TerminateProcess` + API. (Contributed by Miki Tebeka; :issue:`1220212`.) + + * The :func:`os.listdir` function now correctly fails +@@ -2447,17 +2450,17 @@ + family of functions will now raise a :exc:`TypeError` exception + instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`). + +-* Use the new :cfunc:`PyOS_string_to_double` function instead of the old +- :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions, ++* Use the new :c:func:`PyOS_string_to_double` function instead of the old ++ :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions, + which are now deprecated. + + For applications that embed Python: + +-* The :cfunc:`PySys_SetArgvEx` function was added, letting ++* The :c:func:`PySys_SetArgvEx` function was added, letting + applications close a security hole when the existing +- :cfunc:`PySys_SetArgv` function was used. Check whether you're +- calling :cfunc:`PySys_SetArgv` and carefully consider whether the +- application should be using :cfunc:`PySys_SetArgvEx` with ++ :c:func:`PySys_SetArgv` function was used. Check whether you're ++ calling :c:func:`PySys_SetArgv` and carefully consider whether the ++ application should be using :c:func:`PySys_SetArgvEx` with + *updatepath* set to false. + + .. ====================================================================== +diff -r 8527427914a2 Include/fileobject.h +--- a/Include/fileobject.h ++++ b/Include/fileobject.h +@@ -84,6 +84,13 @@ + #define _PyVerify_fd(A) (1) /* dummy */ + #endif + ++/* 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 8527427914a2 Include/patchlevel.h +--- a/Include/patchlevel.h ++++ b/Include/patchlevel.h +@@ -27,7 +27,7 @@ + #define PY_RELEASE_SERIAL 0 + + /* Version as a string */ +-#define PY_VERSION "2.7.2" ++#define PY_VERSION "2.7.2+" + /*--end constants--*/ + + /* Subversion Revision number of this file (not of the repository). Empty +diff -r 8527427914a2 Include/pyctype.h +--- a/Include/pyctype.h ++++ b/Include/pyctype.h +@@ -9,7 +9,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 +@@ -22,8 +22,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 8527427914a2 Include/pystate.h +--- a/Include/pystate.h ++++ b/Include/pystate.h +@@ -111,7 +111,6 @@ + PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *); + #ifdef WITH_THREAD + PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void); +-PyAPI_FUNC(void) _PyGILState_Reinit(void); + #endif + + PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void); +@@ -169,7 +168,7 @@ + + /* Helper/diagnostic function - get the current thread state for + this thread. May return NULL if no GILState API has been used +- on the current thread. Note the main thread always has such a ++ on the current thread. Note that the main thread always has such a + thread-state, even if no auto-thread-state call has been made + on the main thread. + */ +diff -r 8527427914a2 LICENSE +--- a/LICENSE ++++ b/LICENSE +@@ -98,9 +98,9 @@ + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python alone or in any derivative version, + provided, however, that PSF's License Agreement and PSF's notice of copyright, +-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 +-Python Software Foundation; All Rights Reserved" are retained in Python alone or +-in any derivative version prepared by Licensee. ++i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, ++2011, 2012 Python Software Foundation; All Rights Reserved" are retained in Python ++alone or in any derivative version prepared by Licensee. + + 3. In the event Licensee prepares a derivative work that is based on + or incorporates Python or any part thereof, and wants to make +diff -r 8527427914a2 Lib/BaseHTTPServer.py +--- a/Lib/BaseHTTPServer.py ++++ b/Lib/BaseHTTPServer.py +@@ -244,14 +244,11 @@ + self.request_version = version = self.default_request_version + self.close_connection = 1 + requestline = self.raw_requestline +- if requestline[-2:] == '\r\n': +- requestline = requestline[:-2] +- elif requestline[-1:] == '\n': +- requestline = requestline[:-1] ++ requestline = requestline.rstrip('\r\n') + self.requestline = requestline + words = requestline.split() + if len(words) == 3: +- [command, path, version] = words ++ command, path, version = words + if version[:5] != 'HTTP/': + self.send_error(400, "Bad request version (%r)" % version) + return False +@@ -277,7 +274,7 @@ + "Invalid HTTP Version (%s)" % base_version_number) + return False + elif len(words) == 2: +- [command, path] = words ++ command, path = words + self.close_connection = 1 + if command != 'GET': + self.send_error(400, +diff -r 8527427914a2 Lib/ConfigParser.py +--- a/Lib/ConfigParser.py ++++ b/Lib/ConfigParser.py +@@ -142,6 +142,7 @@ + def __init__(self, section): + Error.__init__(self, 'No section: %r' % (section,)) + self.section = section ++ self.args = (section, ) + + class DuplicateSectionError(Error): + """Raised when a section is multiply-created.""" +@@ -149,6 +150,7 @@ + def __init__(self, section): + Error.__init__(self, "Section %r already exists" % section) + self.section = section ++ self.args = (section, ) + + class NoOptionError(Error): + """A requested option was not found.""" +@@ -158,6 +160,7 @@ + (option, section)) + self.option = option + self.section = section ++ self.args = (option, section) + + class InterpolationError(Error): + """Base class for interpolation-related exceptions.""" +@@ -166,6 +169,7 @@ + Error.__init__(self, msg) + self.option = option + self.section = section ++ self.args = (option, section, msg) + + class InterpolationMissingOptionError(InterpolationError): + """A string substitution required a setting which was not available.""" +@@ -179,6 +183,7 @@ + % (section, option, reference, rawval)) + InterpolationError.__init__(self, option, section, msg) + self.reference = reference ++ self.args = (option, section, rawval, reference) + + class InterpolationSyntaxError(InterpolationError): + """Raised when the source text into which substitutions are made +@@ -194,6 +199,7 @@ + "\trawval : %s\n" + % (section, option, rawval)) + InterpolationError.__init__(self, option, section, msg) ++ self.args = (option, section, rawval) + + class ParsingError(Error): + """Raised when a configuration file does not follow legal syntax.""" +@@ -202,6 +208,7 @@ + Error.__init__(self, 'File contains parsing errors: %s' % filename) + self.filename = filename + self.errors = [] ++ self.args = (filename, ) + + def append(self, lineno, line): + self.errors.append((lineno, line)) +@@ -218,6 +225,7 @@ + self.filename = filename + self.lineno = lineno + self.line = line ++ self.args = (filename, lineno, line) + + + class RawConfigParser: +@@ -570,7 +578,7 @@ + def keys(self): + result = [] + seen = set() +- for mapping in self_maps: ++ for mapping in self._maps: + for key in mapping: + if key not in seen: + result.append(key) +diff -r 8527427914a2 Lib/HTMLParser.py +--- a/Lib/HTMLParser.py ++++ b/Lib/HTMLParser.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]') +@@ -24,25 +23,31 @@ + piclose = re.compile('>') + commentclose = re.compile(r'--\s*>') + tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*') ++# see http://www.w3.org/TR/html5/tokenization.html#tag-open-state ++# and http://www.w3.org/TR/html5/tokenization.html#tag-name-state ++tagfind_tolerant = re.compile('[a-zA-Z][^\t\n\r\f />\x00]*') ++ + attrfind = 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 +- (?:[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* ++ )* ++ )? + \s* # trailing whitespace + """, re.VERBOSE) + endendtag = re.compile('>') ++# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between ++# ') + + +@@ -96,6 +101,7 @@ + self.rawdata = '' + self.lasttag = '???' + self.interesting = interesting_normal ++ self.cdata_elem = None + markupbase.ParserBase.reset(self) + + def feed(self, data): +@@ -120,11 +126,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 +@@ -138,6 +146,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) +@@ -153,16 +163,23 @@ + elif startswith("', i + 1) ++ if k < 0: ++ k = rawdata.find('<', i + 1) ++ if k < 0: ++ k = i + 1 ++ else: ++ k += 1 ++ self.handle_data(rawdata[i:k]) + i = self.updatepos(i, k) + elif startswith("&#", i): + match = charref.match(rawdata, i) +@@ -206,11 +223,46 @@ + 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:] + ++ # Internal -- parse html declarations, return length or -1 if not terminated ++ # See w3.org/TR/html5/tokenization.html#markup-declaration-open-state ++ # See also parse_declaration in _markupbase ++ def parse_html_declaration(self, i): ++ rawdata = self.rawdata ++ if rawdata[i:i+2] != ' ++ gtpos = rawdata.find('>', i+9) ++ if gtpos == -1: ++ return -1 ++ self.handle_decl(rawdata[i+2:gtpos]) ++ return gtpos+1 ++ else: ++ return self.parse_bogus_comment(i) ++ ++ # Internal -- parse bogus comment, return length or -1 if not terminated ++ # see http://www.w3.org/TR/html5/tokenization.html#bogus-comment-state ++ def parse_bogus_comment(self, i, report=1): ++ rawdata = self.rawdata ++ if rawdata[i:i+2] not in ('', i+2) ++ if pos == -1: ++ return -1 ++ if report: ++ self.handle_comment(rawdata[i+2:pos]) ++ return pos + 1 ++ + # Internal -- parse processing instr, return end or -1 if not terminated + def parse_pi(self, i): + rawdata = self.rawdata +@@ -249,6 +301,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() +@@ -262,15 +315,15 @@ + - self.__starttag_text.rfind("\n") + else: + offset = offset + len(self.__starttag_text) +- self.error("junk characters in start tag: %r" +- % (rawdata[k:endpos][:20],)) ++ self.handle_data(rawdata[i:endpos]) ++ return endpos + if end.endswith('/>'): + # XHTML-style empty tag: + self.handle_startendtag(tag, attrs) + 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 +@@ -300,8 +353,10 @@ + # end of input in or before attribute value, or we have the + # '/' from a '/>' ending + return -1 +- self.updatepos(i, j) +- self.error("malformed start tag") ++ if j > i: ++ return j ++ else: ++ return i + 1 + raise AssertionError("we should not get here!") + + # Internal -- parse endtag, return end or -1 if incomplete +@@ -311,14 +366,38 @@ + match = endendtag.search(rawdata, i+1) # > + if not match: + return -1 +- j = match.end() ++ gtpos = match.end() + match = endtagfind.match(rawdata, i) # + if not match: +- self.error("bad end tag: %r" % (rawdata[i:j],)) +- tag = match.group(1) +- self.handle_endtag(tag.lower()) ++ if self.cdata_elem is not None: ++ self.handle_data(rawdata[i:gtpos]) ++ return gtpos ++ # find the name: w3.org/TR/html5/tokenization.html#tag-name-state ++ namematch = tagfind_tolerant.match(rawdata, i+2) ++ if not namematch: ++ # w3.org/TR/html5/tokenization.html#end-tag-open-state ++ if rawdata[i:i+3] == '': ++ return i+3 ++ else: ++ return self.parse_bogus_comment(i) ++ tagname = namematch.group().lower() ++ # consume and ignore other stuff between the name and the > ++ # Note: this is not 100% correct, since we might have things like ++ # , but looking for > after tha name should cover ++ # most of the cases and is much simpler ++ gtpos = rawdata.find('>', namematch.end()) ++ self.handle_endtag(tagname) ++ return gtpos+1 ++ ++ 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:gtpos]) ++ return gtpos ++ ++ self.handle_endtag(elem) + self.clear_cdata_mode() +- return j ++ return gtpos + + # Overridable -- finish processing of start+end tag: + def handle_startendtag(self, tag, attrs): +@@ -358,7 +437,7 @@ + pass + + def unknown_decl(self, data): +- self.error("unknown declaration: %r" % (data,)) ++ pass + + # Internal -- helper to remove special character quoting + entitydefs = None +diff -r 8527427914a2 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 +@@ -589,8 +589,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.setDaemon (1) ++ t.daemon = self.daemon_threads + t.start() + + +diff -r 8527427914a2 Lib/_pyio.py +--- a/Lib/_pyio.py ++++ b/Lib/_pyio.py +@@ -8,6 +8,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: +@@ -1074,13 +1078,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 +@@ -1111,24 +1111,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) +diff -r 8527427914a2 Lib/aifc.py +--- a/Lib/aifc.py ++++ b/Lib/aifc.py +@@ -162,6 +162,12 @@ + except struct.error: + raise EOFError + ++def _read_ushort(file): ++ try: ++ return struct.unpack('>H', file.read(2))[0] ++ except struct.error: ++ raise EOFError ++ + def _read_string(file): + length = ord(file.read(1)) + if length == 0: +@@ -194,13 +200,19 @@ + def _write_short(f, x): + f.write(struct.pack('>h', x)) + ++def _write_ushort(f, x): ++ f.write(struct.pack('>H', x)) ++ + def _write_long(f, x): ++ f.write(struct.pack('>l', x)) ++ ++def _write_ulong(f, x): + f.write(struct.pack('>L', x)) + + def _write_string(f, s): + if len(s) > 255: + raise ValueError("string exceeds maximum pstring length") +- f.write(chr(len(s))) ++ f.write(struct.pack('B', len(s))) + f.write(s) + if len(s) & 1 == 0: + f.write(chr(0)) +@@ -218,7 +230,7 @@ + lomant = 0 + else: + fmant, expon = math.frexp(x) +- if expon > 16384 or fmant >= 1: # Infinity or NaN ++ if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN + expon = sign|0x7FFF + himant = 0 + lomant = 0 +@@ -234,9 +246,9 @@ + fmant = math.ldexp(fmant - fsmant, 32) + fsmant = math.floor(fmant) + lomant = long(fsmant) +- _write_short(f, expon) +- _write_long(f, himant) +- _write_long(f, lomant) ++ _write_ushort(f, expon) ++ _write_ulong(f, himant) ++ _write_ulong(f, lomant) + + from chunk import Chunk + +@@ -840,15 +852,15 @@ + if self._aifc: + self._file.write('AIFC') + self._file.write('FVER') +- _write_long(self._file, 4) +- _write_long(self._file, self._version) ++ _write_ulong(self._file, 4) ++ _write_ulong(self._file, self._version) + else: + self._file.write('AIFF') + self._file.write('COMM') +- _write_long(self._file, commlength) ++ _write_ulong(self._file, commlength) + _write_short(self._file, self._nchannels) + self._nframes_pos = self._file.tell() +- _write_long(self._file, self._nframes) ++ _write_ulong(self._file, self._nframes) + _write_short(self._file, self._sampwidth * 8) + _write_float(self._file, self._framerate) + if self._aifc: +@@ -856,9 +868,9 @@ + _write_string(self._file, self._compname) + self._file.write('SSND') + self._ssnd_length_pos = self._file.tell() +- _write_long(self._file, self._datalength + 8) +- _write_long(self._file, 0) +- _write_long(self._file, 0) ++ _write_ulong(self._file, self._datalength + 8) ++ _write_ulong(self._file, 0) ++ _write_ulong(self._file, 0) + + def _write_form_length(self, datalength): + if self._aifc: +@@ -869,8 +881,8 @@ + else: + commlength = 18 + verslength = 0 +- _write_long(self._file, 4 + verslength + self._marklength + \ +- 8 + commlength + 16 + datalength) ++ _write_ulong(self._file, 4 + verslength + self._marklength + \ ++ 8 + commlength + 16 + datalength) + return commlength + + def _patchheader(self): +@@ -888,9 +900,9 @@ + self._file.seek(self._form_length_pos, 0) + dummy = self._write_form_length(datalength) + self._file.seek(self._nframes_pos, 0) +- _write_long(self._file, self._nframeswritten) ++ _write_ulong(self._file, self._nframeswritten) + self._file.seek(self._ssnd_length_pos, 0) +- _write_long(self._file, datalength + 8) ++ _write_ulong(self._file, datalength + 8) + self._file.seek(curpos, 0) + self._nframes = self._nframeswritten + self._datalength = datalength +@@ -905,13 +917,13 @@ + length = length + len(name) + 1 + 6 + if len(name) & 1 == 0: + length = length + 1 +- _write_long(self._file, length) ++ _write_ulong(self._file, length) + self._marklength = length + 8 + _write_short(self._file, len(self._markers)) + for marker in self._markers: + id, pos, name = marker + _write_short(self._file, id) +- _write_long(self._file, pos) ++ _write_ulong(self._file, pos) + _write_string(self._file, name) + + def open(f, mode=None): +diff -r 8527427914a2 Lib/asyncore.py +--- a/Lib/asyncore.py ++++ b/Lib/asyncore.py +@@ -132,7 +132,8 @@ + is_w = obj.writable() + if is_r: + r.append(fd) +- if is_w: ++ # accepting sockets should not be writable ++ if is_w and not obj.accepting: + w.append(fd) + if is_r or is_w: + e.append(fd) +@@ -179,7 +180,8 @@ + flags = 0 + if obj.readable(): + flags |= select.POLLIN | select.POLLPRI +- if obj.writable(): ++ # accepting sockets should not be writable ++ if obj.writable() and not obj.accepting: + flags |= select.POLLOUT + if flags: + # Only check for exceptions if object was either readable +diff -r 8527427914a2 Lib/cgi.py +--- a/Lib/cgi.py ++++ b/Lib/cgi.py +@@ -293,7 +293,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 8527427914a2 Lib/cmd.py +--- a/Lib/cmd.py ++++ b/Lib/cmd.py +@@ -209,6 +209,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 8527427914a2 Lib/collections.py +--- a/Lib/collections.py ++++ b/Lib/collections.py +@@ -312,6 +312,7 @@ + def _asdict(self): + 'Return a new OrderedDict which maps field names to their values' + return OrderedDict(zip(self._fields, self)) \n ++ __dict__ = property(_asdict) \n + def _replace(_self, **kwds): + 'Return a new %(typename)s object replacing specified fields with new values' + result = _self._make(map(kwds.pop, %(field_names)r, _self)) +diff -r 8527427914a2 Lib/compileall.py +--- a/Lib/compileall.py ++++ b/Lib/compileall.py +@@ -1,4 +1,4 @@ +-"""Module/script to "compile" all .py files to .pyc (or .pyo) file. ++"""Module/script to byte-compile all .py files to .pyc (or .pyo) files. + + When called as a script with arguments, this compiles the directories + given as arguments recursively; the -l option prevents it from +@@ -26,8 +26,8 @@ + + dir: the directory to byte-compile + maxlevels: maximum recursion level (default 10) +- ddir: if given, purported directory name (this is the +- directory name that will show up in error messages) ++ ddir: the directory that will be prepended to the path to the ++ file as it is compiled into each byte-code file. + force: if 1, force compilation, even if timestamps are up-to-date + quiet: if 1, be quiet during compilation + """ +@@ -64,8 +64,8 @@ + Arguments (only fullname is required): + + fullname: the file to byte-compile +- ddir: if given, purported directory name (this is the +- directory name that will show up in error messages) ++ ddir: if given, the directory name compiled in to the ++ byte-code file. + force: if 1, force compilation, even if timestamps are up-to-date + quiet: if 1, be quiet during compilation + """ +@@ -157,14 +157,27 @@ + print msg + print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ + "[-x regexp] [-i list] [directory|file ...]" +- print "-l: don't recurse down" ++ print ++ print "arguments: zero or more file and directory names to compile; " \ ++ "if no arguments given, " ++ print " defaults to the equivalent of -l sys.path" ++ print ++ print "options:" ++ print "-l: don't recurse into subdirectories" + print "-f: force rebuild even if timestamps are up-to-date" +- print "-q: quiet operation" +- print "-d destdir: purported directory name for error messages" +- print " if no directory arguments, -l sys.path is assumed" +- print "-x regexp: skip files matching the regular expression regexp" +- print " the regexp is searched for in the full path of the file" +- print "-i list: expand list with its content (file and directory names)" ++ print "-q: output only error messages" ++ print "-d destdir: directory to prepend to file paths for use in " \ ++ "compile-time tracebacks and in" ++ print " runtime tracebacks in cases where the source " \ ++ "file is unavailable" ++ print "-x regexp: skip files matching the regular expression regexp; " \ ++ "the regexp is searched for" ++ print " in the full path of each file considered for " \ ++ "compilation" ++ print "-i file: add all the files and directories listed in file to " \ ++ "the list considered for" ++ print ' compilation; if "-", names are read from stdin' ++ + sys.exit(2) + maxlevels = 10 + ddir = None +@@ -205,7 +218,7 @@ + else: + success = compile_path() + except KeyboardInterrupt: +- print "\n[interrupt]" ++ print "\n[interrupted]" + success = 0 + return success + +diff -r 8527427914a2 Lib/cookielib.py +--- a/Lib/cookielib.py ++++ b/Lib/cookielib.py +@@ -1014,7 +1014,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 8527427914a2 Lib/ctypes/__init__.py +--- a/Lib/ctypes/__init__.py ++++ b/Lib/ctypes/__init__.py +@@ -262,6 +262,22 @@ + + from _ctypes import POINTER, pointer, _pointer_type_cache + ++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) ++ + try: + from _ctypes import set_conversion_mode + except ImportError: +@@ -278,8 +294,6 @@ + class c_wchar(_SimpleCData): + _type_ = "u" + +- POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param +- + def create_unicode_buffer(init, size=None): + """create_unicode_buffer(aString) -> character array + create_unicode_buffer(anInteger) -> character array +@@ -298,8 +312,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): + if _pointer_type_cache.get(cls, None) is not None: +@@ -458,8 +470,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 +@@ -542,8 +552,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 8527427914a2 Lib/ctypes/_endian.py +--- a/Lib/ctypes/_endian.py ++++ b/Lib/ctypes/_endian.py +@@ -4,20 +4,24 @@ + import sys + from ctypes import * + +-_array_type = type(c_int * 3) ++_array_type = type(Array) + + def _other_endian(typ): + """Return the type with the 'other' byte order. Simple types like + c_int and so on already have __ctype_be__ and __ctype_le__ + attributes which contain the types, for more complicated types +- only arrays are supported. ++ arrays and structures are supported. + """ +- try: ++ # check _OTHER_ENDIAN attribute (present if typ is primitive type) ++ if hasattr(typ, _OTHER_ENDIAN): + return getattr(typ, _OTHER_ENDIAN) +- except AttributeError: +- if type(typ) == _array_type: +- return _other_endian(typ._type_) * typ._length_ +- raise TypeError("This type does not support other endian: %s" % typ) ++ # if typ is array ++ if isinstance(typ, _array_type): ++ return _other_endian(typ._type_) * typ._length_ ++ # if typ is structure ++ if issubclass(typ, Structure): ++ return typ ++ raise TypeError("This type does not support other endian: %s" % typ) + + class _swapped_meta(type(Structure)): + def __setattr__(self, attrname, value): +diff -r 8527427914a2 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 8527427914a2 Lib/ctypes/test/test_buffers.py +--- a/Lib/ctypes/test/test_buffers.py ++++ b/Lib/ctypes/test/test_buffers.py +@@ -20,6 +20,10 @@ + self.assertEqual(b[::2], "ac") + self.assertEqual(b[::5], "a") + ++ def test_buffer_interface(self): ++ self.assertEqual(len(bytearray(create_string_buffer(0))), 0) ++ self.assertEqual(len(bytearray(create_string_buffer(1))), 1) ++ + def test_string_conversion(self): + b = create_string_buffer(u"abc") + self.assertEqual(len(b), 4) # trailing nul char +diff -r 8527427914a2 Lib/ctypes/test/test_byteswap.py +--- a/Lib/ctypes/test/test_byteswap.py ++++ b/Lib/ctypes/test/test_byteswap.py +@@ -1,4 +1,4 @@ +-import sys, unittest, struct, math ++import sys, unittest, struct, math, ctypes + from binascii import hexlify + + from ctypes import * +@@ -185,18 +185,32 @@ + self.assertRaises(TypeError, setattr, T, "_fields_", [("x", typ)]) + + def test_struct_struct(self): +- # Nested structures with different byte order not (yet) supported +- if sys.byteorder == "little": +- base = BigEndianStructure +- else: +- base = LittleEndianStructure ++ # nested structures with different byteorders + +- class T(Structure): +- _fields_ = [("a", c_int), +- ("b", c_int)] +- class S(base): +- pass +- self.assertRaises(TypeError, setattr, S, "_fields_", [("s", T)]) ++ # create nested structures with given byteorders and set memory to data ++ ++ for nested, data in ( ++ (BigEndianStructure, b'\0\0\0\1\0\0\0\2'), ++ (LittleEndianStructure, b'\1\0\0\0\2\0\0\0'), ++ ): ++ for parent in ( ++ BigEndianStructure, ++ LittleEndianStructure, ++ Structure, ++ ): ++ class NestedStructure(nested): ++ _fields_ = [("x", c_uint32), ++ ("y", c_uint32)] ++ ++ class TestStructure(parent): ++ _fields_ = [("point", NestedStructure)] ++ ++ self.assertEqual(len(data), sizeof(TestStructure)) ++ ptr = POINTER(TestStructure) ++ s = cast(data, ptr)[0] ++ del ctypes._pointer_type_cache[TestStructure] ++ self.assertEqual(s.point.x, 1) ++ self.assertEqual(s.point.y, 2) + + def test_struct_fields_2(self): + # standard packing in struct uses no alignment. +diff -r 8527427914a2 Lib/ctypes/test/test_callbacks.py +--- a/Lib/ctypes/test/test_callbacks.py ++++ b/Lib/ctypes/test/test_callbacks.py +@@ -140,6 +140,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 8527427914a2 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 8527427914a2 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, u"x\xe9") ++ + def test_intarray_fields(self): + class SomeInts(Structure): + _fields_ = [("a", c_int * 4)] +@@ -324,6 +332,18 @@ + else: + self.assertEqual(msg, "(Phone) exceptions.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 8527427914a2 Lib/ctypes/util.py +--- a/Lib/ctypes/util.py ++++ b/Lib/ctypes/util.py +@@ -182,28 +182,6 @@ + + else: + +- def _findLib_ldconfig(name): +- # XXX assuming GLIBC's ldconfig (with option -p) +- expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) +- f = os.popen('LC_ALL=C LANG=C /sbin/ldconfig -p 2>/dev/null') +- try: +- data = f.read() +- finally: +- f.close() +- res = re.search(expr, data) +- if not res: +- # Hm, this works only for libs needed by the python executable. +- cmd = 'ldd %s 2>/dev/null' % sys.executable +- f = os.popen(cmd) +- try: +- data = f.read() +- finally: +- f.close() +- res = re.search(expr, data) +- if not res: +- return None +- return res.group(0) +- + def _findSoname_ldconfig(name): + import struct + if struct.calcsize('l') == 4: +@@ -220,8 +198,7 @@ + abi_type = mach_map.get(machine, 'libc6') + + # XXX assuming GLIBC's ldconfig (with option -p) +- expr = r'(\S+)\s+\((%s(?:, OS ABI:[^\)]*)?)\)[^/]*(/[^\(\)\s]*lib%s\.[^\(\)\s]*)' \ +- % (abi_type, re.escape(name)) ++ expr = r'\s+(lib%s\.[^\s]+)\s+\(%s' % (re.escape(name), abi_type) + f = os.popen('/sbin/ldconfig -p 2>/dev/null') + try: + data = f.read() +diff -r 8527427914a2 Lib/decimal.py +--- a/Lib/decimal.py ++++ b/Lib/decimal.py +@@ -21,7 +21,7 @@ + This is a Py2.3 implementation of decimal floating point arithmetic based on + the General Decimal Arithmetic Specification: + +- www2.hursley.ibm.com/decimal/decarith.html ++ http://speleotrove.com/decimal/decarith.html + + and IEEE standard 854-1987: + +@@ -1942,9 +1942,9 @@ + nonzero. For efficiency, other._exp should not be too large, + so that 10**abs(other._exp) is a feasible calculation.""" + +- # In the comments below, we write x for the value of self and +- # y for the value of other. Write x = xc*10**xe and y = +- # yc*10**ye. ++ # In the comments below, we write x for the value of self and y for the ++ # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc ++ # and yc positive integers not divisible by 10. + + # The main purpose of this method is to identify the *failure* + # of x**y to be exactly representable with as little effort as +@@ -1952,13 +1952,12 @@ + # eliminate the possibility of x**y being exact. Only if all + # these tests are passed do we go on to actually compute x**y. + +- # Here's the main idea. First normalize both x and y. We +- # express y as a rational m/n, with m and n relatively prime +- # and n>0. Then for x**y to be exactly representable (at +- # *any* precision), xc must be the nth power of a positive +- # integer and xe must be divisible by n. If m is negative +- # then additionally xc must be a power of either 2 or 5, hence +- # a power of 2**n or 5**n. ++ # Here's the main idea. Express y as a rational number m/n, with m and ++ # n relatively prime and n>0. Then for x**y to be exactly ++ # representable (at *any* precision), xc must be the nth power of a ++ # positive integer and xe must be divisible by n. If y is negative ++ # then additionally xc must be a power of either 2 or 5, hence a power ++ # of 2**n or 5**n. + # + # There's a limit to how small |y| can be: if y=m/n as above + # then: +@@ -2030,21 +2029,43 @@ + return None + # now xc is a power of 2; e is its exponent + e = _nbits(xc)-1 +- # find e*y and xe*y; both must be integers +- if ye >= 0: +- y_as_int = yc*10**ye +- e = e*y_as_int +- xe = xe*y_as_int +- else: +- ten_pow = 10**-ye +- e, remainder = divmod(e*yc, ten_pow) +- if remainder: +- return None +- xe, remainder = divmod(xe*yc, ten_pow) +- if remainder: +- return None +- +- if e*65 >= p*93: # 93/65 > log(10)/log(5) ++ ++ # We now have: ++ # ++ # x = 2**e * 10**xe, e > 0, and y < 0. ++ # ++ # The exact result is: ++ # ++ # x**y = 5**(-e*y) * 10**(e*y + xe*y) ++ # ++ # provided that both e*y and xe*y are integers. Note that if ++ # 5**(-e*y) >= 10**p, then the result can't be expressed ++ # exactly with p digits of precision. ++ # ++ # Using the above, we can guard against large values of ye. ++ # 93/65 is an upper bound for log(10)/log(5), so if ++ # ++ # ye >= len(str(93*p//65)) ++ # ++ # then ++ # ++ # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5), ++ # ++ # so 5**(-e*y) >= 10**p, and the coefficient of the result ++ # can't be expressed in p digits. ++ ++ # emax >= largest e such that 5**e < 10**p. ++ emax = p*93//65 ++ if ye >= len(str(emax)): ++ return None ++ ++ # Find -e*y and -xe*y; both must be integers ++ e = _decimal_lshift_exact(e * yc, ye) ++ xe = _decimal_lshift_exact(xe * yc, ye) ++ if e is None or xe is None: ++ return None ++ ++ if e > emax: + return None + xc = 5**e + +@@ -2058,19 +2079,20 @@ + while xc % 5 == 0: + xc //= 5 + e -= 1 +- if ye >= 0: +- y_as_integer = yc*10**ye +- e = e*y_as_integer +- xe = xe*y_as_integer +- else: +- ten_pow = 10**-ye +- e, remainder = divmod(e*yc, ten_pow) +- if remainder: +- return None +- xe, remainder = divmod(xe*yc, ten_pow) +- if remainder: +- return None +- if e*3 >= p*10: # 10/3 > log(10)/log(2) ++ ++ # Guard against large values of ye, using the same logic as in ++ # the 'xc is a power of 2' branch. 10/3 is an upper bound for ++ # log(10)/log(2). ++ emax = p*10//3 ++ if ye >= len(str(emax)): ++ return None ++ ++ e = _decimal_lshift_exact(e * yc, ye) ++ xe = _decimal_lshift_exact(xe * yc, ye) ++ if e is None or xe is None: ++ return None ++ ++ if e > emax: + return None + xc = 2**e + else: +@@ -5463,6 +5485,27 @@ + hex_n = "%x" % n + return 4*len(hex_n) - correction[hex_n[0]] + ++def _decimal_lshift_exact(n, e): ++ """ Given integers n and e, return n * 10**e if it's an integer, else None. ++ ++ The computation is designed to avoid computing large powers of 10 ++ unnecessarily. ++ ++ >>> _decimal_lshift_exact(3, 4) ++ 30000 ++ >>> _decimal_lshift_exact(300, -999999999) # returns None ++ ++ """ ++ if n == 0: ++ return 0 ++ elif e >= 0: ++ return n * 10**e ++ else: ++ # val_n = largest power of 10 dividing n. ++ str_n = str(abs(n)) ++ val_n = len(str_n) - len(str_n.rstrip('0')) ++ return None if val_n < -e else n // 10**-e ++ + def _sqrt_nearest(n, a): + """Closest integer to the square root of the positive integer n. a is + an initial approximation to the square root. Any positive integer +diff -r 8527427914a2 Lib/distutils/ccompiler.py +--- a/Lib/distutils/ccompiler.py ++++ b/Lib/distutils/ccompiler.py +@@ -18,58 +18,6 @@ + from distutils.util import split_quoted, execute + from distutils import log + +-_sysconfig = __import__('sysconfig') +- +-def customize_compiler(compiler): +- """Do any platform-specific customization of a CCompiler instance. +- +- Mainly needed on Unix, so we can plug in the information that +- 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) = \ +- _sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', +- 'CCSHARED', 'LDSHARED', 'SO', 'AR', +- 'ARFLAGS') +- +- if 'CC' in os.environ: +- cc = os.environ['CC'] +- if 'CXX' in os.environ: +- cxx = os.environ['CXX'] +- if 'LDSHARED' in os.environ: +- ldshared = os.environ['LDSHARED'] +- if 'CPP' in os.environ: +- cpp = os.environ['CPP'] +- else: +- cpp = cc + " -E" # not always +- if 'LDFLAGS' in os.environ: +- ldshared = ldshared + ' ' + os.environ['LDFLAGS'] +- if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] +- ldshared = ldshared + ' ' + os.environ['CFLAGS'] +- if 'CPPFLAGS' in os.environ: +- cpp = cpp + ' ' + os.environ['CPPFLAGS'] +- cflags = cflags + ' ' + os.environ['CPPFLAGS'] +- ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] +- if 'AR' in os.environ: +- ar = os.environ['AR'] +- if 'ARFLAGS' in os.environ: +- archiver = ar + ' ' + os.environ['ARFLAGS'] +- else: +- archiver = ar + ' ' + ar_flags +- +- cc_cmd = cc + ' ' + cflags +- compiler.set_executables( +- preprocessor=cpp, +- compiler=cc_cmd, +- compiler_so=cc_cmd + ' ' + ccshared, +- compiler_cxx=cxx, +- linker_so=ldshared, +- linker_exe=cc, +- archiver=archiver) +- +- compiler.shared_lib_extension = so_ext +- + class CCompiler: + """Abstract base class to define the interface that must be implemented + by real compiler classes. Also has some utility methods used by +diff -r 8527427914a2 Lib/distutils/command/bdist_dumb.py +--- a/Lib/distutils/command/bdist_dumb.py ++++ b/Lib/distutils/command/bdist_dumb.py +@@ -58,7 +58,7 @@ + self.format = None + self.keep_temp = 0 + self.dist_dir = None +- self.skip_build = 0 ++ self.skip_build = None + self.relative = 0 + self.owner = None + self.group = None +@@ -78,7 +78,8 @@ + + self.set_undefined_options('bdist', + ('dist_dir', 'dist_dir'), +- ('plat_name', 'plat_name')) ++ ('plat_name', 'plat_name'), ++ ('skip_build', 'skip_build')) + + def run(self): + if not self.skip_build: +diff -r 8527427914a2 Lib/distutils/command/bdist_msi.py +--- a/Lib/distutils/command/bdist_msi.py ++++ b/Lib/distutils/command/bdist_msi.py +@@ -131,18 +131,22 @@ + self.no_target_optimize = 0 + self.target_version = None + self.dist_dir = None +- self.skip_build = 0 ++ self.skip_build = None + self.install_script = None + self.pre_install_script = None + self.versions = None + + def finalize_options (self): ++ self.set_undefined_options('bdist', ('skip_build', 'skip_build')) ++ + if self.bdist_dir is None: + bdist_base = self.get_finalized_command('bdist').bdist_base + self.bdist_dir = os.path.join(bdist_base, 'msi') ++ + short_version = get_python_version() + if (not self.target_version) and self.distribution.has_ext_modules(): + self.target_version = short_version ++ + if self.target_version: + self.versions = [self.target_version] + if not self.skip_build and self.distribution.has_ext_modules()\ +diff -r 8527427914a2 Lib/distutils/command/bdist_wininst.py +--- a/Lib/distutils/command/bdist_wininst.py ++++ b/Lib/distutils/command/bdist_wininst.py +@@ -71,7 +71,7 @@ + self.dist_dir = None + self.bitmap = None + self.title = None +- self.skip_build = 0 ++ self.skip_build = None + self.install_script = None + self.pre_install_script = None + self.user_access_control = None +@@ -80,6 +80,8 @@ + + + def finalize_options (self): ++ self.set_undefined_options('bdist', ('skip_build', 'skip_build')) ++ + if self.bdist_dir is None: + if self.skip_build and self.plat_name: + # If build is skipped and plat_name is overridden, bdist will +@@ -89,8 +91,10 @@ + # next the command will be initialized using that name + bdist_base = self.get_finalized_command('bdist').bdist_base + self.bdist_dir = os.path.join(bdist_base, 'wininst') ++ + if not self.target_version: + self.target_version = "" ++ + if not self.skip_build and self.distribution.has_ext_modules(): + short_version = get_python_version() + if self.target_version and self.target_version != short_version: +diff -r 8527427914a2 Lib/distutils/command/build_clib.py +--- a/Lib/distutils/command/build_clib.py ++++ b/Lib/distutils/command/build_clib.py +@@ -19,7 +19,7 @@ + import os + from distutils.core import Command + from distutils.errors import DistutilsSetupError +-from distutils.ccompiler import customize_compiler ++from distutils.sysconfig import customize_compiler + from distutils import log + + def show_compilers(): +diff -r 8527427914a2 Lib/distutils/command/build_ext.py +--- a/Lib/distutils/command/build_ext.py ++++ b/Lib/distutils/command/build_ext.py +@@ -160,8 +160,7 @@ + if plat_py_include != py_include: + self.include_dirs.append(plat_py_include) + +- if isinstance(self.libraries, str): +- self.libraries = [self.libraries] ++ self.ensure_string_list('libraries') + + # Life is easier if we're not forever checking for None, so + # simplify these options to empty lists if unset +diff -r 8527427914a2 Lib/distutils/command/check.py +--- a/Lib/distutils/command/check.py ++++ b/Lib/distutils/command/check.py +@@ -5,6 +5,7 @@ + __revision__ = "$Id$" + + from distutils.core import Command ++from distutils.dist import PKG_INFO_ENCODING + from distutils.errors import DistutilsSetupError + + try: +@@ -108,6 +109,8 @@ + def check_restructuredtext(self): + """Checks if the long string fields are reST-compliant.""" + data = self.distribution.get_long_description() ++ if not isinstance(data, unicode): ++ data = data.decode(PKG_INFO_ENCODING) + for warning in self._check_rst_data(data): + line = warning[-1].get('line') + if line is None: +diff -r 8527427914a2 Lib/distutils/command/config.py +--- a/Lib/distutils/command/config.py ++++ b/Lib/distutils/command/config.py +@@ -16,7 +16,7 @@ + + from distutils.core import Command + from distutils.errors import DistutilsExecError +-from distutils.ccompiler import customize_compiler ++from distutils.sysconfig import customize_compiler + from distutils import log + + LANG_EXT = {'c': '.c', 'c++': '.cxx'} +diff -r 8527427914a2 Lib/distutils/command/register.py +--- a/Lib/distutils/command/register.py ++++ b/Lib/distutils/command/register.py +@@ -10,7 +10,6 @@ + import urllib2 + import getpass + import urlparse +-import StringIO + from warnings import warn + + from distutils.core import PyPIRCCommand +@@ -260,21 +259,30 @@ + boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' + sep_boundary = '\n--' + boundary + end_boundary = sep_boundary + '--' +- body = StringIO.StringIO() ++ chunks = [] + for key, value in data.items(): + # handle multiple entries for the same name + if type(value) not in (type([]), type( () )): + value = [value] + for value in value: +- body.write(sep_boundary) +- body.write('\nContent-Disposition: form-data; name="%s"'%key) +- body.write("\n\n") +- body.write(value) ++ chunks.append(sep_boundary) ++ chunks.append('\nContent-Disposition: form-data; name="%s"'%key) ++ chunks.append("\n\n") ++ chunks.append(value) + if value and value[-1] == '\r': +- body.write('\n') # write an extra newline (lurve Macs) +- body.write(end_boundary) +- body.write("\n") +- body = body.getvalue() ++ chunks.append('\n') # write an extra newline (lurve Macs) ++ chunks.append(end_boundary) ++ chunks.append("\n") ++ ++ # chunks may be bytes (str) or unicode objects that we need to encode ++ body = [] ++ for chunk in chunks: ++ if isinstance(chunk, unicode): ++ body.append(chunk.encode('utf-8')) ++ else: ++ body.append(chunk) ++ ++ body = ''.join(body) + + # build the Request + headers = { +diff -r 8527427914a2 Lib/distutils/command/sdist.py +--- a/Lib/distutils/command/sdist.py ++++ b/Lib/distutils/command/sdist.py +@@ -182,14 +182,20 @@ + reading the manifest, or just using the default file set -- it all + depends on the user's options. + """ +- # new behavior: ++ # new behavior when using a template: + # the file list is recalculated everytime because + # even if MANIFEST.in or setup.py are not changed + # the user might have added some files in the tree that + # need to be included. + # +- # This makes --force the default and only behavior. ++ # This makes --force the default and only behavior with templates. + template_exists = os.path.isfile(self.template) ++ if not template_exists and self._manifest_is_not_generated(): ++ self.read_manifest() ++ self.filelist.sort() ++ self.filelist.remove_duplicates() ++ return ++ + if not template_exists: + self.warn(("manifest template '%s' does not exist " + + "(using default file list)") % +@@ -314,7 +320,10 @@ + + try: + self.filelist.process_template_line(line) +- except DistutilsTemplateError, 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)) +@@ -352,23 +361,28 @@ + by 'add_defaults()' and 'read_template()') to the manifest file + named by 'self.manifest'. + """ +- if os.path.isfile(self.manifest): +- fp = open(self.manifest) +- try: +- first_line = fp.readline() +- finally: +- fp.close() +- +- if first_line != '# file GENERATED by distutils, do NOT edit\n': +- log.info("not writing to manually maintained " +- "manifest file '%s'" % self.manifest) +- return ++ if self._manifest_is_not_generated(): ++ log.info("not writing to manually maintained " ++ "manifest file '%s'" % self.manifest) ++ return + + content = self.filelist.files[:] + content.insert(0, '# file GENERATED by distutils, do NOT edit') + self.execute(file_util.write_file, (self.manifest, content), + "writing manifest file '%s'" % self.manifest) + ++ def _manifest_is_not_generated(self): ++ # check for special comment used in 2.7.1 and higher ++ if not os.path.isfile(self.manifest): ++ return False ++ ++ fp = open(self.manifest, 'rU') ++ try: ++ first_line = fp.readline() ++ finally: ++ fp.close() ++ return first_line != '# file GENERATED by distutils, do NOT edit\n' ++ + def read_manifest(self): + """Read the manifest file (named by 'self.manifest') and use it to + fill in 'self.filelist', the list of files to include in the source +@@ -376,12 +390,11 @@ + """ + log.info("reading manifest file '%s'", self.manifest) + manifest = open(self.manifest) +- while 1: +- line = manifest.readline() +- if line == '': # end of file +- break +- if line[-1] == '\n': +- line = line[0:-1] ++ for line in manifest: ++ # ignore comments and blank lines ++ line = line.strip() ++ if line.startswith('#') or not line: ++ continue + self.filelist.append(line) + manifest.close() + +diff -r 8527427914a2 Lib/distutils/dep_util.py +--- a/Lib/distutils/dep_util.py ++++ b/Lib/distutils/dep_util.py +@@ -7,6 +7,7 @@ + __revision__ = "$Id$" + + import os ++from stat import ST_MTIME + from distutils.errors import DistutilsFileError + + def newer(source, target): +@@ -27,7 +28,7 @@ + if not os.path.exists(target): + return True + +- return os.stat(source).st_mtime > os.stat(target).st_mtime ++ return os.stat(source)[ST_MTIME] > os.stat(target)[ST_MTIME] + + def newer_pairwise(sources, targets): + """Walk two filename lists in parallel, testing if each source is newer +@@ -71,7 +72,7 @@ + # is more recent than 'target', then 'target' is out-of-date and + # we can immediately return true. If we fall through to the end + # of the loop, then 'target' is up-to-date and we return false. +- target_mtime = os.stat(target).st_mtime ++ target_mtime = os.stat(target)[ST_MTIME] + + for source in sources: + if not os.path.exists(source): +@@ -82,7 +83,7 @@ + elif missing == 'newer': # missing source means target is + return True # out-of-date + +- if os.stat(source).st_mtime > target_mtime: ++ if os.stat(source)[ST_MTIME] > target_mtime: + return True + + return False +diff -r 8527427914a2 Lib/distutils/dist.py +--- a/Lib/distutils/dist.py ++++ b/Lib/distutils/dist.py +@@ -1111,7 +1111,8 @@ + """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' + + self._write_field(file, 'Metadata-Version', version) +diff -r 8527427914a2 Lib/distutils/filelist.py +--- a/Lib/distutils/filelist.py ++++ b/Lib/distutils/filelist.py +@@ -328,7 +328,8 @@ + # 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) ++ # paths should always use / in manifest templates ++ pattern_re = "^%s/.*%s" % (prefix_re, pattern_re) + else: # no prefix -- respect anchor flag + if anchor: + pattern_re = "^" + pattern_re +diff -r 8527427914a2 Lib/distutils/msvc9compiler.py +--- a/Lib/distutils/msvc9compiler.py ++++ b/Lib/distutils/msvc9compiler.py +@@ -640,15 +640,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 +@@ -666,20 +658,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 +- 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, 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, 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 +@@ -688,6 +714,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() +@@ -700,9 +728,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 8527427914a2 Lib/distutils/spawn.py +--- a/Lib/distutils/spawn.py ++++ b/Lib/distutils/spawn.py +@@ -96,17 +96,43 @@ + raise DistutilsExecError, \ + "command '%s' failed with exit status %d" % (cmd[0], rc) + ++if sys.platform == 'darwin': ++ from distutils import sysconfig ++ _cfg_target = None ++ _cfg_target_split = None + + def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0): + log.info(' '.join(cmd)) + if dry_run: + return + exec_fn = search_path and os.execvp or os.execv ++ exec_args = [cmd[0], cmd] ++ if sys.platform == 'darwin': ++ global _cfg_target, _cfg_target_split ++ if _cfg_target is None: ++ _cfg_target = sysconfig.get_config_var( ++ 'MACOSX_DEPLOYMENT_TARGET') or '' ++ if _cfg_target: ++ _cfg_target_split = [int(x) for x in _cfg_target.split('.')] ++ if _cfg_target: ++ # ensure that the deployment target of build process is not less ++ # than that used when the interpreter was built. This ensures ++ # extension modules are built with correct compatibility values ++ cur_target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', _cfg_target) ++ if _cfg_target_split > [int(x) for x in cur_target.split('.')]: ++ my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: ' ++ 'now "%s" but "%s" during configure' ++ % (cur_target, _cfg_target)) ++ raise DistutilsPlatformError(my_msg) ++ env = dict(os.environ, ++ MACOSX_DEPLOYMENT_TARGET=cur_target) ++ exec_fn = search_path and os.execvpe or os.execve ++ exec_args.append(env) + pid = os.fork() + + if pid == 0: # in the child + try: +- exec_fn(cmd[0], cmd) ++ exec_fn(*exec_args) + except OSError, e: + sys.stderr.write("unable to execute %s: %s\n" % + (cmd[0], e.strerror)) +diff -r 8527427914a2 Lib/distutils/sysconfig.py +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -141,6 +141,7 @@ + "I don't know where Python installs its library " + "on platform '%s'" % os.name) + ++_USE_CLANG = None + + def customize_compiler(compiler): + """Do any platform-specific customization of a CCompiler instance. +@@ -149,12 +150,43 @@ + varies across Unices and is stored in Python's Makefile. + """ + if compiler.compiler_type == "unix": +- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext) = \ ++ (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ + get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', +- 'CCSHARED', 'LDSHARED', 'SO') ++ 'CCSHARED', 'LDSHARED', 'SO', 'AR', ++ 'ARFLAGS') + ++ newcc = None + if 'CC' in os.environ: +- cc = os.environ['CC'] ++ newcc = os.environ['CC'] ++ elif sys.platform == 'darwin' and cc == 'gcc-4.2': ++ # Issue #13590: ++ # Since Apple removed gcc-4.2 in Xcode 4.2, we can no ++ # longer assume it is available for extension module builds. ++ # If Python was built with gcc-4.2, check first to see if ++ # it is available on this system; if not, try to use clang ++ # instead unless the caller explicitly set CC. ++ global _USE_CLANG ++ if _USE_CLANG is None: ++ from distutils import log ++ from subprocess import Popen, PIPE ++ p = Popen("! type gcc-4.2 && type clang && exit 2", ++ shell=True, stdout=PIPE, stderr=PIPE) ++ p.wait() ++ if p.returncode == 2: ++ _USE_CLANG = True ++ log.warn("gcc-4.2 not found, using clang instead") ++ else: ++ _USE_CLANG = False ++ if _USE_CLANG: ++ newcc = 'clang' ++ if newcc: ++ # On OS X, if CC is overridden, use that as the default ++ # command for LDSHARED as well ++ if (sys.platform == 'darwin' ++ and 'LDSHARED' not in os.environ ++ and ldshared.startswith(cc)): ++ ldshared = newcc + ldshared[len(cc):] ++ cc = newcc + if 'CXX' in os.environ: + cxx = os.environ['CXX'] + if 'LDSHARED' in os.environ: +@@ -172,6 +204,12 @@ + cpp = cpp + ' ' + os.environ['CPPFLAGS'] + cflags = cflags + ' ' + os.environ['CPPFLAGS'] + ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] ++ if 'AR' in os.environ: ++ ar = os.environ['AR'] ++ if 'ARFLAGS' in os.environ: ++ archiver = ar + ' ' + os.environ['ARFLAGS'] ++ else: ++ archiver = ar + ' ' + ar_flags + + cc_cmd = cc + ' ' + cflags + compiler.set_executables( +@@ -180,7 +218,8 @@ + compiler_so=cc_cmd + ' ' + ccshared, + compiler_cxx=cxx, + linker_so=ldshared, +- linker_exe=cc) ++ linker_exe=cc, ++ archiver=archiver) + + compiler.shared_lib_extension = so_ext + +@@ -380,21 +419,6 @@ + + raise DistutilsPlatformError(my_msg) + +- # On MacOSX we need to check the setting of the environment variable +- # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so +- # it needs to be compatible. +- # If it isn't set we set it to the configure-time value +- if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g: +- cfg_target = g['MACOSX_DEPLOYMENT_TARGET'] +- cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '') +- if cur_target == '': +- cur_target = cfg_target +- os.environ['MACOSX_DEPLOYMENT_TARGET'] = cfg_target +- elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')): +- my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure' +- % (cur_target, cfg_target)) +- raise DistutilsPlatformError(my_msg) +- + # On AIX, there are wrong paths to the linker scripts in the Makefile + # -- these paths are relative to the Python source, but when installed + # the scripts are in another directory. +diff -r 8527427914a2 Lib/distutils/tests/support.py +--- a/Lib/distutils/tests/support.py ++++ b/Lib/distutils/tests/support.py +@@ -1,7 +1,10 @@ + """Support code for distutils test cases.""" + import os ++import sys + import shutil + import tempfile ++import unittest ++import sysconfig + from copy import deepcopy + import warnings + +@@ -9,6 +12,7 @@ + from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL + from distutils.core import Distribution + ++ + def capture_warnings(func): + def _capture_warnings(*args, **kw): + with warnings.catch_warnings(): +@@ -16,6 +20,7 @@ + return func(*args, **kw) + return _capture_warnings + ++ + class LoggingSilencer(object): + + def setUp(self): +@@ -49,6 +54,7 @@ + def clear_logs(self): + self.logs = [] + ++ + class TempdirManager(object): + """Mix-in class that handles temporary directories for test cases. + +@@ -57,9 +63,13 @@ + + def setUp(self): + super(TempdirManager, self).setUp() ++ self.old_cwd = os.getcwd() + self.tempdirs = [] + + def tearDown(self): ++ # Restore working dir, for Solaris and derivatives, where rmdir() ++ # on the current directory fails. ++ os.chdir(self.old_cwd) + super(TempdirManager, self).tearDown() + while self.tempdirs: + d = self.tempdirs.pop() +@@ -105,6 +115,7 @@ + + return pkg_dir, dist + ++ + class DummyCommand: + """Class to store options for retrieval via set_undefined_options().""" + +@@ -115,6 +126,7 @@ + def ensure_finalized(self): + pass + ++ + class EnvironGuard(object): + + def setUp(self): +@@ -131,3 +143,79 @@ + del os.environ[key] + + super(EnvironGuard, self).tearDown() ++ ++ ++def copy_xxmodule_c(directory): ++ """Helper for tests that need the xxmodule.c source file. ++ ++ Example use: ++ ++ 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. ++ """ ++ filename = _get_xxmodule_path() ++ if filename is None: ++ raise unittest.SkipTest('cannot find xxmodule.c (test must run in ' ++ 'the python build dir)') ++ shutil.copy(filename, directory) ++ ++ ++def _get_xxmodule_path(): ++ # FIXME when run from regrtest, srcdir seems to be '.', which does not help ++ # us find the xxmodule.c file ++ srcdir = sysconfig.get_config_var('srcdir') ++ candidates = [ ++ # use installed copy if available ++ os.path.join(os.path.dirname(__file__), 'xxmodule.c'), ++ # otherwise try using copy from build directory ++ os.path.join(srcdir, 'Modules', 'xxmodule.c'), ++ # srcdir mysteriously can be $srcdir/Lib/distutils/tests when ++ # this file is run from its parent directory, so walk up the ++ # tree to find the real srcdir ++ os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'), ++ ] ++ for path in candidates: ++ if os.path.exists(path): ++ return path ++ ++ ++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 in debug mode on Windows, build_ext commands ++ need their debug attribute set, and it is not done automatically for ++ some reason. ++ ++ This function handles both of these things. Example use: ++ ++ cmd = build_ext(dist) ++ support.fixup_build_ext(cmd) ++ cmd.ensure_finalized() ++ ++ Unlike most other Unix platforms, Mac OS X embeds absolute paths ++ to shared libraries into executables, so the fixup is not needed there. ++ """ ++ if os.name == 'nt': ++ cmd.debug = sys.executable.endswith('_d.exe') ++ elif sysconfig.get_config_var('Py_ENABLE_SHARED'): ++ # To further add to the shared builds fun on Unix, we can't just add ++ # library_dirs to the Extension() instance because that doesn't get ++ # plumbed through to the final compiler command. ++ runshared = sysconfig.get_config_var('RUNSHARED') ++ if runshared is None: ++ cmd.library_dirs = ['.'] ++ else: ++ if sys.platform == 'darwin': ++ cmd.library_dirs = [] ++ else: ++ name, equals, value = runshared.partition('=') ++ cmd.library_dirs = value.split(os.pathsep) +diff -r 8527427914a2 Lib/distutils/tests/test_archive_util.py +--- a/Lib/distutils/tests/test_archive_util.py ++++ b/Lib/distutils/tests/test_archive_util.py +@@ -1,8 +1,10 @@ ++# -*- coding: utf-8 -*- + """Tests for distutils.archive_util.""" + __revision__ = "$Id$" + + import unittest + import os ++import sys + import tarfile + from os.path import splitdrive + import warnings +@@ -33,6 +35,18 @@ + except ImportError: + zlib = None + ++def can_fs_encode(filename): ++ """ ++ Return True if the filename can be saved in the file system. ++ """ ++ if os.path.supports_unicode_filenames: ++ return True ++ try: ++ filename.encode(sys.getfilesystemencoding()) ++ except UnicodeEncodeError: ++ return False ++ return True ++ + + class ArchiveUtilTestCase(support.TempdirManager, + support.LoggingSilencer, +@@ -40,6 +54,9 @@ + + @unittest.skipUnless(zlib, "requires zlib") + def test_make_tarball(self): ++ self._make_tarball('archive') ++ ++ def _make_tarball(self, target_name): + # creating something to tar + tmpdir = self.mkdtemp() + self.write_file([tmpdir, 'file1'], 'xxx') +@@ -51,7 +68,7 @@ + unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0], + "source and target should be on same drive") + +- base_name = os.path.join(tmpdir2, 'archive') ++ base_name = os.path.join(tmpdir2, target_name) + + # working with relative paths to avoid tar warnings + old_dir = os.getcwd() +@@ -66,7 +83,7 @@ + self.assertTrue(os.path.exists(tarball)) + + # trying an uncompressed one +- base_name = os.path.join(tmpdir2, 'archive') ++ base_name = os.path.join(tmpdir2, target_name) + old_dir = os.getcwd() + os.chdir(tmpdir) + try: +@@ -277,6 +294,33 @@ + finally: + del ARCHIVE_FORMATS['xxx'] + ++ @unittest.skipUnless(zlib, "requires zlib") ++ def test_make_tarball_unicode(self): ++ """ ++ Mirror test_make_tarball, except filename is unicode. ++ """ ++ self._make_tarball(u'archive') ++ ++ @unittest.skipUnless(zlib, "requires zlib") ++ @unittest.skipUnless(can_fs_encode(u'Ã¥rchiv'), ++ 'File system cannot handle this filename') ++ def test_make_tarball_unicode_latin1(self): ++ """ ++ Mirror test_make_tarball, except filename is unicode and contains ++ latin characters. ++ """ ++ self._make_tarball(u'Ã¥rchiv') # note this isn't a real word ++ ++ @unittest.skipUnless(zlib, "requires zlib") ++ @unittest.skipUnless(can_fs_encode(u'ã®ã‚¢ãƒ¼ã‚«ã‚¤ãƒ–'), ++ 'File system cannot handle this filename') ++ def test_make_tarball_unicode_extended(self): ++ """ ++ Mirror test_make_tarball, except filename is unicode and contains ++ characters outside the latin charset. ++ """ ++ self._make_tarball(u'ã®ã‚¢ãƒ¼ã‚«ã‚¤ãƒ–') # japanese for archive ++ + def test_suite(): + return unittest.makeSuite(ArchiveUtilTestCase) + +diff -r 8527427914a2 Lib/distutils/tests/test_bdist.py +--- a/Lib/distutils/tests/test_bdist.py ++++ b/Lib/distutils/tests/test_bdist.py +@@ -1,42 +1,49 @@ + """Tests for distutils.command.bdist.""" ++import os + import unittest +-import sys +-import os +-import tempfile +-import shutil + + from test.test_support import run_unittest + +-from distutils.core import Distribution + from distutils.command.bdist import bdist + from distutils.tests import support +-from distutils.spawn import find_executable +-from distutils import spawn +-from distutils.errors import DistutilsExecError ++ + + class BuildTestCase(support.TempdirManager, + unittest.TestCase): + + def test_formats(self): +- + # let's create a command and make sure +- # we can fix the format +- pkg_pth, dist = self.create_dist() ++ # we can set the format ++ dist = self.create_dist()[1] + cmd = bdist(dist) + cmd.formats = ['msi'] + cmd.ensure_finalized() + self.assertEqual(cmd.formats, ['msi']) + +- # what format bdist offers ? +- # XXX an explicit list in bdist is +- # not the best way to bdist_* commands +- # we should add a registry +- formats = ['rpm', 'zip', 'gztar', 'bztar', 'ztar', +- 'tar', 'wininst', 'msi'] +- formats.sort() +- founded = cmd.format_command.keys() +- founded.sort() +- self.assertEqual(founded, formats) ++ # what formats does bdist offer? ++ formats = ['bztar', 'gztar', 'msi', 'rpm', 'tar', ++ 'wininst', 'zip', 'ztar'] ++ found = sorted(cmd.format_command) ++ self.assertEqual(found, formats) ++ ++ def test_skip_build(self): ++ # bug #10946: bdist --skip-build should trickle down to subcommands ++ dist = self.create_dist()[1] ++ cmd = bdist(dist) ++ cmd.skip_build = 1 ++ cmd.ensure_finalized() ++ dist.command_obj['bdist'] = cmd ++ ++ names = ['bdist_dumb', 'bdist_wininst'] ++ # bdist_rpm does not support --skip-build ++ if os.name == 'nt': ++ names.append('bdist_msi') ++ ++ for name in names: ++ subcmd = cmd.get_finalized_command(name) ++ self.assertTrue(subcmd.skip_build, ++ '%s should take --skip-build from bdist' % name) ++ + + def test_suite(): + return unittest.makeSuite(BuildTestCase) +diff -r 8527427914a2 Lib/distutils/tests/test_build_clib.py +--- a/Lib/distutils/tests/test_build_clib.py ++++ b/Lib/distutils/tests/test_build_clib.py +@@ -122,7 +122,8 @@ + # before we run the command, we want to make sure + # all commands are present on the system + # by creating a compiler and checking its executables +- from distutils.ccompiler import new_compiler, customize_compiler ++ from distutils.ccompiler import new_compiler ++ from distutils.sysconfig import customize_compiler + + compiler = new_compiler() + customize_compiler(compiler) +diff -r 8527427914a2 Lib/distutils/tests/test_build_ext.py +--- a/Lib/distutils/tests/test_build_ext.py ++++ b/Lib/distutils/tests/test_build_ext.py +@@ -1,7 +1,5 @@ + import sys + import os +-import tempfile +-import shutil + from StringIO import StringIO + import textwrap + +@@ -9,7 +7,8 @@ + from distutils.command.build_ext import build_ext + from distutils import sysconfig + from distutils.tests import support +-from distutils.errors import DistutilsSetupError, CompileError ++from distutils.errors import (DistutilsSetupError, CompileError, ++ DistutilsPlatformError) + + import unittest + from test import test_support +@@ -18,71 +17,40 @@ + # Don't load the xx module more than once. + ALREADY_TESTED = False + +-def _get_source_filename(): +- srcdir = sysconfig.get_config_var('srcdir') +- if srcdir is None: +- return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c') +- return os.path.join(srcdir, 'Modules', 'xxmodule.c') +- +-_XX_MODULE_PATH = _get_source_filename() + + class BuildExtTestCase(support.TempdirManager, + support.LoggingSilencer, + unittest.TestCase): + def setUp(self): +- # Create a simple test environment +- # Note that we're making changes to sys.path + super(BuildExtTestCase, self).setUp() +- self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_") +- if os.path.exists(_XX_MODULE_PATH): +- self.sys_path = sys.path[:] +- sys.path.append(self.tmp_dir) +- shutil.copy(_XX_MODULE_PATH, self.tmp_dir) ++ self.tmp_dir = self.mkdtemp() ++ self.xx_created = False ++ sys.path.append(self.tmp_dir) ++ self.addCleanup(sys.path.remove, self.tmp_dir) ++ if sys.version > "2.6": ++ import site ++ self.old_user_base = site.USER_BASE ++ site.USER_BASE = self.mkdtemp() ++ from distutils.command import build_ext ++ build_ext.USER_BASE = site.USER_BASE + + def tearDown(self): +- # Get everything back to normal +- if os.path.exists(_XX_MODULE_PATH): ++ if self.xx_created: + test_support.unload('xx') +- sys.path[:] = self.sys_path + # XXX on Windows the test leaves a directory + # with xx module in TEMP +- shutil.rmtree(self.tmp_dir, os.name == 'nt' or +- sys.platform == 'cygwin') + super(BuildExtTestCase, self).tearDown() + +- def _fixup_command(self, cmd): +- # When Python was build with --enable-shared, -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. +- # +- # To further add to the fun, we can't just add library_dirs to the +- # Extension() instance because that doesn't get plumbed through to the +- # final compiler command. +- if (sysconfig.get_config_var('Py_ENABLE_SHARED') and +- not sys.platform.startswith('win')): +- runshared = sysconfig.get_config_var('RUNSHARED') +- if runshared is None: +- cmd.library_dirs = ['.'] +- else: +- name, equals, value = runshared.partition('=') +- cmd.library_dirs = value.split(os.pathsep) +- +- @unittest.skipIf(not os.path.exists(_XX_MODULE_PATH), +- 'xxmodule.c not found') + def test_build_ext(self): + global ALREADY_TESTED ++ support.copy_xxmodule_c(self.tmp_dir) ++ self.xx_created = True + xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') + xx_ext = Extension('xx', [xx_c]) + dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) + dist.package_dir = self.tmp_dir + cmd = build_ext(dist) +- self._fixup_command(cmd) +- if os.name == "nt": +- # On Windows, we must build a debug version iff running +- # a debug build of Python +- cmd.debug = sys.executable.endswith("_d.exe") ++ support.fixup_build_ext(cmd) + cmd.build_lib = self.tmp_dir + cmd.build_temp = self.tmp_dir + +@@ -135,6 +103,36 @@ + # make sure we get some library dirs under solaris + self.assertTrue(len(cmd.library_dirs) > 0) + ++ def test_user_site(self): ++ # site.USER_SITE was introduced in 2.6 ++ if sys.version < '2.6': ++ return ++ ++ import site ++ dist = Distribution({'name': 'xx'}) ++ cmd = build_ext(dist) ++ ++ # making sure the user option is there ++ options = [name for name, short, label in ++ cmd.user_options] ++ self.assertIn('user', options) ++ ++ # setting a value ++ cmd.user = 1 ++ ++ # setting user based lib and include ++ lib = os.path.join(site.USER_BASE, 'lib') ++ incl = os.path.join(site.USER_BASE, 'include') ++ os.mkdir(lib) ++ os.mkdir(incl) ++ ++ cmd.ensure_finalized() ++ ++ # see if include_dirs and library_dirs were set ++ self.assertIn(lib, cmd.library_dirs) ++ self.assertIn(lib, cmd.rpath) ++ self.assertIn(incl, cmd.include_dirs) ++ + def test_finalize_options(self): + # Make sure Python's include directories (for Python.h, pyconfig.h, + # etc.) are in the include search path. +@@ -143,7 +141,6 @@ + cmd = build_ext(dist) + cmd.finalize_options() + +- from distutils import sysconfig + py_include = sysconfig.get_python_inc() + self.assertTrue(py_include in cmd.include_dirs) + +@@ -153,21 +150,22 @@ + # make sure cmd.libraries is turned into a list + # if it's a string + cmd = build_ext(dist) +- cmd.libraries = 'my_lib' ++ cmd.libraries = 'my_lib, other_lib lastlib' + cmd.finalize_options() +- self.assertEqual(cmd.libraries, ['my_lib']) ++ self.assertEqual(cmd.libraries, ['my_lib', 'other_lib', 'lastlib']) + + # make sure cmd.library_dirs is turned into a list + # if it's a string + cmd = build_ext(dist) +- cmd.library_dirs = 'my_lib_dir' ++ cmd.library_dirs = 'my_lib_dir%sother_lib_dir' % os.pathsep + cmd.finalize_options() +- self.assertTrue('my_lib_dir' in cmd.library_dirs) ++ self.assertIn('my_lib_dir', cmd.library_dirs) ++ self.assertIn('other_lib_dir', cmd.library_dirs) + + # make sure rpath is turned into a list +- # if it's a list of os.pathsep's paths ++ # if it's a string + cmd = build_ext(dist) +- cmd.rpath = os.pathsep.join(['one', 'two']) ++ cmd.rpath = 'one%stwo' % os.pathsep + cmd.finalize_options() + self.assertEqual(cmd.rpath, ['one', 'two']) + +@@ -271,13 +269,10 @@ + dist = Distribution({'name': 'xx', + 'ext_modules': [ext]}) + cmd = build_ext(dist) +- self._fixup_command(cmd) ++ support.fixup_build_ext(cmd) + cmd.ensure_finalized() + self.assertEqual(len(cmd.get_outputs()), 1) + +- if os.name == "nt": +- cmd.debug = sys.executable.endswith("_d.exe") +- + cmd.build_lib = os.path.join(self.tmp_dir, 'build') + cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') + +@@ -432,18 +427,43 @@ + self.assertEqual(ext_path, wanted) + + @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') +- def test_deployment_target(self): +- self._try_compile_deployment_target() ++ def test_deployment_target_default(self): ++ # Issue 9516: Test that, in the absence of the environment variable, ++ # an extension module is compiled with the same deployment target as ++ # the interpreter. ++ self._try_compile_deployment_target('==', None) + ++ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') ++ def test_deployment_target_too_low(self): ++ # Issue 9516: Test that an extension module is not allowed to be ++ # compiled with a deployment target less than that of the interpreter. ++ self.assertRaises(DistutilsPlatformError, ++ self._try_compile_deployment_target, '>', '10.1') ++ ++ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') ++ def test_deployment_target_higher_ok(self): ++ # Issue 9516: Test that an extension module can be compiled with a ++ # deployment target higher than that of the interpreter: the ext ++ # module may depend on some newer OS feature. ++ deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') ++ if deptarget: ++ # increment the minor version number (i.e. 10.6 -> 10.7) ++ deptarget = [int(x) for x in deptarget.split('.')] ++ deptarget[-1] += 1 ++ deptarget = '.'.join(str(i) for i in deptarget) ++ self._try_compile_deployment_target('<', deptarget) ++ ++ def _try_compile_deployment_target(self, operator, target): + orig_environ = os.environ + os.environ = orig_environ.copy() + self.addCleanup(setattr, os, 'environ', orig_environ) + +- os.environ['MACOSX_DEPLOYMENT_TARGET']='10.1' +- self._try_compile_deployment_target() ++ if target is None: ++ if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): ++ del os.environ['MACOSX_DEPLOYMENT_TARGET'] ++ else: ++ os.environ['MACOSX_DEPLOYMENT_TARGET'] = target + +- +- def _try_compile_deployment_target(self): + deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c') + + with open(deptarget_c, 'w') as fp: +@@ -452,16 +472,17 @@ + + int dummy; + +- #if TARGET != MAC_OS_X_VERSION_MIN_REQUIRED ++ #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED ++ #else + #error "Unexpected target" +- #endif ++ #endif + +- ''')) ++ ''' % operator)) + ++ # get the deployment target that the interpreter was built with + target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') + target = tuple(map(int, target.split('.'))) + target = '%02d%01d0' % target +- + deptarget_ext = Extension( + 'deptarget', + [deptarget_c], +@@ -477,10 +498,8 @@ + cmd.build_temp = self.tmp_dir + + try: +- old_stdout = sys.stdout + cmd.ensure_finalized() + cmd.run() +- + except CompileError: + self.fail("Wrong deployment target during compilation") + +diff -r 8527427914a2 Lib/distutils/tests/test_ccompiler.py +--- a/Lib/distutils/tests/test_ccompiler.py ++++ b/Lib/distutils/tests/test_ccompiler.py +@@ -4,7 +4,8 @@ + from test.test_support import captured_stdout + + from distutils.ccompiler import (gen_lib_options, CCompiler, +- get_default_compiler, customize_compiler) ++ get_default_compiler) ++from distutils.sysconfig import customize_compiler + from distutils import debug + from distutils.tests import support + +diff -r 8527427914a2 Lib/distutils/tests/test_check.py +--- a/Lib/distutils/tests/test_check.py ++++ b/Lib/distutils/tests/test_check.py +@@ -1,3 +1,4 @@ ++# -*- encoding: utf8 -*- + """Tests for distutils.command.check.""" + import unittest + from test.test_support import run_unittest +@@ -46,6 +47,15 @@ + cmd = self._run(metadata, strict=1) + self.assertEqual(cmd._warnings, 0) + ++ # now a test with Unicode entries ++ metadata = {'url': u'xxx', 'author': u'\u00c9ric', ++ 'author_email': u'xxx', u'name': 'xxx', ++ 'version': u'xxx', ++ 'description': u'Something about esszet \u00df', ++ 'long_description': u'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 +90,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'] = u'title\n=====\n\ntest \u00df' + cmd = self._run(metadata, strict=1, restructuredtext=1) + self.assertEqual(cmd._warnings, 0) + +diff -r 8527427914a2 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 8527427914a2 Lib/distutils/tests/test_dist.py +--- a/Lib/distutils/tests/test_dist.py ++++ b/Lib/distutils/tests/test_dist.py +@@ -8,12 +8,13 @@ + import warnings + import textwrap + +-from distutils.dist import Distribution, fix_help_options, DistributionMetadata ++from distutils.dist import Distribution, fix_help_options + from distutils.cmd import Command + import distutils.dist + from test.test_support import TESTFN, captured_stdout, run_unittest + from distutils.tests import support + ++ + class test_dist(Command): + """Sample distutils extension command.""" + +@@ -61,7 +62,7 @@ + + def test_debug_mode(self): + with open(TESTFN, "w") as f: +- f.write("[global]") ++ f.write("[global]\n") + f.write("command_packages = foo.bar, splat") + + files = [TESTFN] +@@ -97,7 +98,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): +@@ -105,8 +106,8 @@ + self.addCleanup(os.unlink, TESTFN) + f = open(TESTFN, "w") + try: +- print >>f, "[global]" +- print >>f, "command_packages = foo.bar, splat" ++ print >> f, "[global]" ++ print >> f, "command_packages = foo.bar, splat" + finally: + f.close() + +@@ -138,7 +139,6 @@ + 'description': u'Café torréfié', + 'long_description': u'Héhéhé'}) + +- + # let's make sure the file can be written + # with Unicode fields. they are encoded with + # PKG_INFO_ENCODING +@@ -152,33 +152,28 @@ + 'long_description': 'Hehehe'}) + + my_file2 = os.path.join(tmp_dir, 'f2') +- dist.metadata.write_pkg_file(open(my_file, 'w')) ++ dist.metadata.write_pkg_file(open(my_file2, 'w')) + + 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'} + +@@ -201,7 +196,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() +@@ -251,15 +245,44 @@ + sys.argv[:] = self.argv[1] + super(MetadataTestCase, self).tearDown() + ++ 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_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", +@@ -271,9 +294,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, +@@ -291,11 +314,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, +@@ -313,11 +336,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, +@@ -353,14 +376,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) +@@ -382,22 +405,7 @@ + + output = [line for line in s.getvalue().split('\n') + if line.strip() != ''] +- self.assertTrue(len(output) > 0) +- +- 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 = distutils.dist.Distribution(attrs) +- meta = self.format_metadata(dist) +- meta = meta.replace('\n' + 8 * ' ', '\n') +- self.assertTrue(long_desc in meta) ++ self.assertTrue(output) + + def test_read_metadata(self): + attrs = {"name": "package", +@@ -426,6 +434,7 @@ + self.assertEqual(metadata.obsoletes, None) + self.assertEqual(metadata.requires, ['foo']) + ++ + def test_suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(DistributionTestCase)) +diff -r 8527427914a2 Lib/distutils/tests/test_filelist.py +--- a/Lib/distutils/tests/test_filelist.py ++++ b/Lib/distutils/tests/test_filelist.py +@@ -1,10 +1,13 @@ + """Tests for distutils.filelist.""" +-from os.path import join ++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 test.test_support import captured_stdout, run_unittest +- +-from distutils.filelist import glob_to_re, FileList +-from distutils import debug ++from distutils.tests import support + + MANIFEST_IN = """\ + include ok +@@ -20,7 +23,17 @@ + prune dir3 + """ + +-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 +@@ -40,15 +53,15 @@ + + # simulated file list + file_list.allfiles = ['foo.tmp', 'ok', 'xo', 'four.txt', +- join('global', 'one.txt'), +- join('global', 'two.txt'), +- join('global', 'files.x'), +- join('global', 'here.tmp'), +- join('f', 'o', 'f.oo'), +- join('dir', 'graft-one'), +- join('dir', 'dir2', 'graft2'), +- join('dir3', 'ok'), +- join('dir3', 'sub', 'ok.txt') ++ 'global/one.txt', ++ 'global/two.txt', ++ 'global/files.x', ++ 'global/here.tmp', ++ 'f/o/f.oo', ++ 'dir/graft-one', ++ 'dir/dir2/graft2', ++ 'dir3/ok', ++ 'dir3/sub/ok.txt', + ] + + for line in MANIFEST_IN.split('\n'): +@@ -56,9 +69,8 @@ + continue + file_list.process_template_line(line) + +- wanted = ['ok', 'four.txt', join('global', 'one.txt'), +- join('global', 'two.txt'), join('f', 'o', 'f.oo'), +- join('dir', 'graft-one'), join('dir', 'dir2', 'graft2')] ++ wanted = ['ok', 'four.txt', 'global/one.txt', 'global/two.txt', ++ 'f/o/f.oo', 'dir/graft-one', 'dir/dir2/graft2'] + + self.assertEqual(file_list.files, wanted) + +@@ -66,18 +78,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 8527427914a2 Lib/distutils/tests/test_install.py +--- a/Lib/distutils/tests/test_install.py ++++ b/Lib/distutils/tests/test_install.py +@@ -1,17 +1,33 @@ + """Tests for distutils.command.install.""" + + import os ++import sys + import unittest ++import site + +-from test.test_support import run_unittest ++from test.test_support import captured_stdout, run_unittest + ++from distutils import sysconfig + from distutils.command.install import install ++from distutils.command import install as install_module ++from distutils.command.build_ext import build_ext ++from distutils.command.install import INSTALL_SCHEMES + from distutils.core import Distribution ++from distutils.errors import DistutilsOptionError ++from distutils.extension import Extension + + from distutils.tests import support + + +-class InstallTestCase(support.TempdirManager, unittest.TestCase): ++def _make_ext_name(modname): ++ if os.name == 'nt' and sys.executable.endswith('_d.exe'): ++ modname += '_d' ++ return modname + sysconfig.get_config_var('SO') ++ ++ ++class InstallTestCase(support.TempdirManager, ++ support.LoggingSilencer, ++ unittest.TestCase): + + def test_home_installation_scheme(self): + # This ensure two things: +@@ -49,6 +65,181 @@ + check_path(cmd.install_scripts, os.path.join(destination, "bin")) + 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 ++ ++ # preparing the environment for the test ++ self.old_user_base = site.USER_BASE ++ self.old_user_site = site.USER_SITE ++ self.tmpdir = self.mkdtemp() ++ self.user_base = os.path.join(self.tmpdir, 'B') ++ self.user_site = os.path.join(self.tmpdir, 'S') ++ site.USER_BASE = self.user_base ++ site.USER_SITE = self.user_site ++ install_module.USER_BASE = self.user_base ++ install_module.USER_SITE = self.user_site ++ ++ def _expanduser(path): ++ return self.tmpdir ++ self.old_expand = os.path.expanduser ++ os.path.expanduser = _expanduser ++ ++ try: ++ # this is the actual test ++ self._test_user_site() ++ finally: ++ 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): ++ for key in ('nt_user', 'unix_user', 'os2_home'): ++ self.assertTrue(key in INSTALL_SCHEMES) ++ ++ dist = Distribution({'name': 'xx'}) ++ cmd = install(dist) ++ ++ # making sure the user option is there ++ options = [name for name, short, lable in ++ cmd.user_options] ++ self.assertTrue('user' in 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)) ++ ++ # let's run finalize ++ cmd.ensure_finalized() ++ ++ # now they should ++ 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) ++ ++ def test_handle_extra_path(self): ++ dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) ++ cmd = install(dist) ++ ++ # two elements ++ cmd.handle_extra_path() ++ self.assertEqual(cmd.extra_path, ['path', 'dirs']) ++ self.assertEqual(cmd.extra_dirs, 'dirs') ++ self.assertEqual(cmd.path_file, 'path') ++ ++ # one element ++ cmd.extra_path = ['path'] ++ cmd.handle_extra_path() ++ self.assertEqual(cmd.extra_path, ['path']) ++ self.assertEqual(cmd.extra_dirs, 'path') ++ self.assertEqual(cmd.path_file, 'path') ++ ++ # none ++ dist.extra_path = cmd.extra_path = None ++ cmd.handle_extra_path() ++ self.assertEqual(cmd.extra_path, None) ++ self.assertEqual(cmd.extra_dirs, '') ++ self.assertEqual(cmd.path_file, None) ++ ++ # three elements (no way !) ++ cmd.extra_path = 'path,dirs,again' ++ self.assertRaises(DistutilsOptionError, cmd.handle_extra_path) ++ ++ def test_finalize_options(self): ++ dist = Distribution({'name': 'xx'}) ++ cmd = install(dist) ++ ++ # must supply either prefix/exec-prefix/home or ++ # install-base/install-platbase -- not both ++ cmd.prefix = 'prefix' ++ cmd.install_base = 'base' ++ self.assertRaises(DistutilsOptionError, cmd.finalize_options) ++ ++ # must supply either home or prefix/exec-prefix -- not both ++ cmd.install_base = None ++ cmd.home = 'home' ++ self.assertRaises(DistutilsOptionError, cmd.finalize_options) ++ ++ # can't combine user with with prefix/exec_prefix/home or ++ # install_(plat)base ++ cmd.prefix = None ++ cmd.user = 'user' ++ self.assertRaises(DistutilsOptionError, cmd.finalize_options) ++ ++ def test_record(self): ++ install_dir = self.mkdtemp() ++ project_dir, dist = self.create_dist(scripts=['hello']) ++ self.addCleanup(os.chdir, os.getcwd()) ++ os.chdir(project_dir) ++ self.write_file('hello', "print('o hai')") ++ ++ cmd = install(dist) ++ dist.command_obj['install'] = cmd ++ cmd.root = install_dir ++ cmd.record = os.path.join(project_dir, 'RECORD') ++ cmd.ensure_finalized() ++ cmd.run() ++ ++ f = open(cmd.record) ++ try: ++ content = f.read() ++ finally: ++ f.close() ++ ++ found = [os.path.basename(line) for line in content.splitlines()] ++ expected = ['hello', ++ 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ self.assertEqual(found, expected) ++ ++ def test_record_extensions(self): ++ 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) ++ ++ buildextcmd = build_ext(dist) ++ support.fixup_build_ext(buildextcmd) ++ buildextcmd.ensure_finalized() ++ ++ cmd = install(dist) ++ dist.command_obj['install'] = cmd ++ dist.command_obj['build_ext'] = buildextcmd ++ cmd.root = install_dir ++ cmd.record = os.path.join(project_dir, 'RECORD') ++ cmd.ensure_finalized() ++ cmd.run() ++ ++ f = open(cmd.record) ++ try: ++ content = f.read() ++ finally: ++ f.close() ++ ++ found = [os.path.basename(line) for line in content.splitlines()] ++ expected = [_make_ext_name('xx'), ++ 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] ++ self.assertEqual(found, expected) ++ ++ def test_debug_mode(self): ++ # this covers the code called when DEBUG is set ++ old_logs_len = len(self.logs) ++ install_module.DEBUG = True ++ try: ++ with captured_stdout(): ++ self.test_record() ++ finally: ++ install_module.DEBUG = False ++ self.assertTrue(len(self.logs) > old_logs_len) + + def test_suite(): + return unittest.makeSuite(InstallTestCase) +diff -r 8527427914a2 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.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 8527427914a2 Lib/distutils/tests/test_register.py +--- a/Lib/distutils/tests/test_register.py ++++ b/Lib/distutils/tests/test_register.py +@@ -1,5 +1,5 @@ ++# -*- encoding: utf8 -*- + """Tests for distutils.command.register.""" +-# -*- encoding: utf8 -*- + import sys + import os + import unittest +@@ -246,6 +246,24 @@ + finally: + del register_module.raw_input + ++ # and finally a Unicode test (bug #12114) ++ metadata = {'url': u'xxx', 'author': u'\u00c9ric', ++ 'author_email': u'xxx', u'name': 'xxx', ++ 'version': u'xxx', ++ 'description': u'Something about esszet \u00df', ++ 'long_description': u'More things about esszet \u00df'} ++ ++ cmd = self._get_cmd(metadata) ++ cmd.ensure_finalized() ++ cmd.strict = 1 ++ inputs = RawInputs('1', 'tarek', 'y') ++ register_module.raw_input = inputs.__call__ ++ # let's run the command ++ try: ++ cmd.run() ++ finally: ++ del register_module.raw_input ++ + def test_check_metadata_deprecated(self): + # makes sure make_metadata is deprecated + cmd = self._get_cmd() +diff -r 8527427914a2 Lib/distutils/tests/test_sdist.py +--- a/Lib/distutils/tests/test_sdist.py ++++ b/Lib/distutils/tests/test_sdist.py +@@ -1,9 +1,11 @@ + """Tests for distutils.command.sdist.""" + import os ++import tarfile + import unittest +-import shutil ++import warnings + import zipfile +-import tarfile ++from os.path import join ++from textwrap import dedent + + # zlib is not used here, but if it's not available + # the tests that use zipfile may fail +@@ -19,20 +21,15 @@ + except ImportError: + UID_GID_SUPPORT = False + +-from os.path import join +-import sys +-import tempfile +-import warnings +- + from test.test_support import captured_stdout, check_warnings, run_unittest + + from distutils.command.sdist import sdist, show_formats + from distutils.core import Distribution + from distutils.tests.test_config import PyPIRCCommandTestCase +-from distutils.errors import DistutilsExecError, DistutilsOptionError ++from distutils.errors import DistutilsOptionError + from distutils.spawn import find_executable +-from distutils.tests import support + from distutils.log import WARN ++from distutils.filelist import FileList + from distutils.archive_util import ARCHIVE_FORMATS + + SETUP_PY = """ +@@ -89,9 +86,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, "requires zlib") +@@ -172,6 +166,28 @@ + self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) + + @unittest.skipUnless(zlib, "requires zlib") ++ def test_unicode_metadata_tgz(self): ++ """ ++ Unicode name or version should not break building to tar.gz format. ++ Reference issue #11638. ++ """ ++ ++ # create the sdist command with unicode parameters ++ dist, cmd = self.get_cmd({'name': u'fake', 'version': u'1.0'}) ++ ++ # create the sdist as gztar and run the command ++ cmd.formats = ['gztar'] ++ cmd.ensure_finalized() ++ cmd.run() ++ ++ # The command should have created the .tar.gz file ++ dist_folder = join(self.tmp_dir, 'dist') ++ result = os.listdir(dist_folder) ++ self.assertEqual(result, ['fake-1.0.tar.gz']) ++ ++ os.remove(join(dist_folder, 'fake-1.0.tar.gz')) ++ ++ @unittest.skipUnless(zlib, "requires zlib") + def test_add_defaults(self): + + # http://bugs.python.org/issue2279 +@@ -246,7 +262,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 +@@ -255,7 +272,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): +@@ -277,7 +295,6 @@ + self.assertEqual(len(output), num_formats) + + def test_finalize_options(self): +- + dist, cmd = self.get_cmd() + cmd.finalize_options() + +@@ -347,6 +364,32 @@ + finally: + archive.close() + ++ # the following tests make sure there is a nice error message instead ++ # of a traceback when parsing an invalid manifest template ++ ++ def _test_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._test_template('taunt knights *') ++ ++ def test_invalid_template_wrong_arguments(self): ++ # this manifest command takes one argument ++ self._test_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._test_template('include examples/') ++ + @unittest.skipUnless(zlib, "requires zlib") + def test_get_file_list(self): + # make sure MANIFEST is recalculated +@@ -355,6 +398,7 @@ + # filling data_files by pointing files in package_data + dist.package_data = {'somecode': ['*.txt']} + self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') ++ cmd.formats = ['gztar'] + cmd.ensure_finalized() + cmd.run() + +@@ -405,13 +449,34 @@ + self.assertEqual(manifest[0], + '# file GENERATED by distutils, do NOT edit') + ++ @unittest.skipUnless(zlib, 'requires zlib') ++ def test_manifest_comments(self): ++ # make sure comments don't cause exceptions or wrong includes ++ contents = dedent("""\ ++ # bad.py ++ #bad.py ++ good.py ++ """) ++ dist, cmd = self.get_cmd() ++ cmd.ensure_finalized() ++ self.write_file((self.tmp_dir, cmd.manifest), contents) ++ self.write_file((self.tmp_dir, 'good.py'), '# pick me!') ++ self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") ++ self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") ++ cmd.run() ++ self.assertEqual(cmd.filelist.files, ['good.py']) ++ + @unittest.skipUnless(zlib, "requires zlib") + def test_manual_manifest(self): + # check that a MANIFEST without a marker is left alone + dist, cmd = self.get_cmd() ++ cmd.formats = ['gztar'] + cmd.ensure_finalized() + self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') ++ self.write_file((self.tmp_dir, 'README.manual'), ++ 'This project maintains its MANIFEST file itself.') + cmd.run() ++ self.assertEqual(cmd.filelist.files, ['README.manual']) + + f = open(cmd.manifest) + try: +@@ -422,6 +487,15 @@ + + self.assertEqual(manifest, ['README.manual']) + ++ archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') ++ archive = tarfile.open(archive_name) ++ try: ++ filenames = [tarinfo.name for tarinfo in archive] ++ finally: ++ archive.close() ++ self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO', ++ 'fake-1.0/README.manual']) ++ + def test_suite(): + return unittest.makeSuite(SDistTestCase) + +diff -r 8527427914a2 Lib/distutils/util.py +--- a/Lib/distutils/util.py ++++ b/Lib/distutils/util.py +@@ -76,6 +76,11 @@ + if release[0] >= "5": # SunOS 5 == Solaris 2 + osname = "solaris" + release = "%d.%s" % (int(release[0]) - 3, release[2:]) ++ # We can't use "platform.architecture()[0]" because a ++ # bootstrap problem. We use a dict to get an error ++ # if some suspicious happens. ++ bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} ++ machine += ".%s" % bitness[sys.maxint] + # fall through to standard osname-release-machine representation + elif osname[:4] == "irix": # could be "irix64"! + return "%s-%s" % (osname, release) +diff -r 8527427914a2 Lib/doctest.py +--- a/Lib/doctest.py ++++ b/Lib/doctest.py +@@ -451,6 +451,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 +@@ -499,6 +518,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 __cmp__(self, other): +@@ -2252,6 +2287,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 8527427914a2 Lib/filecmp.py +--- a/Lib/filecmp.py ++++ b/Lib/filecmp.py +@@ -48,11 +48,12 @@ + if s1[1] != s2[1]: + return False + +- result = _cache.get((f1, f2)) +- if result and (s1, s2) == result[:2]: +- return result[2] +- outcome = _do_cmp(f1, f2) +- _cache[f1, f2] = s1, s2, outcome ++ outcome = _cache.get((f1, f2, s1, s2)) ++ if outcome is None: ++ outcome = _do_cmp(f1, f2) ++ if len(_cache) > 100: # limit the maximum size of the cache ++ _cache.clear() ++ _cache[f1, f2, s1, s2] = outcome + return outcome + + def _sig(st): +diff -r 8527427914a2 Lib/ftplib.py +--- a/Lib/ftplib.py ++++ b/Lib/ftplib.py +@@ -325,32 +325,39 @@ + if self.passiveserver: + host, port = self.makepasv() + conn = socket.create_connection((host, port), self.timeout) +- if rest is not None: +- self.sendcmd("REST %s" % rest) +- resp = self.sendcmd(cmd) +- # Some servers apparently send a 200 reply to +- # a LIST or STOR command, before the 150 reply +- # (and way before the 226 reply). This seems to +- # be in violation of the protocol (which only allows +- # 1xx or error messages for LIST), so we just discard +- # this response. +- if resp[0] == '2': +- resp = self.getresp() +- if resp[0] != '1': +- raise error_reply, resp ++ try: ++ if rest is not None: ++ self.sendcmd("REST %s" % rest) ++ resp = self.sendcmd(cmd) ++ # Some servers apparently send a 200 reply to ++ # a LIST or STOR command, before the 150 reply ++ # (and way before the 226 reply). This seems to ++ # be in violation of the protocol (which only allows ++ # 1xx or error messages for LIST), so we just discard ++ # this response. ++ if resp[0] == '2': ++ resp = self.getresp() ++ if resp[0] != '1': ++ raise error_reply, resp ++ except: ++ conn.close() ++ raise + else: + sock = self.makeport() +- if rest is not None: +- self.sendcmd("REST %s" % rest) +- resp = self.sendcmd(cmd) +- # See above. +- if resp[0] == '2': +- resp = self.getresp() +- if resp[0] != '1': +- raise error_reply, resp +- conn, sockaddr = sock.accept() +- if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT: +- conn.settimeout(self.timeout) ++ try: ++ if rest is not None: ++ self.sendcmd("REST %s" % rest) ++ resp = self.sendcmd(cmd) ++ # See above. ++ if resp[0] == '2': ++ resp = self.getresp() ++ if resp[0] != '1': ++ raise error_reply, resp ++ conn, sockaddr = sock.accept() ++ if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT: ++ conn.settimeout(self.timeout) ++ finally: ++ sock.close() + if resp[:3] == '150': + # this is conditional in case we received a 125 + size = parse150(resp) +@@ -575,11 +582,11 @@ + + def close(self): + '''Close the connection without assuming anything about it.''' +- if self.file: ++ if self.file is not None: + self.file.close() ++ if self.sock is not None: + self.sock.close() +- self.file = self.sock = None +- ++ self.file = self.sock = None + + try: + import ssl +diff -r 8527427914a2 Lib/gzip.py +--- a/Lib/gzip.py ++++ b/Lib/gzip.py +@@ -88,8 +88,12 @@ + if fileobj is None: + fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb') + if filename is None: +- if hasattr(fileobj, 'name'): filename = fileobj.name +- else: filename = '' ++ # Issue #13781: os.fdopen() creates a fileobj with a bogus name ++ # attribute. Avoid saving this in the gzip header's filename field. ++ if hasattr(fileobj, 'name') and fileobj.name != '': ++ filename = fileobj.name ++ else: ++ filename = '' + if mode is None: + if hasattr(fileobj, 'mode'): mode = fileobj.mode + else: mode = 'rb' +diff -r 8527427914a2 Lib/heapq.py +--- a/Lib/heapq.py ++++ b/Lib/heapq.py +@@ -193,6 +193,8 @@ + + Equivalent to: sorted(iterable, reverse=True)[:n] + """ ++ if n < 0: ++ return [] + it = iter(iterable) + result = list(islice(it, n)) + if not result: +@@ -209,6 +211,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 8527427914a2 Lib/httplib.py +--- a/Lib/httplib.py ++++ b/Lib/httplib.py +@@ -715,7 +715,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 +@@ -939,10 +942,10 @@ + """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 ++ 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 possible. The +- message_body should be a string. ++ the same packet as the message headers if it is string, otherwise it is ++ sent as a separate packet. + """ + if self.__state == _CS_REQ_STARTED: + self.__state = _CS_REQ_SENT +@@ -1322,71 +1325,3 @@ + return L + self._file.readlines() + else: + return L + self._file.readlines(size) +- +-def test(): +- """Test this module. +- +- A hodge podge of tests collected here, because they have too many +- external dependencies for the regular test suite. +- """ +- +- import sys +- import getopt +- opts, args = getopt.getopt(sys.argv[1:], 'd') +- dl = 0 +- for o, a in opts: +- if o == '-d': dl = dl + 1 +- host = 'www.python.org' +- selector = '/' +- if args[0:]: host = args[0] +- if args[1:]: selector = args[1] +- h = HTTP() +- h.set_debuglevel(dl) +- h.connect(host) +- h.putrequest('GET', selector) +- h.endheaders() +- status, reason, headers = h.getreply() +- print 'status =', status +- print 'reason =', reason +- print "read", len(h.getfile().read()) +- print +- if headers: +- for header in headers.headers: print header.strip() +- print +- +- # minimal test that code to extract host from url works +- class HTTP11(HTTP): +- _http_vsn = 11 +- _http_vsn_str = 'HTTP/1.1' +- +- h = HTTP11('www.python.org') +- h.putrequest('GET', 'http://www.python.org/~jeremy/') +- h.endheaders() +- h.getreply() +- h.close() +- +- try: +- import ssl +- except ImportError: +- pass +- else: +- +- for host, selector in (('sourceforge.net', '/projects/python'), +- ): +- print "https://%s%s" % (host, selector) +- hs = HTTPS() +- hs.set_debuglevel(dl) +- hs.connect(host) +- hs.putrequest('GET', selector) +- hs.endheaders() +- status, reason, headers = hs.getreply() +- print 'status =', status +- print 'reason =', reason +- print "read", len(hs.getfile().read()) +- print +- if headers: +- for header in headers.headers: print header.strip() +- print +- +-if __name__ == '__main__': +- test() +diff -r 8527427914a2 Lib/idlelib/AutoComplete.py +--- a/Lib/idlelib/AutoComplete.py ++++ b/Lib/idlelib/AutoComplete.py +@@ -190,8 +190,7 @@ + bigl = eval("dir()", namespace) + bigl.sort() + if "__all__" in bigl: +- smalll = eval("__all__", namespace) +- smalll.sort() ++ smalll = sorted(eval("__all__", namespace)) + else: + smalll = [s for s in bigl if s[:1] != '_'] + else: +@@ -200,8 +199,7 @@ + bigl = dir(entity) + bigl.sort() + if "__all__" in bigl: +- smalll = entity.__all__ +- smalll.sort() ++ smalll = sorted(entity.__all__) + else: + smalll = [s for s in bigl if s[:1] != '_'] + except: +diff -r 8527427914a2 Lib/idlelib/EditorWindow.py +--- a/Lib/idlelib/EditorWindow.py ++++ b/Lib/idlelib/EditorWindow.py +@@ -65,6 +65,50 @@ + descr = filename, None, imp.PY_SOURCE + return file, filename, descr + ++ ++class HelpDialog(object): ++ ++ def __init__(self): ++ self.parent = None # parent of help window ++ self.dlg = None # the help window iteself ++ ++ def display(self, parent, near=None): ++ """ Display the help dialog. ++ ++ parent - parent widget for the help window ++ ++ near - a Toplevel widget (e.g. EditorWindow or PyShell) ++ to use as a reference for placing the help window ++ """ ++ if self.dlg is None: ++ self.show_dialog(parent) ++ if near: ++ self.nearwindow(near) ++ ++ def show_dialog(self, parent): ++ self.parent = parent ++ fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') ++ self.dlg = dlg = textView.view_file(parent,'Help',fn, modal=False) ++ dlg.bind('', self.destroy, '+') ++ ++ def nearwindow(self, near): ++ # Place the help dialog near the window specified by parent. ++ # Note - this may not reposition the window in Metacity ++ # if "/apps/metacity/general/disable_workarounds" is enabled ++ dlg = self.dlg ++ geom = (near.winfo_rootx() + 10, near.winfo_rooty() + 10) ++ dlg.withdraw() ++ dlg.geometry("=+%d+%d" % geom) ++ dlg.deiconify() ++ dlg.lift() ++ ++ def destroy(self, ev=None): ++ self.dlg = None ++ self.parent = None ++ ++helpDialog = HelpDialog() # singleton instance ++ ++ + class EditorWindow(object): + from idlelib.Percolator import Percolator + from idlelib.ColorDelegator import ColorDelegator +@@ -459,8 +503,11 @@ + configDialog.ConfigDialog(self.top,'Settings') + + def help_dialog(self, event=None): +- fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') +- textView.view_file(self.top,'Help',fn) ++ if self.root: ++ parent = self.root ++ else: ++ parent = self.top ++ helpDialog.display(parent, near=self.top) + + def python_docs(self, event=None): + if sys.platform[:3] == 'win': +@@ -796,11 +843,16 @@ + 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') + try: +- rf_file.writelines(rf_list) +- finally: +- rf_file.close() ++ with open(self.recent_files_path, 'w') 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.keys(): + menu = instance.recent_files_menu +@@ -1130,7 +1182,10 @@ + assert have > 0 + want = ((have - 1) // self.indentwidth) * self.indentwidth + # Debug prompt is multilined.... +- last_line_of_prompt = sys.ps1.split('\n')[-1] ++ if self.context_use_ps1: ++ last_line_of_prompt = sys.ps1.split('\n')[-1] ++ else: ++ last_line_of_prompt = '' + ncharsdeleted = 0 + while 1: + if chars == last_line_of_prompt: +diff -r 8527427914a2 Lib/idlelib/IOBinding.py +--- a/Lib/idlelib/IOBinding.py ++++ b/Lib/idlelib/IOBinding.py +@@ -266,7 +266,7 @@ + self.reset_undo() + self.set_filename(filename) + self.text.mark_set("insert", "1.0") +- self.text.see("insert") ++ self.text.yview("insert") + self.updaterecentfileslist(filename) + return True + +diff -r 8527427914a2 Lib/idlelib/PyShell.py +--- a/Lib/idlelib/PyShell.py ++++ b/Lib/idlelib/PyShell.py +@@ -61,7 +61,7 @@ + file = warning_stream + try: + file.write(warnings.formatwarning(message, category, filename, +- lineno, file=file, line=line)) ++ lineno, line=line)) + except IOError: + pass ## file (probably __stderr__) is invalid, warning dropped. + warnings.showwarning = idle_showwarning +@@ -207,18 +207,26 @@ + breaks = self.breakpoints + filename = self.io.filename + try: +- lines = open(self.breakpointPath,"r").readlines() ++ with open(self.breakpointPath,"r") as old_file: ++ lines = old_file.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 +@@ -344,6 +352,7 @@ + self.restarting = False + self.subprocess_arglist = None + self.port = PORT ++ self.original_compiler_flags = self.compile.compiler.flags + + rpcclt = None + rpcpid = None +@@ -414,11 +423,11 @@ + self.rpcclt.register("flist", self.tkconsole.flist) + self.rpcclt.register("linecache", linecache) + self.rpcclt.register("interp", self) +- self.transfer_path() ++ self.transfer_path(with_cwd=True) + self.poll_subprocess() + return self.rpcclt + +- def restart_subprocess(self): ++ def restart_subprocess(self, with_cwd=False): + if self.restarting: + return self.rpcclt + self.restarting = True +@@ -442,7 +451,7 @@ + except socket.timeout, err: + self.display_no_subprocess_error() + return None +- self.transfer_path() ++ self.transfer_path(with_cwd=with_cwd) + # annotate restart in shell window and mark it + console.text.delete("iomark", "end-1c") + if was_executing: +@@ -459,6 +468,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 + +@@ -491,12 +501,18 @@ + except OSError: + return + +- def transfer_path(self): ++ def transfer_path(self, with_cwd=False): ++ if with_cwd: # Issue 13506 ++ path = [''] # include Current Working Directory ++ path.extend(sys.path) ++ else: ++ path = sys.path ++ + self.runcommand("""if 1: + import sys as _sys + _sys.path = %r + del _sys +- \n""" % (sys.path,)) ++ \n""" % (path,)) + + active_seq = None + +@@ -1199,7 +1215,8 @@ + self.text.see("restart") + + def restart_shell(self, event=None): +- self.interp.restart_subprocess() ++ "Callback for Run/Restart Shell Cntl-F6" ++ self.interp.restart_subprocess(with_cwd=True) + + def showprompt(self): + self.resetoutput() +diff -r 8527427914a2 Lib/idlelib/ScriptBinding.py +--- a/Lib/idlelib/ScriptBinding.py ++++ b/Lib/idlelib/ScriptBinding.py +@@ -101,7 +101,7 @@ + try: + # If successful, return the compiled code + return compile(source, filename, "exec") +- except (SyntaxError, OverflowError), err: ++ except (SyntaxError, OverflowError, ValueError), err: + try: + msg, (errorfilename, lineno, offset, line) = err + if not errorfilename: +@@ -146,10 +146,9 @@ + return 'break' + if not self.tabnanny(filename): + return 'break' +- shell = self.shell +- interp = shell.interp ++ interp = self.shell.interp + if PyShell.use_subprocess: +- shell.restart_shell() ++ interp.restart_subprocess(with_cwd=False) + dirname = os.path.dirname(filename) + # XXX Too often this discards arguments the user just set... + interp.runcommand("""if 1: +diff -r 8527427914a2 Lib/idlelib/textView.py +--- a/Lib/idlelib/textView.py ++++ b/Lib/idlelib/textView.py +@@ -9,7 +9,7 @@ + """A simple text viewer dialog for IDLE + + """ +- def __init__(self, parent, title, text): ++ def __init__(self, parent, title, text, modal=True): + """Show the given text in a scrollable window with a 'close' button + + """ +@@ -24,8 +24,6 @@ + + self.CreateWidgets() + self.title(title) +- self.transient(parent) +- self.grab_set() + self.protocol("WM_DELETE_WINDOW", self.Ok) + self.parent = parent + self.textView.focus_set() +@@ -34,7 +32,11 @@ + self.bind('',self.Ok) #dismiss dialog + self.textView.insert(0.0, text) + self.textView.config(state=DISABLED) +- self.wait_window() ++ ++ if modal: ++ self.transient(parent) ++ self.grab_set() ++ self.wait_window() + + def CreateWidgets(self): + frameText = Frame(self, relief=SUNKEN, height=700) +@@ -57,10 +59,10 @@ + self.destroy() + + +-def view_text(parent, title, text): +- TextViewer(parent, title, text) ++def view_text(parent, title, text, modal=True): ++ return TextViewer(parent, title, text, modal) + +-def view_file(parent, title, filename, encoding=None): ++def view_file(parent, title, filename, encoding=None, modal=True): + try: + if encoding: + import codecs +@@ -73,7 +75,7 @@ + message='Unable to load file %r .' % filename, + parent=parent) + else: +- return view_text(parent, title, textFile.read()) ++ return view_text(parent, title, textFile.read(), modal) + + + if __name__ == '__main__': +@@ -83,11 +85,15 @@ + filename = './textView.py' + text = file(filename, 'r').read() + btn1 = Button(root, text='view_text', +- command=lambda:view_text(root, 'view_text', text)) ++ command=lambda:view_text(root, 'view_text', text)) + btn1.pack(side=LEFT) + btn2 = Button(root, text='view_file', + command=lambda:view_file(root, 'view_file', filename)) + btn2.pack(side=LEFT) ++ btn3 = Button(root, text='nonmodal view_text', ++ command=lambda:view_text(root, 'nonmodal view_text', text, ++ modal=False)) ++ btn3.pack(side=LEFT) + close = Button(root, text='Close', command=root.destroy) + close.pack(side=RIGHT) + root.mainloop() +diff -r 8527427914a2 Lib/inspect.py +--- a/Lib/inspect.py ++++ b/Lib/inspect.py +@@ -288,30 +288,21 @@ + names = dir(cls) + result = [] + for name in names: +- # Get the object associated with the name. ++ # Get the object associated with the name, and where it was defined. + # Getting an obj from the __dict__ sometimes reveals more than + # using getattr. Static and class methods are dramatic examples. +- if name in cls.__dict__: +- obj = cls.__dict__[name] ++ # Furthermore, some objects may raise an Exception when fetched with ++ # getattr(). This is the case with some descriptors (bug #1785). ++ # Thus, we only use getattr() as a last resort. ++ homecls = None ++ for base in (cls,) + mro: ++ if name in base.__dict__: ++ obj = base.__dict__[name] ++ homecls = base ++ break + else: + obj = getattr(cls, name) +- +- # Figure out where it was defined. +- homecls = getattr(obj, "__objclass__", None) +- if homecls is None: +- # search the dicts. +- for base in mro: +- if name in base.__dict__: +- homecls = base +- break +- +- # Get the object again, in order to get it from the defining +- # __dict__ instead of via getattr (if possible). +- if homecls is not None and name in homecls.__dict__: +- obj = homecls.__dict__[name] +- +- # Also get the object via getattr. +- obj_via_getattr = getattr(cls, name) ++ homecls = getattr(obj, "__objclass__", homecls) + + # Classify the object. + if isinstance(obj, staticmethod): +@@ -320,11 +311,18 @@ + kind = "class method" + elif isinstance(obj, property): + kind = "property" +- elif (ismethod(obj_via_getattr) or +- ismethoddescriptor(obj_via_getattr)): ++ elif ismethoddescriptor(obj): + kind = "method" ++ elif isdatadescriptor(obj): ++ kind = "data" + else: +- kind = "data" ++ obj_via_getattr = getattr(cls, name) ++ if (ismethod(obj_via_getattr) or ++ ismethoddescriptor(obj_via_getattr)): ++ kind = "method" ++ else: ++ kind = "data" ++ obj = obj_via_getattr + + result.append(Attribute(name, kind, homecls, obj)) + +@@ -524,9 +522,13 @@ + or code object. The source code is returned as a list of all the lines + in the file and the line number indexes a line in that list. An IOError + is raised if the source code cannot be retrieved.""" +- file = getsourcefile(object) +- if not file: ++ ++ file = getfile(object) ++ sourcefile = getsourcefile(object) ++ if not sourcefile and file[0] + file[-1] != '<>': + raise IOError('source code not available') ++ file = sourcefile if sourcefile else file ++ + module = getmodule(object, file) + if module: + lines = linecache.getlines(file, module.__dict__) +diff -r 8527427914a2 Lib/json/tests/test_unicode.py +--- a/Lib/json/tests/test_unicode.py ++++ b/Lib/json/tests/test_unicode.py +@@ -80,6 +80,10 @@ + # Issue 10038. + self.assertEqual(type(self.loads('"foo"')), unicode) + ++ def test_bad_encoding(self): ++ self.assertRaises(UnicodeEncodeError, self.loads, '"a"', u"rat\xe9") ++ self.assertRaises(TypeError, self.loads, '"a"', 1) ++ + + class TestPyUnicode(TestUnicode, PyTest): pass + class TestCUnicode(TestUnicode, CTest): pass +diff -r 8527427914a2 Lib/lib-tk/Tix.py +--- a/Lib/lib-tk/Tix.py ++++ b/Lib/lib-tk/Tix.py +@@ -1874,13 +1874,13 @@ + return self.tk.call(self, 'info', 'bbox', x, y) + + def move_column(self, from_, to, offset): +- """Moves the the range of columns from position FROM through TO by ++ """Moves the range of columns from position FROM through TO by + the distance indicated by OFFSET. For example, move_column(2, 4, 1) + moves the columns 2,3,4 to columns 3,4,5.""" + self.tk.call(self, 'move', 'column', from_, to, offset) + + def move_row(self, from_, to, offset): +- """Moves the the range of rows from position FROM through TO by ++ """Moves the range of rows from position FROM through TO by + the distance indicated by OFFSET. + For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5.""" + self.tk.call(self, 'move', 'row', from_, to, offset) +@@ -1939,7 +1939,7 @@ + pad0 pixels + Specifies the paddings to the top of a row. + pad1 pixels +- Specifies the paddings to the the bottom of a row. ++ Specifies the paddings to the bottom of a row. + size val + Specifies the height of a row. + Val may be: "auto" -- the height of the row is set the +diff -r 8527427914a2 Lib/lib-tk/Tkinter.py +--- a/Lib/lib-tk/Tkinter.py ++++ b/Lib/lib-tk/Tkinter.py +@@ -30,7 +30,7 @@ + tk.mainloop() + """ + +-__version__ = "$Revision$" ++__version__ = "$Revision: 81008 $" + + import sys + if sys.platform == "win32": +diff -r 8527427914a2 Lib/lib-tk/test/runtktests.py +--- a/Lib/lib-tk/test/runtktests.py ++++ b/Lib/lib-tk/test/runtktests.py +@@ -14,6 +14,49 @@ + + this_dir_path = os.path.abspath(os.path.dirname(__file__)) + ++_tk_unavailable = None ++ ++def check_tk_availability(): ++ """Check that Tk is installed and available.""" ++ global _tk_unavailable ++ ++ if _tk_unavailable is None: ++ _tk_unavailable = False ++ if sys.platform == 'darwin': ++ # The Aqua Tk implementations on OS X can abort the process if ++ # being called in an environment where a window server connection ++ # cannot be made, for instance when invoked by a buildbot or ssh ++ # process not running under the same user id as the current console ++ # user. To avoid that, raise an exception if the window manager ++ # connection is not available. ++ from ctypes import cdll, c_int, pointer, Structure ++ from ctypes.util import find_library ++ ++ app_services = cdll.LoadLibrary(find_library("ApplicationServices")) ++ ++ if app_services.CGMainDisplayID() == 0: ++ _tk_unavailable = "cannot run without OS X window manager" ++ else: ++ class ProcessSerialNumber(Structure): ++ _fields_ = [("highLongOfPSN", c_int), ++ ("lowLongOfPSN", c_int)] ++ psn = ProcessSerialNumber() ++ psn_p = pointer(psn) ++ if ( (app_services.GetCurrentProcess(psn_p) < 0) or ++ (app_services.SetFrontProcess(psn_p) < 0) ): ++ _tk_unavailable = "cannot run without OS X gui process" ++ else: # not OS X ++ import Tkinter ++ try: ++ Tkinter.Button() ++ except Tkinter.TclError as msg: ++ # assuming tk is not available ++ _tk_unavailable = "tk not available: %s" % msg ++ ++ if _tk_unavailable: ++ raise unittest.SkipTest(_tk_unavailable) ++ return ++ + def is_package(path): + for name in os.listdir(path): + if name in ('__init__.py', '__init__.pyc', '__init.pyo'): +diff -r 8527427914a2 Lib/lib-tk/test/test_ttk/test_widgets.py +--- a/Lib/lib-tk/test/test_ttk/test_widgets.py ++++ b/Lib/lib-tk/test/test_ttk/test_widgets.py +@@ -2,6 +2,7 @@ + import Tkinter + import ttk + from test.test_support import requires, run_unittest ++import sys + + import support + from test_functions import MockTclObj, MockStateSpec +@@ -560,11 +561,19 @@ + + self.nb.pack() + self.nb.wait_visibility() +- self.assertEqual(self.nb.tab('@5,5'), self.nb.tab('current')) ++ if sys.platform == 'darwin': ++ tb_idx = "@20,5" ++ else: ++ tb_idx = "@5,5" ++ self.assertEqual(self.nb.tab(tb_idx), self.nb.tab('current')) + + for i in range(5, 100, 5): +- if self.nb.tab('@%d, 5' % i, text=None) == 'a': +- break ++ try: ++ if self.nb.tab('@%d, 5' % i, text=None) == 'a': ++ break ++ except Tkinter.TclError: ++ pass ++ + else: + self.fail("Tab with text 'a' not found") + +@@ -721,7 +730,10 @@ + self.nb.enable_traversal() + self.nb.focus_force() + support.simulate_mouse_click(self.nb, 5, 5) +- self.nb.event_generate('') ++ if sys.platform == 'darwin': ++ self.nb.event_generate('') ++ else: ++ self.nb.event_generate('') + self.assertEqual(self.nb.select(), str(self.child1)) + + +@@ -925,7 +937,8 @@ + self.assertRaises(Tkinter.TclError, self.tv.heading, '#0', + anchor=1) + +- ++ # XXX skipping for now; should be fixed to work with newer ttk ++ @unittest.skip("skipping pending resolution of Issue #10734") + def test_heading_callback(self): + def simulate_heading_click(x, y): + support.simulate_mouse_click(self.tv, x, y) +diff -r 8527427914a2 Lib/lib-tk/turtle.py +--- a/Lib/lib-tk/turtle.py ++++ b/Lib/lib-tk/turtle.py +@@ -27,10 +27,10 @@ + kids. It was part of the original Logo programming language developed + by Wally Feurzig and Seymour Papert in 1966. + +-Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it ++Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it + the command turtle.forward(15), and it moves (on-screen!) 15 pixels in + the direction it is facing, drawing a line as it moves. Give it the +-command turtle.left(25), and it rotates in-place 25 degrees clockwise. ++command turtle.right(25), and it rotates in-place 25 degrees clockwise. + + By combining together these and similar commands, intricate shapes and + pictures can easily be drawn. +@@ -96,7 +96,7 @@ + docstrings to disc, so it can serve as a template for translations. + + Behind the scenes there are some features included with possible +-extensions in in mind. These will be commented and documented elsewhere. ++extensions in mind. These will be commented and documented elsewhere. + + """ + +@@ -859,7 +859,7 @@ + >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) + >>> s = Shape("compound") + >>> s.addcomponent(poly, "red", "blue") +- ### .. add more components and then use register_shape() ++ >>> # .. add more components and then use register_shape() + """ + if self._type != "compound": + raise TurtleGraphicsError("Cannot add component to %s Shape" +@@ -958,7 +958,7 @@ + No argument. + + Example (for a TurtleScreen instance named screen): +- screen.clear() ++ >>> screen.clear() + + Note: this method is not available as function. + """ +@@ -1030,8 +1030,8 @@ + Example (for a TurtleScreen instance named screen): + >>> screen.setworldcoordinates(-10,-0.5,50,1.5) + >>> for _ in range(36): +- left(10) +- forward(0.5) ++ ... left(10) ++ ... forward(0.5) + """ + if self.mode() != "world": + self.mode("world") +@@ -1136,7 +1136,7 @@ + >>> screen.colormode() + 1.0 + >>> screen.colormode(255) +- >>> turtle.pencolor(240,160,80) ++ >>> pencolor(240,160,80) + """ + if cmode is None: + return self._colormode +@@ -1204,9 +1204,9 @@ + >>> screen.tracer(8, 25) + >>> dist = 2 + >>> for i in range(200): +- fd(dist) +- rt(90) +- dist += 2 ++ ... fd(dist) ++ ... rt(90) ++ ... dist += 2 + """ + if n is None: + return self._tracing +@@ -1233,7 +1233,7 @@ + self._delayvalue = int(delay) + + def _incrementudc(self): +- "Increment upadate counter.""" ++ """Increment upadate counter.""" + if not TurtleScreen._RUNNING: + TurtleScreen._RUNNNING = True + raise Terminator +@@ -1304,13 +1304,10 @@ + Example (for a TurtleScreen instance named screen + and a Turtle instance named turtle): + +- >>> screen.onclick(turtle.goto) +- +- ### Subsequently clicking into the TurtleScreen will +- ### make the turtle move to the clicked point. ++ >>> screen.onclick(goto) ++ >>> # Subsequently clicking into the TurtleScreen will ++ >>> # make the turtle move to the clicked point. + >>> screen.onclick(None) +- +- ### event-binding will be removed + """ + self._onscreenclick(fun, btn, add) + +@@ -1324,20 +1321,18 @@ + In order to be able to register key-events, TurtleScreen + must have focus. (See method listen.) + +- Example (for a TurtleScreen instance named screen +- and a Turtle instance named turtle): ++ Example (for a TurtleScreen instance named screen): + + >>> def f(): +- fd(50) +- lt(60) +- +- ++ ... fd(50) ++ ... lt(60) ++ ... + >>> screen.onkey(f, "Up") + >>> screen.listen() + +- ### Subsequently the turtle can be moved by +- ### repeatedly pressing the up-arrow key, +- ### consequently drawing a hexagon ++ Subsequently the turtle can be moved by repeatedly pressing ++ the up-arrow key, consequently drawing a hexagon ++ + """ + if fun is None: + if key in self._keys: +@@ -1369,12 +1364,12 @@ + + >>> running = True + >>> def f(): +- if running: +- fd(50) +- lt(60) +- screen.ontimer(f, 250) +- +- >>> f() ### makes the turtle marching around ++ ... if running: ++ ... fd(50) ++ ... lt(60) ++ ... screen.ontimer(f, 250) ++ ... ++ >>> f() # makes the turtle marching around + >>> running = False + """ + self._ontimer(fun, t) +@@ -1418,7 +1413,7 @@ + + Example (for a Turtle instance named turtle): + >>> turtle.screensize(2000,1500) +- ### e. g. to search for an erroneously escaped turtle ;-) ++ >>> # e. g. to search for an erroneously escaped turtle ;-) + """ + return self._resize(canvwidth, canvheight, bg) + +@@ -2004,7 +1999,7 @@ + Example (for a Turtle instance named turtle): + >>> turtle.pensize() + 1 +- turtle.pensize(10) # from here on lines of width 10 are drawn ++ >>> turtle.pensize(10) # from here on lines of width 10 are drawn + """ + if width is None: + return self._pensize +@@ -2516,7 +2511,7 @@ + + Example (for a Turtle instance named turtle): + >>> while undobufferentries(): +- undo() ++ ... undo() + """ + if self.undobuffer is None: + return 0 +@@ -2592,9 +2587,9 @@ + >>> turtle.tracer(8, 25) + >>> dist = 2 + >>> for i in range(200): +- turtle.fd(dist) +- turtle.rt(90) +- dist += 2 ++ ... turtle.fd(dist) ++ ... turtle.rt(90) ++ ... dist += 2 + """ + return self.screen.tracer(flag, delay) + +@@ -2763,7 +2758,6 @@ + >>> turtle.shapesize(5,2) + >>> turtle.tilt(45) + >>> turtle.tiltangle() +- >>> + """ + tilt = -self._tilt * (180.0/math.pi) * self._angleOrient + return (tilt / self._degreesPerAU) % self._fullcircle +@@ -2963,7 +2957,7 @@ + + Example (for a Turtle instance named turtle): + >>> for i in range(8): +- turtle.stamp(); turtle.fd(30) ++ ... turtle.stamp(); turtle.fd(30) + ... + >>> turtle.clearstamps(2) + >>> turtle.clearstamps(-2) +@@ -3430,9 +3424,9 @@ + Example for the anonymous turtle, i. e. the procedural way: + + >>> def turn(x, y): +- left(360) +- +- >>> onclick(turn) # Now clicking into the turtle will turn it. ++ ... left(360) ++ ... ++ >>> onclick(turn) # Now clicking into the turtle will turn it. + >>> onclick(None) # event-binding will be removed + """ + self.screen._onclick(self.turtle._item, fun, btn, add) +@@ -3448,16 +3442,17 @@ + + Example (for a MyTurtle instance named joe): + >>> class MyTurtle(Turtle): +- def glow(self,x,y): +- self.fillcolor("red") +- def unglow(self,x,y): +- self.fillcolor("") +- ++ ... def glow(self,x,y): ++ ... self.fillcolor("red") ++ ... def unglow(self,x,y): ++ ... self.fillcolor("") ++ ... + >>> joe = MyTurtle() + >>> joe.onclick(joe.glow) + >>> joe.onrelease(joe.unglow) +- ### clicking on joe turns fillcolor red, +- ### unclicking turns it to transparent. ++ ++ Clicking on joe turns fillcolor red, unclicking turns it to ++ transparent. + """ + self.screen._onrelease(self.turtle._item, fun, btn, add) + self._update() +@@ -3476,9 +3471,9 @@ + Example (for a Turtle instance named turtle): + >>> turtle.ondrag(turtle.goto) + +- ### Subsequently clicking and dragging a Turtle will +- ### move it across the screen thereby producing handdrawings +- ### (if pen is down). ++ Subsequently clicking and dragging a Turtle will move it ++ across the screen thereby producing handdrawings (if pen is ++ down). + """ + self.screen._ondrag(self.turtle._item, fun, btn, add) + +@@ -3525,10 +3520,11 @@ + + Example (for a Turtle instance named turtle): + >>> for i in range(4): +- turtle.fd(50); turtle.lt(80) +- ++ ... turtle.fd(50); turtle.lt(80) ++ ... + >>> for i in range(8): +- turtle.undo() ++ ... turtle.undo() ++ ... + """ + if self.undobuffer is None: + return +diff -r 8527427914a2 Lib/lib2to3/Grammar.txt +--- a/Lib/lib2to3/Grammar.txt ++++ b/Lib/lib2to3/Grammar.txt +@@ -1,4 +1,4 @@ +-# Grammar for Python ++# Grammar for 2to3. This grammar supports Python 2.x and 3.x. + + # Note: Changing the grammar specified in this file will most likely + # require corresponding changes in the parser module +diff -r 8527427914a2 Lib/lib2to3/main.py +--- a/Lib/lib2to3/main.py ++++ b/Lib/lib2to3/main.py +@@ -25,12 +25,41 @@ + + class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): + """ ++ A refactoring tool that can avoid overwriting its input files. + Prints output to stdout. ++ ++ Output files can optionally be written to a different directory and or ++ have an extra file suffix appended to their name for use in situations ++ where you do not want to replace the input files. + """ + +- def __init__(self, fixers, options, explicit, nobackups, show_diffs): ++ def __init__(self, fixers, options, explicit, nobackups, show_diffs, ++ input_base_dir='', output_dir='', append_suffix=''): ++ """ ++ Args: ++ fixers: A list of fixers to import. ++ options: A dict with RefactoringTool configuration. ++ explicit: A list of fixers to run even if they are explicit. ++ nobackups: If true no backup '.bak' files will be created for those ++ files that are being refactored. ++ show_diffs: Should diffs of the refactoring be printed to stdout? ++ input_base_dir: The base directory for all input files. This class ++ will strip this path prefix off of filenames before substituting ++ it with output_dir. Only meaningful if output_dir is supplied. ++ All files processed by refactor() must start with this path. ++ output_dir: If supplied, all converted files will be written into ++ this directory tree instead of input_base_dir. ++ append_suffix: If supplied, all files output by this tool will have ++ this appended to their filename. Useful for changing .py to ++ .py3 for example by passing append_suffix='3'. ++ """ + self.nobackups = nobackups + self.show_diffs = show_diffs ++ if input_base_dir and not input_base_dir.endswith(os.sep): ++ input_base_dir += os.sep ++ self._input_base_dir = input_base_dir ++ self._output_dir = output_dir ++ self._append_suffix = append_suffix + super(StdoutRefactoringTool, self).__init__(fixers, options, explicit) + + def log_error(self, msg, *args, **kwargs): +@@ -38,6 +67,23 @@ + self.logger.error(msg, *args, **kwargs) + + def write_file(self, new_text, filename, old_text, encoding): ++ orig_filename = filename ++ if self._output_dir: ++ if filename.startswith(self._input_base_dir): ++ filename = os.path.join(self._output_dir, ++ filename[len(self._input_base_dir):]) ++ else: ++ raise ValueError('filename %s does not start with the ' ++ 'input_base_dir %s' % ( ++ filename, self._input_base_dir)) ++ if self._append_suffix: ++ filename += self._append_suffix ++ if orig_filename != filename: ++ output_dir = os.path.dirname(filename) ++ if not os.path.isdir(output_dir): ++ os.makedirs(output_dir) ++ self.log_message('Writing converted %s to %s.', orig_filename, ++ filename) + if not self.nobackups: + # Make backup + backup = filename + ".bak" +@@ -55,6 +101,9 @@ + write(new_text, filename, old_text, encoding) + if not self.nobackups: + shutil.copymode(backup, filename) ++ if orig_filename != filename: ++ # Preserve the file mode in the new output directory. ++ shutil.copymode(orig_filename, filename) + + def print_output(self, old, new, filename, equal): + if equal: +@@ -114,11 +163,33 @@ + help="Write back modified files") + parser.add_option("-n", "--nobackups", action="store_true", default=False, + help="Don't write backups for modified files") ++ parser.add_option("-o", "--output-dir", action="store", type="str", ++ default="", help="Put output files in this directory " ++ "instead of overwriting the input files. Requires -n.") ++ parser.add_option("-W", "--write-unchanged-files", action="store_true", ++ help="Also write files even if no changes were required" ++ " (useful with --output-dir); implies -w.") ++ parser.add_option("--add-suffix", action="store", type="str", default="", ++ help="Append this string to all output filenames." ++ " Requires -n if non-empty. " ++ "ex: --add-suffix='3' will generate .py3 files.") + + # Parse command line arguments + refactor_stdin = False + flags = {} + options, args = parser.parse_args(args) ++ if options.write_unchanged_files: ++ flags["write_unchanged_files"] = True ++ if not options.write: ++ warn("--write-unchanged-files/-W implies -w.") ++ options.write = True ++ # If we allowed these, the original files would be renamed to backup names ++ # but not replaced. ++ if options.output_dir and not options.nobackups: ++ parser.error("Can't use --output-dir/-o without -n.") ++ if options.add_suffix and not options.nobackups: ++ parser.error("Can't use --add-suffix without -n.") ++ + if not options.write and options.no_diffs: + warn("not writing files and not printing diffs; that's not very useful") + if not options.write and options.nobackups: +@@ -144,6 +215,7 @@ + # Set up logging handler + level = logging.DEBUG if options.verbose else logging.INFO + logging.basicConfig(format='%(name)s: %(message)s', level=level) ++ logger = logging.getLogger('lib2to3.main') + + # Initialize the refactoring tool + avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg)) +@@ -160,8 +232,23 @@ + else: + requested = avail_fixes.union(explicit) + fixer_names = requested.difference(unwanted_fixes) +- rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit), +- options.nobackups, not options.no_diffs) ++ input_base_dir = os.path.commonprefix(args) ++ if (input_base_dir and not input_base_dir.endswith(os.sep) ++ and not os.path.isdir(input_base_dir)): ++ # One or more similar names were passed, their directory is the base. ++ # os.path.commonprefix() is ignorant of path elements, this corrects ++ # for that weird API. ++ input_base_dir = os.path.dirname(input_base_dir) ++ if options.output_dir: ++ input_base_dir = input_base_dir.rstrip(os.sep) ++ logger.info('Output in %r will mirror the input directory %r layout.', ++ options.output_dir, input_base_dir) ++ rt = StdoutRefactoringTool( ++ sorted(fixer_names), flags, sorted(explicit), ++ options.nobackups, not options.no_diffs, ++ input_base_dir=input_base_dir, ++ output_dir=options.output_dir, ++ append_suffix=options.add_suffix) + + # Refactor all files and directories passed as arguments + if not rt.errors: +diff -r 8527427914a2 Lib/lib2to3/refactor.py +--- a/Lib/lib2to3/refactor.py ++++ b/Lib/lib2to3/refactor.py +@@ -173,7 +173,8 @@ + + class RefactoringTool(object): + +- _default_options = {"print_function" : False} ++ _default_options = {"print_function" : False, ++ "write_unchanged_files" : False} + + CLASS_PREFIX = "Fix" # The prefix for fixer classes + FILE_PREFIX = "fix_" # The prefix for modules with a fixer within +@@ -195,6 +196,10 @@ + self.grammar = pygram.python_grammar_no_print_statement + else: + self.grammar = pygram.python_grammar ++ # When this is True, the refactor*() methods will call write_file() for ++ # files processed even if they were not changed during refactoring. If ++ # and only if the refactor method's write parameter was True. ++ self.write_unchanged_files = self.options.get("write_unchanged_files") + self.errors = [] + self.logger = logging.getLogger("RefactoringTool") + self.fixer_log = [] +@@ -341,13 +346,13 @@ + if doctests_only: + self.log_debug("Refactoring doctests in %s", filename) + output = self.refactor_docstring(input, filename) +- if output != input: ++ if self.write_unchanged_files or output != input: + self.processed_file(output, filename, input, write, encoding) + else: + self.log_debug("No doctest changes in %s", filename) + else: + tree = self.refactor_string(input, filename) +- if tree and tree.was_changed: ++ if self.write_unchanged_files or (tree and tree.was_changed): + # The [:-1] is to take off the \n we added earlier + self.processed_file(unicode(tree)[:-1], filename, + write=write, encoding=encoding) +@@ -386,13 +391,13 @@ + if doctests_only: + self.log_debug("Refactoring doctests in stdin") + output = self.refactor_docstring(input, "") +- if output != input: ++ if self.write_unchanged_files or output != input: + self.processed_file(output, "", input) + else: + self.log_debug("No doctest changes in stdin") + else: + tree = self.refactor_string(input, "") +- if tree and tree.was_changed: ++ if self.write_unchanged_files or (tree and tree.was_changed): + self.processed_file(unicode(tree), "", input) + else: + self.log_debug("No changes in stdin") +@@ -502,7 +507,7 @@ + def processed_file(self, new_text, filename, old_text=None, write=False, + encoding=None): + """ +- Called when a file has been refactored, and there are changes. ++ Called when a file has been refactored and there may be changes. + """ + self.files.append(filename) + if old_text is None: +@@ -513,7 +518,8 @@ + self.print_output(old_text, new_text, filename, equal) + if equal: + self.log_debug("No changes to %s", filename) +- return ++ if not self.write_unchanged_files: ++ return + if write: + self.write_file(new_text, filename, old_text, encoding) + else: +diff -r 8527427914a2 Lib/lib2to3/tests/test_main.py +--- a/Lib/lib2to3/tests/test_main.py ++++ b/Lib/lib2to3/tests/test_main.py +@@ -2,17 +2,40 @@ + import sys + import codecs + import logging ++import os ++import re ++import shutil + import StringIO ++import sys ++import tempfile + import unittest + + from lib2to3 import main + + ++TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data") ++PY2_TEST_MODULE = os.path.join(TEST_DATA_DIR, "py2_test_grammar.py") ++ ++ + class TestMain(unittest.TestCase): + ++ if not hasattr(unittest.TestCase, 'assertNotRegex'): ++ # This method was only introduced in 3.2. ++ def assertNotRegex(self, text, regexp, msg=None): ++ import re ++ if not hasattr(regexp, 'search'): ++ regexp = re.compile(regexp) ++ if regexp.search(text): ++ self.fail("regexp %s MATCHED text %r" % (regexp.pattern, text)) ++ ++ def setUp(self): ++ self.temp_dir = None # tearDown() will rmtree this directory if set. ++ + def tearDown(self): + # Clean up logging configuration down by main. + del logging.root.handlers[:] ++ if self.temp_dir: ++ shutil.rmtree(self.temp_dir) + + def run_2to3_capture(self, args, in_capture, out_capture, err_capture): + save_stdin = sys.stdin +@@ -39,3 +62,88 @@ + self.assertTrue("-print 'nothing'" in output) + self.assertTrue("WARNING: couldn't encode 's diff for " + "your terminal" in err.getvalue()) ++ ++ def setup_test_source_trees(self): ++ """Setup a test source tree and output destination tree.""" ++ self.temp_dir = tempfile.mkdtemp() # tearDown() cleans this up. ++ self.py2_src_dir = os.path.join(self.temp_dir, "python2_project") ++ self.py3_dest_dir = os.path.join(self.temp_dir, "python3_project") ++ os.mkdir(self.py2_src_dir) ++ os.mkdir(self.py3_dest_dir) ++ # Turn it into a package with a few files. ++ self.setup_files = [] ++ open(os.path.join(self.py2_src_dir, "__init__.py"), "w").close() ++ self.setup_files.append("__init__.py") ++ shutil.copy(PY2_TEST_MODULE, self.py2_src_dir) ++ self.setup_files.append(os.path.basename(PY2_TEST_MODULE)) ++ self.trivial_py2_file = os.path.join(self.py2_src_dir, "trivial.py") ++ self.init_py2_file = os.path.join(self.py2_src_dir, "__init__.py") ++ with open(self.trivial_py2_file, "w") as trivial: ++ trivial.write("print 'I need a simple conversion.'") ++ self.setup_files.append("trivial.py") ++ ++ def test_filename_changing_on_output_single_dir(self): ++ """2to3 a single directory with a new output dir and suffix.""" ++ self.setup_test_source_trees() ++ out = StringIO.StringIO() ++ err = StringIO.StringIO() ++ suffix = "TEST" ++ ret = self.run_2to3_capture( ++ ["-n", "--add-suffix", suffix, "--write-unchanged-files", ++ "--no-diffs", "--output-dir", ++ self.py3_dest_dir, self.py2_src_dir], ++ StringIO.StringIO(""), out, err) ++ self.assertEqual(ret, 0) ++ stderr = err.getvalue() ++ self.assertIn(" implies -w.", stderr) ++ self.assertIn( ++ "Output in %r will mirror the input directory %r layout" % ( ++ self.py3_dest_dir, self.py2_src_dir), stderr) ++ self.assertEqual(set(name+suffix for name in self.setup_files), ++ set(os.listdir(self.py3_dest_dir))) ++ for name in self.setup_files: ++ self.assertIn("Writing converted %s to %s" % ( ++ os.path.join(self.py2_src_dir, name), ++ os.path.join(self.py3_dest_dir, name+suffix)), stderr) ++ sep = re.escape(os.sep) ++ self.assertRegexpMatches( ++ stderr, r"No changes to .*/__init__\.py".replace("/", sep)) ++ self.assertNotRegex( ++ stderr, r"No changes to .*/trivial\.py".replace("/", sep)) ++ ++ def test_filename_changing_on_output_two_files(self): ++ """2to3 two files in one directory with a new output dir.""" ++ self.setup_test_source_trees() ++ err = StringIO.StringIO() ++ py2_files = [self.trivial_py2_file, self.init_py2_file] ++ expected_files = set(os.path.basename(name) for name in py2_files) ++ ret = self.run_2to3_capture( ++ ["-n", "-w", "--write-unchanged-files", ++ "--no-diffs", "--output-dir", self.py3_dest_dir] + py2_files, ++ StringIO.StringIO(""), StringIO.StringIO(), err) ++ self.assertEqual(ret, 0) ++ stderr = err.getvalue() ++ self.assertIn( ++ "Output in %r will mirror the input directory %r layout" % ( ++ self.py3_dest_dir, self.py2_src_dir), stderr) ++ self.assertEqual(expected_files, set(os.listdir(self.py3_dest_dir))) ++ ++ def test_filename_changing_on_output_single_file(self): ++ """2to3 a single file with a new output dir.""" ++ self.setup_test_source_trees() ++ err = StringIO.StringIO() ++ ret = self.run_2to3_capture( ++ ["-n", "-w", "--no-diffs", "--output-dir", self.py3_dest_dir, ++ self.trivial_py2_file], ++ StringIO.StringIO(""), StringIO.StringIO(), err) ++ self.assertEqual(ret, 0) ++ stderr = err.getvalue() ++ self.assertIn( ++ "Output in %r will mirror the input directory %r layout" % ( ++ self.py3_dest_dir, self.py2_src_dir), stderr) ++ self.assertEqual(set([os.path.basename(self.trivial_py2_file)]), ++ set(os.listdir(self.py3_dest_dir))) ++ ++ ++if __name__ == '__main__': ++ unittest.main() +diff -r 8527427914a2 Lib/lib2to3/tests/test_refactor.py +--- a/Lib/lib2to3/tests/test_refactor.py ++++ b/Lib/lib2to3/tests/test_refactor.py +@@ -53,6 +53,12 @@ + self.assertTrue(rt.driver.grammar is + pygram.python_grammar_no_print_statement) + ++ def test_write_unchanged_files_option(self): ++ rt = self.rt() ++ self.assertFalse(rt.write_unchanged_files) ++ rt = self.rt({"write_unchanged_files" : True}) ++ self.assertTrue(rt.write_unchanged_files) ++ + def test_fixer_loading_helpers(self): + contents = ["explicit", "first", "last", "parrot", "preorder"] + non_prefixed = refactor.get_all_fix_names("myfixes") +@@ -176,29 +182,59 @@ + "", False] + self.assertEqual(results, expected) + +- def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS): ++ def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS, ++ options=None, mock_log_debug=None, ++ actually_write=True): ++ tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor") ++ self.addCleanup(shutil.rmtree, tmpdir) ++ # make a copy of the tested file that we can write to ++ shutil.copy(test_file, tmpdir) ++ test_file = os.path.join(tmpdir, os.path.basename(test_file)) ++ os.chmod(test_file, 0o644) ++ + def read_file(): + with open(test_file, "rb") as fp: + return fp.read() ++ + old_contents = read_file() +- rt = self.rt(fixers=fixers) ++ rt = self.rt(fixers=fixers, options=options) ++ if mock_log_debug: ++ rt.log_debug = mock_log_debug + + rt.refactor_file(test_file) + self.assertEqual(old_contents, read_file()) + +- try: +- rt.refactor_file(test_file, True) +- new_contents = read_file() +- self.assertNotEqual(old_contents, new_contents) +- finally: +- with open(test_file, "wb") as fp: +- fp.write(old_contents) ++ if not actually_write: ++ return ++ rt.refactor_file(test_file, True) ++ new_contents = read_file() ++ self.assertNotEqual(old_contents, new_contents) + return new_contents + + def test_refactor_file(self): + test_file = os.path.join(FIXER_DIR, "parrot_example.py") + self.check_file_refactoring(test_file, _DEFAULT_FIXERS) + ++ def test_refactor_file_write_unchanged_file(self): ++ test_file = os.path.join(FIXER_DIR, "parrot_example.py") ++ debug_messages = [] ++ def recording_log_debug(msg, *args): ++ debug_messages.append(msg % args) ++ self.check_file_refactoring(test_file, fixers=(), ++ options={"write_unchanged_files": True}, ++ mock_log_debug=recording_log_debug, ++ actually_write=False) ++ # Testing that it logged this message when write=False was passed is ++ # sufficient to see that it did not bail early after "No changes". ++ message_regex = r"Not writing changes to .*%s%s" % ( ++ os.sep, os.path.basename(test_file)) ++ for message in debug_messages: ++ if "Not writing changes" in message: ++ self.assertRegexpMatches(message, message_regex) ++ break ++ else: ++ self.fail("%r not matched in %r" % (message_regex, debug_messages)) ++ + def test_refactor_dir(self): + def check(structure, expected): + def mock_refactor_file(self, f, *args): +diff -r 8527427914a2 Lib/locale.py +--- a/Lib/locale.py ++++ b/Lib/locale.py +@@ -135,8 +135,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):] +@@ -331,6 +329,13 @@ + # overridden below) + _setlocale = setlocale + ++# Avoid relying on the locale-dependent .lower() method ++# (see issue #1813). ++_ascii_lower_map = ''.join( ++ chr(x + 32 if x >= ord('A') and x <= ord('Z') else x) ++ for x in range(256) ++) ++ + def normalize(localename): + + """ Returns a normalized locale code for the given locale +@@ -348,7 +353,9 @@ + + """ + # Normalize the locale name and extract the encoding +- fullname = localename.lower() ++ if isinstance(localename, unicode): ++ localename = localename.encode('ascii') ++ fullname = localename.translate(_ascii_lower_map) + if ':' in fullname: + # ':' is sometimes used as encoding delimiter. + fullname = fullname.replace(':', '.') +@@ -517,9 +524,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. +diff -r 8527427914a2 Lib/logging/__init__.py +--- a/Lib/logging/__init__.py ++++ b/Lib/logging/__init__.py +@@ -478,8 +478,12 @@ + except UnicodeError: + # Sometimes filenames have non-ASCII chars, which can lead + # to errors when s is Unicode and record.exc_text is str +- # See issue 8924 +- s = s + record.exc_text.decode(sys.getfilesystemencoding()) ++ # See issue 8924. ++ # We also use replace for when there are multiple ++ # encodings, e.g. UTF-8 for the filesystem and latin-1 ++ # for a script. See issue 13232. ++ s = s + record.exc_text.decode(sys.getfilesystemencoding(), ++ 'replace') + return s + + # +@@ -790,7 +794,7 @@ + You could, however, replace this with a custom handler if you wish. + The record which was being processed is passed in to this method. + """ +- if raiseExceptions: ++ if raiseExceptions and sys.stderr: # see issue 13807 + ei = sys.exc_info() + try: + traceback.print_exception(ei[0], ei[1], ei[2], +@@ -1003,6 +1007,10 @@ + placeholder to now point to the logger. + """ + rv = None ++ if not isinstance(name, basestring): ++ raise TypeError('A logger name must be string or Unicode') ++ if isinstance(name, unicode): ++ name = name.encode('utf-8') + _acquireLock() + try: + if name in self.loggerDict: +diff -r 8527427914a2 Lib/logging/config.py +--- a/Lib/logging/config.py ++++ b/Lib/logging/config.py +@@ -211,7 +211,7 @@ + #avoid disabling child loggers of explicitly + #named loggers. With a sorted list it is easier + #to find the child loggers. +- existing.sort(key=_encoded) ++ existing.sort() + #We'll keep the list of existing loggers + #which are children of named loggers here... + child_loggers = [] +@@ -589,13 +589,14 @@ + #avoid disabling child loggers of explicitly + #named loggers. With a sorted list it is easier + #to find the child loggers. +- existing.sort(key=_encoded) ++ existing.sort() + #We'll keep the list of existing loggers + #which are children of named loggers here... + child_loggers = [] + #now set up the new ones... + loggers = config.get('loggers', EMPTY_DICT) + for name in loggers: ++ name = _encoded(name) + if name in existing: + i = existing.index(name) + prefixed = name + "." +diff -r 8527427914a2 Lib/mailbox.py +--- a/Lib/mailbox.py ++++ b/Lib/mailbox.py +@@ -247,11 +247,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.""" +@@ -1854,7 +1852,10 @@ + + def close(self): + """Close the file.""" +- del self._file ++ if hasattr(self, '_file'): ++ if hasattr(self._file, 'close'): ++ self._file.close() ++ del self._file + + def _read(self, size, read_method): + """Read size bytes using read_method.""" +@@ -1898,6 +1899,12 @@ + size = remaining + return _ProxyFile._read(self, size, read_method) + ++ def close(self): ++ # do *not* close the underlying file object for partial files, ++ # since it's global to the mailbox object ++ if hasattr(self, '_file'): ++ del self._file ++ + + def _lock_file(f, dotlock=True): + """Lock file f using lockf and dot locking.""" +diff -r 8527427914a2 Lib/markupbase.py +--- a/Lib/markupbase.py ++++ b/Lib/markupbase.py +@@ -108,6 +108,10 @@ + if decltype == "doctype": + self.handle_decl(data) + else: ++ # According to the HTML5 specs sections "8.2.4.44 Bogus ++ # comment state" and "8.2.4.45 Markup declaration open ++ # state", a comment token should be emitted. ++ # Calling unknown_decl provides more flexibility though. + self.unknown_decl(data) + return j + 1 + if c in "\"'": +diff -r 8527427914a2 Lib/msilib/schema.py +--- a/Lib/msilib/schema.py ++++ b/Lib/msilib/schema.py +@@ -958,7 +958,7 @@ + (u'ServiceInstall',u'StartType',u'N',0,4,None, None, None, None, u'Type of the service',), + (u'Shortcut',u'Name',u'N',None, None, None, None, u'Filename',None, u'The name of the shortcut to be created.',), + (u'Shortcut',u'Description',u'Y',None, None, None, None, u'Text',None, u'The description for the shortcut.',), +-(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.',), ++(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the shortcut creation/deletion.',), + (u'Shortcut',u'Icon_',u'Y',None, None, u'Icon',1,u'Identifier',None, u'Foreign key into the File table denoting the external icon file for the shortcut.',), + (u'Shortcut',u'IconIndex',u'Y',-32767,32767,None, None, None, None, u'The icon index for the shortcut.',), + (u'Shortcut',u'Directory_',u'N',None, None, u'Directory',1,u'Identifier',None, u'Foreign key into the Directory table denoting the directory where the shortcut file is created.',), +diff -r 8527427914a2 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 8527427914a2 Lib/multiprocessing/connection.py +--- a/Lib/multiprocessing/connection.py ++++ b/Lib/multiprocessing/connection.py +@@ -249,10 +249,14 @@ + ''' + def __init__(self, address, family, backlog=1): + self._socket = socket.socket(getattr(socket, family)) +- self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +- self._socket.bind(address) +- self._socket.listen(backlog) +- self._address = self._socket.getsockname() ++ try: ++ self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ++ self._socket.bind(address) ++ self._socket.listen(backlog) ++ self._address = self._socket.getsockname() ++ except socket.error: ++ self._socket.close() ++ raise + self._family = family + self._last_accepted = None + +diff -r 8527427914a2 Lib/multiprocessing/heap.py +--- a/Lib/multiprocessing/heap.py ++++ b/Lib/multiprocessing/heap.py +@@ -101,6 +101,8 @@ + self._stop_to_block = {} + self._allocated_blocks = set() + self._arenas = [] ++ # list of pending blocks to free - see free() comment below ++ self._pending_free_blocks = [] + + @staticmethod + def _roundup(n, alignment): +@@ -175,15 +177,39 @@ + + return start, stop + ++ def _free_pending_blocks(self): ++ # Free all the blocks in the pending list - called with the lock held. ++ while True: ++ try: ++ block = self._pending_free_blocks.pop() ++ except IndexError: ++ break ++ self._allocated_blocks.remove(block) ++ self._free(block) ++ + def free(self, block): + # free a block returned by malloc() ++ # Since free() can be called asynchronously by the GC, it could happen ++ # that it's called while self._lock is held: in that case, ++ # self._lock.acquire() would deadlock (issue #12352). To avoid that, a ++ # trylock is used instead, and if the lock can't be acquired ++ # immediately, the block is added to a list of blocks to be freed ++ # synchronously sometimes later from malloc() or free(), by calling ++ # _free_pending_blocks() (appending and retrieving from a list is not ++ # strictly thread-safe but under cPython it's atomic thanks to the GIL). + assert os.getpid() == self._lastpid +- self._lock.acquire() +- try: +- self._allocated_blocks.remove(block) +- self._free(block) +- finally: +- self._lock.release() ++ if not self._lock.acquire(False): ++ # can't acquire the lock right now, add the block to the list of ++ # pending blocks to free ++ self._pending_free_blocks.append(block) ++ else: ++ # we hold the lock ++ try: ++ self._free_pending_blocks() ++ self._allocated_blocks.remove(block) ++ self._free(block) ++ finally: ++ self._lock.release() + + def malloc(self, size): + # return a block of right size (possibly rounded up) +@@ -191,6 +217,7 @@ + if os.getpid() != self._lastpid: + self.__init__() # reinitialize after fork + self._lock.acquire() ++ self._free_pending_blocks() + try: + size = self._roundup(max(size,1), self._alignment) + (arena, start, stop) = self._malloc(size) +diff -r 8527427914a2 Lib/multiprocessing/managers.py +--- a/Lib/multiprocessing/managers.py ++++ b/Lib/multiprocessing/managers.py +@@ -159,7 +159,7 @@ + Listener, Client = listener_client[serializer] + + # do authentication later +- self.listener = Listener(address=address, backlog=5) ++ self.listener = Listener(address=address, backlog=16) + self.address = self.listener.address + + self.id_to_obj = {'0': (None, ())} +diff -r 8527427914a2 Lib/multiprocessing/pool.py +--- a/Lib/multiprocessing/pool.py ++++ b/Lib/multiprocessing/pool.py +@@ -125,6 +125,8 @@ + processes = cpu_count() + except NotImplementedError: + processes = 1 ++ if processes < 1: ++ raise ValueError("Number of processes must be at least 1") + + if initializer is not None and not hasattr(initializer, '__call__'): + raise TypeError('initializer must be a callable') +@@ -292,7 +294,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 8527427914a2 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() +@@ -188,13 +192,7 @@ + debug('... done self._thread.start()') + + # On process exit we will wait for data to be flushed to pipe. +- # +- # However, if this process created the queue then all +- # processes which use the queue will be descendants of this +- # process. Therefore waiting for the queue to be flushed +- # is pointless once all the child processes have been joined. +- created_by_this_process = (self._opid == os.getpid()) +- if not self._joincancelled and not created_by_this_process: ++ if not self._joincancelled: + self._jointhread = Finalize( + self._thread, Queue._finalize_join, + [weakref.ref(self._thread)], +diff -r 8527427914a2 Lib/ntpath.py +--- a/Lib/ntpath.py ++++ b/Lib/ntpath.py +@@ -521,3 +521,13 @@ + if not rel_list: + return curdir + return join(*rel_list) ++ ++try: ++ # The genericpath.isdir implementation uses os.stat and checks the mode ++ # attribute to tell whether or not the path is a directory. ++ # This is overkill on Windows - just pass the path to GetFileAttributes ++ # and check the attribute from there. ++ from nt import _isdir as isdir ++except ImportError: ++ # Use genericpath.isdir as imported above. ++ pass +diff -r 8527427914a2 Lib/pdb.py +--- a/Lib/pdb.py ++++ b/Lib/pdb.py +@@ -1229,7 +1229,7 @@ + self._wait_for_mainpyfile = 1 + self.mainpyfile = self.canonic(filename) + self._user_requested_quit = 0 +- statement = 'execfile( "%s")' % filename ++ statement = 'execfile(%r)' % filename + self.run(statement) + + # Simplified interface +diff -r 8527427914a2 Lib/pickle.py +--- a/Lib/pickle.py ++++ b/Lib/pickle.py +@@ -24,7 +24,7 @@ + + """ + +-__version__ = "$Revision$" # Code version ++__version__ = "$Revision: 72223 $" # Code version + + from types import * + from copy_reg import dispatch_table +@@ -286,20 +286,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, TypeType) +- except TypeError: # t is not a class (old Boost; see SF #502085) +- issc = 0 +- if issc: +- self.save_global(obj) +- return +- + # Check copy_reg.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, TypeType) ++ except TypeError: # t is not a class (old Boost; see SF #502085) ++ issc = 0 ++ 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: +diff -r 8527427914a2 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 8527427914a2 Lib/pkgutil.py +--- a/Lib/pkgutil.py ++++ b/Lib/pkgutil.py +@@ -194,8 +194,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: +@@ -208,7 +211,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 8527427914a2 Lib/plat-mac/findertools.py +--- a/Lib/plat-mac/findertools.py ++++ b/Lib/plat-mac/findertools.py +@@ -128,7 +128,7 @@ + def comment(object, comment=None): + """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window.""" + object = Carbon.File.FSRef(object) +- object_alias = object.FSNewAliasMonimal() ++ object_alias = object.FSNewAliasMinimal() + if comment is None: + return _getcomment(object_alias) + else: +diff -r 8527427914a2 Lib/platform.py +--- a/Lib/platform.py ++++ b/Lib/platform.py +@@ -183,7 +183,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 +@@ -554,7 +554,7 @@ + + """ Get additional version information from the Windows Registry + and return a tuple (version,csd,ptype) referring to version +- number, CSD level and OS type (multi/single ++ number, CSD level (service pack), and OS type (multi/single + processor). + + As a hint: ptype returns 'Uniprocessor Free' on single +@@ -765,6 +765,7 @@ + 0x2: 'PowerPC', + 0xa: 'i386'}.get(sysa,'') + ++ versioninfo=('', '', '') + return release,versioninfo,machine + + def _mac_ver_xml(): +diff -r 8527427914a2 Lib/pty.py +--- a/Lib/pty.py ++++ b/Lib/pty.py +@@ -142,15 +142,21 @@ + Copies + pty master -> standard output (master_read) + standard input -> pty master (stdin_read)""" +- while 1: +- rfds, wfds, xfds = select( +- [master_fd, STDIN_FILENO], [], []) ++ fds = [master_fd, STDIN_FILENO] ++ while True: ++ rfds, wfds, xfds = select(fds, [], []) + if master_fd in rfds: + data = master_read(master_fd) +- os.write(STDOUT_FILENO, data) ++ if not data: # Reached EOF. ++ fds.remove(master_fd) ++ else: ++ os.write(STDOUT_FILENO, data) + if STDIN_FILENO in rfds: + data = stdin_read(STDIN_FILENO) +- _writen(master_fd, data) ++ if not data: ++ fds.remove(STDIN_FILENO) ++ else: ++ _writen(master_fd, data) + + def spawn(argv, master_read=_read, stdin_read=_read): + """Create a spawned process.""" +diff -r 8527427914a2 Lib/pydoc.py +--- a/Lib/pydoc.py ++++ b/Lib/pydoc.py +@@ -37,7 +37,7 @@ + __author__ = "Ka-Ping Yee " + __date__ = "26 February 2001" + +-__version__ = "$Revision$" ++__version__ = "$Revision: 88564 $" + __credits__ = """Guido van Rossum, for an excellent programming language. + Tommy Burnette, the original creator of manpy. + Paul Prescod, for all his work on onlinehelp. +@@ -52,7 +52,7 @@ + # the current directory is changed with os.chdir(), an incorrect + # path will be displayed. + +-import sys, imp, os, re, types, inspect, __builtin__, pkgutil ++import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings + from repr import Repr + from string import expandtabs, find, join, lower, split, strip, rfind, rstrip + from traceback import extract_tb +@@ -212,8 +212,8 @@ + def synopsis(filename, cache={}): + """Get the one-line summary out of a module file.""" + mtime = os.stat(filename).st_mtime +- lastupdate, result = cache.get(filename, (0, None)) +- if lastupdate < mtime: ++ lastupdate, result = cache.get(filename, (None, None)) ++ if lastupdate is None or lastupdate < mtime: + info = inspect.getmoduleinfo(filename) + try: + file = open(filename) +@@ -740,8 +740,15 @@ + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: +- push(self.document(getattr(object, name), name, mod, +- funcs, classes, mdict, object)) ++ try: ++ value = getattr(object, name) ++ except Exception: ++ # Some descriptors may meet a failure in their __get__. ++ # (bug #1785) ++ push(self._docdescriptor(name, value, mod)) ++ else: ++ push(self.document(value, name, mod, ++ funcs, classes, mdict, object)) + push('\n') + return attrs + +@@ -781,7 +788,12 @@ + mdict = {} + for key, kind, homecls, value in attrs: + mdict[key] = anchor = '#' + name + '-' + key +- value = getattr(object, key) ++ try: ++ value = getattr(object, name) ++ except Exception: ++ # Some descriptors may meet a failure in their __get__. ++ # (bug #1785) ++ pass + try: + # The value may not be hashable (e.g., a data attr with + # a dict or list value). +@@ -1161,8 +1173,15 @@ + hr.maybe() + push(msg) + for name, kind, homecls, value in ok: +- push(self.document(getattr(object, name), +- name, mod, object)) ++ try: ++ value = getattr(object, name) ++ except Exception: ++ # Some descriptors may meet a failure in their __get__. ++ # (bug #1785) ++ push(self._docdescriptor(name, value, mod)) ++ else: ++ push(self.document(value, ++ name, mod, object)) + return attrs + + def spilldescriptors(msg, attrs, predicate): +@@ -1454,13 +1473,14 @@ + else: break + if module: + object = module +- for part in parts[n:]: +- try: object = getattr(object, part) +- except AttributeError: return None +- return object + else: +- if hasattr(__builtin__, path): +- return getattr(__builtin__, path) ++ object = __builtin__ ++ for part in parts[n:]: ++ try: ++ object = getattr(object, part) ++ except AttributeError: ++ return None ++ return object + + # --------------------------------------- interactive interpreter interface + +@@ -1967,10 +1987,11 @@ + if modname[-9:] == '.__init__': + modname = modname[:-9] + ' (package)' + print modname, desc and '- ' + desc +- try: import warnings +- except ImportError: pass +- else: warnings.filterwarnings('ignore') # ignore problems during import +- ModuleScanner().run(callback, key) ++ def onerror(modname): ++ pass ++ with warnings.catch_warnings(): ++ warnings.filterwarnings('ignore') # ignore problems during import ++ ModuleScanner().run(callback, key, onerror=onerror) + + # --------------------------------------------------- web browser interface + +diff -r 8527427914a2 Lib/random.py +--- a/Lib/random.py ++++ b/Lib/random.py +@@ -427,11 +427,9 @@ + # lambd: rate lambd = 1/mean + # ('lambda' is a Python reserved word) + +- random = self.random +- u = random() +- while u <= 1e-7: +- u = random() +- return -_log(u)/lambd ++ # we use 1-random() instead of random() to preclude the ++ # possibility of taking the log of zero. ++ return -_log(1.0 - self.random())/lambd + + ## -------------------- von Mises distribution -------------------- + +diff -r 8527427914a2 Lib/rfc822.py +--- a/Lib/rfc822.py ++++ b/Lib/rfc822.py +@@ -34,7 +34,7 @@ + libraries in which tell() discards buffered data before discovering that the + lseek() system call doesn't work. For maximum portability, you should set the + seekable argument to zero to prevent that initial \code{tell} when passing in +-an unseekable object such as a a file object created from a socket object. If ++an unseekable object such as a file object created from a socket object. If + it is 1 on entry -- which it is by default -- the tell() method of the open + file object is called once; if this raises an exception, seekable is reset to + 0. For other nonzero values of seekable, this test is not made. +diff -r 8527427914a2 Lib/sched.py +--- a/Lib/sched.py ++++ b/Lib/sched.py +@@ -88,7 +88,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 8527427914a2 Lib/shutil.py +--- a/Lib/shutil.py ++++ b/Lib/shutil.py +@@ -25,7 +25,8 @@ + __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", + "copytree", "move", "rmtree", "Error", "SpecialFileError", + "ExecError", "make_archive", "get_archive_formats", +- "register_archive_format", "unregister_archive_format"] ++ "register_archive_format", "unregister_archive_format", ++ "ignore_patterns"] + + class Error(EnvironmentError): + pass +@@ -359,7 +360,8 @@ + archive_dir = os.path.dirname(archive_name) + + if not os.path.exists(archive_dir): +- logger.info("creating %s" % archive_dir) ++ if logger is not None: ++ logger.info("creating %s", archive_dir) + if not dry_run: + os.makedirs(archive_dir) + +diff -r 8527427914a2 Lib/site.py +--- a/Lib/site.py ++++ b/Lib/site.py +@@ -312,7 +312,7 @@ + # locations. + from sysconfig import get_config_var + framework = get_config_var("PYTHONFRAMEWORK") +- if framework and "/%s.framework/"%(framework,) in prefix: ++ if framework: + sitepackages.append( + os.path.join("/Library", framework, + sys.version[:3], "site-packages")) +diff -r 8527427914a2 Lib/smtpd.py +--- a/Lib/smtpd.py ++++ b/Lib/smtpd.py +@@ -524,6 +524,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 +@@ -539,16 +549,6 @@ + print >> sys.stderr, \ + 'Cannot setuid "nobody"; try running with -n option.' + 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 8527427914a2 Lib/smtplib.py +--- a/Lib/smtplib.py ++++ b/Lib/smtplib.py +@@ -149,6 +149,13 @@ + else: + return "<%s>" % m + ++def _addr_only(addrstring): ++ displayname, addr = email.utils.parseaddr(addrstring) ++ if (displayname, addr) == ('', ''): ++ # parseaddr couldn't parse it, so use it as is. ++ return addrstring ++ return addr ++ + def quotedata(data): + """Quote data for email. + +@@ -345,8 +352,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 line == '': + self.close() + raise SMTPServerDisconnected("Connection unexpectedly closed") +@@ -497,14 +506,14 @@ + + def verify(self, address): + """SMTP 'verify' command -- checks for address validity.""" +- self.putcmd("vrfy", quoteaddr(address)) ++ self.putcmd("vrfy", _addr_only(address)) + return self.getreply() + # a.k.a. + vrfy = verify + + def expn(self, address): + """SMTP 'expn' command -- expands a mailing list.""" +- self.putcmd("expn", quoteaddr(address)) ++ self.putcmd("expn", _addr_only(address)) + return self.getreply() + + # some useful methods +diff -r 8527427914a2 Lib/sqlite3/dump.py +--- a/Lib/sqlite3/dump.py ++++ b/Lib/sqlite3/dump.py +@@ -1,6 +1,12 @@ + # Mimic the sqlite3 console shell's .dump command + # Author: Paul Kippes + ++# Every identifier in sql is quoted based on a comment in sqlite ++# documentation "SQLite adds new keywords from time to time when it ++# takes on new features. So to prevent your code from being broken by ++# future enhancements, you should normally quote any identifier that ++# is an English language word, even if you do not have to." ++ + def _iterdump(connection): + """ + Returns an iterator to the dump of the database in an SQL text format. +@@ -15,49 +21,49 @@ + + # sqlite_master table contains the SQL CREATE statements for the database. + q = """ +- SELECT name, type, sql +- FROM sqlite_master +- WHERE sql NOT NULL AND +- type == 'table' ++ SELECT "name", "type", "sql" ++ FROM "sqlite_master" ++ WHERE "sql" NOT NULL AND ++ "type" == 'table' + """ + schema_res = cu.execute(q) +- for table_name, type, sql in schema_res.fetchall(): ++ for table_name, type, sql in sorted(schema_res.fetchall()): + if table_name == 'sqlite_sequence': +- yield('DELETE FROM sqlite_sequence;') ++ yield('DELETE FROM "sqlite_sequence";') + elif table_name == 'sqlite_stat1': +- yield('ANALYZE sqlite_master;') ++ yield('ANALYZE "sqlite_master";') + elif table_name.startswith('sqlite_'): + continue + # NOTE: Virtual table support not implemented + #elif sql.startswith('CREATE VIRTUAL TABLE'): + # qtable = table_name.replace("'", "''") + # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\ +- # "VALUES('table','%s','%s',0,'%s');" % ++ # "VALUES('table','{0}','{0}',0,'{1}');".format( + # qtable, +- # qtable, +- # sql.replace("''")) ++ # sql.replace("''"))) + else: +- yield('%s;' % sql) ++ yield('{0};'.format(sql)) + + # Build the insert statement for each row of the current table +- res = cu.execute("PRAGMA table_info('%s')" % table_name) ++ table_name_ident = table_name.replace('"', '""') ++ res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident)) + column_names = [str(table_info[1]) for table_info in res.fetchall()] +- q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES(" +- q += ",".join(["'||quote(" + col + ")||'" for col in column_names]) +- q += ")' FROM '%(tbl_name)s'" +- query_res = cu.execute(q % {'tbl_name': table_name}) ++ q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format( ++ table_name_ident, ++ ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names)) ++ query_res = cu.execute(q) + for row in query_res: +- yield("%s;" % row[0]) ++ yield("{0};".format(row[0])) + + # Now when the type is 'index', 'trigger', or 'view' + q = """ +- SELECT name, type, sql +- FROM sqlite_master +- WHERE sql NOT NULL AND +- type IN ('index', 'trigger', 'view') ++ SELECT "name", "type", "sql" ++ FROM "sqlite_master" ++ WHERE "sql" NOT NULL AND ++ "type" IN ('index', 'trigger', 'view') + """ + schema_res = cu.execute(q) + for name, type, sql in schema_res.fetchall(): +- yield('%s;' % sql) ++ yield('{0};'.format(sql)) + + yield('COMMIT;') +diff -r 8527427914a2 Lib/sqlite3/test/dbapi.py +--- a/Lib/sqlite3/test/dbapi.py ++++ b/Lib/sqlite3/test/dbapi.py +@@ -203,6 +203,13 @@ + def CheckExecuteArgString(self): + self.cu.execute("insert into test(name) values (?)", ("Hugo",)) + ++ def CheckExecuteArgStringWithZeroByte(self): ++ self.cu.execute("insert into test(name) values (?)", ("Hu\x00go",)) ++ ++ self.cu.execute("select name from test where id=?", (self.cu.lastrowid,)) ++ row = self.cu.fetchone() ++ self.assertEqual(row[0], "Hu\x00go") ++ + def CheckExecuteWrongNoOfArgs1(self): + # too many parameters + try: +diff -r 8527427914a2 Lib/sqlite3/test/dump.py +--- a/Lib/sqlite3/test/dump.py ++++ b/Lib/sqlite3/test/dump.py +@@ -13,6 +13,14 @@ + + def CheckTableDump(self): + expected_sqls = [ ++ """CREATE TABLE "index"("index" blob);""" ++ , ++ """INSERT INTO "index" VALUES(X'01');""" ++ , ++ """CREATE TABLE "quoted""table"("quoted""field" text);""" ++ , ++ """INSERT INTO "quoted""table" VALUES('quoted''value');""" ++ , + "CREATE TABLE t1(id integer primary key, s1 text, " \ + "t1_i1 integer not null, i2 integer, unique (s1), " \ + "constraint t1_idx1 unique (i2));" +diff -r 8527427914a2 Lib/sqlite3/test/factory.py +--- a/Lib/sqlite3/test/factory.py ++++ b/Lib/sqlite3/test/factory.py +@@ -189,13 +189,52 @@ + def tearDown(self): + self.con.close() + ++class TextFactoryTestsWithEmbeddedZeroBytes(unittest.TestCase): ++ def setUp(self): ++ self.con = sqlite.connect(":memory:") ++ self.con.execute("create table test (value text)") ++ self.con.execute("insert into test (value) values (?)", ("a\x00b",)) ++ ++ def CheckString(self): ++ # text_factory defaults to unicode ++ row = self.con.execute("select value from test").fetchone() ++ self.assertIs(type(row[0]), unicode) ++ self.assertEqual(row[0], "a\x00b") ++ ++ def CheckCustom(self): ++ # A custom factory should receive an str argument ++ self.con.text_factory = lambda x: x ++ row = self.con.execute("select value from test").fetchone() ++ self.assertIs(type(row[0]), str) ++ self.assertEqual(row[0], "a\x00b") ++ ++ def CheckOptimizedUnicodeAsString(self): ++ # ASCII -> str argument ++ self.con.text_factory = sqlite.OptimizedUnicode ++ row = self.con.execute("select value from test").fetchone() ++ self.assertIs(type(row[0]), str) ++ self.assertEqual(row[0], "a\x00b") ++ ++ def CheckOptimizedUnicodeAsUnicode(self): ++ # Non-ASCII -> unicode argument ++ self.con.text_factory = sqlite.OptimizedUnicode ++ self.con.execute("delete from test") ++ self.con.execute("insert into test (value) values (?)", (u'ä\0ö',)) ++ row = self.con.execute("select value from test").fetchone() ++ self.assertIs(type(row[0]), unicode) ++ self.assertEqual(row[0], u"ä\x00ö") ++ ++ def tearDown(self): ++ self.con.close() ++ + def suite(): + connection_suite = unittest.makeSuite(ConnectionFactoryTests, "Check") + cursor_suite = unittest.makeSuite(CursorFactoryTests, "Check") + row_suite_compat = unittest.makeSuite(RowFactoryTestsBackwardsCompat, "Check") + row_suite = unittest.makeSuite(RowFactoryTests, "Check") + text_suite = unittest.makeSuite(TextFactoryTests, "Check") +- return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite)) ++ text_zero_bytes_suite = unittest.makeSuite(TextFactoryTestsWithEmbeddedZeroBytes, "Check") ++ return unittest.TestSuite((connection_suite, cursor_suite, row_suite_compat, row_suite, text_suite, text_zero_bytes_suite)) + + def test(): + runner = unittest.TextTestRunner() +diff -r 8527427914a2 Lib/sqlite3/test/regression.py +--- a/Lib/sqlite3/test/regression.py ++++ b/Lib/sqlite3/test/regression.py +@@ -264,6 +264,28 @@ + """ + self.assertRaises(sqlite.Warning, self.con, 1) + ++ def CheckRecursiveCursorUse(self): ++ """ ++ http://bugs.python.org/issue10811 ++ ++ Recursively using a cursor, such as when reusing it from a generator led to segfaults. ++ Now we catch recursive cursor usage and raise a ProgrammingError. ++ """ ++ con = sqlite.connect(":memory:") ++ ++ cur = con.cursor() ++ cur.execute("create table a (bar)") ++ cur.execute("create table b (baz)") ++ ++ def foo(): ++ cur.execute("insert into a (bar) values (?)", (1,)) ++ yield 1 ++ ++ with self.assertRaises(sqlite.ProgrammingError): ++ cur.executemany("insert into b (baz) values (?)", ++ ((i,) for i in foo())) ++ ++ + def suite(): + regression_suite = unittest.makeSuite(RegressionTests, "Check") + return unittest.TestSuite((regression_suite,)) +diff -r 8527427914a2 Lib/ssl.py +--- a/Lib/ssl.py ++++ b/Lib/ssl.py +@@ -81,8 +81,9 @@ + } + try: + from _ssl import PROTOCOL_SSLv2 ++ _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 + except ImportError: +- pass ++ _SSLv2_IF_EXISTS = None + else: + _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" + +@@ -91,6 +92,11 @@ + import base64 # for DER-to-PEM translation + import errno + ++# Disable weak or insecure ciphers by default ++# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL') ++_DEFAULT_CIPHERS = 'DEFAULT:!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2' ++ ++ + class SSLSocket(socket): + + """This class implements a subtype of socket.socket that wraps +@@ -112,6 +118,9 @@ + except AttributeError: + pass + ++ if ciphers is None and ssl_version != _SSLv2_IF_EXISTS: ++ ciphers = _DEFAULT_CIPHERS ++ + if certfile and not keyfile: + keyfile = certfile + # see if it's connected +diff -r 8527427914a2 Lib/stat.py +--- a/Lib/stat.py ++++ b/Lib/stat.py +@@ -87,6 +87,8 @@ + UF_APPEND = 0x00000004 + UF_OPAQUE = 0x00000008 + UF_NOUNLINK = 0x00000010 ++UF_COMPRESSED = 0x00000020 # OS X: file is hfs-compressed ++UF_HIDDEN = 0x00008000 # OS X: file should not be displayed + SF_ARCHIVED = 0x00010000 + SF_IMMUTABLE = 0x00020000 + SF_APPEND = 0x00040000 +diff -r 8527427914a2 Lib/subprocess.py +--- a/Lib/subprocess.py ++++ b/Lib/subprocess.py +@@ -460,7 +460,7 @@ + def _cleanup(): + for inst in _active[:]: + res = inst._internal_poll(_deadstate=sys.maxint) +- if res is not None and res >= 0: ++ if res is not None: + try: + _active.remove(inst) + except ValueError: +@@ -476,7 +476,7 @@ + while True: + try: + return func(*args) +- except OSError, e: ++ except (OSError, IOError) as e: + if e.errno == errno.EINTR: + continue + raise +@@ -707,7 +707,10 @@ + + + def __del__(self, _maxint=sys.maxint, _active=_active): +- if not self._child_created: ++ # If __init__ hasn't had a chance to execute (e.g. if it ++ # was passed an undeclared keyword argument), we don't ++ # have a _child_created attribute at all. ++ if not getattr(self, '_child_created', False): + # We didn't get to successfully create a child process. + return + # In case the child hasn't been waited on, check if it's done. +@@ -740,10 +743,10 @@ + raise + self.stdin.close() + elif self.stdout: +- stdout = self.stdout.read() ++ stdout = _eintr_retry_call(self.stdout.read) + self.stdout.close() + elif self.stderr: +- stderr = self.stderr.read() ++ stderr = _eintr_retry_call(self.stderr.read) + self.stderr.close() + self.wait() + return (stdout, stderr) +@@ -1032,7 +1035,7 @@ + if stdin is None: + pass + elif stdin == PIPE: +- p2cread, p2cwrite = os.pipe() ++ p2cread, p2cwrite = self.pipe_cloexec() + elif isinstance(stdin, int): + p2cread = stdin + else: +@@ -1042,7 +1045,7 @@ + if stdout is None: + pass + elif stdout == PIPE: +- c2pread, c2pwrite = os.pipe() ++ c2pread, c2pwrite = self.pipe_cloexec() + elif isinstance(stdout, int): + c2pwrite = stdout + else: +@@ -1052,7 +1055,7 @@ + if stderr is None: + pass + elif stderr == PIPE: +- errread, errwrite = os.pipe() ++ errread, errwrite = self.pipe_cloexec() + elif stderr == STDOUT: + errwrite = c2pwrite + elif isinstance(stderr, int): +@@ -1079,6 +1082,18 @@ + fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag) + + ++ def pipe_cloexec(self): ++ """Create a pipe with FDs set CLOEXEC.""" ++ # Pipes' FDs are set CLOEXEC by default because we don't want them ++ # to be inherited by other subprocesses: the CLOEXEC flag is removed ++ # from the child's FDs by _dup2(), between fork() and exec(). ++ # This is not atomic: we would need the pipe2() syscall for that. ++ r, w = os.pipe() ++ self._set_cloexec_flag(r) ++ self._set_cloexec_flag(w) ++ return r, w ++ ++ + def _close_fds(self, but): + if hasattr(os, 'closerange'): + os.closerange(3, but) +@@ -1117,11 +1132,9 @@ + # For transferring possible exec failure from child to parent + # The first char specifies the exception type: 0 means + # OSError, 1 means some other error. +- errpipe_read, errpipe_write = os.pipe() ++ errpipe_read, errpipe_write = self.pipe_cloexec() + try: + try: +- self._set_cloexec_flag(errpipe_write) +- + gc_was_enabled = gc.isenabled() + # Disable gc to avoid bug where gc -> file_dealloc -> + # write to stderr -> hang. http://bugs.python.org/issue1336 +@@ -1145,6 +1158,14 @@ + os.close(errread) + os.close(errpipe_read) + ++ # When duping fds, if there arises a situation ++ # where one of the fds is either 0, 1 or 2, it ++ # is possible that it is overwritten (#12607). ++ if c2pwrite == 0: ++ c2pwrite = os.dup(c2pwrite) ++ if errwrite == 0 or errwrite == 1: ++ errwrite = os.dup(errwrite) ++ + # Dup fds for child + def _dup2(a, b): + # dup2() removes the CLOEXEC flag but +diff -r 8527427914a2 Lib/sysconfig.py +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -176,8 +176,9 @@ + if sys.platform == "darwin": + framework = get_config_var("PYTHONFRAMEWORK") + if framework: +- return joinuser("~", "Library", framework, "%d.%d"%( +- sys.version_info[:2])) ++ return env_base if env_base else \ ++ joinuser("~", "Library", framework, "%d.%d" ++ % (sys.version_info[:2])) + + return env_base if env_base else joinuser("~", ".local") + +@@ -582,6 +583,11 @@ + if release[0] >= "5": # SunOS 5 == Solaris 2 + osname = "solaris" + release = "%d.%s" % (int(release[0]) - 3, release[2:]) ++ # We can't use "platform.architecture()[0]" because a ++ # bootstrap problem. We use a dict to get an error ++ # if some suspicious happens. ++ bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} ++ machine += ".%s" % bitness[sys.maxint] + # fall through to standard osname-release-machine representation + elif osname[:4] == "irix": # could be "irix64"! + return "%s-%s" % (osname, release) +diff -r 8527427914a2 Lib/tarfile.py +--- a/Lib/tarfile.py ++++ b/Lib/tarfile.py +@@ -30,7 +30,7 @@ + """Read from and write to tar format archives. + """ + +-__version__ = "$Revision$" ++__version__ = "$Revision: 85213 $" + # $Source$ + + version = "0.9.0" +@@ -454,6 +454,8 @@ + 0) + timestamp = struct.pack("e$NL\E*$K$O$"$^$jE,$7$F$$$^$;$s$G$7$?!#(B ++$B$3$N$?$a!"(BGuido $B$O$h$j$E$1$^$7$?!#(B ++$B$3$N$h$&$JGX7J$+$i@8$^$l$?(B Python $B$N8@8l@_7W$O!"!V%7%s%W%k!W$G!V=,F@$,MF0W!W$H$$$&L\I8$K=EE@$,CV$+$l$F$$$^$9!#(B ++$BB?$/$N%9%/%j%W%H7O8@8l$G$O%f!<%6$NL\@h$NMxJX@-$rM%@h$7$F?'!9$J5!G=$r8@8lMWAG$H$7$Fl9g$,B?$$$N$G$9$,!"(BPython $B$G$O$=$&$$$C$?>.:Y9)$,DI2C$5$l$k$3$H$O$"$^$j$"$j$^$;$s!#(B ++$B8@8l<+BN$N5!G=$O:G>.8B$K2!$5$(!"I,MW$J5!G=$O3HD%%b%8%e!<%k$H$7$FDI2C$9$k!"$H$$$&$N$,(B Python $B$N%]%j%7!<$G$9!#(B ++ +diff -r 8527427914a2 Lib/test/cjkencodings/iso2022_kr-utf8.txt +--- /dev/null ++++ b/Lib/test/cjkencodings/iso2022_kr-utf8.txt +@@ -0,0 +1,7 @@ ++â—Ž 파ì´ì¬(Python)ì€ ë°°ìš°ê¸° 쉽고, 강력한 í”„ë¡œê·¸ëž˜ë° ì–¸ì–´ìž…ë‹ˆë‹¤. 파ì´ì¬ì€ ++효율ì ì¸ 고수준 ë°ì´í„° 구조와 간단하지만 효율ì ì¸ ê°ì²´ì§€í–¥í”„로그래ë°ì„ ++지ì›í•©ë‹ˆë‹¤. 파ì´ì¬ì˜ ìš°ì•„(優雅)í•œ 문법과 ë™ì  타ì´í•‘, 그리고 ì¸í„°í”„리팅 ++í™˜ê²½ì€ íŒŒì´ì¬ì„ 스í¬ë¦½íŒ…ê³¼ 여러 분야ì—서와 ëŒ€ë¶€ë¶„ì˜ í”Œëž«í¼ì—ì„œì˜ ë¹ ë¥¸ ++애플리케ì´ì…˜ ê°œë°œì„ í•  수 있는 ì´ìƒì ì¸ 언어로 만들어ì¤ë‹ˆë‹¤. ++ ++☆첫가ë: ë‚ ì•„ë¼ ì“©~ í¼! ê¸ˆì—†ì´ ì „ë‹ˆë‹¤. 그런거 다. +diff -r 8527427914a2 Lib/test/cjkencodings/iso2022_kr.txt +--- /dev/null ++++ b/Lib/test/cjkencodings/iso2022_kr.txt +@@ -0,0 +1,7 @@ ++$)C!] FD@L=c(Python)@: 9h?l1b =10m, 0-7BGQ GA7N1W7!9V >p>n@T4O4Y. FD@L=c@: ++H?@2@{@N 0mF(iPd:)GQ 9.9}0z 5?@{ E8@LGN, 1W8.0m @NEMGA8.FC ++H/0f@: FD@L=c@; =:E)83FC0z ?)7/ :P>_?!<-?M 4k:N:P@G GC7'F{?!<-@G :|8% ++>VGC8.DI@Lp>n7N 885i>nA]4O4Y. ++ ++!YC90!3!: 3/>F6s >1~ E-! 1]>x@L @|4O4Y. 1W710E 4Y. +diff -r 8527427914a2 Lib/test/decimaltestdata/extra.decTest +--- a/Lib/test/decimaltestdata/extra.decTest ++++ b/Lib/test/decimaltestdata/extra.decTest +@@ -222,12 +222,25 @@ + extr1701 power 100.0 -557.71e-742888888 -> 1.000000000000000 Inexact Rounded + extr1702 power 10 1e-100 -> 1.000000000000000 Inexact Rounded + ++-- Another one (see issue #12080). Thanks again to Stefan Krah. ++extr1703 power 4 -1.2e-999999999 -> 1.000000000000000 Inexact Rounded ++ + -- A couple of interesting exact cases for power. Note that the specification + -- requires these to be reported as Inexact. + extr1710 power 1e375 56e-3 -> 1.000000000000000E+21 Inexact Rounded + extr1711 power 10000 0.75 -> 1000.000000000000 Inexact Rounded + extr1712 power 1e-24 0.875 -> 1.000000000000000E-21 Inexact Rounded + ++-- Some more exact cases, exercising power with negative second argument. ++extr1720 power 400 -0.5 -> 0.05000000000000000 Inexact Rounded ++extr1721 power 4096 -0.75 -> 0.001953125000000000 Inexact Rounded ++extr1722 power 625e4 -0.25 -> 0.02000000000000000 Inexact Rounded ++ ++-- Nonexact cases, to exercise some of the early exit conditions from ++-- _power_exact. ++extr1730 power 2048 -0.75 -> 0.003284751622084822 Inexact Rounded ++ ++ + -- Tests for the is_* boolean operations + precision: 9 + maxExponent: 999 +diff -r 8527427914a2 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 8527427914a2 Lib/test/pickletester.py +--- a/Lib/test/pickletester.py ++++ b/Lib/test/pickletester.py +@@ -124,6 +124,21 @@ + class use_metaclass(object): + __metaclass__ = metaclass + ++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) ++ ++ __hash__ = None ++ ++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(). + +@@ -609,6 +624,14 @@ + b = self.loads(s) + self.assertEqual(a.__class__, b.__class__) + ++ def test_dynamic_class(self): ++ a = create_dynamic_class("my_dynamic_class", (object,)) ++ copy_reg.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 +diff -r 8527427914a2 Lib/test/regex_tests.py +--- a/Lib/test/regex_tests.py ++++ /dev/null +@@ -1,287 +0,0 @@ +-# Regex test suite and benchmark suite v1.5a2 +-# Due to the use of r"aw" strings, this file will +-# only work with Python 1.5 or higher. +- +-# The 3 possible outcomes for each pattern +-[SUCCEED, FAIL, SYNTAX_ERROR] = range(3) +- +-# Benchmark suite (needs expansion) +-# +-# The benchmark suite does not test correctness, just speed. The +-# first element of each tuple is the regex pattern; the second is a +-# string to match it against. The benchmarking code will embed the +-# second string inside several sizes of padding, to test how regex +-# matching performs on large strings. +- +-benchmarks = [ +- ('Python', 'Python'), # Simple text literal +- ('.*Python', 'Python'), # Bad text literal +- ('.*Python.*', 'Python'), # Worse text literal +- ('.*\\(Python\\)', 'Python'), # Bad text literal with grouping +- +- ('(Python\\|Perl\\|Tcl', 'Perl'), # Alternation +- ('\\(Python\\|Perl\\|Tcl\\)', 'Perl'), # Grouped alternation +- ('\\(Python\\)\\1', 'PythonPython'), # Backreference +-# ('\\([0a-z][a-z]*,\\)+', 'a5,b7,c9,'), # Disable the fastmap optimization +- ('\\([a-z][a-z0-9]*,\\)+', 'a5,b7,c9,') # A few sets +-] +- +-# Test suite (for verifying correctness) +-# +-# The test suite is a list of 5- or 3-tuples. The 5 parts of a +-# complete tuple are: +-# element 0: a string containing the pattern +-# 1: the string to match against the pattern +-# 2: the expected result (SUCCEED, FAIL, SYNTAX_ERROR) +-# 3: a string that will be eval()'ed to produce a test string. +-# This is an arbitrary Python expression; the available +-# variables are "found" (the whole match), and "g1", "g2", ... +-# up to "g10" contain the contents of each group, or the +-# string 'None' if the group wasn't given a value. +-# 4: The expected result of evaluating the expression. +-# If the two don't match, an error is reported. +-# +-# If the regex isn't expected to work, the latter two elements can be omitted. +- +-tests = [ +-('abc', 'abc', SUCCEED, +- 'found', 'abc'), +-('abc', 'xbc', FAIL), +-('abc', 'axc', FAIL), +-('abc', 'abx', FAIL), +-('abc', 'xabcy', SUCCEED, +- 'found', 'abc'), +-('abc', 'ababc', SUCCEED, +- 'found', 'abc'), +-('ab*c', 'abc', SUCCEED, +- 'found', 'abc'), +-('ab*bc', 'abc', SUCCEED, +- 'found', 'abc'), +-('ab*bc', 'abbc', SUCCEED, +- 'found', 'abbc'), +-('ab*bc', 'abbbbc', SUCCEED, +- 'found', 'abbbbc'), +-('ab+bc', 'abbc', SUCCEED, +- 'found', 'abbc'), +-('ab+bc', 'abc', FAIL), +-('ab+bc', 'abq', FAIL), +-('ab+bc', 'abbbbc', SUCCEED, +- 'found', 'abbbbc'), +-('ab?bc', 'abbc', SUCCEED, +- 'found', 'abbc'), +-('ab?bc', 'abc', SUCCEED, +- 'found', 'abc'), +-('ab?bc', 'abbbbc', FAIL), +-('ab?c', 'abc', SUCCEED, +- 'found', 'abc'), +-('^abc$', 'abc', SUCCEED, +- 'found', 'abc'), +-('^abc$', 'abcc', FAIL), +-('^abc', 'abcc', SUCCEED, +- 'found', 'abc'), +-('^abc$', 'aabc', FAIL), +-('abc$', 'aabc', SUCCEED, +- 'found', 'abc'), +-('^', 'abc', SUCCEED, +- 'found+"-"', '-'), +-('$', 'abc', SUCCEED, +- 'found+"-"', '-'), +-('a.c', 'abc', SUCCEED, +- 'found', 'abc'), +-('a.c', 'axc', SUCCEED, +- 'found', 'axc'), +-('a.*c', 'axyzc', SUCCEED, +- 'found', 'axyzc'), +-('a.*c', 'axyzd', FAIL), +-('a[bc]d', 'abc', FAIL), +-('a[bc]d', 'abd', SUCCEED, +- 'found', 'abd'), +-('a[b-d]e', 'abd', FAIL), +-('a[b-d]e', 'ace', SUCCEED, +- 'found', 'ace'), +-('a[b-d]', 'aac', SUCCEED, +- 'found', 'ac'), +-('a[-b]', 'a-', SUCCEED, +- 'found', 'a-'), +-('a[b-]', 'a-', SUCCEED, +- 'found', 'a-'), +-('a[]b', '-', SYNTAX_ERROR), +-('a[', '-', SYNTAX_ERROR), +-('a\\', '-', SYNTAX_ERROR), +-('abc\\)', '-', SYNTAX_ERROR), +-('\\(abc', '-', SYNTAX_ERROR), +-('a]', 'a]', SUCCEED, +- 'found', 'a]'), +-('a[]]b', 'a]b', SUCCEED, +- 'found', 'a]b'), +-('a[^bc]d', 'aed', SUCCEED, +- 'found', 'aed'), +-('a[^bc]d', 'abd', FAIL), +-('a[^-b]c', 'adc', SUCCEED, +- 'found', 'adc'), +-('a[^-b]c', 'a-c', FAIL), +-('a[^]b]c', 'a]c', FAIL), +-('a[^]b]c', 'adc', SUCCEED, +- 'found', 'adc'), +-('\\ba\\b', 'a-', SUCCEED, +- '"-"', '-'), +-('\\ba\\b', '-a', SUCCEED, +- '"-"', '-'), +-('\\ba\\b', '-a-', SUCCEED, +- '"-"', '-'), +-('\\by\\b', 'xy', FAIL), +-('\\by\\b', 'yz', FAIL), +-('\\by\\b', 'xyz', FAIL), +-('ab\\|cd', 'abc', SUCCEED, +- 'found', 'ab'), +-('ab\\|cd', 'abcd', SUCCEED, +- 'found', 'ab'), +-('\\(\\)ef', 'def', SUCCEED, +- 'found+"-"+g1', 'ef-'), +-('$b', 'b', FAIL), +-('a(b', 'a(b', SUCCEED, +- 'found+"-"+g1', 'a(b-None'), +-('a(*b', 'ab', SUCCEED, +- 'found', 'ab'), +-('a(*b', 'a((b', SUCCEED, +- 'found', 'a((b'), +-('a\\\\b', 'a\\b', SUCCEED, +- 'found', 'a\\b'), +-('\\(\\(a\\)\\)', 'abc', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'a-a-a'), +-('\\(a\\)b\\(c\\)', 'abc', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'abc-a-c'), +-('a+b+c', 'aabbabc', SUCCEED, +- 'found', 'abc'), +-('\\(a+\\|b\\)*', 'ab', SUCCEED, +- 'found+"-"+g1', 'ab-b'), +-('\\(a+\\|b\\)+', 'ab', SUCCEED, +- 'found+"-"+g1', 'ab-b'), +-('\\(a+\\|b\\)?', 'ab', SUCCEED, +- 'found+"-"+g1', 'a-a'), +-('\\)\\(', '-', SYNTAX_ERROR), +-('[^ab]*', 'cde', SUCCEED, +- 'found', 'cde'), +-('abc', '', FAIL), +-('a*', '', SUCCEED, +- 'found', ''), +-('a\\|b\\|c\\|d\\|e', 'e', SUCCEED, +- 'found', 'e'), +-('\\(a\\|b\\|c\\|d\\|e\\)f', 'ef', SUCCEED, +- 'found+"-"+g1', 'ef-e'), +-('abcd*efg', 'abcdefg', SUCCEED, +- 'found', 'abcdefg'), +-('ab*', 'xabyabbbz', SUCCEED, +- 'found', 'ab'), +-('ab*', 'xayabbbz', SUCCEED, +- 'found', 'a'), +-('\\(ab\\|cd\\)e', 'abcde', SUCCEED, +- 'found+"-"+g1', 'cde-cd'), +-('[abhgefdc]ij', 'hij', SUCCEED, +- 'found', 'hij'), +-('^\\(ab\\|cd\\)e', 'abcde', FAIL, +- 'xg1y', 'xy'), +-('\\(abc\\|\\)ef', 'abcdef', SUCCEED, +- 'found+"-"+g1', 'ef-'), +-('\\(a\\|b\\)c*d', 'abcd', SUCCEED, +- 'found+"-"+g1', 'bcd-b'), +-('\\(ab\\|ab*\\)bc', 'abc', SUCCEED, +- 'found+"-"+g1', 'abc-a'), +-('a\\([bc]*\\)c*', 'abc', SUCCEED, +- 'found+"-"+g1', 'abc-bc'), +-('a\\([bc]*\\)\\(c*d\\)', 'abcd', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'abcd-bc-d'), +-('a\\([bc]+\\)\\(c*d\\)', 'abcd', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'abcd-bc-d'), +-('a\\([bc]*\\)\\(c+d\\)', 'abcd', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'abcd-b-cd'), +-('a[bcd]*dcdcde', 'adcdcde', SUCCEED, +- 'found', 'adcdcde'), +-('a[bcd]+dcdcde', 'adcdcde', FAIL), +-('\\(ab\\|a\\)b*c', 'abc', SUCCEED, +- 'found+"-"+g1', 'abc-ab'), +-('\\(\\(a\\)\\(b\\)c\\)\\(d\\)', 'abcd', SUCCEED, +- 'g1+"-"+g2+"-"+g3+"-"+g4', 'abc-a-b-d'), +-('[a-zA-Z_][a-zA-Z0-9_]*', 'alpha', SUCCEED, +- 'found', 'alpha'), +-('^a\\(bc+\\|b[eh]\\)g\\|.h$', 'abh', SUCCEED, +- 'found+"-"+g1', 'bh-None'), +-('\\(bc+d$\\|ef*g.\\|h?i\\(j\\|k\\)\\)', 'effgz', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'effgz-effgz-None'), +-('\\(bc+d$\\|ef*g.\\|h?i\\(j\\|k\\)\\)', 'ij', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'ij-ij-j'), +-('\\(bc+d$\\|ef*g.\\|h?i\\(j\\|k\\)\\)', 'effg', FAIL), +-('\\(bc+d$\\|ef*g.\\|h?i\\(j\\|k\\)\\)', 'bcdd', FAIL), +-('\\(bc+d$\\|ef*g.\\|h?i\\(j\\|k\\)\\)', 'reffgz', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'effgz-effgz-None'), +-('\\(\\(\\(\\(\\(\\(\\(\\(\\(a\\)\\)\\)\\)\\)\\)\\)\\)\\)', 'a', SUCCEED, +- 'found', 'a'), +-('multiple words of text', 'uh-uh', FAIL), +-('multiple words', 'multiple words, yeah', SUCCEED, +- 'found', 'multiple words'), +-('\\(.*\\)c\\(.*\\)', 'abcde', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'abcde-ab-de'), +-('(\\(.*\\), \\(.*\\))', '(a, b)', SUCCEED, +- 'g2+"-"+g1', 'b-a'), +-('[k]', 'ab', FAIL), +-('a[-]?c', 'ac', SUCCEED, +- 'found', 'ac'), +-('\\(abc\\)\\1', 'abcabc', SUCCEED, +- 'g1', 'abc'), +-('\\([a-c]*\\)\\1', 'abcabc', SUCCEED, +- 'g1', 'abc'), +-('^\\(.+\\)?B', 'AB', SUCCEED, +- 'g1', 'A'), +-('\\(a+\\).\\1$', 'aaaaa', SUCCEED, +- 'found+"-"+g1', 'aaaaa-aa'), +-('^\\(a+\\).\\1$', 'aaaa', FAIL), +-('\\(abc\\)\\1', 'abcabc', SUCCEED, +- 'found+"-"+g1', 'abcabc-abc'), +-('\\([a-c]+\\)\\1', 'abcabc', SUCCEED, +- 'found+"-"+g1', 'abcabc-abc'), +-('\\(a\\)\\1', 'aa', SUCCEED, +- 'found+"-"+g1', 'aa-a'), +-('\\(a+\\)\\1', 'aa', SUCCEED, +- 'found+"-"+g1', 'aa-a'), +-('\\(a+\\)+\\1', 'aa', SUCCEED, +- 'found+"-"+g1', 'aa-a'), +-('\\(a\\).+\\1', 'aba', SUCCEED, +- 'found+"-"+g1', 'aba-a'), +-('\\(a\\)ba*\\1', 'aba', SUCCEED, +- 'found+"-"+g1', 'aba-a'), +-('\\(aa\\|a\\)a\\1$', 'aaa', SUCCEED, +- 'found+"-"+g1', 'aaa-a'), +-('\\(a\\|aa\\)a\\1$', 'aaa', SUCCEED, +- 'found+"-"+g1', 'aaa-a'), +-('\\(a+\\)a\\1$', 'aaa', SUCCEED, +- 'found+"-"+g1', 'aaa-a'), +-('\\([abc]*\\)\\1', 'abcabc', SUCCEED, +- 'found+"-"+g1', 'abcabc-abc'), +-('\\(a\\)\\(b\\)c\\|ab', 'ab', SUCCEED, +- 'found+"-"+g1+"-"+g2', 'ab-None-None'), +-('\\(a\\)+x', 'aaax', SUCCEED, +- 'found+"-"+g1', 'aaax-a'), +-('\\([ac]\\)+x', 'aacx', SUCCEED, +- 'found+"-"+g1', 'aacx-c'), +-('\\([^/]*/\\)*sub1/', 'd:msgs/tdir/sub1/trial/away.cpp', SUCCEED, +- 'found+"-"+g1', 'd:msgs/tdir/sub1/-tdir/'), +-('\\([^.]*\\)\\.\\([^:]*\\):[T ]+\\(.*\\)', 'track1.title:TBlah blah blah', SUCCEED, +- 'found+"-"+g1+"-"+g2+"-"+g3', 'track1.title:TBlah blah blah-track1-title-Blah blah blah'), +-('\\([^N]*N\\)+', 'abNNxyzN', SUCCEED, +- 'found+"-"+g1', 'abNNxyzN-xyzN'), +-('\\([^N]*N\\)+', 'abNNxyz', SUCCEED, +- 'found+"-"+g1', 'abNN-N'), +-('\\([abc]*\\)x', 'abcx', SUCCEED, +- 'found+"-"+g1', 'abcx-abc'), +-('\\([abc]*\\)x', 'abc', FAIL), +-('\\([xyz]*\\)x', 'abcx', SUCCEED, +- 'found+"-"+g1', 'x-'), +-('\\(a\\)+b\\|aac', 'aac', SUCCEED, +- 'found+"-"+g1', 'aac-None'), +-('\', 'ab', FAIL), +-('a\>', 'a!', SUCCEED, 'found', 'a'), +-('a\>', 'a', SUCCEED, 'found', 'a'), +-] +diff -r 8527427914a2 Lib/test/regrtest.py +--- a/Lib/test/regrtest.py ++++ b/Lib/test/regrtest.py +@@ -1076,6 +1076,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 8527427914a2 Lib/test/svn_python_org_https_cert.pem +--- a/Lib/test/svn_python_org_https_cert.pem ++++ /dev/null +@@ -1,31 +0,0 @@ +------BEGIN CERTIFICATE----- +-MIIFQTCCBCmgAwIBAgIQL2qw7lpsHqTLcBh1PVjsaTANBgkqhkiG9w0BAQUFADCB +-lzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug +-Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho +-dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3Qt +-SGFyZHdhcmUwHhcNMDcwNDEwMDAwMDAwWhcNMTAwNDA5MjM1OTU5WjCBvjELMAkG +-A1UEBhMCVVMxDjAMBgNVBBETBTAxOTM4MRYwFAYDVQQIEw1NYXNzYWNodXNldHRz +-MREwDwYDVQQHEwhJcHN3aXRjaDEMMAoGA1UECRMDbi9hMQwwCgYDVQQSEwM2NTMx +-IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMRowGAYDVQQLExFD +-b21vZG8gSW5zdGFudFNTTDEXMBUGA1UEAxMOc3ZuLnB5dGhvbi5vcmcwgZ8wDQYJ +-KoZIhvcNAQEBBQADgY0AMIGJAoGBAMFOfFeLpiIN9UzTCehCgQ4W3ufaq524qPoX +-00iNDiI/ehd6kC0BXIP5/y9lPoMn7nRsjdjczUaVmlPWG8BhvADK3ZZIm7m/3mZW +-O/+C5vGE9YuOqIKe0VoNz/cZaYkz+C2xmOwDTp6a+ls29jjUfoxMd9gtGtuOp7s+ +-IouVD3wZAgMBAAGjggHiMIIB3jAfBgNVHSMEGDAWgBShcl8mGyiYQ5VdBzfVhZad +-S9LDRTAdBgNVHQ4EFgQUkeNAqLbnKq86W/ghBV9xfC+7h9swDgYDVR0PAQH/BAQD +-AgWgMAwGA1UdEwEB/wQCMAAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMC +-MBEGCWCGSAGG+EIBAQQEAwIGwDBGBgNVHSAEPzA9MDsGDCsGAQQBsjEBAgEDBDAr +-MCkGCCsGAQUFBwIBFh1odHRwczovL3NlY3VyZS5jb21vZG8ubmV0L0NQUzB7BgNV +-HR8EdDByMDigNqA0hjJodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9VVE4tVVNFUkZp +-cnN0LUhhcmR3YXJlLmNybDA2oDSgMoYwaHR0cDovL2NybC5jb21vZG8ubmV0L1VU +-Ti1VU0VSRmlyc3QtSGFyZHdhcmUuY3JsMIGGBggrBgEFBQcBAQR6MHgwOwYIKwYB +-BQUHMAKGL2h0dHA6Ly9jcnQuY29tb2RvY2EuY29tL1VUTkFkZFRydXN0U2VydmVy +-Q0EuY3J0MDkGCCsGAQUFBzAChi1odHRwOi8vY3J0LmNvbW9kby5uZXQvVVROQWRk +-VHJ1c3RTZXJ2ZXJDQS5jcnQwDQYJKoZIhvcNAQEFBQADggEBAFBxEOeKr5+vurzE +-6DiP4THhQsp+LA0+tnZ5rkV7RODAmF6strjONl3FKWGSqrucWNnFTo/HMgrgZJHQ +-CunxrJf4J5CVz/CvGlfdBDmCpYz5agc8b7EJhmM2WoWSqC+5CYIXuRzUuYcKWjPt +-3LV312Zil4BaeZ+wv4SKR8cL8jsB/sj8QxLxrZjOGXtVX3J95AnrY7BMDjuCBDxx +-dUUOUJpdJ4undAG1of0ZsPOGJ5viSJYNeJ9iOjSua24mfZ2aQ/mULirnqF8Gkr38 +-CMlC8io5ct5NnLgkWmPr0FS5UyalLeWXiopS6hMofvu952VGLyacLgMl7d9S5AaL +-mxMHHeo= +------END CERTIFICATE----- +diff -r 8527427914a2 Lib/test/test_StringIO.py +--- a/Lib/test/test_StringIO.py ++++ b/Lib/test/test_StringIO.py +@@ -4,6 +4,7 @@ + import StringIO + import cStringIO + import types ++import array + from test import test_support + + +@@ -127,6 +128,34 @@ + class TestcStringIO(TestGenericStringIO): + MODULE = cStringIO + ++ def test_array_support(self): ++ # Issue #1730114: cStringIO should accept array objects ++ a = array.array('B', [0,1,2]) ++ f = self.MODULE.StringIO(a) ++ self.assertEqual(f.getvalue(), '\x00\x01\x02') ++ ++ def test_unicode(self): ++ ++ if not test_support.have_unicode: return ++ ++ # The cStringIO module converts Unicode strings to character ++ # strings when writing them to cStringIO objects. ++ # Check that this works. ++ ++ f = self.MODULE.StringIO() ++ f.write(u'abcde') ++ s = f.getvalue() ++ self.assertEqual(s, 'abcde') ++ self.assertEqual(type(s), str) ++ ++ f = self.MODULE.StringIO(u'abcde') ++ s = f.getvalue() ++ self.assertEqual(s, 'abcde') ++ self.assertEqual(type(s), str) ++ ++ self.assertRaises(UnicodeEncodeError, self.MODULE.StringIO, u'\xf4') ++ ++ + import sys + if sys.platform.startswith('java'): + # Jython doesn't have a buffer object, so we just do a useless +diff -r 8527427914a2 Lib/test/test_aifc.py +--- a/Lib/test/test_aifc.py ++++ b/Lib/test/test_aifc.py +@@ -1,6 +1,7 @@ + from test.test_support import findfile, run_unittest, TESTFN + import unittest + import os ++import io + + import aifc + +@@ -107,8 +108,45 @@ + self.assertEqual(testfile.closed, True) + + ++class AIFCLowLevelTest(unittest.TestCase): ++ ++ def test_read_written(self): ++ def read_written(self, what): ++ f = io.BytesIO() ++ getattr(aifc, '_write_' + what)(f, x) ++ f.seek(0) ++ return getattr(aifc, '_read_' + what)(f) ++ for x in (-1, 0, 0.1, 1): ++ self.assertEqual(read_written(x, 'float'), x) ++ for x in (float('NaN'), float('Inf')): ++ self.assertEqual(read_written(x, 'float'), aifc._HUGE_VAL) ++ for x in (b'', b'foo', b'a' * 255): ++ self.assertEqual(read_written(x, 'string'), x) ++ for x in (-0x7FFFFFFF, -1, 0, 1, 0x7FFFFFFF): ++ self.assertEqual(read_written(x, 'long'), x) ++ for x in (0, 1, 0xFFFFFFFF): ++ self.assertEqual(read_written(x, 'ulong'), x) ++ for x in (-0x7FFF, -1, 0, 1, 0x7FFF): ++ self.assertEqual(read_written(x, 'short'), x) ++ for x in (0, 1, 0xFFFF): ++ self.assertEqual(read_written(x, 'ushort'), x) ++ ++ def test_read_raises(self): ++ f = io.BytesIO(b'\x00') ++ self.assertRaises(EOFError, aifc._read_ulong, f) ++ self.assertRaises(EOFError, aifc._read_long, f) ++ self.assertRaises(EOFError, aifc._read_ushort, f) ++ self.assertRaises(EOFError, aifc._read_short, f) ++ ++ def test_write_long_string_raises(self): ++ f = io.BytesIO() ++ with self.assertRaises(ValueError): ++ aifc._write_string(f, b'too long' * 255) ++ ++ + def test_main(): + run_unittest(AIFCTest) ++ run_unittest(AIFCLowLevelTest) + + + if __name__ == "__main__": +diff -r 8527427914a2 Lib/test/test_argparse.py +--- a/Lib/test/test_argparse.py ++++ b/Lib/test/test_argparse.py +@@ -1509,6 +1509,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""" + +@@ -2133,8 +2135,9 @@ + parents = [self.abcd_parent, self.wxyz_parent] + parser = ErrorRaisingArgumentParser(parents=parents) + parser_help = parser.format_help() ++ progname = self.main_program + self.assertEqual(parser_help, textwrap.dedent('''\ +- usage: {} [-h] [-b B] [--d D] [--w W] [-y Y] a z ++ usage: {}{}[-h] [-b B] [--d D] [--w W] [-y Y] a z + + positional arguments: + a +@@ -2150,7 +2153,7 @@ + + x: + -y Y +- '''.format(self.main_program))) ++ '''.format(progname, ' ' if progname else '' ))) + + def test_groups_parents(self): + parent = ErrorRaisingArgumentParser(add_help=False) +@@ -2166,8 +2169,9 @@ + ['-y', 'Y', '-z', 'Z']) + + parser_help = parser.format_help() ++ progname = self.main_program + self.assertEqual(parser_help, textwrap.dedent('''\ +- usage: {} [-h] [-w W] [-x X] [-y Y | -z Z] ++ usage: {}{}[-h] [-w W] [-x X] [-y Y | -z Z] + + optional arguments: + -h, --help show this help message and exit +@@ -2179,7 +2183,7 @@ + + -w W + -x X +- '''.format(self.main_program))) ++ '''.format(progname, ' ' if progname else '' ))) + + # ============================== + # Mutually exclusive group tests +diff -r 8527427914a2 Lib/test/test_array.py +--- a/Lib/test/test_array.py ++++ b/Lib/test/test_array.py +@@ -4,6 +4,7 @@ + """ + + import unittest ++import warnings + from test import test_support + from weakref import proxy + import array, cStringIO +@@ -783,7 +784,9 @@ + + def test_subclass_with_kwargs(self): + # SF bug #1486663 -- this used to erroneously raise a TypeError +- ArraySubclassWithKwargs('b', newarg=1) ++ with warnings.catch_warnings(): ++ warnings.filterwarnings("ignore", '', DeprecationWarning) ++ ArraySubclassWithKwargs('b', newarg=1) + + + class StringTest(BaseTest): +diff -r 8527427914a2 Lib/test/test_ast.py +--- a/Lib/test/test_ast.py ++++ b/Lib/test/test_ast.py +@@ -20,10 +20,24 @@ + # These tests are compiled through "exec" + # There should be atleast one test per statement + exec_tests = [ ++ # None ++ "None", + # FunctionDef + "def f(): pass", ++ # FunctionDef with arg ++ "def f(a): pass", ++ # FunctionDef with arg and default value ++ "def f(a=0): pass", ++ # FunctionDef with varargs ++ "def f(*args): pass", ++ # FunctionDef with kwargs ++ "def f(**kwargs): pass", ++ # FunctionDef with all kind of args ++ "def f(a, b=1, c=None, d=[], e={}, *args, **kwargs): pass", + # ClassDef + "class C:pass", ++ # ClassDef, new style class ++ "class C(object): pass", + # Return + "def f():return 1", + # Delete +@@ -68,6 +82,27 @@ + "for a,b in c: pass", + "[(a,b) for a,b in c]", + "((a,b) for a,b in c)", ++ "((a,b) for (a,b) in c)", ++ # Multiline generator expression (test for .lineno & .col_offset) ++ """( ++ ( ++ Aa ++ , ++ Bb ++ ) ++ for ++ Aa ++ , ++ Bb in Cc ++ )""", ++ # dictcomp ++ "{a : b for w in x for m in p if g}", ++ # dictcomp with naked tuple ++ "{a : b for v,w in x}", ++ # setcomp ++ "{r for l in x if g}", ++ # setcomp with naked tuple ++ "{r for l,m in x}", + ] + + # These are compiled through "single" +@@ -80,6 +115,8 @@ + # These are compiled through "eval" + # It should test all expressions + eval_tests = [ ++ # None ++ "None", + # BoolOp + "a and b", + # BinOp +@@ -90,6 +127,16 @@ + "lambda:None", + # Dict + "{ 1:2 }", ++ # Empty dict ++ "{}", ++ # Set ++ "{None,}", ++ # Multiline dict (test for .lineno & .col_offset) ++ """{ ++ 1 ++ : ++ 2 ++ }""", + # ListComp + "[a for b in c if d]", + # GeneratorExp +@@ -114,8 +161,14 @@ + "v", + # List + "[1,2,3]", ++ # Empty list ++ "[]", + # Tuple + "1,2,3", ++ # Tuple ++ "(1,2,3)", ++ # Empty tuple ++ "()", + # Combination + "a.b.c.d(a.b[1:2])", + +@@ -141,6 +194,23 @@ + elif value is not None: + self._assertTrueorder(value, parent_pos) + ++ def test_AST_objects(self): ++ x = ast.AST() ++ self.assertEqual(x._fields, ()) ++ ++ with self.assertRaises(AttributeError): ++ x.vararg ++ ++ with self.assertRaises(AttributeError): ++ x.foobar = 21 ++ ++ with self.assertRaises(AttributeError): ++ ast.AST(lineno=2) ++ ++ with self.assertRaises(TypeError): ++ # "_ast.AST constructor takes 0 positional arguments" ++ ast.AST(2) ++ + def test_snippets(self): + for input, output, kind in ((exec_tests, exec_results, "exec"), + (single_tests, single_results, "single"), +@@ -169,7 +239,83 @@ + self.assertTrue(issubclass(ast.comprehension, ast.AST)) + self.assertTrue(issubclass(ast.Gt, ast.AST)) + ++ def test_field_attr_existence(self): ++ for name, item in ast.__dict__.iteritems(): ++ if isinstance(item, type) and name != 'AST' and name[0].isupper(): ++ x = item() ++ if isinstance(x, ast.AST): ++ self.assertEqual(type(x._fields), tuple) ++ ++ def test_arguments(self): ++ x = ast.arguments() ++ self.assertEqual(x._fields, ('args', 'vararg', 'kwarg', 'defaults')) ++ ++ with self.assertRaises(AttributeError): ++ x.vararg ++ ++ x = ast.arguments(1, 2, 3, 4) ++ self.assertEqual(x.vararg, 2) ++ ++ def test_field_attr_writable(self): ++ x = ast.Num() ++ # We can assign to _fields ++ x._fields = 666 ++ self.assertEqual(x._fields, 666) ++ ++ def test_classattrs(self): ++ x = ast.Num() ++ self.assertEqual(x._fields, ('n',)) ++ ++ with self.assertRaises(AttributeError): ++ x.n ++ ++ x = ast.Num(42) ++ self.assertEqual(x.n, 42) ++ ++ with self.assertRaises(AttributeError): ++ x.lineno ++ ++ with self.assertRaises(AttributeError): ++ x.foobar ++ ++ x = ast.Num(lineno=2) ++ self.assertEqual(x.lineno, 2) ++ ++ x = ast.Num(42, lineno=0) ++ self.assertEqual(x.lineno, 0) ++ self.assertEqual(x._fields, ('n',)) ++ self.assertEqual(x.n, 42) ++ ++ self.assertRaises(TypeError, ast.Num, 1, 2) ++ self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0) ++ ++ def test_module(self): ++ body = [ast.Num(42)] ++ x = ast.Module(body) ++ self.assertEqual(x.body, body) ++ + def test_nodeclasses(self): ++ # Zero arguments constructor explicitely allowed ++ x = ast.BinOp() ++ self.assertEqual(x._fields, ('left', 'op', 'right')) ++ ++ # Random attribute allowed too ++ x.foobarbaz = 5 ++ self.assertEqual(x.foobarbaz, 5) ++ ++ n1 = ast.Num(1) ++ n3 = ast.Num(3) ++ addop = ast.Add() ++ x = ast.BinOp(n1, addop, n3) ++ self.assertEqual(x.left, n1) ++ self.assertEqual(x.op, addop) ++ self.assertEqual(x.right, n3) ++ ++ x = ast.BinOp(1, 2, 3) ++ self.assertEqual(x.left, 1) ++ self.assertEqual(x.op, 2) ++ self.assertEqual(x.right, 3) ++ + x = ast.BinOp(1, 2, 3, lineno=0) + self.assertEqual(x.left, 1) + self.assertEqual(x.op, 2) +@@ -178,6 +324,12 @@ + + # node raises exception when not given enough arguments + self.assertRaises(TypeError, ast.BinOp, 1, 2) ++ # node raises exception when given too many arguments ++ self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4) ++ # node raises exception when not given enough arguments ++ self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0) ++ # node raises exception when given too many arguments ++ self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0) + + # can set attributes through kwargs too + x = ast.BinOp(left=1, op=2, right=3, lineno=0) +@@ -186,8 +338,14 @@ + self.assertEqual(x.right, 3) + self.assertEqual(x.lineno, 0) + ++ # Random kwargs also allowed ++ x = ast.BinOp(1, 2, 3, foobarbaz=42) ++ self.assertEqual(x.foobarbaz, 42) ++ ++ def test_no_fields(self): + # this used to fail because Sub._fields was None + x = ast.Sub() ++ self.assertEqual(x._fields, ()) + + def test_pickling(self): + import pickle +@@ -204,6 +362,20 @@ + ast2 = mod.loads(mod.dumps(ast, protocol)) + self.assertEqual(to_tuple(ast2), to_tuple(ast)) + ++ def test_invalid_identitifer(self): ++ m = ast.Module([ast.Expr(ast.Name(u"x", ast.Load()))]) ++ ast.fix_missing_locations(m) ++ with self.assertRaises(TypeError) as cm: ++ compile(m, "", "exec") ++ self.assertIn("identifier must be of type str", str(cm.exception)) ++ ++ def test_invalid_string(self): ++ m = ast.Module([ast.Expr(ast.Str(43))]) ++ ast.fix_missing_locations(m) ++ with self.assertRaises(TypeError) as cm: ++ compile(m, "", "exec") ++ self.assertIn("string must be of type str or uni", str(cm.exception)) ++ + + class ASTHelpers_Test(unittest.TestCase): + +@@ -330,8 +502,15 @@ + + #### EVERYTHING BELOW IS GENERATED ##### + exec_results = [ ++('Module', [('Expr', (1, 0), ('Name', (1, 0), 'None', ('Load',)))]), + ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Pass', (1, 9))], [])]), ++('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('Name', (1, 6), 'a', ('Param',))], None, None, []), [('Pass', (1, 10))], [])]), ++('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('Name', (1, 6), 'a', ('Param',))], None, None, [('Num', (1, 8), 0)]), [('Pass', (1, 12))], [])]), ++('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], 'args', None, []), [('Pass', (1, 14))], [])]), ++('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, 'kwargs', []), [('Pass', (1, 17))], [])]), ++('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('Name', (1, 6), 'a', ('Param',)), ('Name', (1, 9), 'b', ('Param',)), ('Name', (1, 14), 'c', ('Param',)), ('Name', (1, 22), 'd', ('Param',)), ('Name', (1, 28), 'e', ('Param',))], 'args', 'kwargs', [('Num', (1, 11), 1), ('Name', (1, 16), 'None', ('Load',)), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])]), [('Pass', (1, 52))], [])]), + ('Module', [('ClassDef', (1, 0), 'C', [], [('Pass', (1, 8))], [])]), ++('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [('Pass', (1, 17))], [])]), + ('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, []), [('Return', (1, 8), ('Num', (1, 15), 1))], [])]), + ('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]), + ('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]), +@@ -355,16 +534,26 @@ + ('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [])]), + ('Module', [('Expr', (1, 0), ('ListComp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]), + ('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]), ++('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 12), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [])]))]), ++('Module', [('Expr', (1, 0), ('GeneratorExp', (2, 4), ('Tuple', (3, 4), [('Name', (3, 4), 'Aa', ('Load',)), ('Name', (5, 7), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4), [('Name', (8, 4), 'Aa', ('Store',)), ('Name', (10, 4), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10), 'Cc', ('Load',)), [])]))]), ++('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Name', (1, 11), 'w', ('Store',)), ('Name', (1, 16), 'x', ('Load',)), []), ('comprehension', ('Name', (1, 22), 'm', ('Store',)), ('Name', (1, 27), 'p', ('Load',)), [('Name', (1, 32), 'g', ('Load',))])]))]), ++('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'v', ('Store',)), ('Name', (1, 13), 'w', ('Store',))], ('Store',)), ('Name', (1, 18), 'x', ('Load',)), [])]))]), ++('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 12), 'x', ('Load',)), [('Name', (1, 17), 'g', ('Load',))])]))]), ++('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7), [('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 9), 'm', ('Store',))], ('Store',)), ('Name', (1, 14), 'x', ('Load',)), [])]))]), + ] + single_results = [ + ('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]), + ] + eval_results = [ ++('Expression', ('Name', (1, 0), 'None', ('Load',))), + ('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])), + ('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))), + ('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))), + ('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, []), ('Name', (1, 7), 'None', ('Load',)))), + ('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])), ++('Expression', ('Dict', (1, 0), [], [])), ++('Expression', ('Set', (1, 0), [('Name', (1, 1), 'None', ('Load',))])), ++('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])), + ('Expression', ('ListComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])), + ('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])), + ('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])), +@@ -376,7 +565,10 @@ + ('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))), + ('Expression', ('Name', (1, 0), 'v', ('Load',))), + ('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))), ++('Expression', ('List', (1, 0), [], ('Load',))), + ('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))), ++('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))), ++('Expression', ('Tuple', (1, 0), [], ('Load',))), + ('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)), + ] + main() +diff -r 8527427914a2 Lib/test/test_audioop.py +--- a/Lib/test/test_audioop.py ++++ b/Lib/test/test_audioop.py +@@ -2,18 +2,19 @@ + import unittest + from test.test_support import run_unittest + ++endian = 'big' if audioop.getsample('\0\1', 2, 0) == 1 else 'little' + + def gendata1(): + return '\0\1\2' + + def gendata2(): +- if audioop.getsample('\0\1', 2, 0) == 1: ++ if endian == 'big': + return '\0\0\0\1\0\2' + else: + return '\0\0\1\0\2\0' + + def gendata4(): +- if audioop.getsample('\0\0\0\1', 4, 0) == 1: ++ if endian == 'big': + return '\0\0\0\0\0\0\0\1\0\0\0\2' + else: + return '\0\0\0\0\1\0\0\0\2\0\0\0' +@@ -21,9 +22,9 @@ + data = [gendata1(), gendata2(), gendata4()] + + INVALID_DATA = [ +- ('abc', 0), +- ('abc', 2), +- ('abc', 4), ++ (b'abc', 0), ++ (b'abc', 2), ++ (b'abc', 4), + ] + + +@@ -94,7 +95,9 @@ + + def test_adpcm2lin(self): + # Very cursory test +- self.assertEqual(audioop.adpcm2lin('\0\0', 1, None), ('\0\0\0\0', (0,0))) ++ self.assertEqual(audioop.adpcm2lin(b'\0\0', 1, None), (b'\0' * 4, (0,0))) ++ self.assertEqual(audioop.adpcm2lin(b'\0\0', 2, None), (b'\0' * 8, (0,0))) ++ self.assertEqual(audioop.adpcm2lin(b'\0\0', 4, None), (b'\0' * 16, (0,0))) + + def test_lin2adpcm(self): + # Very cursory test +@@ -109,6 +112,16 @@ + # Cursory + d = audioop.lin2alaw(data[0], 1) + self.assertEqual(audioop.alaw2lin(d, 1), data[0]) ++ if endian == 'big': ++ self.assertEqual(audioop.alaw2lin(d, 2), ++ b'\x00\x08\x01\x08\x02\x10') ++ self.assertEqual(audioop.alaw2lin(d, 4), ++ b'\x00\x08\x00\x00\x01\x08\x00\x00\x02\x10\x00\x00') ++ else: ++ self.assertEqual(audioop.alaw2lin(d, 2), ++ b'\x08\x00\x08\x01\x10\x02') ++ self.assertEqual(audioop.alaw2lin(d, 4), ++ b'\x00\x00\x08\x00\x00\x00\x08\x01\x00\x00\x10\x02') + + def test_lin2ulaw(self): + self.assertEqual(audioop.lin2ulaw(data[0], 1), '\xff\xe7\xdb') +@@ -119,6 +132,16 @@ + # Cursory + d = audioop.lin2ulaw(data[0], 1) + self.assertEqual(audioop.ulaw2lin(d, 1), data[0]) ++ if endian == 'big': ++ self.assertEqual(audioop.ulaw2lin(d, 2), ++ b'\x00\x00\x01\x04\x02\x0c') ++ self.assertEqual(audioop.ulaw2lin(d, 4), ++ b'\x00\x00\x00\x00\x01\x04\x00\x00\x02\x0c\x00\x00') ++ else: ++ self.assertEqual(audioop.ulaw2lin(d, 2), ++ b'\x00\x00\x04\x01\x0c\x02') ++ self.assertEqual(audioop.ulaw2lin(d, 4), ++ b'\x00\x00\x00\x00\x00\x00\x04\x01\x00\x00\x0c\x02') + + def test_mul(self): + data2 = [] +@@ -193,10 +216,15 @@ + self.assertRaises(audioop.error, audioop.lin2lin, data, size, size2) + self.assertRaises(audioop.error, audioop.ratecv, data, size, 1, 1, 1, state) + self.assertRaises(audioop.error, audioop.lin2ulaw, data, size) ++ self.assertRaises(audioop.error, audioop.lin2alaw, data, size) ++ self.assertRaises(audioop.error, audioop.lin2adpcm, data, size, state) ++ ++ def test_wrongsize(self): ++ data = b'abc' ++ state = None ++ for size in (-1, 3, 5): + self.assertRaises(audioop.error, audioop.ulaw2lin, data, size) +- self.assertRaises(audioop.error, audioop.lin2alaw, data, size) + self.assertRaises(audioop.error, audioop.alaw2lin, data, size) +- self.assertRaises(audioop.error, audioop.lin2adpcm, data, size, state) + self.assertRaises(audioop.error, audioop.adpcm2lin, data, size, state) + + def test_main(): +diff -r 8527427914a2 Lib/test/test_bool.py +--- a/Lib/test/test_bool.py ++++ b/Lib/test/test_bool.py +@@ -180,9 +180,8 @@ + self.assertIs(hasattr([], "wobble"), False) + + def test_callable(self): +- with test_support.check_py3k_warnings(): +- self.assertIs(callable(len), True) +- self.assertIs(callable(1), False) ++ self.assertIs(callable(len), True) ++ self.assertIs(callable(1), False) + + def test_isinstance(self): + self.assertIs(isinstance(True, bool), True) +diff -r 8527427914a2 Lib/test/test_cfgparser.py +--- a/Lib/test/test_cfgparser.py ++++ b/Lib/test/test_cfgparser.py +@@ -529,6 +529,28 @@ + class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase): + allow_no_value = True + ++class TestChainMap(unittest.TestCase): ++ def test_issue_12717(self): ++ d1 = dict(red=1, green=2) ++ d2 = dict(green=3, blue=4) ++ dcomb = d2.copy() ++ dcomb.update(d1) ++ cm = ConfigParser._Chainmap(d1, d2) ++ self.assertIsInstance(cm.keys(), list) ++ self.assertEqual(set(cm.keys()), set(dcomb.keys())) # keys() ++ self.assertEqual(set(cm.values()), set(dcomb.values())) # values() ++ self.assertEqual(set(cm.items()), set(dcomb.items())) # items() ++ self.assertEqual(set(cm), set(dcomb)) # __iter__ () ++ self.assertEqual(cm, dcomb) # __eq__() ++ self.assertEqual([cm[k] for k in dcomb], dcomb.values()) # __getitem__() ++ klist = 'red green blue black brown'.split() ++ self.assertEqual([cm.get(k, 10) for k in klist], ++ [dcomb.get(k, 10) for k in klist]) # get() ++ self.assertEqual([k in cm for k in klist], ++ [k in dcomb for k in klist]) # __contains__() ++ with test_support.check_py3k_warnings(): ++ self.assertEqual([cm.has_key(k) for k in klist], ++ [dcomb.has_key(k) for k in klist]) # has_key() + + class Issue7005TestCase(unittest.TestCase): + """Test output when None is set() as a value and allow_no_value == False. +@@ -582,6 +604,122 @@ + "o4 = 1\n\n") + + ++class ExceptionPicklingTestCase(unittest.TestCase): ++ """Tests for issue #13760: ConfigParser exceptions are not picklable.""" ++ ++ def test_error(self): ++ import pickle ++ e1 = ConfigParser.Error('value') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_nosectionerror(self): ++ import pickle ++ e1 = ConfigParser.NoSectionError('section') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_nooptionerror(self): ++ import pickle ++ e1 = ConfigParser.NoOptionError('option', 'section') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(e1.option, e2.option) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_duplicatesectionerror(self): ++ import pickle ++ e1 = ConfigParser.DuplicateSectionError('section') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_interpolationerror(self): ++ import pickle ++ e1 = ConfigParser.InterpolationError('option', 'section', 'msg') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(e1.option, e2.option) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_interpolationmissingoptionerror(self): ++ import pickle ++ e1 = ConfigParser.InterpolationMissingOptionError('option', 'section', ++ 'rawval', 'reference') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(e1.option, e2.option) ++ self.assertEqual(e1.reference, e2.reference) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_interpolationsyntaxerror(self): ++ import pickle ++ e1 = ConfigParser.InterpolationSyntaxError('option', 'section', 'msg') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(e1.option, e2.option) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_interpolationdeptherror(self): ++ import pickle ++ e1 = ConfigParser.InterpolationDepthError('option', 'section', ++ 'rawval') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.section, e2.section) ++ self.assertEqual(e1.option, e2.option) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_parsingerror(self): ++ import pickle ++ e1 = ConfigParser.ParsingError('source') ++ e1.append(1, 'line1') ++ e1.append(2, 'line2') ++ e1.append(3, 'line3') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.filename, e2.filename) ++ self.assertEqual(e1.errors, e2.errors) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ def test_missingsectionheadererror(self): ++ import pickle ++ e1 = ConfigParser.MissingSectionHeaderError('filename', 123, 'line') ++ pickled = pickle.dumps(e1) ++ e2 = pickle.loads(pickled) ++ self.assertEqual(e1.message, e2.message) ++ self.assertEqual(e1.args, e2.args) ++ self.assertEqual(e1.line, e2.line) ++ self.assertEqual(e1.filename, e2.filename) ++ self.assertEqual(e1.lineno, e2.lineno) ++ self.assertEqual(repr(e1), repr(e2)) ++ ++ + def test_main(): + test_support.run_unittest( + ConfigParserTestCase, +@@ -591,6 +729,8 @@ + SafeConfigParserTestCaseNoValue, + SortedTestCase, + Issue7005TestCase, ++ TestChainMap, ++ ExceptionPicklingTestCase, + ) + + +diff -r 8527427914a2 Lib/test/test_cgi.py +--- a/Lib/test/test_cgi.py ++++ b/Lib/test/test_cgi.py +@@ -377,6 +377,9 @@ + 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'})) + + + def test_main(): +diff -r 8527427914a2 Lib/test/test_class.py +--- a/Lib/test/test_class.py ++++ b/Lib/test/test_class.py +@@ -350,6 +350,19 @@ + AllTests.__delslice__ = delslice + + ++ @test_support.cpython_only ++ def testDelItem(self): ++ class A: ++ ok = False ++ def __delitem__(self, key): ++ self.ok = True ++ a = A() ++ # Subtle: we need to call PySequence_SetItem, not PyMapping_SetItem. ++ from _testcapi import sequence_delitem ++ sequence_delitem(a, 2) ++ self.assertTrue(a.ok) ++ ++ + def testUnaryOps(self): + testme = AllTests() + +diff -r 8527427914a2 Lib/test/test_codecencodings_iso2022.py +--- /dev/null ++++ b/Lib/test/test_codecencodings_iso2022.py +@@ -0,0 +1,46 @@ ++#!/usr/bin/env python ++# ++# Codec encoding tests for ISO 2022 encodings. ++ ++from test import test_support ++from test import test_multibytecodec_support ++import unittest ++ ++COMMON_CODEC_TESTS = ( ++ # invalid bytes ++ (b'ab\xFFcd', 'replace', u'ab\uFFFDcd'), ++ (b'ab\x1Bdef', 'replace', u'ab\x1Bdef'), ++ (b'ab\x1B$def', 'replace', u'ab\uFFFD'), ++ ) ++ ++class Test_ISO2022_JP(test_multibytecodec_support.TestBase, unittest.TestCase): ++ encoding = 'iso2022_jp' ++ tstring = test_multibytecodec_support.load_teststring('iso2022_jp') ++ codectests = COMMON_CODEC_TESTS + ( ++ (b'ab\x1BNdef', 'replace', u'ab\x1BNdef'), ++ ) ++ ++class Test_ISO2022_JP2(test_multibytecodec_support.TestBase, unittest.TestCase): ++ encoding = 'iso2022_jp_2' ++ tstring = test_multibytecodec_support.load_teststring('iso2022_jp') ++ codectests = COMMON_CODEC_TESTS + ( ++ (b'ab\x1BNdef', 'replace', u'abdef'), ++ ) ++ ++class Test_ISO2022_KR(test_multibytecodec_support.TestBase, unittest.TestCase): ++ encoding = 'iso2022_kr' ++ tstring = test_multibytecodec_support.load_teststring('iso2022_kr') ++ codectests = COMMON_CODEC_TESTS + ( ++ (b'ab\x1BNdef', 'replace', u'ab\x1BNdef'), ++ ) ++ ++ # iso2022_kr.txt cannot be used to test "chunk coding": the escape ++ # sequence is only written on the first line ++ def test_chunkcoding(self): ++ pass ++ ++def test_main(): ++ test_support.run_unittest(__name__) ++ ++if __name__ == "__main__": ++ test_main() +diff -r 8527427914a2 Lib/test/test_codecs.py +--- a/Lib/test/test_codecs.py ++++ b/Lib/test/test_codecs.py +@@ -1,6 +1,7 @@ + from test import test_support + import unittest + import codecs ++import locale + import sys, StringIO, _testcapi + + class Queue(object): +@@ -1153,6 +1154,19 @@ + self.assertRaises(TypeError, codecs.getwriter) + self.assertRaises(LookupError, codecs.getwriter, "__spam__") + ++ def test_lookup_issue1813(self): ++ # Issue #1813: under Turkish locales, lookup of some codecs failed ++ # because 'I' is lowercased as a dotless "i" ++ oldlocale = locale.getlocale(locale.LC_CTYPE) ++ self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) ++ try: ++ locale.setlocale(locale.LC_CTYPE, 'tr_TR') ++ except locale.Error: ++ # Unsupported locale on this system ++ self.skipTest('test needs Turkish locale') ++ c = codecs.lookup('ASCII') ++ self.assertEqual(c.name, 'ascii') ++ + class StreamReaderTest(unittest.TestCase): + + def setUp(self): +diff -r 8527427914a2 Lib/test/test_collections.py +--- a/Lib/test/test_collections.py ++++ b/Lib/test/test_collections.py +@@ -78,12 +78,12 @@ + self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument + self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument + self.assertEqual(repr(p), 'Point(x=11, y=22)') +- self.assertNotIn('__dict__', dir(p)) # verify instance has no dict + self.assertNotIn('__weakref__', dir(p)) + self.assertEqual(p, Point._make([11, 22])) # test _make classmethod + self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute + self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method + self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method ++ self.assertEqual(vars(p), p._asdict()) # verify that vars() works + + try: + p._replace(x=1, error=2) +diff -r 8527427914a2 Lib/test/test_csv.py +--- a/Lib/test/test_csv.py ++++ b/Lib/test/test_csv.py +@@ -207,6 +207,18 @@ + fileobj.close() + os.unlink(name) + ++ def test_write_float(self): ++ # Issue 13573: loss of precision because csv.writer ++ # uses str() for floats instead of repr() ++ orig_row = [1.234567890123, 1.0/7.0, 'abc'] ++ f = StringIO() ++ c = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC) ++ c.writerow(orig_row) ++ f.seek(0) ++ c = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) ++ new_row = next(c) ++ self.assertEqual(orig_row, new_row) ++ + def _read_test(self, input, expect, **kwargs): + reader = csv.reader(input, **kwargs) + result = list(reader) +@@ -784,7 +796,7 @@ + try: + writer = csv.writer(fileobj, dialect="excel") + writer.writerow(a) +- expected = ",".join([str(i) for i in a])+"\r\n" ++ expected = ",".join([repr(i) for i in a])+"\r\n" + fileobj.seek(0) + self.assertEqual(fileobj.read(), expected) + finally: +@@ -800,7 +812,7 @@ + try: + writer = csv.writer(fileobj, dialect="excel") + writer.writerow(a) +- expected = ",".join([str(i) for i in a])+"\r\n" ++ expected = ",".join([repr(i) for i in a])+"\r\n" + fileobj.seek(0) + self.assertEqual(fileobj.read(), expected) + finally: +diff -r 8527427914a2 Lib/test/test_defaultdict.py +--- a/Lib/test/test_defaultdict.py ++++ b/Lib/test/test_defaultdict.py +@@ -171,6 +171,8 @@ + finally: + os.remove(tfn) + ++ def test_callable_arg(self): ++ self.assertRaises(TypeError, defaultdict, {}) + + def test_main(): + test_support.run_unittest(TestDefaultDict) +diff -r 8527427914a2 Lib/test/test_descr.py +--- a/Lib/test/test_descr.py ++++ b/Lib/test/test_descr.py +@@ -4581,6 +4581,14 @@ + with self.assertRaises(TypeError): + str.__add__(fake_str, "abc") + ++ def test_repr_as_str(self): ++ # Issue #11603: crash or infinite loop when rebinding __str__ as ++ # __repr__. ++ class Foo(object): ++ pass ++ Foo.__repr__ = Foo.__str__ ++ foo = Foo() ++ str(foo) + + class DictProxyTests(unittest.TestCase): + def setUp(self): +@@ -4589,6 +4597,10 @@ + pass + self.C = C + ++ def test_repr(self): ++ self.assertIn('dict_proxy({', repr(vars(self.C))) ++ self.assertIn("'meth':", repr(vars(self.C))) ++ + def test_iter_keys(self): + # Testing dict-proxy iterkeys... + keys = [ key for key in self.C.__dict__.iterkeys() ] +diff -r 8527427914a2 Lib/test/test_dis.py +--- a/Lib/test/test_dis.py ++++ b/Lib/test/test_dis.py +@@ -54,7 +54,7 @@ + + dis_bug1333982 = """\ + %-4d 0 LOAD_CONST 1 (0) +- 3 POP_JUMP_IF_TRUE 38 ++ 3 POP_JUMP_IF_TRUE 41 + 6 LOAD_GLOBAL 0 (AssertionError) + 9 BUILD_LIST 0 + 12 LOAD_FAST 0 (x) +@@ -67,10 +67,11 @@ + + %-4d >> 31 LOAD_CONST 2 (1) + 34 BINARY_ADD +- 35 RAISE_VARARGS 2 ++ 35 CALL_FUNCTION 1 ++ 38 RAISE_VARARGS 1 + +- %-4d >> 38 LOAD_CONST 0 (None) +- 41 RETURN_VALUE ++ %-4d >> 41 LOAD_CONST 0 (None) ++ 44 RETURN_VALUE + """%(bug1333982.func_code.co_firstlineno + 1, + bug1333982.func_code.co_firstlineno + 2, + bug1333982.func_code.co_firstlineno + 3) +diff -r 8527427914a2 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 8527427914a2 Lib/test/test_epoll.py +--- a/Lib/test/test_epoll.py ++++ b/Lib/test/test_epoll.py +@@ -36,6 +36,7 @@ + except IOError, e: + if e.errno == errno.ENOSYS: + raise unittest.SkipTest("kernel doesn't support epoll()") ++ raise + + class TestEPoll(unittest.TestCase): + +diff -r 8527427914a2 Lib/test/test_exceptions.py +--- a/Lib/test/test_exceptions.py ++++ b/Lib/test/test_exceptions.py +@@ -464,6 +464,20 @@ + self.assertTrue(e is RuntimeError, e) + self.assertIn("maximum recursion depth exceeded", str(v)) + ++ def test_new_returns_invalid_instance(self): ++ # See issue #11627. ++ class MyException(Exception): ++ def __new__(cls, *args): ++ return object() ++ ++ with self.assertRaises(TypeError): ++ raise MyException ++ ++ def test_assert_with_tuple_arg(self): ++ try: ++ assert False, (3,) ++ except AssertionError as e: ++ self.assertEqual(str(e), "(3,)") + + + # Helper class used by TestSameStrAndUnicodeMsg +diff -r 8527427914a2 Lib/test/test_fcntl.py +--- a/Lib/test/test_fcntl.py ++++ b/Lib/test/test_fcntl.py +@@ -27,12 +27,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 8527427914a2 Lib/test/test_float.py +--- a/Lib/test/test_float.py ++++ b/Lib/test/test_float.py +@@ -164,6 +164,12 @@ + self.assertAlmostEqual(float(FooUnicode('8')), 9.) + 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 8527427914a2 Lib/test/test_ftplib.py +--- a/Lib/test/test_ftplib.py ++++ b/Lib/test/test_ftplib.py +@@ -667,7 +667,7 @@ + def setUp(self): + self.evt = threading.Event() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +- self.sock.settimeout(3) ++ self.sock.settimeout(10) + self.port = test_support.bind_port(self.sock) + threading.Thread(target=self.server, args=(self.evt,self.sock)).start() + # Wait for the server to be ready. +diff -r 8527427914a2 Lib/test/test_gdb.py +--- a/Lib/test/test_gdb.py ++++ b/Lib/test/test_gdb.py +@@ -32,6 +32,14 @@ + if gdbpy_version == '': + raise unittest.SkipTest("gdb not built with embedded python support") + ++def python_is_optimized(): ++ cflags = sysconfig.get_config_vars()['PY_CFLAGS'] ++ final_opt = "" ++ for opt in cflags.split(): ++ if opt.startswith('-O'): ++ final_opt = opt ++ return (final_opt and final_opt != '-O0') ++ + def gdb_has_frame_select(): + # Does this build of gdb have gdb.Frame.select ? + cmd = "--eval-command=python print(dir(gdb.Frame))" +@@ -543,6 +551,8 @@ + re.DOTALL), + 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output)) + ++@unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + class PyListTests(DebuggerTests): + def assertListing(self, expected, actual): + self.assertEndsWith(actual, expected) +@@ -585,6 +595,8 @@ + + class StackNavigationTests(DebuggerTests): + @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_pyup_command(self): + 'Verify that the "py-up" command works' + bt = self.get_stack_trace(script=self.get_sample_script(), +@@ -612,6 +624,8 @@ + 'Unable to find an older python frame\n') + + @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_up_then_down(self): + 'Verify "py-up" followed by "py-down"' + bt = self.get_stack_trace(script=self.get_sample_script(), +@@ -625,6 +639,8 @@ + $''') + + class PyBtTests(DebuggerTests): ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_basic_command(self): + 'Verify that the "py-bt" command works' + bt = self.get_stack_trace(script=self.get_sample_script(), +@@ -636,10 +652,12 @@ + #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\) + bar\(a, b, c\) + #[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in \(\) +-foo\(1, 2, 3\) ++ foo\(1, 2, 3\) + ''') + + class PyPrintTests(DebuggerTests): ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_basic_command(self): + 'Verify that the "py-print" command works' + bt = self.get_stack_trace(script=self.get_sample_script(), +@@ -648,18 +666,24 @@ + r".*\nlocal 'args' = \(1, 2, 3\)\n.*") + + @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_print_after_up(self): + bt = self.get_stack_trace(script=self.get_sample_script(), + cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a']) + self.assertMultilineMatches(bt, + r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*") + ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_printing_global(self): + bt = self.get_stack_trace(script=self.get_sample_script(), + cmds_after_breakpoint=['py-print __name__']) + self.assertMultilineMatches(bt, + r".*\nglobal '__name__' = '__main__'\n.*") + ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_printing_builtin(self): + bt = self.get_stack_trace(script=self.get_sample_script(), + cmds_after_breakpoint=['py-print len']) +@@ -667,6 +691,8 @@ + r".*\nbuiltin 'len' = \n.*") + + class PyLocalsTests(DebuggerTests): ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_basic_command(self): + bt = self.get_stack_trace(script=self.get_sample_script(), + cmds_after_breakpoint=['py-locals']) +@@ -674,6 +700,8 @@ + r".*\nargs = \(1, 2, 3\)\n.*") + + @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") ++ @unittest.skipIf(python_is_optimized(), ++ "Python was compiled with optimizations") + def test_locals_after_up(self): + bt = self.get_stack_trace(script=self.get_sample_script(), + cmds_after_breakpoint=['py-up', 'py-locals']) +@@ -681,15 +709,6 @@ + r".*\na = 1\nb = 2\nc = 3\n.*") + + def test_main(): +- cflags = sysconfig.get_config_vars()['PY_CFLAGS'] +- final_opt = "" +- for opt in cflags.split(): +- if opt.startswith('-O'): +- final_opt = opt +- if final_opt and final_opt != '-O0': +- raise unittest.SkipTest("Python was built with compiler optimizations, " +- "tests can't reliably succeed") +- + run_unittest(PrettyPrintTests, + PyListTests, + StackNavigationTests, +diff -r 8527427914a2 Lib/test/test_grammar.py +--- a/Lib/test/test_grammar.py ++++ b/Lib/test/test_grammar.py +@@ -551,13 +551,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, 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 8527427914a2 Lib/test/test_gzip.py +--- a/Lib/test/test_gzip.py ++++ b/Lib/test/test_gzip.py +@@ -274,6 +274,14 @@ + d = f.read() + self.assertEqual(d, data1 * 50, "Incorrect data in file") + ++ def test_fileobj_from_fdopen(self): ++ # Issue #13781: Creating a GzipFile using a fileobj from os.fdopen() ++ # should not embed the fake filename "" in the output file. ++ fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT) ++ with os.fdopen(fd, "wb") as f: ++ with gzip.GzipFile(fileobj=f, mode="w") as g: ++ self.assertEqual(g.name, "") ++ + def test_main(verbose=None): + test_support.run_unittest(TestGzip) + +diff -r 8527427914a2 Lib/test/test_htmlparser.py +--- a/Lib/test/test_htmlparser.py ++++ b/Lib/test/test_htmlparser.py +@@ -114,7 +114,7 @@ + sample + text + “ +- ++ + + """, [ + ("data", "\n"), +@@ -142,24 +142,6 @@ + ("data", " foo"), + ]) + +- def test_doctype_decl(self): +- inside = """\ +-DOCTYPE html [ +- +- +- +- +- +- +- %paramEntity; +- +-]""" +- self._run_check("" % inside, [ +- ("decl", inside), +- ]) +- + def test_bad_nesting(self): + # Strangely, this *is* supposed to test that overlapping + # elements are allowed. HTMLParser is more geared toward +@@ -181,62 +163,9 @@ + ("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(u"\u4e2d\u6587", [ +- ("starttag", "img", [("src", "/foo/bar.png"), +- ("alt", u"\u4e2d\u6587")]), +- ]) +- self._run_check(u"", [ +- ("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"), +- ("href", u"\u30c6\u30b9\u30c8.html")]), +- ]) +- self._run_check(u'', [ +- ("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"), +- ("href", u"\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('') ++ self._run_check('', ++ [('comment', 'spacer type="block" height="25"')]) + + def test_starttag_end_boundary(self): + self._run_check("""""", [("starttag", "a", [("b", "<")])]) +@@ -273,23 +202,46 @@ + self._run_check(["", ""], output) + + def test_starttag_junk_chars(self): +- self._parse_error("") +- self._parse_error("") +- self._parse_error("") +- self._parse_error("") +- self._parse_error("") +- self._parse_error("'") +- self._parse_error("", [('data', '", [('endtag', 'a'", [('data', "" % dtd, ++ [('decl', 'DOCTYPE ' + dtd)]) + + def test_declaration_junk_chars(self): +- self._parse_error("") ++ self._run_check("", [('decl', 'DOCTYPE foo $ ')]) + + def test_startendtag(self): + self._run_check("

", [ +@@ -305,6 +257,44 @@ + ("endtag", "p"), + ]) + ++ def test_invalid_end_tags(self): ++ # A collection of broken end tags.
is used as separator. ++ # see http://www.w3.org/TR/html5/tokenization.html#end-tag-open-state ++ # and #13993 ++ html = ('



' ++ '


') ++ expected = [('starttag', 'br', []), ++ # < is part of the name, / is discarded, p is an attribute ++ ('endtag', 'label<'), ++ ('starttag', 'br', []), ++ # text and attributes are discarded ++ ('endtag', 'div'), ++ ('starttag', 'br', []), ++ # comment because the first char after is ignored ++ ('starttag', 'br', [])] ++ self._run_check(html, expected) ++ ++ def test_broken_invalid_end_tag(self): ++ # This is technically wrong (the "> shouldn't be included in the 'data') ++ # but is probably not worth fixing it (in addition to all the cases of ++ # the previous test, it would require a full attribute parsing). ++ # see #13993 ++ html = 'This confuses the parser' ++ expected = [('starttag', 'b', []), ++ ('data', 'This'), ++ ('endtag', 'b'), ++ ('data', '"> confuses the parser')] ++ self._run_check(html, expected) ++ + def test_get_starttag_text(self): + s = """""" + self._run_check_extra(s, [ +@@ -312,23 +302,56 @@ + ("starttag_text", s)]) + + def test_cdata_content(self): +- s = """""" +- self._run_check(s, [ +- ("starttag", "script", []), +- ("data", " ¬-an-entity-ref; "), +- ("endtag", "script"), +- ]) +- s = """""" +- 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 = "";', ++ u'', ++ # 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 = u'<{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", u"\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']: ++ s = u'`` 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 #7334: close source files on ElementTree.parse and iterparse. ++ ++- Issue #13232: logging: Improved logging of exceptions in the presence of ++ multiple encodings. ++ ++- Issue #10332: multiprocessing: fix a race condition when a Pool is closed ++ before all tasks have completed. ++ ++- Issue #1548891: The cStringIO.StringIO() constructor now encodes unicode ++ arguments with the system default encoding just like the write() method ++ does, instead of converting it to a raw buffer. This also fixes handling of ++ unicode input in the shlex module (#6988, #1170). ++ ++- 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 #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 #13114: Fix the distutils commands check and register when the ++ long description is a Unicode string with non-ASCII characters. ++ ++- Issue #7367: Fix pkgutil.walk_paths to skip directories whose ++ contents cannot be read. ++ ++- Issue #7425: Prevent pydoc -k failures due to module import errors. ++ (Backport to 2.7 of existing 3.x fix) ++ ++- Issue #13099: Fix sqlite3.Cursor.lastrowid under a Turkish locale. ++ Reported and diagnosed by Thomas Kluyver. ++ ++- Issue #7689: Allow pickling of dynamically created classes when their ++ metaclass is registered with copy_reg. Patch by Nicolas M. Thiéry and ++ Craig Citro. ++ ++- Issue #13058: ossaudiodev: fix a file descriptor leak on error. Patch by ++ Thomas Jarosch. ++ ++- Issue #12931: xmlrpclib now encodes Unicode URI to ISO-8859-1, instead of ++ failing with a UnicodeDecodeError. ++ ++- 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 #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. ++ ++- Issue #12287: Fix a stack corruption in ossaudiodev module when the FD is ++ greater than FD_SETSIZE. ++ ++- Issue #12839: Fix crash in zlib module due to version mismatch. ++ Fix by Richard M. Tew. ++ ++- Issue #12786: Set communication pipes used by subprocess.Popen CLOEXEC to ++ avoid them being inherited by other subprocesses. ++ ++- Issue #4106: Fix occasional exceptions printed out by multiprocessing on ++ interpreter shutdown. ++ ++- Issue #11657: Fix sending file descriptors over 255 over a multiprocessing ++ Pipe. ++ ++- Issue #12213: Fix a buffering bug with interleaved reads and writes that ++ could appear on io.BufferedRandom streams. ++ ++- Issue #12326: sys.platform is now always 'linux2' on Linux, even if Python ++ is compiled on Linux 3. ++ ++- Issue #13007: whichdb should recognize gdbm 1.9 magic numbers. ++ ++- Issue #9173: Let shutil._make_archive work if the logger argument is None. ++ ++- Issue #12650: Fix a race condition where a subprocess.Popen could leak ++ resources (FD/zombie) when killed at the wrong time. ++ ++- Issue #12752: Fix regression which prevented locale.normalize() from ++ accepting unicode strings. ++ ++- Issue #12683: urlparse updated to include svn as schemes that uses relative ++ paths. (svn from 1.5 onwards support relative path). ++ ++- Issue #11933: Fix incorrect mtime comparison in distutils. ++ ++- Issues #11104, #8688: Fix the behavior of distutils' sdist command with ++ manually-maintained MANIFEST files. ++ ++- Issue #8887: "pydoc somebuiltin.somemethod" (or help('somebuiltin.somemethod') ++ in Python code) now finds the doc of the method. ++ ++- Issue #12603: Fix pydoc.synopsis() on files with non-negative st_mtime. ++ ++- Issue #12514: Use try/finally to assure the timeit module restores garbage ++ collections when it is done. ++ ++- Issue #12607: In subprocess, fix issue where if stdin, stdout or stderr is ++ given as a low fd, it gets overwritten. ++ ++- Issue #12102: Document that buffered files must be flushed before being used ++ with mmap. Patch by Steffen Daode Nurpmeso. ++ ++- Issue #12560: Build libpython.so on OpenBSD. Patch by Stefan Sperling. ++ ++- Issue #1813: Fix codec lookup and setting/getting locales under Turkish ++ locales. ++ ++- Issue #10883: Fix socket leaks in urllib when using FTP. ++ ++- Issue #12592: Make Python build on OpenBSD 5 (and future major releases). ++ ++- Issue #12372: POSIX semaphores are broken on AIX: don't use them. ++ ++- Issue #12571: Add a plat-linux3 directory mirroring the plat-linux2 ++ directory, so that "import DLFCN" and other similar imports work on ++ Linux 3.0. ++ ++- Issue #7484: smtplib no longer puts <> around addresses in VRFY and EXPN ++ commands; they aren't required and in fact postfix doesn't support that form. ++ ++- Issue #11603: Fix a crash when __str__ is rebound as __repr__. Patch by ++ Andreas Stührk. ++ ++- Issue #12502: asyncore: fix polling loop with AF_UNIX sockets. ++ ++- Issue #4376: ctypes now supports nested structures in a endian different than ++ the parent structure. Patch by Vlad Riscutia. ++ ++- Issue #12493: subprocess: Popen.communicate() now also handles EINTR errors ++ if the process has only one pipe. ++ ++- Issue #12467: warnings: fix a race condition if a warning is emitted at ++ shutdown, if globals()['__file__'] is None. ++ ++- Issue #12352: Fix a deadlock in multiprocessing.Heap when a block is freed by ++ the garbage collector while the Heap lock is held. ++ ++- Issue #9516: On Mac OS X, change Distutils to no longer globally attempt to ++ check or set the MACOSX_DEPLOYMENT_TARGET environment variable for the ++ interpreter process. This could cause failures in non-Distutils subprocesses ++ and was unreliable since tests or user programs could modify the interpreter ++ environment after Distutils set it. Instead, have Distutils set the the ++ deployment target only in the environment of each build subprocess. It is ++ still possible to globally override the default by setting ++ MACOSX_DEPLOYMENT_TARGET before launching the interpreter; its value must be ++ greater or equal to the default value, the value with which the interpreter ++ was built. ++ ++- Issue #11802: The cache in filecmp now has a maximum size of 100 so that ++ it won't grow without bound. ++ ++- Issue #12404: Remove C89 incompatible code from mmap module. Patch by Akira ++ Kitada. ++ ++- Issue #11700: mailbox proxy object close methods can now be called multiple ++ times without error, and _ProxyFile now closes the wrapped file. ++ ++- Issue #12133: AbstractHTTPHandler.do_open() of urllib.request closes the HTTP ++ connection if its getresponse() method fails with a socket error. Patch ++ written by Ezio Melotti. ++ ++- Issue #9284: Allow inspect.findsource() to find the source of doctest ++ functions. ++ ++- Issue #10694: zipfile now ignores garbage at the end of a zipfile. ++ ++- Issue #11583: Speed up os.path.isdir on Windows by using GetFileAttributes ++ instead of os.stat. ++ ++- Issue #12080: Fix a performance issue in Decimal._power_exact that caused ++ some corner-case Decimal.__pow__ calls to take an unreasonably long time. ++ ++- Named tuples now work correctly with vars(). ++ ++- sys.setcheckinterval() now updates the current ticker count as well as ++ updating the check interval, so if the user decreases the check interval, ++ the ticker doesn't have to wind down to zero from the old starting point ++ before the new interval takes effect. And if the user increases the ++ interval, it makes sure the new limit takes effect right away rather have an ++ early task switch before recognizing the new interval. ++ ++- Issue #12085: Fix an attribute error in subprocess.Popen destructor if the ++ constructor has failed, e.g. because of an undeclared keyword argument. Patch ++ written by Oleg Oshmyan. ++ ++Extension Modules ++----------------- ++ ++- bsddb module: Erratic behaviour of "DBEnv->rep_elect()" because a typo. ++ Possible crash. ++ ++- Issue #13774: json: Fix a SystemError when a bogus encoding is passed to ++ json.loads(). ++ ++- Issue #9975: socket: Fix incorrect use of flowinfo and scope_id. Patch by ++ Vilmos Nebehaj. ++ ++- Issue #13159: FileIO, BZ2File, and the built-in file class now use a ++ linear-time buffer growth strategy instead of a quadratic 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 #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. ++ ++- Issue #12764: Fix a crash in ctypes when the name of a Structure field is not ++ a string. ++ ++- Issue #9651: Fix a crash when ctypes.create_string_buffer(0) was passed to ++ some functions like file.write(). ++ ++- 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. ++ ++Build ++----- ++ ++- Issue #8746: Correct faulty configure checks so that os.chflags() and ++ os.lchflags() are once again built on systems that support these ++ functions (*BSD and OS X). Also add new stat file flags for OS X ++ (UF_HIDDEN and UF_COMPRESSED). ++ ++Tools/Demos ++----------- ++ ++- Issue #13930: 2to3 is now able to write its converted output files to another ++ directory tree as well as copying unchanged files and altering the file ++ suffix. See its new -o, -W and --add-suffix options. This makes it more ++ useful in many automated code translation workflows. ++ ++- Issue #10639: reindent.py no longer converts newlines and will raise ++ an error if attempting to convert a file with mixed newlines. ++ ++- Issue #13628: python-gdb.py is now able to retrieve more frames in the Python ++ traceback if Python is optimized. ++ ++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. ++ ++- Issue #12331: The test suite for lib2to3 can now run from an installed ++ Python. ++ ++- Issue #12549: Correct test_platform to not fail when OS X returns 'x86_64' ++ as the processor type on some Mac systems. ++ ++- 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_robotparser when mueblesmoraleda.com is flaky and ++ an overzealous DNS service (e.g. OpenDNS) redirects to a placeholder ++ Web site. ++ ++- 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. ++ ++- Issue #8716: Avoid crashes caused by Aqua Tk on OSX when attempting to run ++ test_tk or test_ttk_guionly under a username that is not currently logged ++ in to the console windowserver (as may be the case under buildbot or ssh). ++ ++- Issue #12141: Install a copy of template C module file so that ++ test_build_ext of test_distutils is no longer silently skipped when ++ run outside of a build directory. ++ ++- Issue #8746: Add additional tests for os.chflags() and os.lchflags(). ++ Patch by Garrett Cooper. ++ ++- Issue #10736: Fix test_ttk test_widgets failures with Cocoa Tk 8.5.9 ++ on Mac OS X. (Patch by Ronald Oussoren) ++ ++- Issue #12057: Add tests for ISO 2022 codecs (iso2022_jp, iso2022_jp_2, ++ iso2022_kr). ++ ++Documentation ++------------- ++ ++- Issue #13402: Document absoluteness of sys.executable. ++ ++- Issue #13883: PYTHONCASEOK also works on OS X, OS/2, and RiscOS. ++ ++- Issue #2134: The tokenize documentation has been clarified to explain why ++ all operator and delimiter tokens are treated as token.OP tokens. ++ ++- 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 2.7.2? + =========================== +@@ -106,6 +695,9 @@ + Library + ------- + ++- Issue #12590: IDLE editor window now always displays the first line ++ when opening a long file. With Tk 8.5, the first line was hidden. ++ + - Issue #12161: Cause StringIO.getvalue() to raise a ValueError when used on a + closed StringIO instance. + +diff -r 8527427914a2 Misc/build.sh +--- a/Misc/build.sh ++++ /dev/null +@@ -1,279 +0,0 @@ +-#!/bin/sh +- +-## Script to build and test the latest python from svn. It basically +-## does this: +-## svn up ; ./configure ; make ; make test ; make install ; cd Doc ; make +-## +-## Logs are kept and rsync'ed to the webhost. If there are test failure(s), +-## information about the failure(s) is mailed. +-## +-## The user must be a member of the webmaster group locally and on webhost. +-## +-## This script is run on the PSF's machine as user neal via crontab. +-## +-## Yes, this script would probably be easier in python, but then +-## there's a bootstrap problem. What if Python doesn't build? +-## +-## This script should be fairly clean Bourne shell, ie not too many +-## bash-isms. We should try to keep it portable to other Unixes. +-## Even though it will probably only run on Linux. I'm sure there are +-## several GNU-isms currently (date +%s and readlink). +-## +-## Perhaps this script should be broken up into 2 (or more) components. +-## Building doc is orthogonal to the rest of the python build/test. +-## +- +-## FIXME: we should detect test hangs (eg, if they take more than 45 minutes) +- +-## FIXME: we should run valgrind +-## FIXME: we should run code coverage +- +-## Utilities invoked in this script include: +-## basename, date, dirname, expr, grep, readlink, uname +-## cksum, make, mutt, rsync, svn +- +-## remember where did we started from +-DIR=`dirname $0` +-if [ "$DIR" = "" ]; then +- DIR="." +-fi +- +-## make directory absolute +-DIR=`readlink -f $DIR` +-FULLPATHNAME="$DIR/`basename $0`" +-## we want Misc/.. +-DIR=`dirname $DIR` +- +-## Configurable options +- +-FAILURE_SUBJECT="Python Regression Test Failures" +-#FAILURE_MAILTO="YOUR_ACCOUNT@gmail.com" +-FAILURE_MAILTO="python-checkins@python.org" +-#FAILURE_CC="optional--uncomment and set to desired address" +- +-REMOTE_SYSTEM="neal@dinsdale.python.org" +-REMOTE_DIR="/data/ftp.python.org/pub/docs.python.org/dev/" +-RESULT_FILE="$DIR/build/index.html" +-INSTALL_DIR="/tmp/python-test/local" +-RSYNC_OPTS="-C -e ssh -rlogD" +- +-# Always run the installed version of Python. +-PYTHON=$INSTALL_DIR/bin/python +- +-# Python options and regression test program that should always be run. +-REGRTEST_ARGS="-E -tt $INSTALL_DIR/lib/python2.7/test/regrtest.py" +- +-REFLOG="build/reflog.txt.out" +-# These tests are not stable and falsely report leaks sometimes. +-# The entire leak report will be mailed if any test not in this list leaks. +-# Note: test_XXX (none currently) really leak, but are disabled +-# so we don't send spam. Any test which really leaks should only +-# be listed here if there are also test cases under Lib/test/leakers. +-LEAKY_TESTS="test_(asynchat|cmd_line|docxmlrpc|dumbdbm|file|ftplib|httpservers|imaplib|popen2|socket|smtplib|sys|telnetlib|threadedtempfile|threading|threadsignals|xmlrpc)" +- +-# Skip these tests altogether when looking for leaks. These tests +-# do not need to be stored above in LEAKY_TESTS too. +-# test_compiler almost never finishes with the same number of refs +-# since it depends on other modules, skip it. +-# test_logging causes hangs, skip it. +-# KBK 21Apr09: test_httpservers causes hangs, skip for now. +-LEAKY_SKIPS="-x test_compiler test_logging test_httpservers" +- +-# Change this flag to "yes" for old releases to only update/build the docs. +-BUILD_DISABLED="no" +- +-## utility functions +-current_time() { +- date +%s +-} +- +-update_status() { +- now=`current_time` +- time=`expr $now - $3` +- echo "

  • $1 ($time seconds)
  • " >> $RESULT_FILE +-} +- +-place_summary_first() { +- testf=$1 +- sed -n '/^[0-9][0-9]* tests OK\./,$p' < $testf \ +- | egrep -v '\[[0-9]+ refs\]' > $testf.tmp +- echo "" >> $testf.tmp +- cat $testf >> $testf.tmp +- mv $testf.tmp $testf +-} +- +-count_failures () { +- testf=$1 +- n=`grep -ic " failed:" $testf` +- if [ $n -eq 1 ] ; then +- n=`grep " failed:" $testf | sed -e 's/ .*//'` +- fi +- echo $n +-} +- +-mail_on_failure() { +- if [ "$NUM_FAILURES" != "0" ]; then +- dest=$FAILURE_MAILTO +- # FAILURE_CC is optional. +- if [ "$FAILURE_CC" != "" ]; then +- dest="$dest -c $FAILURE_CC" +- fi +- if [ "x$3" != "x" ] ; then +- (echo "More important issues:" +- echo "----------------------" +- egrep -v "$3" < $2 +- echo "" +- echo "Less important issues:" +- echo "----------------------" +- egrep "$3" < $2) +- else +- cat $2 +- fi | mutt -s "$FAILURE_SUBJECT $1 ($NUM_FAILURES)" $dest +- fi +-} +- +-## setup +-cd $DIR +-make clobber > /dev/null 2>&1 +-cp -p Modules/Setup.dist Modules/Setup +-# But maybe there was no Makefile - we are only building docs. Clear build: +-rm -rf build/ +-mkdir -p build +-rm -rf $INSTALL_DIR +-## get the path we are building +-repo_path=$(grep "url=" .svn/entries | sed -e s/\\W*url=// -e s/\"//g) +- +-## create results file +-TITLE="Automated Python Build Results" +-echo "" >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " $TITLE" >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo "" >> $RESULT_FILE +-echo "

    Automated Python Build Results

    " >> $RESULT_FILE +-echo "" >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo " " >> $RESULT_FILE +-echo "
    Built on:`date`
    Hostname:`uname -n`
    Platform:`uname -srmpo`
    URL:$repo_path
    " >> $RESULT_FILE +-echo "
      " >> $RESULT_FILE +- +-## update, build, and test +-ORIG_CHECKSUM=`cksum $FULLPATHNAME` +-F=svn-update.out +-start=`current_time` +-svn update >& build/$F +-err=$? +-update_status "Updating" "$F" $start +-if [ $err = 0 -a "$BUILD_DISABLED" != "yes" ]; then +- ## FIXME: we should check if this file has changed. +- ## If it has changed, we should re-run the script to pick up changes. +- if [ "$ORIG_CHECKSUM" != "$ORIG_CHECKSUM" ]; then +- exec $FULLPATHNAME $@ +- fi +- +- F=svn-stat.out +- start=`current_time` +- svn stat >& build/$F +- ## ignore some of the diffs +- NUM_DIFFS=`egrep -vc '^. (@test|db_home|Lib/test/(regrtest\.py|db_home))$' build/$F` +- update_status "svn stat ($NUM_DIFFS possibly important diffs)" "$F" $start +- +- F=configure.out +- start=`current_time` +- ./configure --prefix=$INSTALL_DIR --with-pydebug >& build/$F +- err=$? +- update_status "Configuring" "$F" $start +- if [ $err = 0 ]; then +- F=make.out +- start=`current_time` +- make >& build/$F +- err=$? +- warnings=`grep warning build/$F | egrep -vc "te?mpnam(_r|)' is dangerous,"` +- update_status "Building ($warnings warnings)" "$F" $start +- if [ $err = 0 ]; then +- ## make install +- F=make-install.out +- start=`current_time` +- make install >& build/$F +- update_status "Installing" "$F" $start +- +- if [ ! -x $PYTHON ]; then +- ln -s ${PYTHON}2.* $PYTHON +- fi +- +- ## make and run basic tests +- F=make-test.out +- start=`current_time` +- $PYTHON $REGRTEST_ARGS -W -u urlfetch >& build/$F +- NUM_FAILURES=`count_failures build/$F` +- place_summary_first build/$F +- update_status "Testing basics ($NUM_FAILURES failures)" "$F" $start +- mail_on_failure "basics" build/$F +- +- F=make-test-opt.out +- start=`current_time` +- $PYTHON -O $REGRTEST_ARGS -W -u urlfetch >& build/$F +- NUM_FAILURES=`count_failures build/$F` +- place_summary_first build/$F +- update_status "Testing opt ($NUM_FAILURES failures)" "$F" $start +- mail_on_failure "opt" build/$F +- +- ## run the tests looking for leaks +- F=make-test-refleak.out +- start=`current_time` +- ## ensure that the reflog exists so the grep doesn't fail +- touch $REFLOG +- $PYTHON $REGRTEST_ARGS -R 4:3:$REFLOG -u network $LEAKY_SKIPS >& build/$F +- LEAK_PAT="($LEAKY_TESTS|sum=0)" +- NUM_FAILURES=`egrep -vc "$LEAK_PAT" $REFLOG` +- place_summary_first build/$F +- update_status "Testing refleaks ($NUM_FAILURES failures)" "$F" $start +- mail_on_failure "refleak" $REFLOG "$LEAK_PAT" +- +- ## now try to run all the tests +- F=make-testall.out +- start=`current_time` +- ## skip curses when running from cron since there's no terminal +- ## skip sound since it's not setup on the PSF box (/dev/dsp) +- $PYTHON $REGRTEST_ARGS -W -uall -x test_curses test_linuxaudiodev test_ossaudiodev >& build/$F +- NUM_FAILURES=`count_failures build/$F` +- place_summary_first build/$F +- update_status "Testing all except curses and sound ($NUM_FAILURES failures)" "$F" $start +- mail_on_failure "all" build/$F +- fi +- fi +-fi +- +- +-## make doc +-cd $DIR/Doc +-F="make-doc.out" +-start=`current_time` +-make clean > ../build/$F 2>&1 +-make checkout html >> ../build/$F 2>&1 +-err=$? +-update_status "Making doc" "$F" $start +-if [ $err != 0 ]; then +- NUM_FAILURES=1 +- mail_on_failure "doc" ../build/$F +-fi +- +-echo "
    " >> $RESULT_FILE +-echo "" >> $RESULT_FILE +-echo "" >> $RESULT_FILE +- +-## copy results +-## (not used anymore, the daily build is now done directly on the server) +-#chgrp -R webmaster build/html +-#chmod -R g+w build/html +-#rsync $RSYNC_OPTS build/html/* $REMOTE_SYSTEM:$REMOTE_DIR +-#cd ../build +-#rsync $RSYNC_OPTS index.html *.out $REMOTE_SYSTEM:$REMOTE_DIR/results/ +diff -r 8527427914a2 Modules/_bsddb.c +--- a/Modules/_bsddb.c ++++ b/Modules/_bsddb.c +@@ -7257,7 +7257,7 @@ + } + CHECK_ENV_NOT_CLOSED(self); + MYDB_BEGIN_ALLOW_THREADS; +- err = self->db_env->rep_elect(self->db_env, nvotes, nvotes, 0); ++ err = self->db_env->rep_elect(self->db_env, nsites, nvotes, 0); + MYDB_END_ALLOW_THREADS; + RETURN_IF_ERR(); + RETURN_NONE(); +@@ -8795,7 +8795,7 @@ + {"txn_recover", (PyCFunction)DBEnv_txn_recover, METH_NOARGS}, + #if (DBVER < 48) + {"set_rpc_server", (PyCFunction)DBEnv_set_rpc_server, +- METH_VARARGS||METH_KEYWORDS}, ++ METH_VARARGS|METH_KEYWORDS}, + #endif + #if (DBVER >= 43) + {"set_mp_max_openfd", (PyCFunction)DBEnv_set_mp_max_openfd, METH_VARARGS}, +diff -r 8527427914a2 Modules/_collectionsmodule.c +--- a/Modules/_collectionsmodule.c ++++ b/Modules/_collectionsmodule.c +@@ -1475,8 +1475,10 @@ + { + int status = Py_ReprEnter(dd->default_factory); + if (status != 0) { +- if (status < 0) ++ if (status < 0) { ++ Py_DECREF(baserepr); + return NULL; ++ } + defrepr = PyString_FromString("..."); + } + else +diff -r 8527427914a2 Modules/_csv.c +--- a/Modules/_csv.c ++++ b/Modules/_csv.c +@@ -1184,7 +1184,11 @@ + else { + PyObject *str; + +- str = PyObject_Str(field); ++ if (PyFloat_Check(field)) { ++ str = PyObject_Repr(field); ++ } else { ++ str = PyObject_Str(field); ++ } + Py_DECREF(field); + if (str == NULL) + return NULL; +diff -r 8527427914a2 Modules/_ctypes/_ctypes.c +--- a/Modules/_ctypes/_ctypes.c ++++ b/Modules/_ctypes/_ctypes.c +@@ -2576,8 +2576,10 @@ + view->ndim = dict->ndim; + view->shape = dict->shape; + view->itemsize = self->b_size; +- for (i = 0; i < view->ndim; ++i) { +- view->itemsize /= dict->shape[i]; ++ if (view->itemsize) { ++ for (i = 0; i < view->ndim; ++i) { ++ view->itemsize /= dict->shape[i]; ++ } + } + view->strides = NULL; + view->suboffsets = NULL; +@@ -4676,6 +4678,7 @@ + if (!PyType_Check(itemtype)) { + PyErr_SetString(PyExc_TypeError, + "Expected a type object"); ++ Py_DECREF(key); + return NULL; + } + #ifdef MS_WIN64 +diff -r 8527427914a2 Modules/_ctypes/callbacks.c +--- a/Modules/_ctypes/callbacks.c ++++ b/Modules/_ctypes/callbacks.c +@@ -18,6 +18,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 8527427914a2 Modules/_ctypes/libffi/src/dlmalloc.c +--- a/Modules/_ctypes/libffi/src/dlmalloc.c ++++ b/Modules/_ctypes/libffi/src/dlmalloc.c +@@ -457,6 +457,11 @@ + #define LACKS_ERRNO_H + #define MALLOC_FAILURE_ACTION + #define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */ ++#elif !defined _GNU_SOURCE ++/* mremap() on Linux requires this via sys/mman.h ++ * See roundup issue 10309 ++ */ ++#define _GNU_SOURCE 1 + #endif /* WIN32 */ + + #if defined(DARWIN) || defined(_DARWIN) +diff -r 8527427914a2 Modules/_ctypes/stgdict.c +--- a/Modules/_ctypes/stgdict.c ++++ b/Modules/_ctypes/stgdict.c +@@ -494,14 +494,33 @@ + char *fieldfmt = dict->format ? dict->format : "B"; + char *fieldname = PyString_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 8527427914a2 Modules/_elementtree.c +--- a/Modules/_elementtree.c ++++ b/Modules/_elementtree.c +@@ -2915,19 +2915,25 @@ + + "class ElementTree(ET.ElementTree):\n" /* public */ + " def parse(self, source, parser=None):\n" ++ " close_source = False\n" + " if not hasattr(source, 'read'):\n" + " source = open(source, 'rb')\n" +- " if parser is not None:\n" +- " while 1:\n" +- " data = source.read(65536)\n" +- " if not data:\n" +- " break\n" +- " parser.feed(data)\n" +- " self._root = parser.close()\n" +- " else:\n" +- " parser = cElementTree.XMLParser()\n" +- " self._root = parser._parse(source)\n" +- " return self._root\n" ++ " close_source = False\n" ++ " try:\n" ++ " if parser is not None:\n" ++ " while 1:\n" ++ " data = source.read(65536)\n" ++ " if not data:\n" ++ " break\n" ++ " parser.feed(data)\n" ++ " self._root = parser.close()\n" ++ " else:\n" ++ " parser = cElementTree.XMLParser()\n" ++ " self._root = parser._parse(source)\n" ++ " return self._root\n" ++ " finally:\n" ++ " if close_source:\n" ++ " source.close()\n" + "cElementTree.ElementTree = ElementTree\n" + + "def iter(node, tag=None):\n" /* helper */ +@@ -2957,11 +2963,14 @@ + "class iterparse(object):\n" + " root = None\n" + " def __init__(self, file, events=None):\n" ++ " self._close_file = False\n" + " if not hasattr(file, 'read'):\n" + " file = open(file, 'rb')\n" ++ " self._close_file = True\n" + " 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" +@@ -2970,22 +2979,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" +- " 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 8527427914a2 Modules/_io/bufferedio.c +--- a/Modules/_io/bufferedio.c ++++ b/Modules/_io/bufferedio.c +@@ -550,7 +550,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 +@@ -571,6 +571,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 * +@@ -721,6 +733,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; +@@ -730,16 +764,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; +@@ -760,7 +785,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); +@@ -795,19 +820,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; + } + +@@ -833,13 +857,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. */ + +@@ -859,6 +876,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); +@@ -881,24 +905,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 * +@@ -936,12 +946,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; +@@ -955,9 +959,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); +@@ -1088,7 +1099,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); +@@ -1126,20 +1137,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; +@@ -1341,17 +1343,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) { +@@ -1434,6 +1437,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) { +@@ -1684,6 +1695,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; +@@ -1696,11 +1708,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) { +@@ -1717,7 +1739,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; +@@ -1739,14 +1761,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; +@@ -1759,16 +1778,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: +@@ -1821,7 +1830,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) +@@ -1844,14 +1853,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); +@@ -1876,11 +1890,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, +@@ -1888,8 +1900,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(); +@@ -2180,6 +2193,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 8527427914a2 Modules/_io/fileio.c +--- a/Modules/_io/fileio.c ++++ b/Modules/_io/fileio.c +@@ -42,12 +42,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; +@@ -474,7 +468,7 @@ + fileio_readinto(fileio *self, PyObject *args) + { + Py_buffer pbuf; +- Py_ssize_t n; ++ Py_ssize_t n, len; + + if (self->fd < 0) + return err_closed(); +@@ -485,9 +479,16 @@ + return NULL; + + if (_PyVerify_fd(self->fd)) { ++ len = pbuf.len; + Py_BEGIN_ALLOW_THREADS + errno = 0; +- n = read(self->fd, pbuf.buf, pbuf.len); ++#if defined(MS_WIN64) || defined(MS_WINDOWS) ++ if (len > INT_MAX) ++ len = INT_MAX; ++ n = read(self->fd, pbuf.buf, (int)len); ++#else ++ n = read(self->fd, pbuf.buf, len); ++#endif + Py_END_ALLOW_THREADS + } else + n = -1; +@@ -521,15 +522,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 * +@@ -620,6 +616,10 @@ + return fileio_readall(self); + } + ++#if defined(MS_WIN64) || defined(MS_WINDOWS) ++ if (size > INT_MAX) ++ size = INT_MAX; ++#endif + bytes = PyBytes_FromStringAndSize(NULL, size); + if (bytes == NULL) + return NULL; +@@ -628,7 +628,11 @@ + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; ++#if defined(MS_WIN64) || defined(MS_WINDOWS) ++ n = read(self->fd, ptr, (int)size); ++#else + n = read(self->fd, ptr, size); ++#endif + Py_END_ALLOW_THREADS + } else + n = -1; +@@ -655,7 +659,7 @@ + fileio_write(fileio *self, PyObject *args) + { + Py_buffer pbuf; +- Py_ssize_t n; ++ Py_ssize_t n, len; + + if (self->fd < 0) + return err_closed(); +@@ -668,7 +672,14 @@ + if (_PyVerify_fd(self->fd)) { + Py_BEGIN_ALLOW_THREADS + errno = 0; +- n = write(self->fd, pbuf.buf, pbuf.len); ++ len = pbuf.len; ++#if defined(MS_WIN64) || defined(MS_WINDOWS) ++ if (len > INT_MAX) ++ len = INT_MAX; ++ n = write(self->fd, pbuf.buf, (int)len); ++#else ++ n = write(self->fd, pbuf.buf, len); ++#endif + Py_END_ALLOW_THREADS + } else + n = -1; +diff -r 8527427914a2 Modules/_io/stringio.c +--- a/Modules/_io/stringio.c ++++ b/Modules/_io/stringio.c +@@ -464,7 +464,7 @@ + + CHECK_INITIALIZED(self); + if (!PyUnicode_Check(obj)) { +- PyErr_Format(PyExc_TypeError, "string argument expected, got '%s'", ++ PyErr_Format(PyExc_TypeError, "unicode argument expected, got '%s'", + Py_TYPE(obj)->tp_name); + return NULL; + } +diff -r 8527427914a2 Modules/_json.c +--- a/Modules/_json.c ++++ b/Modules/_json.c +@@ -1725,8 +1725,15 @@ + Py_DECREF(s->encoding); + s->encoding = tmp; + } +- if (s->encoding == NULL || !PyString_Check(s->encoding)) ++ if (s->encoding == NULL) + goto bail; ++ if (!PyString_Check(s->encoding)) { ++ PyErr_Format(PyExc_TypeError, ++ "encoding must be a string, not %.80s", ++ Py_TYPE(s->encoding)->tp_name); ++ goto bail; ++ } ++ + + /* All of these will fail "gracefully" so we don't need to verify them */ + s->strict = PyObject_GetAttrString(ctx, "strict"); +diff -r 8527427914a2 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 8527427914a2 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; +@@ -268,16 +268,17 @@ + } + } + +-PyObject* pysqlite_unicode_from_string(const char* val_str, int optimize) ++PyObject* pysqlite_unicode_from_string(const char* val_str, Py_ssize_t size, int optimize) + { + const char* check; ++ Py_ssize_t pos; + int is_ascii = 0; + + if (optimize) { + is_ascii = 1; + + check = val_str; +- while (*check) { ++ for (pos = 0; pos < size; pos++) { + if (*check & 0x80) { + is_ascii = 0; + break; +@@ -288,9 +289,9 @@ + } + + if (is_ascii) { +- return PyString_FromString(val_str); ++ return PyString_FromStringAndSize(val_str, size); + } else { +- return PyUnicode_DecodeUTF8(val_str, strlen(val_str), NULL); ++ return PyUnicode_DecodeUTF8(val_str, size, NULL); + } + } + +@@ -375,10 +376,11 @@ + converted = PyFloat_FromDouble(sqlite3_column_double(self->statement->st, i)); + } else if (coltype == SQLITE_TEXT) { + val_str = (const char*)sqlite3_column_text(self->statement->st, i); ++ nbytes = sqlite3_column_bytes(self->statement->st, i); + if ((self->connection->text_factory == (PyObject*)&PyUnicode_Type) + || (self->connection->text_factory == pysqlite_OptimizedUnicode)) { + +- converted = pysqlite_unicode_from_string(val_str, ++ converted = pysqlite_unicode_from_string(val_str, nbytes, + self->connection->text_factory == pysqlite_OptimizedUnicode ? 1 : 0); + + if (!converted) { +@@ -391,9 +393,9 @@ + PyErr_SetString(pysqlite_OperationalError, buf); + } + } else if (self->connection->text_factory == (PyObject*)&PyString_Type) { +- converted = PyString_FromString(val_str); ++ converted = PyString_FromStringAndSize(val_str, nbytes); + } else { +- converted = PyObject_CallFunction(self->connection->text_factory, "s", val_str); ++ converted = PyObject_CallFunction(self->connection->text_factory, "s#", val_str, nbytes); + } + } else { + /* coltype == SQLITE_BLOB */ +@@ -441,9 +443,14 @@ + if (cur->closed) { + PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed cursor."); + return 0; +- } else { +- return pysqlite_check_thread(cur->connection) && pysqlite_check_connection(cur->connection); + } ++ ++ if (cur->locked) { ++ PyErr_SetString(pysqlite_ProgrammingError, "Recursive use of cursors not allowed."); ++ return 0; ++ } ++ ++ return pysqlite_check_thread(cur->connection) && pysqlite_check_connection(cur->connection); + } + + PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* args) +@@ -466,9 +473,10 @@ + int allow_8bit_chars; + + if (!check_cursor(self)) { +- return NULL; ++ goto error; + } + ++ self->locked = 1; + self->reset = 0; + + /* Make shooting yourself in the foot with not utf-8 decodable 8-bit-strings harder */ +@@ -481,12 +489,12 @@ + if (multiple) { + /* executemany() */ + if (!PyArg_ParseTuple(args, "OO", &operation, &second_argument)) { +- return NULL; ++ goto error; + } + + if (!PyString_Check(operation) && !PyUnicode_Check(operation)) { + PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode"); +- return NULL; ++ goto error; + } + + if (PyIter_Check(second_argument)) { +@@ -497,23 +505,23 @@ + /* sequence */ + parameters_iter = PyObject_GetIter(second_argument); + if (!parameters_iter) { +- return NULL; ++ goto error; + } + } + } else { + /* execute() */ + if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) { +- return NULL; ++ goto error; + } + + if (!PyString_Check(operation) && !PyUnicode_Check(operation)) { + PyErr_SetString(PyExc_ValueError, "operation parameter must be str or unicode"); +- return NULL; ++ goto error; + } + + parameters_list = PyList_New(0); + if (!parameters_list) { +- return NULL; ++ goto error; + } + + if (second_argument == NULL) { +@@ -759,7 +767,8 @@ + * ROLLBACK could have happened */ + #ifdef SQLITE_VERSION_NUMBER + #if SQLITE_VERSION_NUMBER >= 3002002 +- self->connection->inTransaction = !sqlite3_get_autocommit(self->connection->db); ++ if (self->connection && self->connection->db) ++ self->connection->inTransaction = !sqlite3_get_autocommit(self->connection->db); + #endif + #endif + +@@ -768,6 +777,8 @@ + Py_XDECREF(parameters_iter); + Py_XDECREF(parameters_list); + ++ self->locked = 0; ++ + if (PyErr_Occurred()) { + self->rowcount = -1L; + return NULL; +diff -r 8527427914a2 Modules/_sqlite/cursor.h +--- a/Modules/_sqlite/cursor.h ++++ b/Modules/_sqlite/cursor.h +@@ -42,6 +42,7 @@ + pysqlite_Statement* statement; + int closed; + int reset; ++ int locked; + int initialized; + + /* the next row to be returned, NULL if no next row available */ +diff -r 8527427914a2 Modules/_sqlite/statement.c +--- a/Modules/_sqlite/statement.c ++++ b/Modules/_sqlite/statement.c +@@ -166,13 +166,13 @@ + rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter)); + break; + case TYPE_STRING: +- string = PyString_AS_STRING(parameter); +- rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); ++ PyString_AsStringAndSize(parameter, &string, &buflen); ++ rc = sqlite3_bind_text(self->st, pos, string, buflen, SQLITE_TRANSIENT); + break; + case TYPE_UNICODE: + stringval = PyUnicode_AsUTF8String(parameter); +- string = PyString_AsString(stringval); +- rc = sqlite3_bind_text(self->st, pos, string, -1, SQLITE_TRANSIENT); ++ PyString_AsStringAndSize(stringval, &string, &buflen); ++ rc = sqlite3_bind_text(self->st, pos, string, buflen, SQLITE_TRANSIENT); + Py_DECREF(stringval); + break; + case TYPE_BUFFER: +diff -r 8527427914a2 Modules/_sre.c +--- a/Modules/_sre.c ++++ b/Modules/_sre.c +@@ -2744,7 +2744,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 8527427914a2 Modules/_ssl.c +--- a/Modules/_ssl.c ++++ b/Modules/_ssl.c +@@ -369,7 +369,8 @@ + } + + /* ssl compatibility */ +- SSL_CTX_set_options(self->ctx, SSL_OP_ALL); ++ SSL_CTX_set_options(self->ctx, ++ SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); + + verification_mode = SSL_VERIFY_NONE; + if (certreq == PY_SSL_CERT_OPTIONAL) +@@ -643,15 +644,20 @@ + goto fail1; + } + /* now, there's typically a dangling RDN */ +- if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { +- rdnt = PyList_AsTuple(rdn); +- Py_DECREF(rdn); +- if (rdnt == NULL) +- goto fail0; +- retcode = PyList_Append(dn, rdnt); +- Py_DECREF(rdnt); +- if (retcode < 0) +- goto fail0; ++ if (rdn != NULL) { ++ if (PyList_GET_SIZE(rdn) > 0) { ++ rdnt = PyList_AsTuple(rdn); ++ Py_DECREF(rdn); ++ if (rdnt == NULL) ++ goto fail0; ++ retcode = PyList_Append(dn, rdnt); ++ Py_DECREF(rdnt); ++ if (retcode < 0) ++ goto fail0; ++ } ++ else { ++ Py_DECREF(rdn); ++ } + } + + /* convert list to tuple */ +@@ -702,7 +708,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) { + +@@ -798,6 +804,7 @@ + } + Py_DECREF(t); + } ++ sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); + } + BIO_free(biobuf); + if (peer_alt_names != Py_None) { +@@ -1145,10 +1152,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 8527427914a2 Modules/_testcapimodule.c +--- a/Modules/_testcapimodule.c ++++ b/Modules/_testcapimodule.c +@@ -1106,6 +1106,41 @@ + } + + static PyObject * ++unicode_encodedecimal(PyObject *self, PyObject *args) ++{ ++ Py_UNICODE *unicode; ++ int 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 * + test_empty_argparse(PyObject *self) + { + /* Test that formats can begin with '|'. See issue #4720. */ +@@ -1639,6 +1674,19 @@ + return PyErr_NewExceptionWithDoc(name, doc, base, dict); + } + ++static PyObject * ++sequence_delitem(PyObject *self, PyObject *args) ++{ ++ PyObject *seq; ++ Py_ssize_t i; ++ ++ if (!PyArg_ParseTuple(args, "On", &seq, &i)) ++ return NULL; ++ if (PySequence_DelItem(seq, i) < 0) ++ return NULL; ++ Py_RETURN_NONE; ++} ++ + static PyMethodDef TestMethods[] = { + {"raise_exception", raise_exception, METH_VARARGS}, + {"test_config", (PyCFunction)test_config, METH_NOARGS}, +@@ -1685,6 +1733,7 @@ + #ifdef Py_USING_UNICODE + {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS}, + {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS}, ++ {"unicode_encodedecimal", unicode_encodedecimal, METH_VARARGS}, + #endif + #ifdef WITH_THREAD + {"_test_thread_state", test_thread_state, METH_VARARGS}, +@@ -1695,6 +1744,7 @@ + {"code_newempty", code_newempty, METH_VARARGS}, + {"make_exception_with_doc", (PyCFunction)make_exception_with_doc, + METH_VARARGS | METH_KEYWORDS}, ++ {"sequence_delitem", (PyCFunction)sequence_delitem, METH_VARARGS}, + {NULL, NULL} /* sentinel */ + }; + +diff -r 8527427914a2 Modules/_tkinter.c +--- a/Modules/_tkinter.c ++++ b/Modules/_tkinter.c +@@ -663,8 +663,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); + +diff -r 8527427914a2 Modules/arraymodule.c +--- a/Modules/arraymodule.c ++++ b/Modules/arraymodule.c +@@ -2050,7 +2050,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\ +diff -r 8527427914a2 Modules/audioop.c +--- a/Modules/audioop.c ++++ b/Modules/audioop.c +@@ -1298,7 +1298,7 @@ + &cp, &len, &size) ) + return 0; + +- if (!audioop_check_parameters(len, size)) ++ if (!audioop_check_size(size)) + return NULL; + + if (len > INT_MAX/size) { +@@ -1367,7 +1367,7 @@ + &cp, &len, &size) ) + return 0; + +- if (!audioop_check_parameters(len, size)) ++ if (!audioop_check_size(size)) + return NULL; + + if (len > INT_MAX/size) { +@@ -1509,7 +1509,7 @@ + &cp, &len, &size, &state) ) + return 0; + +- if (!audioop_check_parameters(len, size)) ++ if (!audioop_check_size(size)) + return NULL; + + /* Decode state, should have (value, step) */ +diff -r 8527427914a2 Modules/binascii.c +--- a/Modules/binascii.c ++++ b/Modules/binascii.c +@@ -1105,8 +1105,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 8527427914a2 Modules/bsddb.h +--- a/Modules/bsddb.h ++++ b/Modules/bsddb.h +@@ -109,7 +109,7 @@ + #error "eek! DBVER can't handle minor versions > 9" + #endif + +-#define PY_BSDDB_VERSION "4.8.4.1" ++#define PY_BSDDB_VERSION "4.8.4.2" + + /* Python object definitions */ + +diff -r 8527427914a2 Modules/bz2module.c +--- a/Modules/bz2module.c ++++ b/Modules/bz2module.c +@@ -224,25 +224,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 8527427914a2 Modules/cPickle.c +--- a/Modules/cPickle.c ++++ b/Modules/cPickle.c +@@ -2697,11 +2697,6 @@ + } + } + +- if (PyType_IsSubtype(type, &PyType_Type)) { +- res = save_global(self, args, NULL); +- goto finally; +- } +- + /* Get a reduction callable, and call it. This may come from + * copy_reg.dispatch_table, the object's __reduce_ex__ method, + * or the object's __reduce__ method. +@@ -2717,6 +2712,11 @@ + } + } + else { ++ if (PyType_IsSubtype(type, &PyType_Type)) { ++ res = save_global(self, args, NULL); ++ goto finally; ++ } ++ + /* Check for a __reduce_ex__ method. */ + __reduce__ = PyObject_GetAttr(args, __reduce_ex___str); + if (__reduce__ != NULL) { +diff -r 8527427914a2 Modules/cStringIO.c +--- a/Modules/cStringIO.c ++++ b/Modules/cStringIO.c +@@ -661,7 +661,11 @@ + char *buf; + Py_ssize_t size; + +- if (PyObject_AsReadBuffer(s, (const void **)&buf, &size)) { ++ if (PyUnicode_Check(s)) { ++ if (PyObject_AsCharBuffer(s, (const char **)&buf, &size) != 0) ++ return NULL; ++ } ++ else if (PyObject_AsReadBuffer(s, (const void **)&buf, &size)) { + PyErr_Format(PyExc_TypeError, "expected read buffer, %.200s found", + s->ob_type->tp_name); + return NULL; +diff -r 8527427914a2 Modules/cjkcodecs/_codecs_hk.c +--- a/Modules/cjkcodecs/_codecs_hk.c ++++ b/Modules/cjkcodecs/_codecs_hk.c +@@ -115,55 +115,56 @@ + + REQUIRE_INBUF(2) + +- if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1)) +- goto hkscsdec; ++ if (0xc6 > c || c > 0xc8 || (c < 0xc7 && IN2 < 0xa1)) { ++ TRYMAP_DEC(big5, **outbuf, c, IN2) { ++ NEXT(2, 1) ++ continue; ++ } ++ } + +- TRYMAP_DEC(big5, **outbuf, c, IN2) { +- NEXT(2, 1) ++ TRYMAP_DEC(big5hkscs, decoded, c, IN2) ++ { ++ int s = BH2S(c, IN2); ++ const unsigned char *hintbase; ++ ++ assert(0x87 <= c && c <= 0xfe); ++ assert(0x40 <= IN2 && IN2 <= 0xfe); ++ ++ if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { ++ hintbase = big5hkscs_phint_0; ++ s -= BH2S(0x87, 0x40); ++ } ++ else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ ++ hintbase = big5hkscs_phint_12130; ++ s -= BH2S(0xc6, 0xa1); ++ } ++ else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ ++ hintbase = big5hkscs_phint_21924; ++ s -= BH2S(0xf9, 0xd6); ++ } ++ else ++ return MBERR_INTERNAL; ++ ++ if (hintbase[s >> 3] & (1 << (s & 7))) { ++ WRITEUCS4(decoded | 0x20000) ++ NEXT_IN(2) ++ } ++ else { ++ OUT1(decoded) ++ NEXT(2, 1) ++ } ++ continue; + } +- else +-hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) { +- int s = BH2S(c, IN2); +- const unsigned char *hintbase; + +- assert(0x87 <= c && c <= 0xfe); +- assert(0x40 <= IN2 && IN2 <= 0xfe); ++ switch ((c << 8) | IN2) { ++ case 0x8862: WRITE2(0x00ca, 0x0304); break; ++ case 0x8864: WRITE2(0x00ca, 0x030c); break; ++ case 0x88a3: WRITE2(0x00ea, 0x0304); break; ++ case 0x88a5: WRITE2(0x00ea, 0x030c); break; ++ default: return 2; ++ } + +- if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) { +- hintbase = big5hkscs_phint_0; +- s -= BH2S(0x87, 0x40); +- } +- else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){ +- hintbase = big5hkscs_phint_12130; +- s -= BH2S(0xc6, 0xa1); +- } +- else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){ +- hintbase = big5hkscs_phint_21924; +- s -= BH2S(0xf9, 0xd6); +- } +- else +- return MBERR_INTERNAL; +- +- if (hintbase[s >> 3] & (1 << (s & 7))) { +- WRITEUCS4(decoded | 0x20000) +- NEXT_IN(2) +- } +- else { +- OUT1(decoded) +- NEXT(2, 1) +- } +- } +- else { +- switch ((c << 8) | IN2) { +- case 0x8862: WRITE2(0x00ca, 0x0304); break; +- case 0x8864: WRITE2(0x00ca, 0x030c); break; +- case 0x88a3: WRITE2(0x00ea, 0x0304); break; +- case 0x88a5: WRITE2(0x00ea, 0x030c); break; +- default: return 2; +- } +- +- NEXT(2, 2) /* all decoded codepoints are pairs, above. */ +- } ++ NEXT(2, 2) /* all decoded codepoints are pairs, above. */ + } + + return 0; +diff -r 8527427914a2 Modules/cjkcodecs/_codecs_jp.c +--- a/Modules/cjkcodecs/_codecs_jp.c ++++ b/Modules/cjkcodecs/_codecs_jp.c +@@ -371,11 +371,11 @@ + + REQUIRE_OUTBUF(1) + +- if (c < 0x80) { +- OUT1(c) +- NEXT(1, 1) +- continue; +- } ++ if (c < 0x80) { ++ OUT1(c) ++ NEXT(1, 1) ++ continue; ++ } + + if (c == 0x8e) { + /* JIS X 0201 half-width katakana */ +diff -r 8527427914a2 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 8527427914a2 Modules/mmapmodule.c +--- a/Modules/mmapmodule.c ++++ b/Modules/mmapmodule.c +@@ -1188,12 +1188,13 @@ + # endif + if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { + if (map_size == 0) { ++ off_t calc_size; + if (offset >= st.st_size) { + PyErr_SetString(PyExc_ValueError, + "mmap offset is greater than file size"); + return NULL; + } +- off_t calc_size = st.st_size - offset; ++ calc_size = st.st_size - offset; + map_size = calc_size; + if (map_size != calc_size) { + PyErr_SetString(PyExc_ValueError, +diff -r 8527427914a2 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, "s#: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 8527427914a2 Modules/posixmodule.c +--- a/Modules/posixmodule.c ++++ b/Modules/posixmodule.c +@@ -11,8 +11,6 @@ + compiler is assumed to be IBM's VisualAge C++ (VACPP). PYCC_GCC is used + as the compiler specific macro for the EMX port of gcc to OS/2. */ + +-/* See also ../Dos/dosmodule.c */ +- + #ifdef __APPLE__ + /* + * Step 1 of support for weak-linking a number of symbols existing on +@@ -338,20 +336,6 @@ + #define USE_TMPNAM_R + #endif + +-/* choose the appropriate stat and fstat functions and return structs */ +-#undef STAT +-#undef FSTAT +-#undef STRUCT_STAT +-#if defined(MS_WIN64) || defined(MS_WINDOWS) +-# define STAT win32_stat +-# define FSTAT win32_fstat +-# define STRUCT_STAT struct win32_stat +-#else +-# define STAT stat +-# define FSTAT fstat +-# define STRUCT_STAT struct stat +-#endif +- + #if defined(MAJOR_IN_MKDEV) + #include + #else +@@ -842,6 +826,20 @@ + } + #endif + ++/* choose the appropriate stat and fstat functions and return structs */ ++#undef STAT ++#undef FSTAT ++#undef STRUCT_STAT ++#if defined(MS_WIN64) || defined(MS_WINDOWS) ++# define STAT win32_stat ++# define FSTAT win32_fstat ++# define STRUCT_STAT struct win32_stat ++#else ++# define STAT stat ++# define FSTAT fstat ++# define STRUCT_STAT struct stat ++#endif ++ + #ifdef MS_WINDOWS + /* The CRT of Windows has a number of flaws wrt. its stat() implementation: + - time stamps are restricted to second resolution +@@ -3903,7 +3901,7 @@ + #endif + gid_t grouplist[MAX_GROUPS]; + +- /* On MacOSX getgroups(2) can return more than MAX_GROUPS results ++ /* On MacOSX getgroups(2) can return more than MAX_GROUPS results + * This is a helper variable to store the intermediate result when + * that happens. + * +@@ -4199,6 +4197,44 @@ + CloseHandle(handle); + return result; + } ++ ++PyDoc_STRVAR(posix__isdir__doc__, ++"Return true if the pathname refers to an existing directory."); ++ ++static PyObject * ++posix__isdir(PyObject *self, PyObject *args) ++{ ++ PyObject *opath; ++ char *path; ++ PyUnicodeObject *po; ++ DWORD attributes; ++ ++ if (PyArg_ParseTuple(args, "U|:_isdir", &po)) { ++ Py_UNICODE *wpath = PyUnicode_AS_UNICODE(po); ++ ++ attributes = GetFileAttributesW(wpath); ++ if (attributes == INVALID_FILE_ATTRIBUTES) ++ Py_RETURN_FALSE; ++ goto check; ++ } ++ /* Drop the argument parsing error as narrow strings ++ are also valid. */ ++ PyErr_Clear(); ++ ++ if (!PyArg_ParseTuple(args, "et:_isdir", ++ Py_FileSystemDefaultEncoding, &path)) ++ return NULL; ++ ++ attributes = GetFileAttributesA(path); ++ if (attributes == INVALID_FILE_ATTRIBUTES) ++ Py_RETURN_FALSE; ++ ++check: ++ if (attributes & FILE_ATTRIBUTE_DIRECTORY) ++ Py_RETURN_TRUE; ++ else ++ Py_RETURN_FALSE; ++} + #endif /* MS_WINDOWS */ + + #ifdef HAVE_PLOCK +@@ -6610,7 +6646,7 @@ + { + Py_buffer pbuf; + int fd; +- Py_ssize_t size; ++ Py_ssize_t size, len; + + if (!PyArg_ParseTuple(args, "is*:write", &fd, &pbuf)) + return NULL; +@@ -6618,8 +6654,15 @@ + PyBuffer_Release(&pbuf); + return posix_error(); + } ++ len = pbuf.len; + Py_BEGIN_ALLOW_THREADS +- size = write(fd, pbuf.buf, (size_t)pbuf.len); ++#if defined(MS_WIN64) || defined(MS_WINDOWS) ++ if (len > INT_MAX) ++ len = INT_MAX; ++ size = write(fd, pbuf.buf, (int)len); ++#else ++ size = write(fd, pbuf.buf, len); ++#endif + Py_END_ALLOW_THREADS + PyBuffer_Release(&pbuf); + if (size < 0) +@@ -6712,6 +6755,8 @@ + PyMem_FREE(mode); + if (fp == NULL) + return posix_error(); ++ /* The dummy filename used here must be kept in sync with the value ++ tested against in gzip.GzipFile.__init__() - see issue #13781. */ + f = PyFile_FromFile(fp, "", orgmode, fclose); + if (f != NULL) + PyFile_SetBufSize(f, bufsize); +@@ -6951,6 +6996,14 @@ + + /* XXX This can leak memory -- not easy to fix :-( */ + len = strlen(s1) + strlen(s2) + 2; ++#ifdef MS_WINDOWS ++ if (_MAX_ENV < (len - 1)) { ++ PyErr_Format(PyExc_ValueError, ++ "the environment variable is longer than %u bytes", ++ _MAX_ENV); ++ return NULL; ++ } ++#endif + /* len includes space for a trailing \0; the size arg to + PyString_FromStringAndSize does not count that */ + newstr = PyString_FromStringAndSize(NULL, (int)len - 1); +@@ -6993,11 +7046,20 @@ + posix_unsetenv(PyObject *self, PyObject *args) + { + char *s1; ++#ifndef HAVE_BROKEN_UNSETENV ++ int err; ++#endif + + if (!PyArg_ParseTuple(args, "s:unsetenv", &s1)) + return NULL; + ++#ifdef HAVE_BROKEN_UNSETENV + unsetenv(s1); ++#else ++ err = unsetenv(s1); ++ if (err) ++ return posix_error(); ++#endif + + /* Remove the key from posix_putenv_garbage; + * this will cause it to be collected. This has to +@@ -8968,6 +9030,7 @@ + {"abort", posix_abort, METH_NOARGS, posix_abort__doc__}, + #ifdef MS_WINDOWS + {"_getfullpathname", posix__getfullpathname, METH_VARARGS, NULL}, ++ {"_isdir", posix__isdir, METH_VARARGS, posix__isdir__doc__}, + #endif + #ifdef HAVE_GETLOADAVG + {"getloadavg", posix_getloadavg, METH_NOARGS, posix_getloadavg__doc__}, +diff -r 8527427914a2 Modules/selectmodule.c +--- a/Modules/selectmodule.c ++++ b/Modules/selectmodule.c +@@ -114,7 +114,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; +@@ -164,13 +164,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 */ +@@ -912,7 +905,7 @@ + PyDoc_STRVAR(pyepoll_register_doc, + "register(fd[, eventmask]) -> None\n\ + \n\ +-Registers a new fd or modifies an already registered fd.\n\ ++Registers a new fd or raises an IOError if the fd is already registered.\n\ + fd is the target file descriptor of the operation.\n\ + events is a bit set composed of the various EPOLL constants; the default\n\ + is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\ +diff -r 8527427914a2 Modules/signalmodule.c +--- a/Modules/signalmodule.c ++++ b/Modules/signalmodule.c +@@ -976,11 +976,12 @@ + PyOS_AfterFork(void) + { + #ifdef WITH_THREAD +- _PyGILState_Reinit(); ++ /* PyThread_ReInitTLS() must be called early, to make sure that the TLS API ++ * can be called safely. */ ++ PyThread_ReInitTLS(); + PyEval_ReInitThreads(); + main_thread = PyThread_get_thread_ident(); + main_pid = getpid(); + _PyImport_ReInitLock(); +- PyThread_ReInitTLS(); + #endif + } +diff -r 8527427914a2 Modules/socketmodule.c +--- a/Modules/socketmodule.c ++++ b/Modules/socketmodule.c +@@ -456,18 +456,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* +@@ -1032,10 +1028,10 @@ + PyObject *ret = NULL; + if (addrobj) { + a = (struct sockaddr_in6 *)addr; +- ret = Py_BuildValue("Oiii", ++ ret = Py_BuildValue("OiII", + addrobj, + ntohs(a->sin6_port), +- a->sin6_flowinfo, ++ ntohl(a->sin6_flowinfo), + a->sin6_scope_id); + Py_DECREF(addrobj); + } +@@ -1286,7 +1282,8 @@ + { + struct sockaddr_in6* addr; + char *host; +- int port, flowinfo, scope_id, result; ++ int port, result; ++ unsigned int flowinfo, scope_id; + flowinfo = scope_id = 0; + if (!PyTuple_Check(args)) { + PyErr_Format( +@@ -1296,7 +1293,7 @@ + Py_TYPE(args)->tp_name); + return 0; + } +- if (!PyArg_ParseTuple(args, "eti|ii", ++ if (!PyArg_ParseTuple(args, "eti|II", + "idna", &host, &port, &flowinfo, + &scope_id)) { + return 0; +@@ -1313,9 +1310,15 @@ + "getsockaddrarg: port must be 0-65535."); + return 0; + } ++ if (flowinfo < 0 || flowinfo > 0xfffff) { ++ PyErr_SetString( ++ PyExc_OverflowError, ++ "getsockaddrarg: flowinfo must be 0-1048575."); ++ return 0; ++ } + addr->sin6_family = s->sock_family; + addr->sin6_port = htons((short)port); +- addr->sin6_flowinfo = flowinfo; ++ addr->sin6_flowinfo = htonl(flowinfo); + addr->sin6_scope_id = scope_id; + *len_ret = sizeof *addr; + return 1; +@@ -1784,7 +1787,7 @@ + PyDoc_STRVAR(gettimeout_doc, + "gettimeout() -> timeout\n\ + \n\ +-Returns the timeout in floating seconds associated with socket \n\ ++Returns the timeout in seconds (float) associated with socket \n\ + operations. A timeout of None indicates that timeouts on socket \n\ + operations are disabled."); + +@@ -4160,7 +4163,8 @@ + PyObject *sa = (PyObject *)NULL; + int flags; + char *hostp; +- int port, flowinfo, scope_id; ++ int port; ++ unsigned int flowinfo, scope_id; + char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV]; + struct addrinfo hints, *res = NULL; + int error; +@@ -4174,9 +4178,14 @@ + "getnameinfo() argument 1 must be a tuple"); + return NULL; + } +- if (!PyArg_ParseTuple(sa, "si|ii", ++ if (!PyArg_ParseTuple(sa, "si|II", + &hostp, &port, &flowinfo, &scope_id)) + return NULL; ++ if (flowinfo < 0 || flowinfo > 0xfffff) { ++ PyErr_SetString(PyExc_OverflowError, ++ "getsockaddrarg: flowinfo must be 0-1048575."); ++ return NULL; ++ } + PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; +@@ -4210,7 +4219,7 @@ + { + struct sockaddr_in6 *sin6; + sin6 = (struct sockaddr_in6 *)res->ai_addr; +- sin6->sin6_flowinfo = flowinfo; ++ sin6->sin6_flowinfo = htonl(flowinfo); + sin6->sin6_scope_id = scope_id; + break; + } +@@ -4252,7 +4261,7 @@ + PyDoc_STRVAR(getdefaulttimeout_doc, + "getdefaulttimeout() -> timeout\n\ + \n\ +-Returns the default timeout in floating seconds for new socket objects.\n\ ++Returns the default timeout in seconds (float) for new socket objects.\n\ + A value of None indicates that new socket objects have no timeout.\n\ + When the socket module is first imported, the default is None."); + +@@ -4282,7 +4291,7 @@ + PyDoc_STRVAR(setdefaulttimeout_doc, + "setdefaulttimeout(timeout)\n\ + \n\ +-Set the default timeout in floating seconds for new socket objects.\n\ ++Set the default timeout in seconds (float) for new socket objects.\n\ + A value of None indicates that new socket objects have no timeout.\n\ + When the socket module is first imported, the default is None."); + +diff -r 8527427914a2 Modules/threadmodule.c +--- a/Modules/threadmodule.c ++++ b/Modules/threadmodule.c +@@ -715,7 +715,7 @@ + + PyDoc_STRVAR(exit_doc, + "exit()\n\ +-(PyThread_exit_thread() is an obsolete synonym)\n\ ++(exit_thread() is an obsolete synonym)\n\ + \n\ + This is synonymous to ``raise SystemExit''. It will cause the current\n\ + thread to exit silently unless the exception is caught."); +diff -r 8527427914a2 Modules/unicodedata.c +--- a/Modules/unicodedata.c ++++ b/Modules/unicodedata.c +@@ -830,7 +830,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; +@@ -978,7 +978,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'; +diff -r 8527427914a2 Modules/zlibmodule.c +--- a/Modules/zlibmodule.c ++++ b/Modules/zlibmodule.c +@@ -72,7 +72,13 @@ + static void + zlib_error(z_stream zst, int err, char *msg) + { +- const char *zmsg = zst.msg; ++ const char *zmsg = Z_NULL; ++ /* In case of a version mismatch, zst.msg won't be initialized. ++ Check for this case first, before looking at zst.msg. */ ++ if (err == Z_VERSION_ERROR) ++ zmsg = "library version mismatch"; ++ if (zmsg == Z_NULL) ++ zmsg = zst.msg; + if (zmsg == Z_NULL) { + switch (err) { + case Z_BUF_ERROR: +diff -r 8527427914a2 Objects/abstract.c +--- a/Objects/abstract.c ++++ b/Objects/abstract.c +@@ -156,7 +156,7 @@ + "be integer, not '%.200s'", key); + } + +- return type_error("'%.200s' object is not subscriptable", o); ++ return type_error("'%.200s' object has no attribute '__getitem__'", o); + } + + int +diff -r 8527427914a2 Objects/bytearrayobject.c +--- a/Objects/bytearrayobject.c ++++ b/Objects/bytearrayobject.c +@@ -1170,7 +1170,7 @@ + "B.find(sub [,start [,end]]) -> int\n\ + \n\ + Return the lowest index in B where subsection sub is found,\n\ +-such that sub is contained within s[start,end]. Optional\n\ ++such that sub is contained within B[start,end]. Optional\n\ + arguments start and end are interpreted as in slice notation.\n\ + \n\ + Return -1 on failure."); +@@ -1240,7 +1240,7 @@ + "B.rfind(sub [,start [,end]]) -> int\n\ + \n\ + Return the highest index in B where subsection sub is found,\n\ +-such that sub is contained within s[start,end]. Optional\n\ ++such that sub is contained within B[start,end]. Optional\n\ + arguments start and end are interpreted as in slice notation.\n\ + \n\ + Return -1 on failure."); +diff -r 8527427914a2 Objects/classobject.c +--- a/Objects/classobject.c ++++ b/Objects/classobject.c +@@ -1221,7 +1221,7 @@ + if (func == NULL) + return -1; + if (item == NULL) +- arg = PyInt_FromSsize_t(i); ++ arg = Py_BuildValue("(n)", i); + else + arg = Py_BuildValue("(nO)", i, item); + if (arg == NULL) { +diff -r 8527427914a2 Objects/descrobject.c +--- a/Objects/descrobject.c ++++ b/Objects/descrobject.c +@@ -801,6 +801,20 @@ + return PyObject_Str(pp->dict); + } + ++static PyObject * ++proxy_repr(proxyobject *pp) ++{ ++ PyObject *dictrepr; ++ PyObject *result; ++ ++ dictrepr = PyObject_Repr(pp->dict); ++ if (dictrepr == NULL) ++ return NULL; ++ result = PyString_FromFormat("dict_proxy(%s)", PyString_AS_STRING(dictrepr)); ++ Py_DECREF(dictrepr); ++ return result; ++} ++ + static int + proxy_traverse(PyObject *self, visitproc visit, void *arg) + { +@@ -832,7 +846,7 @@ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + (cmpfunc)proxy_compare, /* tp_compare */ +- 0, /* tp_repr */ ++ (reprfunc)proxy_repr, /* tp_repr */ + 0, /* tp_as_number */ + &proxy_as_sequence, /* tp_as_sequence */ + &proxy_as_mapping, /* tp_as_mapping */ +diff -r 8527427914a2 Objects/dictobject.c +--- a/Objects/dictobject.c ++++ b/Objects/dictobject.c +@@ -1335,14 +1335,18 @@ + PyObject *key; + long 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; + } +@@ -1353,14 +1357,18 @@ + PyObject *key; + long 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; + } +@@ -2159,9 +2167,9 @@ + "D.values() -> list of D's values"); + + 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 8527427914a2 Objects/exceptions.c +--- a/Objects/exceptions.c ++++ b/Objects/exceptions.c +@@ -306,7 +306,8 @@ + return -1; + } + seq = PySequence_Tuple(val); +- if (!seq) return -1; ++ if (!seq) ++ return -1; + Py_CLEAR(self->args); + self->args = seq; + return 0; +@@ -773,7 +774,8 @@ + * file name given to EnvironmentError. */ + if (PyTuple_GET_SIZE(args) == 2 && self->filename) { + args = PyTuple_New(3); +- if (!args) return NULL; ++ if (!args) ++ return NULL; + + tmp = PyTuple_GET_ITEM(self->args, 0); + Py_INCREF(tmp); +@@ -1071,7 +1073,8 @@ + if (lenargs == 2) { + info = PyTuple_GET_ITEM(args, 1); + info = PySequence_Tuple(info); +- if (!info) return -1; ++ if (!info) ++ return -1; + + if (PyTuple_GET_SIZE(info) != 4) { + /* not a very good error message, but it's what Python 2.4 gives */ +@@ -1167,9 +1170,11 @@ + str = PyObject_Str(self->msg); + else + str = PyObject_Str(Py_None); +- if (!str) return NULL; ++ if (!str) ++ return NULL; + /* Don't fiddle with non-string return (shouldn't happen anyway) */ +- if (!PyString_Check(str)) return str; ++ if (!PyString_Check(str)) ++ return str; + + /* XXX -- do all the additional formatting with filename and + lineno here */ +@@ -2111,7 +2116,8 @@ + + m = Py_InitModule4("exceptions", functions, exceptions_doc, + (PyObject *)NULL, PYTHON_API_VERSION); +- if (m == NULL) return; ++ if (m == NULL) ++ return; + + bltinmod = PyImport_ImportModule("__builtin__"); + if (bltinmod == NULL) +@@ -2203,7 +2209,6 @@ + Py_FatalError("init of pre-allocated RuntimeError failed"); + Py_DECREF(args_tuple); + } +- + Py_DECREF(bltinmod); + } + +diff -r 8527427914a2 Objects/fileobject.c +--- a/Objects/fileobject.c ++++ b/Objects/fileobject.c +@@ -468,28 +468,34 @@ + PyObject * + PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *)) + { +- PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, +- NULL, NULL); +- if (f != NULL) { +- PyObject *o_name = PyString_FromString(name); +- if (o_name == NULL) +- return NULL; +- if (fill_file_fields(f, fp, o_name, mode, close) == NULL) { +- Py_DECREF(f); +- f = NULL; +- } ++ PyFileObject *f; ++ PyObject *o_name; ++ ++ f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL); ++ if (f == NULL) ++ return NULL; ++ o_name = PyString_FromString(name); ++ if (o_name == NULL) { ++ if (close != NULL && fp != NULL) ++ close(fp); ++ Py_DECREF(f); ++ return NULL; ++ } ++ if (fill_file_fields(f, fp, o_name, mode, close) == NULL) { ++ Py_DECREF(f); + Py_DECREF(o_name); ++ return NULL; + } +- return (PyObject *) f; ++ Py_DECREF(o_name); ++ return (PyObject *)f; + } + + PyObject * + PyFile_FromString(char *name, char *mode) + { +- extern int fclose(FILE *); + PyFileObject *f; + +- f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose); ++ f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, NULL); + if (f != NULL) { + if (open_the_file(f, name, mode) == NULL) { + Py_DECREF(f); +@@ -986,12 +992,6 @@ + #define SMALLCHUNK BUFSIZ + #endif + +-#if SIZEOF_INT < 4 +-#define BIGCHUNK (512 * 32) +-#else +-#define BIGCHUNK (512 * 1024) +-#endif +- + static size_t + new_buffersize(PyFileObject *f, size_t currentsize) + { +@@ -1020,15 +1020,10 @@ + /* Add 1 so if the file were to grow we'd notice. */ + } + #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; + } + + #if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN +diff -r 8527427914a2 Objects/floatobject.c +--- a/Objects/floatobject.c ++++ b/Objects/floatobject.c +@@ -1086,6 +1086,7 @@ + char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; + int decpt, sign, val, halfway_case; + PyObject *result = NULL; ++ _Py_SET_53BIT_PRECISION_HEADER; + + /* The basic idea is very simple: convert and round the double to a + decimal string using _Py_dg_dtoa, then convert that decimal string +@@ -1142,7 +1143,9 @@ + halfway_case = 0; + + /* round to a decimal string; use an extra place for halfway case */ ++ _Py_SET_53BIT_PRECISION_START; + buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end); ++ _Py_SET_53BIT_PRECISION_END; + if (buf == NULL) { + PyErr_NoMemory(); + return NULL; +@@ -1186,7 +1189,9 @@ + + /* and convert the resulting string back to a double */ + errno = 0; ++ _Py_SET_53BIT_PRECISION_START; + rounded = _Py_dg_strtod(mybuf, NULL); ++ _Py_SET_53BIT_PRECISION_END; + if (errno == ERANGE && fabs(rounded) >= 1.) + PyErr_SetString(PyExc_OverflowError, + "rounded value too large to represent"); +diff -r 8527427914a2 Objects/intobject.c +--- a/Objects/intobject.c ++++ b/Objects/intobject.c +@@ -751,7 +751,13 @@ + while (iw > 0) { + prev = ix; /* Save value for overflow check */ + if (iw & 1) { +- ix = ix*temp; ++ /* ++ * The (unsigned long) cast below ensures that the multiplication ++ * is interpreted as an unsigned operation rather than a signed one ++ * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour ++ * from signed arithmetic overflow (C99 6.5p5). See issue #12973. ++ */ ++ ix = (unsigned long)ix * temp; + if (temp == 0) + break; /* Avoid ix / 0 */ + if (ix / temp != prev) { +@@ -764,7 +770,7 @@ + iw >>= 1; /* Shift exponent down by 1 bit */ + if (iw==0) break; + prev = temp; +- temp *= temp; /* Square the value of temp */ ++ temp = (unsigned long)temp * temp; /* Square the value of temp */ + if (prev != 0 && temp / prev != prev) { + return PyLong_Type.tp_as_number->nb_power( + (PyObject *)v, (PyObject *)w, (PyObject *)z); +diff -r 8527427914a2 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; +@@ -551,9 +551,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 8527427914a2 Objects/setobject.c +--- a/Objects/setobject.c ++++ b/Objects/setobject.c +@@ -1871,7 +1871,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; +@@ -1925,7 +1925,7 @@ + static PyObject * + set_discard(PySetObject *so, PyObject *key) + { +- PyObject *tmpkey, *result; ++ PyObject *tmpkey; + int rv; + + rv = set_discard_key(so, key); +@@ -1936,9 +1936,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 8527427914a2 Objects/stringobject.c +--- a/Objects/stringobject.c ++++ b/Objects/stringobject.c +@@ -1727,7 +1727,7 @@ + "S.find(sub [,start [,end]]) -> int\n\ + \n\ + Return the lowest index in S where substring sub is found,\n\ +-such that sub is contained within s[start:end]. Optional\n\ ++such that sub is contained within S[start:end]. Optional\n\ + arguments start and end are interpreted as in slice notation.\n\ + \n\ + Return -1 on failure."); +@@ -1766,7 +1766,7 @@ + "S.rfind(sub [,start [,end]]) -> int\n\ + \n\ + Return the highest index in S where substring sub is found,\n\ +-such that sub is contained within s[start:end]. Optional\n\ ++such that sub is contained within S[start:end]. Optional\n\ + arguments start and end are interpreted as in slice notation.\n\ + \n\ + Return -1 on failure."); +@@ -2173,7 +2173,9 @@ + Return a copy of the string S, where all characters occurring\n\ + in the optional argument deletechars are removed, and the\n\ + remaining characters have been mapped through the given\n\ +-translation table, which must be a string of length 256."); ++translation table, which must be a string of length 256 or None.\n\ ++If the table argument is None, no translation is applied and\n\ ++the operation simply removes the characters in deletechars."); + + static PyObject * + string_translate(PyStringObject *self, PyObject *args) +diff -r 8527427914a2 Objects/structseq.c +--- a/Objects/structseq.c ++++ b/Objects/structseq.c +@@ -175,32 +175,33 @@ + if (min_len != max_len) { + if (len < min_len) { + PyErr_Format(PyExc_TypeError, +- "%.500s() takes an at least %zd-sequence (%zd-sequence given)", +- type->tp_name, min_len, len); +- Py_DECREF(arg); +- return NULL; ++ "%.500s() takes an at least %zd-sequence (%zd-sequence given)", ++ type->tp_name, min_len, len); ++ Py_DECREF(arg); ++ return NULL; + } + + if (len > max_len) { + PyErr_Format(PyExc_TypeError, +- "%.500s() takes an at most %zd-sequence (%zd-sequence given)", +- type->tp_name, max_len, len); +- Py_DECREF(arg); +- return NULL; ++ "%.500s() takes an at most %zd-sequence (%zd-sequence given)", ++ type->tp_name, max_len, len); ++ Py_DECREF(arg); ++ return NULL; + } + } + else { + if (len != min_len) { + PyErr_Format(PyExc_TypeError, +- "%.500s() takes a %zd-sequence (%zd-sequence given)", +- type->tp_name, min_len, len); +- Py_DECREF(arg); +- return NULL; ++ "%.500s() takes a %zd-sequence (%zd-sequence given)", ++ type->tp_name, min_len, len); ++ Py_DECREF(arg); ++ return NULL; + } + } + + res = (PyStructSequence*) PyStructSequence_New(type); + if (res == NULL) { ++ Py_DECREF(arg); + return NULL; + } + for (i = 0; i < len; ++i) { +diff -r 8527427914a2 Objects/typeobject.c +--- a/Objects/typeobject.c ++++ b/Objects/typeobject.c +@@ -2233,8 +2233,10 @@ + (add_weak && strcmp(s, "__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++; + } +@@ -2703,15 +2705,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. + +@@ -2728,6 +2731,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; +@@ -2978,7 +2984,7 @@ + unaryfunc f; + + f = Py_TYPE(self)->tp_repr; +- if (f == NULL) ++ if (f == NULL || f == object_str) + f = object_repr; + return f(self); + } +@@ -5933,27 +5939,27 @@ + 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("__idiv__", nb_inplace_divide, slot_nb_inplace_divide, +- 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 8527427914a2 Objects/unicodeobject.c +--- a/Objects/unicodeobject.c ++++ b/Objects/unicodeobject.c +@@ -1628,21 +1628,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; + } +@@ -1652,8 +1648,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) { +@@ -5164,11 +5160,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 +@@ -5485,13 +5480,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; + } +@@ -6491,7 +6486,7 @@ + "S.find(sub [,start [,end]]) -> int\n\ + \n\ + Return the lowest index in S where substring sub is found,\n\ +-such that sub is contained within s[start:end]. Optional\n\ ++such that sub is contained within S[start:end]. Optional\n\ + arguments start and end are interpreted as in slice notation.\n\ + \n\ + Return -1 on failure."); +@@ -7226,7 +7221,7 @@ + "S.rfind(sub [,start [,end]]) -> int\n\ + \n\ + Return the highest index in S where substring sub is found,\n\ +-such that sub is contained within s[start:end]. Optional\n\ ++such that sub is contained within S[start:end]. Optional\n\ + arguments start and end are interpreted as in slice notation.\n\ + \n\ + Return -1 on failure."); +diff -r 8527427914a2 PC/pyconfig.h +--- a/PC/pyconfig.h ++++ b/PC/pyconfig.h +@@ -643,6 +643,9 @@ + #define HAVE_WCSCOLL 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 8527427914a2 Parser/asdl_c.py +--- a/Parser/asdl_c.py ++++ b/Parser/asdl_c.py +@@ -800,8 +800,25 @@ + return 0; + } + +-#define obj2ast_identifier obj2ast_object +-#define obj2ast_string obj2ast_object ++static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena) ++{ ++ if (!PyString_CheckExact(obj) && obj != Py_None) { ++ PyErr_Format(PyExc_TypeError, ++ "AST identifier must be of type str"); ++ return 1; ++ } ++ return obj2ast_object(obj, out, arena); ++} ++ ++static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena) ++{ ++ if (!PyString_CheckExact(obj) && !PyUnicode_CheckExact(obj)) { ++ PyErr_SetString(PyExc_TypeError, ++ "AST string must be of type str or unicode"); ++ return 1; ++ } ++ return obj2ast_object(obj, out, arena); ++} + + static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) + { +@@ -903,9 +920,6 @@ + self.emit("if (!%s_singleton) return 0;" % cons.name, 1) + + +-def parse_version(mod): +- return mod.version.value[12:-3] +- + class ASTModuleVisitor(PickleVisitor): + + def visitModule(self, mod): +@@ -922,7 +936,7 @@ + self.emit("return;", 2) + # Value of version: "$Revision$" + self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' +- % parse_version(mod), 1) ++ % mod.version, 1) + self.emit("return;", 2) + for dfn in mod.dfns: + self.visit(dfn) +@@ -1160,6 +1174,7 @@ + argv0 = os.sep.join(components[-2:]) + auto_gen_msg = common_msg % argv0 + mod = asdl.parse(srcfile) ++ mod.version = "82160" + if not asdl.check(mod): + sys.exit(1) + if INC_DIR: +@@ -1181,7 +1196,7 @@ + p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") + f = open(p, "wb") + f.write(auto_gen_msg) +- f.write(c_file_msg % parse_version(mod)) ++ f.write(c_file_msg % mod.version) + f.write('#include "Python.h"\n') + f.write('#include "%s-ast.h"\n' % mod.name) + f.write('\n') +diff -r 8527427914a2 Parser/myreadline.c +--- a/Parser/myreadline.c ++++ b/Parser/myreadline.c +@@ -44,6 +44,7 @@ + if (PyOS_InputHook != NULL) + (void)(PyOS_InputHook)(); + errno = 0; ++ clearerr(fp); + p = fgets(buf, len, fp); + if (p != NULL) + return 0; /* No error */ +diff -r 8527427914a2 Python/Python-ast.c +--- a/Python/Python-ast.c ++++ b/Python/Python-ast.c +@@ -594,8 +594,25 @@ + return 0; + } + +-#define obj2ast_identifier obj2ast_object +-#define obj2ast_string obj2ast_object ++static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena) ++{ ++ if (!PyString_CheckExact(obj) && obj != Py_None) { ++ PyErr_Format(PyExc_TypeError, ++ "AST identifier must be of type str"); ++ return 1; ++ } ++ return obj2ast_object(obj, out, arena); ++} ++ ++static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena) ++{ ++ if (!PyString_CheckExact(obj) && !PyUnicode_CheckExact(obj)) { ++ PyErr_SetString(PyExc_TypeError, ++ "AST string must be of type str or unicode"); ++ return 1; ++ } ++ return obj2ast_object(obj, out, arena); ++} + + static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) + { +diff -r 8527427914a2 Python/_warnings.c +--- a/Python/_warnings.c ++++ b/Python/_warnings.c +@@ -491,7 +491,7 @@ + + /* Setup filename. */ + *filename = PyDict_GetItemString(globals, "__file__"); +- if (*filename != NULL) { ++ if (*filename != NULL && PyString_Check(*filename)) { + Py_ssize_t len = PyString_Size(*filename); + const char *file_str = PyString_AsString(*filename); + if (file_str == NULL || (len < 0 && PyErr_Occurred())) +@@ -514,6 +514,7 @@ + } + else { + const char *module_str = PyString_AsString(*module); ++ *filename = NULL; + if (module_str && strcmp(module_str, "__main__") == 0) { + PyObject *argv = PySys_GetObject("argv"); + if (argv != NULL && PyList_Size(argv) > 0) { +diff -r 8527427914a2 Python/bltinmodule.c +--- a/Python/bltinmodule.c ++++ b/Python/bltinmodule.c +@@ -224,9 +224,6 @@ + static PyObject * + builtin_callable(PyObject *self, PyObject *v) + { +- if (PyErr_WarnPy3k("callable() not supported in 3.x; " +- "use isinstance(x, collections.Callable)", 1) < 0) +- return NULL; + return PyBool_FromLong((long)PyCallable_Check(v)); + } + +@@ -604,7 +601,7 @@ + } + + PyDoc_STRVAR(divmod_doc, +-"divmod(x, y) -> (div, mod)\n\ ++"divmod(x, y) -> (quotient, remainder)\n\ + \n\ + Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x."); + +diff -r 8527427914a2 Python/ceval.c +--- a/Python/ceval.c ++++ b/Python/ceval.c +@@ -3515,9 +3515,17 @@ + Py_DECREF(tmp); + } + +- if (PyExceptionClass_Check(type)) ++ if (PyExceptionClass_Check(type)) { + PyErr_NormalizeException(&type, &value, &tb); +- ++ if (!PyExceptionInstance_Check(value)) { ++ PyErr_Format(PyExc_TypeError, ++ "calling %s() should have returned an instance of " ++ "BaseException, not '%s'", ++ ((PyTypeObject *)type)->tp_name, ++ Py_TYPE(value)->tp_name); ++ goto raise_error; ++ } ++ } + else if (PyExceptionInstance_Check(type)) { + /* Raising an instance. The value should be a dummy. */ + if (value != Py_None) { +diff -r 8527427914a2 Python/codecs.c +--- a/Python/codecs.c ++++ b/Python/codecs.c +@@ -70,7 +70,7 @@ + if (ch == ' ') + ch = '-'; + else +- ch = tolower(Py_CHARMASK(ch)); ++ ch = Py_TOLOWER(Py_CHARMASK(ch)); + p[i] = ch; + } + return v; +diff -r 8527427914a2 Python/compile.c +--- a/Python/compile.c ++++ b/Python/compile.c +@@ -2079,11 +2079,9 @@ + ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); + if (s->v.Assert.msg) { + VISIT(c, expr, s->v.Assert.msg); +- ADDOP_I(c, RAISE_VARARGS, 2); ++ ADDOP_I(c, CALL_FUNCTION, 1); + } +- else { +- ADDOP_I(c, RAISE_VARARGS, 1); +- } ++ ADDOP_I(c, RAISE_VARARGS, 1); + compiler_use_next_block(c, end); + return 1; + } +diff -r 8527427914a2 Python/errors.c +--- a/Python/errors.c ++++ b/Python/errors.c +@@ -111,9 +111,11 @@ + PyErr_Fetch(&exception, &value, &tb); + /* Temporarily bump the recursion limit, so that in the most + common case PyObject_IsSubclass will not raise a recursion +- error we have to ignore anyway. */ ++ error we have to ignore anyway. Don't do it when the limit ++ is already insanely high, to avoid overflow */ + reclimit = Py_GetRecursionLimit(); +- Py_SetRecursionLimit(reclimit + 5); ++ if (reclimit < (1 << 30)) ++ Py_SetRecursionLimit(reclimit + 5); + res = PyObject_IsSubclass(err, exc); + Py_SetRecursionLimit(reclimit); + /* This function must not fail, so print the error here */ +diff -r 8527427914a2 Python/getcopyright.c +--- a/Python/getcopyright.c ++++ b/Python/getcopyright.c +@@ -4,7 +4,7 @@ + + static char cprt[] = + "\ +-Copyright (c) 2001-2011 Python Software Foundation.\n\ ++Copyright (c) 2001-2012 Python Software Foundation.\n\ + All Rights Reserved.\n\ + \n\ + Copyright (c) 2000 BeOpen.com.\n\ +diff -r 8527427914a2 Python/import.c +--- a/Python/import.c ++++ b/Python/import.c +@@ -905,9 +905,9 @@ + (void) unlink(cpathname); + return; + } +- /* Now write the true mtime */ ++ /* Now write the true mtime (as a 32-bit field) */ + fseek(fp, 4L, 0); +- assert(mtime < LONG_MAX); ++ assert(mtime <= 0xFFFFFFFF); + PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION); + fflush(fp); + fclose(fp); +@@ -979,17 +979,14 @@ + pathname); + return NULL; + } +-#if SIZEOF_TIME_T > 4 +- /* Python's .pyc timestamp handling presumes that the timestamp fits +- in 4 bytes. This will be fine until sometime in the year 2038, +- when a 4-byte signed time_t will overflow. +- */ +- if (st.st_mtime >> 32) { +- PyErr_SetString(PyExc_OverflowError, +- "modification time overflows a 4 byte field"); +- return NULL; ++ if (sizeof st.st_mtime > 4) { ++ /* Python's .pyc timestamp handling presumes that the timestamp fits ++ in 4 bytes. Since the code only does an equality comparison, ++ ordering is not important and we can safely ignore the higher bits ++ (collisions are extremely unlikely). ++ */ ++ st.st_mtime &= 0xFFFFFFFF; + } +-#endif + cpathname = make_compiled_pathname(pathname, buf, + (size_t)MAXPATHLEN + 1); + if (cpathname != NULL && +@@ -1235,7 +1232,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; +@@ -1304,14 +1301,14 @@ + path = PySys_GetObject("path"); + } + 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; +@@ -1319,7 +1316,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; + } +@@ -2064,7 +2061,9 @@ + { + PyObject *result; + PyObject *modules; ++#ifdef WITH_THREAD + long me; ++#endif + + /* Try to get the module from sys.modules[name] */ + modules = PyImport_GetModuleDict(); +@@ -2843,10 +2842,8 @@ + return NULL; + if (fp != NULL) { + fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose); +- if (fob == NULL) { +- fclose(fp); ++ if (fob == NULL) + return NULL; +- } + } + else { + fob = Py_None; +diff -r 8527427914a2 Python/pystate.c +--- a/Python/pystate.c ++++ b/Python/pystate.c +@@ -537,23 +537,6 @@ + autoInterpreterState = NULL; + } + +-/* 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. +- */ +-void +-_PyGILState_Reinit(void) +-{ +- PyThreadState *tstate = PyGILState_GetThisThreadState(); +- PyThread_delete_key(autoTLSkey); +- 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) +- Py_FatalError("Couldn't create autoTLSkey mapping"); +-} +- + /* When a thread state is created for a thread by some mechanism other than + PyGILState_Ensure, it's important that the GILState machinery knows about + it so it doesn't try to create another thread state for the thread (this is +diff -r 8527427914a2 Python/sysmodule.c +--- a/Python/sysmodule.c ++++ b/Python/sysmodule.c +@@ -466,6 +466,7 @@ + { + if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval)) + return NULL; ++ _Py_Ticker = _Py_CheckInterval; + Py_INCREF(Py_None); + return Py_None; + } +@@ -1092,7 +1093,7 @@ + hexversion -- version information encoded as a single integer\n\ + copyright -- copyright notice pertaining to this interpreter\n\ + platform -- platform identifier\n\ +-executable -- pathname of this Python interpreter\n\ ++executable -- absolute path of the executable binary of the Python interpreter\n\ + prefix -- prefix used to find the Python library\n\ + exec_prefix -- prefix used to find the machine-specific Python library\n\ + float_repr_style -- string indicating the style of repr() output for floats\n\ +diff -r 8527427914a2 README +--- a/README ++++ b/README +@@ -1,8 +1,8 @@ + This is Python version 2.7.2 + ============================ + +-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 +-Python Software Foundation. All rights reserved. ++Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, ++2012 Python Software Foundation. All rights reserved. + + Copyright (c) 2000 BeOpen.com. + All rights reserved. +diff -r 8527427914a2 Tools/gdb/libpython.py +--- a/Tools/gdb/libpython.py ++++ b/Tools/gdb/libpython.py +@@ -47,7 +47,6 @@ + _type_char_ptr = gdb.lookup_type('char').pointer() # char* + _type_unsigned_char_ptr = gdb.lookup_type('unsigned char').pointer() # unsigned char* + _type_void_ptr = gdb.lookup_type('void').pointer() # void* +-_type_size_t = gdb.lookup_type('size_t') + + SIZEOF_VOID_P = _type_void_ptr.sizeof + +@@ -410,11 +409,15 @@ + self.address) + + def _PyObject_VAR_SIZE(typeobj, nitems): ++ if _PyObject_VAR_SIZE._type_size_t is None: ++ _PyObject_VAR_SIZE._type_size_t = gdb.lookup_type('size_t') ++ + return ( ( typeobj.field('tp_basicsize') + + nitems * typeobj.field('tp_itemsize') + + (SIZEOF_VOID_P - 1) + ) & ~(SIZEOF_VOID_P - 1) +- ).cast(_type_size_t) ++ ).cast(_PyObject_VAR_SIZE._type_size_t) ++_PyObject_VAR_SIZE._type_size_t = None + + class HeapTypeObjectPtr(PyObjectPtr): + _typename = 'PyObject' +@@ -786,7 +789,7 @@ + class PyFrameObjectPtr(PyObjectPtr): + _typename = 'PyFrameObject' + +- def __init__(self, gdbval, cast_to): ++ def __init__(self, gdbval, cast_to=None): + PyObjectPtr.__init__(self, gdbval, cast_to) + + if not self.is_optimized_out(): +@@ -820,7 +823,7 @@ + the global variables of this frame + ''' + if self.is_optimized_out(): +- return ++ return () + + pyop_globals = self.pyop_field('f_globals') + return pyop_globals.iteritems() +@@ -831,7 +834,7 @@ + the builtin variables + ''' + if self.is_optimized_out(): +- return ++ return () + + pyop_builtins = self.pyop_field('f_builtins') + return pyop_builtins.iteritems() +@@ -1205,7 +1208,20 @@ + def get_pyop(self): + try: + f = self._gdbframe.read_var('f') +- return PyFrameObjectPtr.from_pyobject_ptr(f) ++ frame = PyFrameObjectPtr.from_pyobject_ptr(f) ++ if not frame.is_optimized_out(): ++ return frame ++ # gdb is unable to get the "f" argument of PyEval_EvalFrameEx() ++ # because it was "optimized out". Try to get "f" from the frame ++ # of the caller, PyEval_EvalCodeEx(). ++ orig_frame = frame ++ caller = self._gdbframe.older() ++ if caller: ++ f = caller.read_var('f') ++ frame = PyFrameObjectPtr.from_pyobject_ptr(f) ++ if not frame.is_optimized_out(): ++ return frame ++ return orig_frame + except ValueError: + return None + +@@ -1235,7 +1251,9 @@ + pyop = self.get_pyop() + if pyop: + sys.stdout.write('#%i %s\n' % (self.get_index(), pyop.get_truncated_repr(MAX_OUTPUT_LEN))) +- sys.stdout.write(pyop.current_line()) ++ if not pyop.is_optimized_out(): ++ line = pyop.current_line() ++ sys.stdout.write(' %s\n' % line.strip()) + else: + sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index()) + else: +@@ -1281,7 +1299,7 @@ + return + + pyop = frame.get_pyop() +- if not pyop: ++ if not pyop or pyop.is_optimized_out(): + print 'Unable to read information on python frame' + return + +diff -r 8527427914a2 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 8527427914a2 Tools/scripts/analyze_dxp.py +--- a/Tools/scripts/analyze_dxp.py ++++ b/Tools/scripts/analyze_dxp.py +@@ -1,3 +1,4 @@ ++#!/usr/bin/env python + """ + Some helper functions to analyze the output of sys.getdxp() (which is + only available if Python was built with -DDYNAMIC_EXECUTION_PROFILE). +diff -r 8527427914a2 Tools/scripts/byext.py +--- a/Tools/scripts/byext.py ++++ b/Tools/scripts/byext.py +@@ -23,12 +23,11 @@ + def statdir(self, dir): + self.addstats("", "dirs", 1) + try: +- names = os.listdir(dir) +- except os.error, err: ++ names = sorted(os.listdir(dir)) ++ except os.error as err: + sys.stderr.write("Can't list %s: %s\n" % (dir, err)) + self.addstats("", "unlistable", 1) + return +- names.sort() + for name in names: + if name.startswith(".#"): + continue # Skip CVS temp files +@@ -53,14 +52,14 @@ + self.addstats(ext, "files", 1) + try: + f = open(filename, "rb") +- except IOError, err: ++ except IOError as err: + sys.stderr.write("Can't open %s: %s\n" % (filename, err)) + self.addstats(ext, "unopenable", 1) + return + data = f.read() + f.close() + self.addstats(ext, "bytes", len(data)) +- if '\0' in data: ++ if b'\0' in data: + self.addstats(ext, "binary", 1) + return + if not data: +@@ -77,14 +76,12 @@ + d[key] = d.get(key, 0) + n + + def report(self): +- exts = self.stats.keys() +- exts.sort() ++ exts = sorted(self.stats.keys()) + # Get the column keys + columns = {} + for ext in exts: + columns.update(self.stats[ext]) +- cols = columns.keys() +- cols.sort() ++ cols = sorted(columns.keys()) + colwidth = {} + colwidth["ext"] = max([len(ext) for ext in exts]) + minwidth = 6 +@@ -109,14 +106,14 @@ + cols.insert(0, "ext") + def printheader(): + for col in cols: +- print "%*s" % (colwidth[col], col), +- print ++ print("%*s" % (colwidth[col], col), end=" ") ++ print() + printheader() + for ext in exts: + for col in cols: + value = self.stats[ext].get(col, "") +- print "%*s" % (colwidth[col], value), +- print ++ print("%*s" % (colwidth[col], value), end=" ") ++ print() + printheader() # Another header at the bottom + + def main(): +diff -r 8527427914a2 Tools/scripts/diff.py +--- a/Tools/scripts/diff.py ++++ b/Tools/scripts/diff.py +@@ -1,3 +1,4 @@ ++#!/usr/bin/env python + """ Command line interface to difflib.py providing diffs in four formats: + + * ndiff: lists every line and highlights interline changes. +diff -r 8527427914a2 Tools/scripts/mailerdaemon.py +--- a/Tools/scripts/mailerdaemon.py ++++ b/Tools/scripts/mailerdaemon.py +@@ -1,3 +1,4 @@ ++#!/usr/bin/env python + """mailerdaemon - classes to parse mailer-daemon messages""" + + import rfc822 +diff -r 8527427914a2 Tools/scripts/patchcheck.py +--- a/Tools/scripts/patchcheck.py ++++ b/Tools/scripts/patchcheck.py +@@ -1,13 +1,18 @@ ++#!/usr/bin/env python + import re + import sys + import shutil + import os.path + import subprocess ++import sysconfig + + import reindent + import untabify + + ++SRCDIR = sysconfig.get_config_var('srcdir') ++ ++ + def n_files_str(count): + """Return 'N file(s)' with the proper plurality on 'file'.""" + return "{} file{}".format(count, "s" if count != 1 else "") +@@ -35,7 +40,7 @@ + info=lambda x: n_files_str(len(x))) + def changed_files(): + """Get the list of changed or added files from the VCS.""" +- if os.path.isdir('.hg'): ++ if os.path.isdir(os.path.join(SRCDIR, '.hg')): + vcs = 'hg' + cmd = 'hg status --added --modified --no-status' + elif os.path.isdir('.svn'): +@@ -74,7 +79,7 @@ + reindent.makebackup = False # No need to create backups. + fixed = [] + for path in (x for x in file_paths if x.endswith('.py')): +- if reindent.check(path): ++ if reindent.check(os.path.join(SRCDIR, path)): + fixed.append(path) + return fixed + +@@ -84,10 +89,11 @@ + """Report if any C files """ + fixed = [] + for path in file_paths: +- with open(path, 'r') as f: ++ abspath = os.path.join(SRCDIR, path) ++ with open(abspath, 'r') as f: + if '\t' not in f.read(): + continue +- untabify.process(path, 8, verbose=False) ++ untabify.process(abspath, 8, verbose=False) + fixed.append(path) + return fixed + +@@ -98,13 +104,14 @@ + def normalize_docs_whitespace(file_paths): + fixed = [] + for path in file_paths: ++ abspath = os.path.join(SRCDIR, path) + try: +- with open(path, 'rb') as f: ++ with open(abspath, 'rb') as f: + lines = f.readlines() + new_lines = [ws_re.sub(br'\1', line) for line in lines] + if new_lines != lines: +- shutil.copyfile(path, path + '.bak') +- with open(path, 'wb') as f: ++ shutil.copyfile(abspath, abspath + '.bak') ++ with open(abspath, 'wb') as f: + f.writelines(new_lines) + fixed.append(path) + except Exception as err: +@@ -150,8 +157,9 @@ + reported_news(special_files) + + # Test suite run and passed. +- print +- print "Did you run the test suite?" ++ if python_files or c_files: ++ print ++ print "Did you run the test suite?" + + + if __name__ == '__main__': +diff -r 8527427914a2 Tools/scripts/redemo.py +--- a/Tools/scripts/redemo.py ++++ b/Tools/scripts/redemo.py +@@ -1,3 +1,4 @@ ++#!/usr/bin/env python + """Basic regular expression demostration facility (Perl style syntax).""" + + from Tkinter import * +diff -r 8527427914a2 Tools/scripts/reindent.py +--- a/Tools/scripts/reindent.py ++++ b/Tools/scripts/reindent.py +@@ -35,7 +35,7 @@ + + The backup file is a copy of the one that is being reindented. The ".bak" + file is generated with shutil.copy(), but some corner cases regarding +-user/group and permissions could leave the backup file more readable that ++user/group and permissions could leave the backup file more readable than + you'd prefer. You can always use the --nobackup option to prevent this. + """ + +@@ -44,6 +44,7 @@ + import tokenize + import os, shutil + import sys ++import io + + verbose = 0 + recurse = 0 +@@ -108,13 +109,19 @@ + if verbose: + print "checking", file, "...", + try: +- f = open(file) ++ f = io.open(file) + except IOError, msg: + errprint("%s: I/O Error: %s" % (file, str(msg))) + return + + r = Reindenter(f) + f.close() ++ ++ newline = r.newlines ++ if isinstance(newline, tuple): ++ errprint("%s: mixed newlines detected; cannot process file" % file) ++ return ++ + if r.run(): + if verbose: + print "changed." +@@ -126,7 +133,7 @@ + shutil.copyfile(file, bak) + if verbose: + print "backed up", file, "to", bak +- f = open(file, "w") ++ f = io.open(file, "w", newline=newline) + r.write(f) + f.close() + if verbose: +@@ -173,6 +180,10 @@ + # indeed, they're our headache! + self.stats = [] + ++ # Save the newlines found in the file so they can be used to ++ # create output without mutating the newlines. ++ self.newlines = f.newlines ++ + def run(self): + tokenize.tokenize(self.getline, self.tokeneater) + # Remove trailing empty lines. +diff -r 8527427914a2 configure.in +--- a/configure.in ++++ b/configure.in +@@ -293,6 +293,7 @@ + MACHDEP="$ac_md_system$ac_md_release" + + case $MACHDEP in ++ linux*) MACHDEP="linux2";; + cygwin*) MACHDEP="cygwin";; + darwin*) MACHDEP="darwin";; + atheos*) MACHDEP="atheos";; +@@ -317,14 +318,14 @@ + # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. + # In addition, Stefan Krah confirms that issue #1244610 exists through + # OpenBSD 4.6, but is fixed in 4.7. +- OpenBSD/2.* | OpenBSD/3.@<:@0123456789@:>@ | OpenBSD/4.@<:@0123456@:>@) ++ OpenBSD/2.* | OpenBSD/3.* | OpenBSD/4.@<:@0123456@:>@) + define_xopen_source=no + # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is + # also defined. This can be overridden by defining _BSD_SOURCE + # As this has a different meaning on Linux, only define it on OpenBSD + AC_DEFINE(_BSD_SOURCE, 1, [Define on OpenBSD to activate all library features]) + ;; +- OpenBSD/4.@<:@789@:>@) ++ OpenBSD/*) + # OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is + # also defined. This can be overridden by defining _BSD_SOURCE + # As this has a different meaning on Linux, only define it on OpenBSD +@@ -778,7 +779,7 @@ + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; +- Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*) ++ Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*) + LDLIBRARY='libpython$(VERSION).so' + BLDLIBRARY='-L. -lpython$(VERSION)' + RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH} +@@ -931,6 +932,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 +@@ -2359,18 +2367,15 @@ + + # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8. + case $ac_sys_system/$ac_sys_release in +- SunOS/5.6) AC_DEFINE(HAVE_PTHREAD_DESTRUCTOR, 1, ++ SunOS/5.6) AC_DEFINE(HAVE_PTHREAD_DESTRUCTOR, 1, + [Defined for Solaris 2.6 bug in pthread header.]) + ;; + SunOS/5.8) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, + [Define if the Posix semaphores do not work on your system]) + ;; +- AIX/5) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, ++ AIX/*) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, + [Define if the Posix semaphores do not work on your system]) + ;; +- AIX/6) AC_DEFINE(HAVE_BROKEN_POSIX_SEMAPHORES, 1, +- Define if the Posix semaphores do not work on your system) +- ;; + esac + + AC_MSG_CHECKING(if PTHREAD_SCOPE_SYSTEM is supported) +@@ -2827,6 +2832,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) + +@@ -2839,7 +2853,7 @@ + # On Tru64, chflags seems to be present, but calling it will + # exit Python + AC_CACHE_CHECK([for chflags], [ac_cv_have_chflags], [dnl +-AC_RUN_IFELSE([AC_LANG_SOURCE([[[ ++AC_RUN_IFELSE([AC_LANG_SOURCE([[ + #include + #include + int main(int argc, char*argv[]) +@@ -2848,7 +2862,7 @@ + return 1; + return 0; + } +-]]])], ++]])], + [ac_cv_have_chflags=yes], + [ac_cv_have_chflags=no], + [ac_cv_have_chflags=cross]) +@@ -2857,11 +2871,11 @@ + AC_CHECK_FUNC([chflags], [ac_cv_have_chflags="yes"], [ac_cv_have_chflags="no"]) + fi + if test "$ac_cv_have_chflags" = yes ; then +- AC_DEFINE(HAVE_CHFLAGS, 1, [Define to 1 if you have the `chflags' function.]) ++ AC_DEFINE(HAVE_CHFLAGS, 1, [Define to 1 if you have the 'chflags' function.]) + fi + + AC_CACHE_CHECK([for lchflags], [ac_cv_have_lchflags], [dnl +-AC_RUN_IFELSE([AC_LANG_SOURCE([[[ ++AC_RUN_IFELSE([AC_LANG_SOURCE([[ + #include + #include + int main(int argc, char*argv[]) +@@ -2870,13 +2884,13 @@ + return 1; + return 0; + } +-]]])],[ac_cv_have_lchflags=yes],[ac_cv_have_lchflags=no],[ac_cv_have_lchflags=cross]) ++]])],[ac_cv_have_lchflags=yes],[ac_cv_have_lchflags=no],[ac_cv_have_lchflags=cross]) + ]) + if test "$ac_cv_have_lchflags" = cross ; then + AC_CHECK_FUNC([lchflags], [ac_cv_have_lchflags="yes"], [ac_cv_have_lchflags="no"]) + fi + if test "$ac_cv_have_lchflags" = yes ; then +- AC_DEFINE(HAVE_LCHFLAGS, 1, [Define to 1 if you have the `lchflags' function.]) ++ AC_DEFINE(HAVE_LCHFLAGS, 1, [Define to 1 if you have the 'lchflags' function.]) + fi + + dnl Check if system zlib has *Copy() functions +diff -r 8527427914a2 pyconfig.h.in +--- a/pyconfig.h.in ++++ b/pyconfig.h.in +@@ -97,10 +97,13 @@ + /* 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 + +-/* Define to 1 if you have the `chflags' function. */ ++/* Define to 1 if you have the 'chflags' function. */ + #undef HAVE_CHFLAGS + + /* Define to 1 if you have the `chown' function. */ +@@ -391,7 +394,7 @@ + Solaris and Linux, the necessary defines are already defined.) */ + #undef HAVE_LARGEFILE_SUPPORT + +-/* Define to 1 if you have the `lchflags' function. */ ++/* Define to 1 if you have the 'lchflags' function. */ + #undef HAVE_LCHFLAGS + + /* Define to 1 if you have the `lchmod' function. */ +@@ -1137,6 +1140,9 @@ + /* This must be defined on some systems to enable large file support. */ + #undef _LARGEFILE_SOURCE + ++/* This must be defined on AIX systems to enable large file support. */ ++#undef _LARGE_FILES ++ + /* Define to 1 if on MINIX. */ + #undef _MINIX + --- python2.7-2.7.2.orig/debian/patches/enable-fpectl.diff +++ python2.7-2.7.2/debian/patches/enable-fpectl.diff @@ -0,0 +1,14 @@ +# DP: Enable the build of the fpectl module. + +--- a/setup.py ++++ b/setup.py +@@ -1276,6 +1276,9 @@ + else: + missing.append('_curses_panel') + ++ #fpectl fpectlmodule.c ... ++ exts.append( Extension('fpectl', ['fpectlmodule.c']) ) ++ + # Andrew Kuchling's zlib module. Note that some versions of zlib + # 1.1.3 have security problems. See CERT Advisory CA-2002-07: + # http://www.cert.org/advisories/CA-2002-07.html --- python2.7-2.7.2.orig/debian/patches/db5.1.diff +++ python2.7-2.7.2/debian/patches/db5.1.diff @@ -0,0 +1,1768 @@ +Index: b/setup.py +=================================================================== +--- a/setup.py ++++ b/setup.py +@@ -799,7 +799,7 @@ + # a release. Most open source OSes come with one or more + # versions of BerkeleyDB already installed. + +- max_db_ver = (4, 8) ++ max_db_ver = (5, 1) + min_db_ver = (4, 1) + db_setup_debug = False # verbose debug prints from this script? + +@@ -821,7 +821,11 @@ + return True + + def gen_db_minor_ver_nums(major): +- if major == 4: ++ if major == 5: ++ for x in range(max_db_ver[1]+1): ++ if allow_db_ver((5, x)): ++ yield x ++ elif major == 4: + for x in range(max_db_ver[1]+1): + if allow_db_ver((4, x)): + yield x +Index: b/Lib/bsddb/__init__.py +=================================================================== +--- a/Lib/bsddb/__init__.py ++++ b/Lib/bsddb/__init__.py +@@ -33,7 +33,7 @@ + #---------------------------------------------------------------------- + + +-"""Support for Berkeley DB 4.1 through 4.8 with a simple interface. ++"""Support for Berkeley DB 4.2 through 5.1 with a simple interface. + + For the full featured object oriented interface use the bsddb.db module + instead. It mirrors the Oracle Berkeley DB C API. +Index: b/Lib/bsddb/test/test_all.py +=================================================================== +--- a/Lib/bsddb/test/test_all.py ++++ b/Lib/bsddb/test/test_all.py +@@ -484,6 +484,8 @@ + print '-=' * 38 + print db.DB_VERSION_STRING + print 'bsddb.db.version(): %s' % (db.version(), ) ++ if db.version() >= (5, 0) : ++ print 'bsddb.db.full_version(): %s' %repr(db.full_version()) + print 'bsddb.db.__version__: %s' % db.__version__ + print 'bsddb.db.cvsid: %s' % db.cvsid + +@@ -528,7 +530,8 @@ + + # This path can be overriden via "set_test_path_prefix()". + import os, os.path +-get_new_path.prefix=os.path.join(os.sep,"tmp","z-Berkeley_DB") ++get_new_path.prefix=os.path.join(os.environ.get("TMPDIR", ++ os.path.join(os.sep,"tmp")), "z-Berkeley_DB") + get_new_path.num=0 + + def get_test_path_prefix() : +Index: b/Lib/bsddb/test/test_associate.py +=================================================================== +--- a/Lib/bsddb/test/test_associate.py ++++ b/Lib/bsddb/test/test_associate.py +@@ -76,6 +76,11 @@ + #---------------------------------------------------------------------- + + class AssociateErrorTestCase(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + def setUp(self): + self.filename = self.__class__.__name__ + '.db' + self.homeDir = get_new_environment_path() +@@ -120,6 +125,11 @@ + + + class AssociateTestCase(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + keytype = '' + envFlags = 0 + dbFlags = 0 +Index: b/Lib/bsddb/test/test_basics.py +=================================================================== +--- a/Lib/bsddb/test/test_basics.py ++++ b/Lib/bsddb/test/test_basics.py +@@ -74,7 +74,6 @@ + # create and open the DB + self.d = db.DB(self.env) + if not self.useEnv : +- if db.version() >= (4, 2) : + self.d.set_cachesize(*self.cachesize) + cachesize = self.d.get_cachesize() + self.assertEqual(cachesize[0], self.cachesize[0]) +@@ -792,7 +791,6 @@ + for log in logs: + if verbose: + print 'log file: ' + log +- if db.version() >= (4,2): + logs = self.env.log_archive(db.DB_ARCH_REMOVE) + self.assertTrue(not logs) + +@@ -875,7 +873,6 @@ + + #---------------------------------------- + +- if db.version() >= (4, 2) : + def test_get_tx_max(self) : + self.assertEqual(self.env.get_tx_max(), 30) + +Index: b/Lib/bsddb/test/test_compat.py +=================================================================== +--- a/Lib/bsddb/test/test_compat.py ++++ b/Lib/bsddb/test/test_compat.py +@@ -11,6 +11,11 @@ + + + class CompatibilityTestCase(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + def setUp(self): + self.filename = get_new_database_path() + +Index: b/Lib/bsddb/test/test_db.py +=================================================================== +--- a/Lib/bsddb/test/test_db.py ++++ b/Lib/bsddb/test/test_db.py +@@ -11,6 +11,8 @@ + if sys.version_info < (2, 4) : + def assertTrue(self, expr, msg=None): + self.failUnless(expr,msg=msg) ++ def assertFalse(self, expr, msg=None): ++ self.failIf(expr,msg=msg) + + def setUp(self): + self.path = get_new_database_path() +@@ -19,10 +21,28 @@ + def tearDown(self): + self.db.close() + del self.db +- test_support.rmtree(self.path) ++ test_support.unlink(self.path) + + class DB_general(DB) : +- if db.version() >= (4, 2) : ++ def test_get_open_flags(self) : ++ self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE) ++ self.assertEqual(db.DB_CREATE, self.db.get_open_flags()) ++ ++ def test_get_open_flags2(self) : ++ self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE | ++ db.DB_THREAD) ++ self.assertEqual(db.DB_CREATE | db.DB_THREAD, self.db.get_open_flags()) ++ ++ def test_get_dbname_filename(self) : ++ self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE) ++ self.assertEqual((self.path, None), self.db.get_dbname()) ++ ++ def test_get_dbname_filename_database(self) : ++ name = "jcea-random-name" ++ self.db.open(self.path, dbname=name, dbtype=db.DB_HASH, ++ flags = db.DB_CREATE) ++ self.assertEqual((self.path, name), self.db.get_dbname()) ++ + def test_bt_minkey(self) : + for i in [17, 108, 1030] : + self.db.set_bt_minkey(i) +@@ -44,8 +64,13 @@ + self.db.set_priority(flag) + self.assertEqual(flag, self.db.get_priority()) + ++ if db.version() >= (4, 3) : ++ def test_get_transactional(self) : ++ self.assertFalse(self.db.get_transactional()) ++ self.db.open(self.path, dbtype=db.DB_HASH, flags = db.DB_CREATE) ++ self.assertFalse(self.db.get_transactional()) ++ + class DB_hash(DB) : +- if db.version() >= (4, 2) : + def test_h_ffactor(self) : + for ffactor in [4, 16, 256] : + self.db.set_h_ffactor(ffactor) +@@ -84,7 +109,6 @@ + del self.env + test_support.rmtree(self.homeDir) + +- if db.version() >= (4, 2) : + def test_flags(self) : + self.db.set_flags(db.DB_CHKSUM) + self.assertEqual(db.DB_CHKSUM, self.db.get_flags()) +@@ -92,8 +116,15 @@ + self.assertEqual(db.DB_TXN_NOT_DURABLE | db.DB_CHKSUM, + self.db.get_flags()) + ++ if db.version() >= (4, 3) : ++ def test_get_transactional(self) : ++ self.assertFalse(self.db.get_transactional()) ++ # DB_AUTO_COMMIT = Implicit transaction ++ self.db.open("XXX", dbtype=db.DB_HASH, ++ flags = db.DB_CREATE | db.DB_AUTO_COMMIT) ++ self.assertTrue(self.db.get_transactional()) ++ + class DB_recno(DB) : +- if db.version() >= (4, 2) : + def test_re_pad(self) : + for i in [' ', '*'] : # Check chars + self.db.set_re_pad(i) +@@ -116,7 +147,6 @@ + self.assertEqual(i, self.db.get_re_source()) + + class DB_queue(DB) : +- if db.version() >= (4, 2) : + def test_re_len(self) : + for i in [33, 65, 300, 2000] : + self.db.set_re_len(i) +Index: b/Lib/bsddb/test/test_dbenv.py +=================================================================== +--- a/Lib/bsddb/test/test_dbenv.py ++++ b/Lib/bsddb/test/test_dbenv.py +@@ -25,12 +25,31 @@ + test_support.rmtree(self.homeDir) + + class DBEnv_general(DBEnv) : ++ def test_get_open_flags(self) : ++ flags = db.DB_CREATE | db.DB_INIT_MPOOL ++ self.env.open(self.homeDir, flags) ++ self.assertEqual(flags, self.env.get_open_flags()) ++ ++ def test_get_open_flags2(self) : ++ flags = db.DB_CREATE | db.DB_INIT_MPOOL | \ ++ db.DB_INIT_LOCK | db.DB_THREAD ++ self.env.open(self.homeDir, flags) ++ self.assertEqual(flags, self.env.get_open_flags()) ++ + if db.version() >= (4, 7) : + def test_lk_partitions(self) : + for i in [10, 20, 40] : + self.env.set_lk_partitions(i) + self.assertEqual(i, self.env.get_lk_partitions()) + ++ def test_getset_intermediate_dir_mode(self) : ++ self.assertEqual(None, self.env.get_intermediate_dir_mode()) ++ for mode in ["rwx------", "rw-rw-rw-", "rw-r--r--"] : ++ self.env.set_intermediate_dir_mode(mode) ++ self.assertEqual(mode, self.env.get_intermediate_dir_mode()) ++ self.assertRaises(db.DBInvalidArgError, ++ self.env.set_intermediate_dir_mode, "abcde") ++ + if db.version() >= (4, 6) : + def test_thread(self) : + for i in [16, 100, 1000] : +@@ -72,7 +91,6 @@ + v=self.env.get_mp_max_write() + self.assertEqual((i, j), v) + +- if db.version() >= (4, 2) : + def test_invalid_txn(self) : + # This environment doesn't support transactions + self.assertRaises(db.DBInvalidArgError, self.env.txn_begin) +@@ -115,7 +133,7 @@ + self.assertEqual(i, self.env.get_lk_max_lockers()) + + def test_lg_regionmax(self) : +- for i in [128, 256, 1024] : ++ for i in [128, 256, 1000] : + i = i*1024*1024 + self.env.set_lg_regionmax(i) + j = self.env.get_lg_regionmax() +@@ -172,8 +190,12 @@ + self.env.open(self.homeDir, db.DB_CREATE | db.DB_INIT_MPOOL) + cachesize = (0, 2*1024*1024, 1) + self.assertRaises(db.DBInvalidArgError, +- self.env.set_cachesize, *cachesize) +- self.assertEqual(cachesize2, self.env.get_cachesize()) ++ self.env.set_cachesize, *cachesize) ++ cachesize3 = self.env.get_cachesize() ++ self.assertEqual(cachesize2[0], cachesize3[0]) ++ self.assertEqual(cachesize2[2], cachesize3[2]) ++ # In Berkeley DB 5.1, the cachesize can change when opening the Env ++ self.assertTrue(cachesize2[1] <= cachesize3[1]) + + def test_set_cachesize_dbenv_db(self) : + # You can not configure the cachesize using +Index: b/Lib/bsddb/test/test_dbtables.py +=================================================================== +--- a/Lib/bsddb/test/test_dbtables.py ++++ b/Lib/bsddb/test/test_dbtables.py +@@ -38,6 +38,11 @@ + #---------------------------------------------------------------------- + + class TableDBTestCase(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + db_name = 'test-table.db' + + def setUp(self): +Index: b/Lib/bsddb/test/test_distributed_transactions.py +=================================================================== +--- a/Lib/bsddb/test/test_distributed_transactions.py ++++ b/Lib/bsddb/test/test_distributed_transactions.py +@@ -19,6 +19,11 @@ + #---------------------------------------------------------------------- + + class DBTxn_distributed(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + num_txns=1234 + nosync=True + must_open_db=False +@@ -37,15 +42,11 @@ + self.db = db.DB(self.dbenv) + self.db.set_re_len(db.DB_GID_SIZE) + if must_open_db : +- if db.version() >= (4,2) : + txn=self.dbenv.txn_begin() + self.db.open(self.filename, + db.DB_QUEUE, db.DB_CREATE | db.DB_THREAD, 0666, + txn=txn) + txn.commit() +- else : +- self.db.open(self.filename, +- db.DB_QUEUE, db.DB_CREATE | db.DB_THREAD, 0666) + + def setUp(self) : + self.homeDir = get_new_environment_path() +Index: b/Lib/bsddb/test/test_get_none.py +=================================================================== +--- a/Lib/bsddb/test/test_get_none.py ++++ b/Lib/bsddb/test/test_get_none.py +@@ -11,6 +11,11 @@ + #---------------------------------------------------------------------- + + class GetReturnsNoneTestCase(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + def setUp(self): + self.filename = get_new_database_path() + +Index: b/Lib/bsddb/test/test_join.py +=================================================================== +--- a/Lib/bsddb/test/test_join.py ++++ b/Lib/bsddb/test/test_join.py +@@ -30,6 +30,11 @@ + ] + + class JoinTestCase(unittest.TestCase): ++ import sys ++ if sys.version_info < (2, 4) : ++ def assertTrue(self, expr, msg=None): ++ self.failUnless(expr,msg=msg) ++ + keytype = '' + + def setUp(self): +Index: b/Lib/bsddb/test/test_lock.py +=================================================================== +--- a/Lib/bsddb/test/test_lock.py ++++ b/Lib/bsddb/test/test_lock.py +@@ -89,7 +89,6 @@ + for t in threads: + t.join() + +- if db.version() >= (4, 2) : + def test03_lock_timeout(self): + self.env.set_timeout(0, db.DB_SET_LOCK_TIMEOUT) + self.assertEqual(self.env.get_timeout(db.DB_SET_LOCK_TIMEOUT), 0) +Index: b/Lib/bsddb/test/test_misc.py +=================================================================== +--- a/Lib/bsddb/test/test_misc.py ++++ b/Lib/bsddb/test/test_misc.py +@@ -97,10 +97,6 @@ + test_support.unlink(self.filename) + + def test07_DB_set_flags_persists(self): +- if db.version() < (4,2): +- # The get_flags API required for this to work is only available +- # in Berkeley DB >= 4.2 +- return + try: + db1 = db.DB() + db1.set_flags(db.DB_DUPSORT) +Index: b/Lib/bsddb/test/test_queue.py +=================================================================== +--- a/Lib/bsddb/test/test_queue.py ++++ b/Lib/bsddb/test/test_queue.py +@@ -99,11 +99,6 @@ + print '\n', '-=' * 30 + print "Running %s.test02_basicPost32..." % self.__class__.__name__ + +- if db.version() < (3, 2, 0): +- if verbose: +- print "Test not run, DB not new enough..." +- return +- + d = db.DB() + d.set_re_len(40) # Queues must be fixed length + d.open(self.filename, db.DB_QUEUE, db.DB_CREATE) +Index: b/Lib/bsddb/test/test_recno.py +=================================================================== +--- a/Lib/bsddb/test/test_recno.py ++++ b/Lib/bsddb/test/test_recno.py +@@ -236,7 +236,9 @@ + d.close() + + # get the text from the backing source +- text = open(source, 'r').read() ++ f = open(source, 'r') ++ text = f.read() ++ f.close() + text = text.strip() + if verbose: + print text +@@ -256,7 +258,9 @@ + d.sync() + d.close() + +- text = open(source, 'r').read() ++ f = open(source, 'r') ++ text = f.read() ++ f.close() + text = text.strip() + if verbose: + print text +@@ -298,6 +302,18 @@ + c.close() + d.close() + ++ def test04_get_size_empty(self) : ++ d = db.DB() ++ d.open(self.filename, dbtype=db.DB_RECNO, flags=db.DB_CREATE) ++ ++ row_id = d.append(' ') ++ self.assertEqual(1, d.get_size(key=row_id)) ++ row_id = d.append('') ++ self.assertEqual(0, d.get_size(key=row_id)) ++ ++ ++ ++ + + #---------------------------------------------------------------------- + +Index: b/Modules/_bsddb.c +=================================================================== +--- a/Modules/_bsddb.c ++++ b/Modules/_bsddb.c +@@ -202,9 +202,7 @@ + static PyObject* DBNoSuchFileError; /* ENOENT */ + static PyObject* DBPermissionsError; /* EPERM */ + +-#if (DBVER >= 42) + static PyObject* DBRepHandleDeadError; /* DB_REP_HANDLE_DEAD */ +-#endif + #if (DBVER >= 44) + static PyObject* DBRepLockoutError; /* DB_REP_LOCKOUT */ + #endif +@@ -715,9 +713,7 @@ + case ENOENT: errObj = DBNoSuchFileError; break; + case EPERM : errObj = DBPermissionsError; break; + +-#if (DBVER >= 42) + case DB_REP_HANDLE_DEAD : errObj = DBRepHandleDeadError; break; +-#endif + #if (DBVER >= 44) + case DB_REP_LOCKOUT : errObj = DBRepLockoutError; break; + #endif +@@ -2132,7 +2128,7 @@ + MYDB_BEGIN_ALLOW_THREADS; + err = self->db->get(self->db, txn, &key, &data, flags); + MYDB_END_ALLOW_THREADS; +- if (err == DB_BUFFER_SMALL) { ++ if ((err == DB_BUFFER_SMALL) || (err == 0)) { + retval = NUMBER_FromLong((long)data.size); + err = 0; + } +@@ -2385,9 +2381,7 @@ + return NULL; + } + +-#if (DBVER >= 42) + self->db->get_flags(self->db, &self->setflags); +-#endif + + self->flags = flags; + +@@ -2539,6 +2533,37 @@ + #endif + + static PyObject* ++DB_get_dbname(DBObject* self) ++{ ++ int err; ++ const char *filename, *dbname; ++ ++ CHECK_DB_NOT_CLOSED(self); ++ ++ MYDB_BEGIN_ALLOW_THREADS; ++ err = self->db->get_dbname(self->db, &filename, &dbname); ++ MYDB_END_ALLOW_THREADS; ++ RETURN_IF_ERR(); ++ /* If "dbname==NULL", it is correctly converted to "None" */ ++ return Py_BuildValue("(ss)", filename, dbname); ++} ++ ++static PyObject* ++DB_get_open_flags(DBObject* self) ++{ ++ int err; ++ unsigned int flags; ++ ++ CHECK_DB_NOT_CLOSED(self); ++ ++ MYDB_BEGIN_ALLOW_THREADS; ++ err = self->db->get_open_flags(self->db, &flags); ++ MYDB_END_ALLOW_THREADS; ++ RETURN_IF_ERR(); ++ return NUMBER_FromLong(flags); ++} ++ ++static PyObject* + DB_set_q_extentsize(DBObject* self, PyObject* args) + { + int err; +@@ -2555,7 +2580,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_q_extentsize(DBObject* self) + { +@@ -2570,7 +2594,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(extentsize); + } +-#endif + + static PyObject* + DB_set_bt_minkey(DBObject* self, PyObject* args) +@@ -2588,7 +2611,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_bt_minkey(DBObject* self) + { +@@ -2603,7 +2625,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(bt_minkey); + } +-#endif + + static int + _default_cmp(const DBT *leftKey, +@@ -2759,7 +2780,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_cachesize(DBObject* self) + { +@@ -2777,7 +2797,6 @@ + + return Py_BuildValue("(iii)", gbytes, bytes, ncache); + } +-#endif + + static PyObject* + DB_set_flags(DBObject* self, PyObject* args) +@@ -2797,7 +2816,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_flags(DBObject* self) + { +@@ -2812,6 +2830,35 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(flags); + } ++ ++#if (DBVER >= 43) ++static PyObject* ++DB_get_transactional(DBObject* self) ++{ ++ int err; ++ ++ CHECK_DB_NOT_CLOSED(self); ++ ++ MYDB_BEGIN_ALLOW_THREADS; ++ err = self->db->get_transactional(self->db); ++ MYDB_END_ALLOW_THREADS; ++ ++ if(err == 0) { ++ Py_INCREF(Py_False); ++ return Py_False; ++ } else if(err == 1) { ++ Py_INCREF(Py_True); ++ return Py_True; ++ } ++ ++ /* ++ ** If we reach there, there was an error. The ++ ** "return" should be unreachable. ++ */ ++ RETURN_IF_ERR(); ++ assert(0); /* This coude SHOULD be unreachable */ ++ return NULL; ++} + #endif + + static PyObject* +@@ -2830,7 +2877,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_h_ffactor(DBObject* self) + { +@@ -2845,7 +2891,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(ffactor); + } +-#endif + + static PyObject* + DB_set_h_nelem(DBObject* self, PyObject* args) +@@ -2863,7 +2908,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_h_nelem(DBObject* self) + { +@@ -2878,7 +2922,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(nelem); + } +-#endif + + static PyObject* + DB_set_lorder(DBObject* self, PyObject* args) +@@ -2896,7 +2939,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_lorder(DBObject* self) + { +@@ -2911,7 +2953,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lorder); + } +-#endif + + static PyObject* + DB_set_pagesize(DBObject* self, PyObject* args) +@@ -2929,7 +2970,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_pagesize(DBObject* self) + { +@@ -2944,7 +2984,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(pagesize); + } +-#endif + + static PyObject* + DB_set_re_delim(DBObject* self, PyObject* args) +@@ -2967,7 +3006,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_re_delim(DBObject* self) + { +@@ -2981,7 +3019,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(re_delim); + } +-#endif + + static PyObject* + DB_set_re_len(DBObject* self, PyObject* args) +@@ -2999,7 +3036,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_re_len(DBObject* self) + { +@@ -3014,7 +3050,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(re_len); + } +-#endif + + static PyObject* + DB_set_re_pad(DBObject* self, PyObject* args) +@@ -3036,7 +3071,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_re_pad(DBObject* self) + { +@@ -3050,7 +3084,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(re_pad); + } +-#endif + + static PyObject* + DB_set_re_source(DBObject* self, PyObject* args) +@@ -3069,7 +3102,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_re_source(DBObject* self) + { +@@ -3084,7 +3116,6 @@ + RETURN_IF_ERR(); + return PyBytes_FromString(source); + } +-#endif + + static PyObject* + DB_stat(DBObject* self, PyObject* args, PyObject* kwargs) +@@ -3381,7 +3412,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DB_get_encrypt_flags(DBObject* self) + { +@@ -3396,7 +3426,6 @@ + + return NUMBER_FromLong(flags); + } +-#endif + + + +@@ -4987,7 +5016,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_encrypt_flags(DBEnvObject* self) + { +@@ -5025,7 +5053,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(timeout); + } +-#endif + + + static PyObject* +@@ -5064,7 +5091,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_shm_key(DBEnvObject* self) + { +@@ -5081,7 +5107,6 @@ + + return NUMBER_FromLong(shm_key); + } +-#endif + + #if (DBVER >= 46) + static PyObject* +@@ -5170,7 +5195,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_cachesize(DBEnvObject* self) + { +@@ -5188,7 +5212,6 @@ + + return Py_BuildValue("(iii)", gbytes, bytes, ncache); + } +-#endif + + + static PyObject* +@@ -5208,7 +5231,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_flags(DBEnvObject* self) + { +@@ -5223,7 +5245,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(flags); + } +-#endif + + #if (DBVER >= 47) + static PyObject* +@@ -5423,7 +5444,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_data_dirs(DBEnvObject* self) + { +@@ -5463,7 +5483,6 @@ + } + return tuple; + } +-#endif + + #if (DBVER >= 44) + static PyObject* +@@ -5513,7 +5532,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lg_bsize(DBEnvObject* self) + { +@@ -5528,7 +5546,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lg_bsize); + } +-#endif + + static PyObject* + DBEnv_set_lg_dir(DBEnvObject* self, PyObject* args) +@@ -5547,7 +5564,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lg_dir(DBEnvObject* self) + { +@@ -5562,7 +5578,6 @@ + RETURN_IF_ERR(); + return PyBytes_FromString(dirp); + } +-#endif + + static PyObject* + DBEnv_set_lg_max(DBEnvObject* self, PyObject* args) +@@ -5580,7 +5595,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lg_max(DBEnvObject* self) + { +@@ -5595,8 +5609,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lg_max); + } +-#endif +- + + static PyObject* + DBEnv_set_lg_regionmax(DBEnvObject* self, PyObject* args) +@@ -5614,7 +5626,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lg_regionmax(DBEnvObject* self) + { +@@ -5629,7 +5640,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lg_regionmax); + } +-#endif + + #if (DBVER >= 47) + static PyObject* +@@ -5680,7 +5690,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lk_detect(DBEnvObject* self) + { +@@ -5695,8 +5704,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lk_detect); + } +-#endif +- + + #if (DBVER < 45) + static PyObject* +@@ -5734,7 +5741,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lk_max_locks(DBEnvObject* self) + { +@@ -5749,7 +5755,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lk_max); + } +-#endif + + static PyObject* + DBEnv_set_lk_max_lockers(DBEnvObject* self, PyObject* args) +@@ -5767,7 +5772,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lk_max_lockers(DBEnvObject* self) + { +@@ -5782,7 +5786,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lk_max); + } +-#endif + + static PyObject* + DBEnv_set_lk_max_objects(DBEnvObject* self, PyObject* args) +@@ -5800,7 +5803,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_lk_max_objects(DBEnvObject* self) + { +@@ -5815,9 +5817,7 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(lk_max); + } +-#endif + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_mp_mmapsize(DBEnvObject* self) + { +@@ -5832,8 +5832,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(mmapsize); + } +-#endif +- + + static PyObject* + DBEnv_set_mp_mmapsize(DBEnvObject* self, PyObject* args) +@@ -5869,8 +5867,6 @@ + RETURN_NONE(); + } + +- +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_tmp_dir(DBEnvObject* self) + { +@@ -5887,8 +5883,6 @@ + + return PyBytes_FromString(dirpp); + } +-#endif +- + + static PyObject* + DBEnv_txn_recover(DBEnvObject* self) +@@ -6003,8 +5997,6 @@ + RETURN_NONE(); + } + +- +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_tx_max(DBEnvObject* self) + { +@@ -6019,8 +6011,6 @@ + RETURN_IF_ERR(); + return PyLong_FromUnsignedLong(max); + } +-#endif +- + + static PyObject* + DBEnv_set_tx_max(DBEnvObject* self, PyObject* args) +@@ -6038,8 +6028,6 @@ + RETURN_NONE(); + } + +- +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_tx_timestamp(DBEnvObject* self) + { +@@ -6054,7 +6042,6 @@ + RETURN_IF_ERR(); + return NUMBER_FromLong(timestamp); + } +-#endif + + static PyObject* + DBEnv_set_tx_timestamp(DBEnvObject* self, PyObject* args) +@@ -6756,6 +6743,55 @@ + RETURN_NONE(); + } + ++#if (DBVER >= 47) ++static PyObject* ++DBEnv_set_intermediate_dir_mode(DBEnvObject* self, PyObject* args) ++{ ++ int err; ++ const char *mode; ++ ++ if (!PyArg_ParseTuple(args,"s:set_intermediate_dir_mode", &mode)) ++ return NULL; ++ ++ CHECK_ENV_NOT_CLOSED(self); ++ ++ MYDB_BEGIN_ALLOW_THREADS; ++ err = self->db_env->set_intermediate_dir_mode(self->db_env, mode); ++ MYDB_END_ALLOW_THREADS; ++ RETURN_IF_ERR(); ++ RETURN_NONE(); ++} ++ ++static PyObject* ++DBEnv_get_intermediate_dir_mode(DBEnvObject* self) ++{ ++ int err; ++ const char *mode; ++ ++ CHECK_ENV_NOT_CLOSED(self); ++ ++ MYDB_BEGIN_ALLOW_THREADS; ++ err = self->db_env->get_intermediate_dir_mode(self->db_env, &mode); ++ MYDB_END_ALLOW_THREADS; ++ RETURN_IF_ERR(); ++ return Py_BuildValue("s", mode); ++} ++#endif ++ ++static PyObject* ++DBEnv_get_open_flags(DBEnvObject* self) ++{ ++ int err; ++ unsigned int flags; ++ ++ CHECK_ENV_NOT_CLOSED(self); ++ ++ MYDB_BEGIN_ALLOW_THREADS; ++ err = self->db_env->get_open_flags(self->db_env, &flags); ++ MYDB_END_ALLOW_THREADS; ++ RETURN_IF_ERR(); ++ return NUMBER_FromLong(flags); ++} + + #if (DBVER < 48) + static PyObject* +@@ -6875,7 +6911,6 @@ + RETURN_NONE(); + } + +-#if (DBVER >= 42) + static PyObject* + DBEnv_get_verbose(DBEnvObject* self, PyObject* args) + { +@@ -6893,7 +6928,6 @@ + RETURN_IF_ERR(); + return PyBool_FromLong(verbose); + } +-#endif + + #if (DBVER >= 45) + static void +@@ -6975,9 +7009,7 @@ + PyObject *control_py, *rec_py; + DBT control, rec; + int envid; +-#if (DBVER >= 42) + DB_LSN lsn; +-#endif + + if (!PyArg_ParseTuple(args, "OOi:rep_process_message", &control_py, + &rec_py, &envid)) +@@ -6994,13 +7026,8 @@ + err = self->db_env->rep_process_message(self->db_env, &control, &rec, + envid, &lsn); + #else +-#if (DBVER >= 42) + err = self->db_env->rep_process_message(self->db_env, &control, &rec, + &envid, &lsn); +-#else +- err = self->db_env->rep_process_message(self->db_env, &control, &rec, +- &envid); +-#endif + #endif + MYDB_END_ALLOW_THREADS; + switch (err) { +@@ -7029,12 +7056,10 @@ + return r; + break; + } +-#if (DBVER >= 42) + case DB_REP_NOTPERM : + case DB_REP_ISPERM : + return Py_BuildValue("(i(ll))", err, lsn.file, lsn.offset); + break; +-#endif + } + RETURN_IF_ERR(); + return Py_BuildValue("(OO)", Py_None, Py_None); +@@ -7086,20 +7111,6 @@ + return ret; + } + +-#if (DBVER <= 41) +-static int +-_DBEnv_rep_transportCallbackOLD(DB_ENV* db_env, const DBT* control, const DBT* rec, +- int envid, u_int32_t flags) +-{ +- DB_LSN lsn; +- +- lsn.file = -1; /* Dummy values */ +- lsn.offset = -1; +- return _DBEnv_rep_transportCallback(db_env, control, rec, &lsn, envid, +- flags); +-} +-#endif +- + static PyObject* + DBEnv_rep_set_transport(DBEnvObject* self, PyObject* args) + { +@@ -7120,13 +7131,8 @@ + err = self->db_env->rep_set_transport(self->db_env, envid, + &_DBEnv_rep_transportCallback); + #else +-#if (DBVER >= 42) + err = self->db_env->set_rep_transport(self->db_env, envid, + &_DBEnv_rep_transportCallback); +-#else +- err = self->db_env->set_rep_transport(self->db_env, envid, +- &_DBEnv_rep_transportCallbackOLD); +-#endif + #endif + MYDB_END_ALLOW_THREADS; + RETURN_IF_ERR(); +@@ -8482,65 +8488,43 @@ + {"remove", (PyCFunction)DB_remove, METH_VARARGS|METH_KEYWORDS}, + {"rename", (PyCFunction)DB_rename, METH_VARARGS}, + {"set_bt_minkey", (PyCFunction)DB_set_bt_minkey, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_bt_minkey", (PyCFunction)DB_get_bt_minkey, METH_NOARGS}, +-#endif + {"set_bt_compare", (PyCFunction)DB_set_bt_compare, METH_O}, + {"set_cachesize", (PyCFunction)DB_set_cachesize, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_cachesize", (PyCFunction)DB_get_cachesize, METH_NOARGS}, +-#endif + {"set_encrypt", (PyCFunction)DB_set_encrypt, METH_VARARGS|METH_KEYWORDS}, +-#if (DBVER >= 42) + {"get_encrypt_flags", (PyCFunction)DB_get_encrypt_flags, METH_NOARGS}, +-#endif +- + {"set_flags", (PyCFunction)DB_set_flags, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_flags", (PyCFunction)DB_get_flags, METH_NOARGS}, ++#if (DBVER >= 43) ++ {"get_transactional", (PyCFunction)DB_get_transactional, METH_NOARGS}, + #endif + {"set_h_ffactor", (PyCFunction)DB_set_h_ffactor, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_h_ffactor", (PyCFunction)DB_get_h_ffactor, METH_NOARGS}, +-#endif + {"set_h_nelem", (PyCFunction)DB_set_h_nelem, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_h_nelem", (PyCFunction)DB_get_h_nelem, METH_NOARGS}, +-#endif + {"set_lorder", (PyCFunction)DB_set_lorder, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lorder", (PyCFunction)DB_get_lorder, METH_NOARGS}, +-#endif + {"set_pagesize", (PyCFunction)DB_set_pagesize, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_pagesize", (PyCFunction)DB_get_pagesize, METH_NOARGS}, +-#endif + {"set_re_delim", (PyCFunction)DB_set_re_delim, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_re_delim", (PyCFunction)DB_get_re_delim, METH_NOARGS}, +-#endif + {"set_re_len", (PyCFunction)DB_set_re_len, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_re_len", (PyCFunction)DB_get_re_len, METH_NOARGS}, +-#endif + {"set_re_pad", (PyCFunction)DB_set_re_pad, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_re_pad", (PyCFunction)DB_get_re_pad, METH_NOARGS}, +-#endif + {"set_re_source", (PyCFunction)DB_set_re_source, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_re_source", (PyCFunction)DB_get_re_source, METH_NOARGS}, +-#endif + {"set_q_extentsize",(PyCFunction)DB_set_q_extentsize, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_q_extentsize",(PyCFunction)DB_get_q_extentsize, METH_NOARGS}, +-#endif + {"set_private", (PyCFunction)DB_set_private, METH_O}, + {"get_private", (PyCFunction)DB_get_private, METH_NOARGS}, + #if (DBVER >= 46) + {"set_priority", (PyCFunction)DB_set_priority, METH_VARARGS}, + {"get_priority", (PyCFunction)DB_get_priority, METH_NOARGS}, + #endif ++ {"get_dbname", (PyCFunction)DB_get_dbname, METH_NOARGS}, ++ {"get_open_flags", (PyCFunction)DB_get_open_flags, METH_NOARGS}, + {"stat", (PyCFunction)DB_stat, METH_VARARGS|METH_KEYWORDS}, + #if (DBVER >= 43) + {"stat_print", (PyCFunction)DB_stat_print, +@@ -8639,24 +8623,18 @@ + {"get_thread_count", (PyCFunction)DBEnv_get_thread_count, METH_NOARGS}, + #endif + {"set_encrypt", (PyCFunction)DBEnv_set_encrypt, METH_VARARGS|METH_KEYWORDS}, +-#if (DBVER >= 42) + {"get_encrypt_flags", (PyCFunction)DBEnv_get_encrypt_flags, METH_NOARGS}, + {"get_timeout", (PyCFunction)DBEnv_get_timeout, + METH_VARARGS|METH_KEYWORDS}, +-#endif + {"set_timeout", (PyCFunction)DBEnv_set_timeout, METH_VARARGS|METH_KEYWORDS}, + {"set_shm_key", (PyCFunction)DBEnv_set_shm_key, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_shm_key", (PyCFunction)DBEnv_get_shm_key, METH_NOARGS}, +-#endif + #if (DBVER >= 46) + {"set_cache_max", (PyCFunction)DBEnv_set_cache_max, METH_VARARGS}, + {"get_cache_max", (PyCFunction)DBEnv_get_cache_max, METH_NOARGS}, + #endif + {"set_cachesize", (PyCFunction)DBEnv_set_cachesize, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_cachesize", (PyCFunction)DBEnv_get_cachesize, METH_NOARGS}, +-#endif + {"memp_trickle", (PyCFunction)DBEnv_memp_trickle, METH_VARARGS}, + {"memp_sync", (PyCFunction)DBEnv_memp_sync, METH_VARARGS}, + {"memp_stat", (PyCFunction)DBEnv_memp_stat, +@@ -8685,33 +8663,21 @@ + #endif + #endif + {"set_data_dir", (PyCFunction)DBEnv_set_data_dir, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_data_dirs", (PyCFunction)DBEnv_get_data_dirs, METH_NOARGS}, +-#endif +-#if (DBVER >= 42) + {"get_flags", (PyCFunction)DBEnv_get_flags, METH_NOARGS}, +-#endif + {"set_flags", (PyCFunction)DBEnv_set_flags, METH_VARARGS}, + #if (DBVER >= 47) + {"log_set_config", (PyCFunction)DBEnv_log_set_config, METH_VARARGS}, + {"log_get_config", (PyCFunction)DBEnv_log_get_config, METH_VARARGS}, + #endif + {"set_lg_bsize", (PyCFunction)DBEnv_set_lg_bsize, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lg_bsize", (PyCFunction)DBEnv_get_lg_bsize, METH_NOARGS}, +-#endif + {"set_lg_dir", (PyCFunction)DBEnv_set_lg_dir, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lg_dir", (PyCFunction)DBEnv_get_lg_dir, METH_NOARGS}, +-#endif + {"set_lg_max", (PyCFunction)DBEnv_set_lg_max, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lg_max", (PyCFunction)DBEnv_get_lg_max, METH_NOARGS}, +-#endif + {"set_lg_regionmax",(PyCFunction)DBEnv_set_lg_regionmax, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lg_regionmax",(PyCFunction)DBEnv_get_lg_regionmax, METH_NOARGS}, +-#endif + #if (DBVER >= 44) + {"set_lg_filemode", (PyCFunction)DBEnv_set_lg_filemode, METH_VARARGS}, + {"get_lg_filemode", (PyCFunction)DBEnv_get_lg_filemode, METH_NOARGS}, +@@ -8721,36 +8687,24 @@ + {"get_lk_partitions", (PyCFunction)DBEnv_get_lk_partitions, METH_NOARGS}, + #endif + {"set_lk_detect", (PyCFunction)DBEnv_set_lk_detect, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lk_detect", (PyCFunction)DBEnv_get_lk_detect, METH_NOARGS}, +-#endif + #if (DBVER < 45) + {"set_lk_max", (PyCFunction)DBEnv_set_lk_max, METH_VARARGS}, + #endif + {"set_lk_max_locks", (PyCFunction)DBEnv_set_lk_max_locks, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lk_max_locks", (PyCFunction)DBEnv_get_lk_max_locks, METH_NOARGS}, +-#endif + {"set_lk_max_lockers", (PyCFunction)DBEnv_set_lk_max_lockers, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lk_max_lockers", (PyCFunction)DBEnv_get_lk_max_lockers, METH_NOARGS}, +-#endif + {"set_lk_max_objects", (PyCFunction)DBEnv_set_lk_max_objects, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_lk_max_objects", (PyCFunction)DBEnv_get_lk_max_objects, METH_NOARGS}, +-#endif + #if (DBVER >= 43) + {"stat_print", (PyCFunction)DBEnv_stat_print, + METH_VARARGS|METH_KEYWORDS}, + #endif + {"set_mp_mmapsize", (PyCFunction)DBEnv_set_mp_mmapsize, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_mp_mmapsize", (PyCFunction)DBEnv_get_mp_mmapsize, METH_NOARGS}, +-#endif + {"set_tmp_dir", (PyCFunction)DBEnv_set_tmp_dir, METH_VARARGS}, +-#if (DBVER >= 42) + {"get_tmp_dir", (PyCFunction)DBEnv_get_tmp_dir, METH_NOARGS}, +-#endif + {"txn_begin", (PyCFunction)DBEnv_txn_begin, METH_VARARGS|METH_KEYWORDS}, + {"txn_checkpoint", (PyCFunction)DBEnv_txn_checkpoint, METH_VARARGS}, + {"txn_stat", (PyCFunction)DBEnv_txn_stat, METH_VARARGS}, +@@ -8758,10 +8712,8 @@ + {"txn_stat_print", (PyCFunction)DBEnv_txn_stat_print, + METH_VARARGS|METH_KEYWORDS}, + #endif +-#if (DBVER >= 42) + {"get_tx_max", (PyCFunction)DBEnv_get_tx_max, METH_NOARGS}, + {"get_tx_timestamp", (PyCFunction)DBEnv_get_tx_timestamp, METH_NOARGS}, +-#endif + {"set_tx_max", (PyCFunction)DBEnv_set_tx_max, METH_VARARGS}, + {"set_tx_timestamp", (PyCFunction)DBEnv_set_tx_timestamp, METH_VARARGS}, + {"lock_detect", (PyCFunction)DBEnv_lock_detect, METH_VARARGS}, +@@ -8804,11 +8756,16 @@ + {"get_mp_max_write", (PyCFunction)DBEnv_get_mp_max_write, METH_NOARGS}, + #endif + {"set_verbose", (PyCFunction)DBEnv_set_verbose, METH_VARARGS}, +-#if (DBVER >= 42) +- {"get_verbose", (PyCFunction)DBEnv_get_verbose, METH_VARARGS}, ++ {"get_verbose", (PyCFunction)DBEnv_get_verbose, METH_VARARGS}, ++ {"set_private", (PyCFunction)DBEnv_set_private, METH_O}, ++ {"get_private", (PyCFunction)DBEnv_get_private, METH_NOARGS}, ++ {"get_open_flags", (PyCFunction)DBEnv_get_open_flags, METH_NOARGS}, ++#if (DBVER >= 47) ++ {"set_intermediate_dir_mode", (PyCFunction)DBEnv_set_intermediate_dir_mode, ++ METH_VARARGS}, ++ {"get_intermediate_dir_mode", (PyCFunction)DBEnv_get_intermediate_dir_mode, ++ METH_NOARGS}, + #endif +- {"set_private", (PyCFunction)DBEnv_set_private, METH_O}, +- {"get_private", (PyCFunction)DBEnv_get_private, METH_NOARGS}, + {"rep_start", (PyCFunction)DBEnv_rep_start, + METH_VARARGS|METH_KEYWORDS}, + {"rep_set_transport", (PyCFunction)DBEnv_rep_set_transport, METH_VARARGS}, +@@ -8922,13 +8879,9 @@ + + CHECK_ENV_NOT_CLOSED(self); + +-#if (DBVER >= 42) + MYDB_BEGIN_ALLOW_THREADS; + self->db_env->get_home(self->db_env, &home); + MYDB_END_ALLOW_THREADS; +-#else +- home=self->db_env->db_home; +-#endif + + if (home == NULL) { + RETURN_NONE(); +@@ -9298,10 +9251,25 @@ + { + int major, minor, patch; + ++ /* This should be instantaneous, no need to release the GIL */ + db_version(&major, &minor, &patch); + return Py_BuildValue("(iii)", major, minor, patch); + } + ++#if (DBVER >= 50) ++static PyObject* ++bsddb_version_full(PyObject* self) ++{ ++ char *version_string; ++ int family, release, major, minor, patch; ++ ++ /* This should be instantaneous, no need to release the GIL */ ++ version_string = db_full_version(&family, &release, &major, &minor, &patch); ++ return Py_BuildValue("(siiiii)", ++ version_string, family, release, major, minor, patch); ++} ++#endif ++ + + /* List of functions defined in the module */ + static PyMethodDef bsddb_methods[] = { +@@ -9311,6 +9279,9 @@ + {"DBSequence", (PyCFunction)DBSequence_construct, METH_VARARGS | METH_KEYWORDS }, + #endif + {"version", (PyCFunction)bsddb_version, METH_NOARGS, bsddb_version_doc}, ++#if (DBVER >= 50) ++ {"full_version", (PyCFunction)bsddb_version_full, METH_NOARGS}, ++#endif + {NULL, NULL} /* sentinel */ + }; + +@@ -9328,6 +9299,11 @@ + */ + #define ADD_INT(dict, NAME) _addIntToDict(dict, #NAME, NAME) + ++/* ++** We can rename the module at import time, so the string allocated ++** must be big enough, and any use of the name must use this particular ++** string. ++*/ + #define MODULE_NAME_MAX_LEN 11 + static char _bsddbModuleName[MODULE_NAME_MAX_LEN+1] = "_bsddb"; + +@@ -9428,13 +9404,7 @@ + ADD_INT(d, DB_MAX_RECORDS); + + #if (DBVER < 48) +-#if (DBVER >= 42) + ADD_INT(d, DB_RPCCLIENT); +-#else +- ADD_INT(d, DB_CLIENT); +- /* allow apps to be written using DB_RPCCLIENT on older Berkeley DB */ +- _addIntToDict(d, "DB_RPCCLIENT", DB_CLIENT); +-#endif + #endif + + #if (DBVER < 48) +@@ -9477,6 +9447,14 @@ + ADD_INT(d, DB_TXN_SYNC); + ADD_INT(d, DB_TXN_NOWAIT); + ++#if (DBVER >= 51) ++ ADD_INT(d, DB_TXN_BULK); ++#endif ++ ++#if (DBVER >= 48) ++ ADD_INT(d, DB_CURSOR_BULK); ++#endif ++ + #if (DBVER >= 46) + ADD_INT(d, DB_TXN_WAIT); + #endif +@@ -9561,9 +9539,7 @@ + ADD_INT(d, DB_ARCH_ABS); + ADD_INT(d, DB_ARCH_DATA); + ADD_INT(d, DB_ARCH_LOG); +-#if (DBVER >= 42) + ADD_INT(d, DB_ARCH_REMOVE); +-#endif + + ADD_INT(d, DB_BTREE); + ADD_INT(d, DB_HASH); +@@ -9591,9 +9567,6 @@ + ADD_INT(d, DB_CACHED_COUNTS); + #endif + +-#if (DBVER <= 41) +- ADD_INT(d, DB_COMMIT); +-#endif + ADD_INT(d, DB_CONSUME); + ADD_INT(d, DB_CONSUME_WAIT); + ADD_INT(d, DB_CURRENT); +@@ -9671,6 +9644,10 @@ + #if (DBVER >= 43) + ADD_INT(d, DB_STAT_SUBSYSTEM); + ADD_INT(d, DB_STAT_MEMP_HASH); ++ ADD_INT(d, DB_STAT_LOCK_CONF); ++ ADD_INT(d, DB_STAT_LOCK_LOCKERS); ++ ADD_INT(d, DB_STAT_LOCK_OBJECTS); ++ ADD_INT(d, DB_STAT_LOCK_PARAMS); + #endif + + #if (DBVER >= 48) +@@ -9690,7 +9667,6 @@ + ADD_INT(d, DB_EID_INVALID); + ADD_INT(d, DB_EID_BROADCAST); + +-#if (DBVER >= 42) + ADD_INT(d, DB_TIME_NOTGRANTED); + ADD_INT(d, DB_TXN_NOT_DURABLE); + ADD_INT(d, DB_TXN_WRITE_NOSYNC); +@@ -9698,9 +9674,8 @@ + ADD_INT(d, DB_INIT_REP); + ADD_INT(d, DB_ENCRYPT); + ADD_INT(d, DB_CHKSUM); +-#endif + +-#if (DBVER >= 42) && (DBVER < 47) ++#if (DBVER < 47) + ADD_INT(d, DB_LOG_AUTOREMOVE); + ADD_INT(d, DB_DIRECT_LOG); + #endif +@@ -9733,6 +9708,20 @@ + ADD_INT(d, DB_VERB_REPLICATION); + ADD_INT(d, DB_VERB_WAITSFOR); + ++#if (DBVER >= 50) ++ ADD_INT(d, DB_VERB_REP_SYSTEM); ++#endif ++ ++#if (DBVER >= 47) ++ ADD_INT(d, DB_VERB_REP_ELECT); ++ ADD_INT(d, DB_VERB_REP_LEASE); ++ ADD_INT(d, DB_VERB_REP_MISC); ++ ADD_INT(d, DB_VERB_REP_MSGS); ++ ADD_INT(d, DB_VERB_REP_SYNC); ++ ADD_INT(d, DB_VERB_REPMGR_CONNFAIL); ++ ADD_INT(d, DB_VERB_REPMGR_MISC); ++#endif ++ + #if (DBVER >= 45) + ADD_INT(d, DB_EVENT_PANIC); + ADD_INT(d, DB_EVENT_REP_CLIENT); +@@ -9748,16 +9737,25 @@ + ADD_INT(d, DB_EVENT_WRITE_FAILED); + #endif + ++#if (DBVER >= 50) ++ ADD_INT(d, DB_REPMGR_CONF_ELECTIONS); ++ ADD_INT(d, DB_EVENT_REP_MASTER_FAILURE); ++ ADD_INT(d, DB_EVENT_REP_DUPMASTER); ++ ADD_INT(d, DB_EVENT_REP_ELECTION_FAILED); ++#endif ++#if (DBVER >= 48) ++ ADD_INT(d, DB_EVENT_REG_ALIVE); ++ ADD_INT(d, DB_EVENT_REG_PANIC); ++#endif ++ + ADD_INT(d, DB_REP_DUPMASTER); + ADD_INT(d, DB_REP_HOLDELECTION); + #if (DBVER >= 44) + ADD_INT(d, DB_REP_IGNORE); + ADD_INT(d, DB_REP_JOIN_FAILURE); + #endif +-#if (DBVER >= 42) + ADD_INT(d, DB_REP_ISPERM); + ADD_INT(d, DB_REP_NOTPERM); +-#endif + ADD_INT(d, DB_REP_NEWSITE); + + ADD_INT(d, DB_REP_MASTER); +@@ -9766,7 +9764,13 @@ + ADD_INT(d, DB_REP_PERMANENT); + + #if (DBVER >= 44) ++#if (DBVER >= 50) ++ ADD_INT(d, DB_REP_CONF_AUTOINIT); ++#else + ADD_INT(d, DB_REP_CONF_NOAUTOINIT); ++#endif /* 5.0 */ ++#endif /* 4.4 */ ++#if (DBVER >= 44) + ADD_INT(d, DB_REP_CONF_DELAYCLIENT); + ADD_INT(d, DB_REP_CONF_BULK); + ADD_INT(d, DB_REP_CONF_NOWAIT); +@@ -9774,9 +9778,7 @@ + ADD_INT(d, DB_REP_REREQUEST); + #endif + +-#if (DBVER >= 42) + ADD_INT(d, DB_REP_NOBUFFER); +-#endif + + #if (DBVER >= 46) + ADD_INT(d, DB_REP_LEASE_EXPIRED); +@@ -9819,6 +9821,28 @@ + ADD_INT(d, DB_STAT_ALL); + #endif + ++#if (DBVER >= 51) ++ ADD_INT(d, DB_REPMGR_ACKS_ALL_AVAILABLE); ++#endif ++ ++#if (DBVER >= 48) ++ ADD_INT(d, DB_REP_CONF_INMEM); ++#endif ++ ++ ADD_INT(d, DB_TIMEOUT); ++ ++#if (DBVER >= 50) ++ ADD_INT(d, DB_FORCESYNC); ++#endif ++ ++#if (DBVER >= 48) ++ ADD_INT(d, DB_FAILCHK); ++#endif ++ ++#if (DBVER >= 51) ++ ADD_INT(d, DB_HOTBACKUP_IN_PROGRESS); ++#endif ++ + #if (DBVER >= 43) + ADD_INT(d, DB_BUFFER_SMALL); + ADD_INT(d, DB_SEQ_DEC); +@@ -9856,6 +9880,10 @@ + ADD_INT(d, DB_SET_LOCK_TIMEOUT); + ADD_INT(d, DB_SET_TXN_TIMEOUT); + ++#if (DBVER >= 48) ++ ADD_INT(d, DB_SET_REG_TIMEOUT); ++#endif ++ + /* The exception name must be correct for pickled exception * + * objects to unpickle properly. */ + #ifdef PYBSDDB_STANDALONE /* different value needed for standalone pybsddb */ +@@ -9927,9 +9955,7 @@ + MAKE_EX(DBNoSuchFileError); + MAKE_EX(DBPermissionsError); + +-#if (DBVER >= 42) + MAKE_EX(DBRepHandleDeadError); +-#endif + #if (DBVER >= 44) + MAKE_EX(DBRepLockoutError); + #endif +@@ -9947,6 +9973,7 @@ + #undef MAKE_EX + + /* Initialise the C API structure and add it to the module */ ++ bsddb_api.api_version = PYBSDDB_API_VERSION; + bsddb_api.db_type = &DB_Type; + bsddb_api.dbcursor_type = &DBCursor_Type; + bsddb_api.dblogcursor_type = &DBLogCursor_Type; +@@ -9955,19 +9982,25 @@ + bsddb_api.dblock_type = &DBLock_Type; + #if (DBVER >= 43) + bsddb_api.dbsequence_type = &DBSequence_Type; ++#else ++ bsddb_api.dbsequence_type = NULL; + #endif + bsddb_api.makeDBError = makeDBError; + + /* +- ** Capsules exist from Python 3.1, but I +- ** don't want to break the API compatibility +- ** for already published Python versions. ++ ** Capsules exist from Python 2.7 and 3.1. ++ ** We don't support Python 3.0 anymore, so... ++ ** #if (PY_VERSION_HEX < ((PY_MAJOR_VERSION < 3) ? 0x02070000 : 0x03020000)) + */ +-#if (PY_VERSION_HEX < 0x03020000) ++#if (PY_VERSION_HEX < 0x02070000) + py_api = PyCObject_FromVoidPtr((void*)&bsddb_api, NULL); + #else + { +- char py_api_name[250]; ++ /* ++ ** The data must outlive the call!!. So, the static definition. ++ ** The buffer must be big enough... ++ */ ++ static char py_api_name[MODULE_NAME_MAX_LEN+10]; + + strcpy(py_api_name, _bsddbModuleName); + strcat(py_api_name, ".api"); +Index: b/Modules/bsddb.h +=================================================================== +--- a/Modules/bsddb.h ++++ b/Modules/bsddb.h +@@ -109,7 +109,7 @@ + #error "eek! DBVER can't handle minor versions > 9" + #endif + +-#define PY_BSDDB_VERSION "4.8.4.2" ++#define PY_BSDDB_VERSION "5.1.2" + + /* Python object definitions */ + +@@ -236,7 +236,7 @@ + /* To access the structure from an external module, use code like the + following (error checking missed out for clarity): + +- // If you are using Python before 3.2: ++ // If you are using Python before 2.7: + BSDDB_api* bsddb_api; + PyObject* mod; + PyObject* cobj; +@@ -249,7 +249,7 @@ + Py_DECREF(mod); + + +- // If you are using Python 3.2 or up: ++ // If you are using Python 2.7 or up: (except Python 3.0, unsupported) + BSDDB_api* bsddb_api; + + // Use "bsddb3._pybsddb.api" if you're using +@@ -257,10 +257,14 @@ + bsddb_api = (void **)PyCapsule_Import("bsddb._bsddb.api", 1); + + ++ Check "api_version" number before trying to use the API. ++ + The structure's members must not be changed. + */ + ++#define PYBSDDB_API_VERSION 1 + typedef struct { ++ unsigned int api_version; + /* Type objects */ + PyTypeObject* db_type; + PyTypeObject* dbcursor_type; +@@ -268,9 +272,7 @@ + PyTypeObject* dbenv_type; + PyTypeObject* dbtxn_type; + PyTypeObject* dblock_type; +-#if (DBVER >= 43) +- PyTypeObject* dbsequence_type; +-#endif ++ PyTypeObject* dbsequence_type; /* If DBVER < 43 -> NULL */ + + /* Functions */ + int (*makeDBError)(int err); +@@ -289,9 +291,9 @@ + #define DBEnvObject_Check(v) ((v)->ob_type == bsddb_api->dbenv_type) + #define DBTxnObject_Check(v) ((v)->ob_type == bsddb_api->dbtxn_type) + #define DBLockObject_Check(v) ((v)->ob_type == bsddb_api->dblock_type) +-#if (DBVER >= 43) +-#define DBSequenceObject_Check(v) ((v)->ob_type == bsddb_api->dbsequence_type) +-#endif ++#define DBSequenceObject_Check(v) \ ++ ((bsddb_api->dbsequence_type) && \ ++ ((v)->ob_type == bsddb_api->dbsequence_type)) + + #endif /* COMPILING_BSDDB_C */ + --- python2.7-2.7.2.orig/debian/patches/series.in +++ python2.7-2.7.2/debian/patches/series.in @@ -0,0 +1,61 @@ +hg-updates.diff +issue9189.diff +deb-setup.diff +deb-locations.diff +site-locations.diff +distutils-install-layout.diff +locale-module.diff +distutils-link.diff +distutils-sysconfig.diff +test-sundry.diff +tkinter-import.diff +link-opt.diff +debug-build.diff +hotshot-import.diff +webbrowser.diff +linecache.diff +doc-nodownload.diff +profiled-build.diff +no-zip-on-sys.path.diff +platform-lsbrelease.diff +bdist-wininst-notfound.diff +setup-modules-ssl.diff +makesetup-bashism.diff +hurd-broken-poll.diff +hurd-disable-nonworking-constants.diff +#ifdef WITH_FPECTL +enable-fpectl.diff +#endif +statvfs-f_flag-constants.diff +#if defined (arch_alpha) +plat-linux2_alpha.diff +#elif defined (arch_hppa) +plat-linux2_hppa.diff +#elif defined (arch_mips) || defined(arch_mipsel) +plat-linux2_mips.diff +#elif defined (arch_sparc) || defined (arch_sparc64) +plat-linux2_sparc.diff +#endif +#if defined (BROKEN_UTIMES) +disable-utimes.diff +#endif +#if defined (Ubuntu) +langpack-gettext.diff +#endif +#if defined (arch_os_hurd) +no-large-file-support.diff +cthreads.diff +#endif +issue9012a.diff +link-system-expat.diff +plat-gnukfreebsd.diff +link-whole-archive.diff +profile-pstats.diff +bsddb-libpath.diff +disable-sem-check.diff +ncursesw-incdir.diff +multiprocessing-typos.diff +ctypes-arm.diff +db5.1.diff +lto-link-flags.diff +disable-ssl-cert-tests.diff --- python2.7-2.7.2.orig/debian/patches/locale-module.diff +++ python2.7-2.7.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 +@@ -1520,8 +1520,8 @@ + 'uk_ua.iso88595': 'uk_UA.ISO8859-5', + 'uk_ua.koi8u': 'uk_UA.KOI8-U', + 'uk_ua.microsoftcp1251': 'uk_UA.CP1251', +- 'univ': 'en_US.utf', +- 'universal': 'en_US.utf', ++ 'univ': 'en_US.UTF-8', ++ 'universal': 'en_US.UTF-8', + 'universal.utf8@ucs4': 'en_US.UTF-8', + 'ur': 'ur_PK.CP1256', + 'ur_pk': 'ur_PK.CP1256', --- python2.7-2.7.2.orig/debian/patches/webbrowser.diff +++ python2.7-2.7.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 +@@ -449,9 +449,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)) +@@ -489,6 +493,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")) --- python2.7-2.7.2.orig/debian/patches/bsddb-libpath.diff +++ python2.7-2.7.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 +@@ -977,7 +977,13 @@ + if db_setup_debug: + print "bsddb using BerkeleyDB lib:", db_ver, dblib + print "bsddb lib dir:", dblib_dir, " inc dir:", db_incdir +- db_incs = [db_incdir] ++ # only add db_incdir/dblib_dir if not in the standard paths ++ if db_incdir in inc_dirs: ++ db_incs = [] ++ else: ++ db_incs = [db_incdir] ++ if dblib_dir[0] in lib_dirs: ++ dblib_dir = [] + dblibs = [dblib] + # We add the runtime_library_dirs argument because the + # BerkeleyDB lib we're linking against often isn't in the --- python2.7-2.7.2.orig/debian/patches/langpack-gettext.diff +++ python2.7-2.7.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 +@@ -446,11 +446,26 @@ + if lang == 'C': + break + mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) ++ mofile_lp = os.path.join("/usr/share/locale-langpack", lang, ++ 'LC_MESSAGES', '%s.mo' % domain) ++ ++ # first look into the standard locale dir, then into the ++ # langpack locale dir ++ ++ # standard mo file + if os.path.exists(mofile): + if all: + result.append(mofile) + else: + return mofile ++ ++ # langpack mofile -> use it ++ if os.path.exists(mofile_lp): ++ if all: ++ result.append(mofile_lp) ++ else: ++ return mofile_lp ++ + return result + + --- python2.7-2.7.2.orig/debian/patches/issue9189.diff +++ python2.7-2.7.2/debian/patches/issue9189.diff @@ -0,0 +1,344 @@ +Index: b/Lib/sysconfig.py +=================================================================== +--- a/Lib/sysconfig.py ++++ b/Lib/sysconfig.py +@@ -226,11 +226,19 @@ + done[n] = v + + # do variable interpolation here +- while notdone: +- for name in notdone.keys(): ++ variables = list(notdone.keys()) ++ ++ # Variables with a 'PY_' prefix in the makefile. These need to ++ # be made available without that prefix through sysconfig. ++ # Special care is needed to ensure that variable expansion works, even ++ # if the expansion uses the name without a prefix. ++ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') ++ ++ while len(variables) > 0: ++ for name in tuple(variables): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) +- if m: ++ if m is not None: + n = m.group(1) + found = True + if n in done: +@@ -241,23 +249,48 @@ + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] ++ ++ elif n in renamed_variables: ++ if name.startswith('PY_') and name[3:] in renamed_variables: ++ item = "" ++ ++ elif 'PY_' + n in notdone: ++ found = False ++ ++ else: ++ item = str(done['PY_' + n]) ++ + else: + done[n] = item = "" ++ + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: +- try: value = int(value) ++ try: ++ value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value +- del notdone[name] ++ variables.remove(name) ++ ++ if name.startswith('PY_') \ ++ and name[3:] in renamed_variables: ++ ++ name = name[3:] ++ if name not in done: ++ done[name] = value ++ ++ + else: +- # bogus variable reference; just drop it since we can't deal +- del notdone[name] ++ # bogus variable reference (e.g. "prefix=$/opt/python"); ++ # just drop it since we can't deal ++ done[name] = value ++ variables.remove(name) ++ + # strip spurious spaces + for k, v in done.items(): + if isinstance(v, str): +Index: b/Makefile.pre.in +=================================================================== +--- a/Makefile.pre.in ++++ b/Makefile.pre.in +@@ -62,12 +62,18 @@ + # Compiler options + OPT= @OPT@ + BASECFLAGS= @BASECFLAGS@ +-CFLAGS= $(BASECFLAGS) @CFLAGS@ $(OPT) $(EXTRA_CFLAGS) ++CONFIGURE_CFLAGS= @CFLAGS@ ++CONFIGURE_CPPFLAGS= @CPPFLAGS@ ++CONFIGURE_LDFLAGS= @LDFLAGS@ ++# Avoid assigning CFLAGS, LDFLAGS, etc. so users can use them on the ++# command line to append to these values without stomping the pre-set ++# values. ++PY_CFLAGS= $(BASECFLAGS) $(OPT) $(CONFIGURE_CFLAGS) $(CFLAGS) $(EXTRA_CFLAGS) + # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to + # be able to build extension modules using the directories specified in the + # environment variables +-CPPFLAGS= -I. -IInclude -I$(srcdir)/Include @CPPFLAGS@ +-LDFLAGS= @LDFLAGS@ ++PY_CPPFLAGS= -I. -IInclude -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS) ++PY_LDFLAGS= $(CONFIGURE_LDFLAGS) $(LDFLAGS) + LDLAST= @LDLAST@ + SGI_ABI= @SGI_ABI@ + CCSHARED= @CCSHARED@ +@@ -76,7 +82,7 @@ + # Extra C flags added for building the interpreter object files. + CFLAGSFORSHARED=@CFLAGSFORSHARED@ + # C flags used for building the interpreter object files +-PY_CFLAGS= $(CFLAGS) $(CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE ++PY_CORE_CFLAGS= $(PY_CFLAGS) $(PY_CPPFLAGS) $(CFLAGSFORSHARED) -DPy_BUILD_CORE + + + # Machine-dependent subdirectories +@@ -396,7 +402,7 @@ + + # Build the interpreter + $(BUILDPYTHON): Modules/python.o $(LIBRARY) $(LDLIBRARY) +- $(LINKCC) $(LDFLAGS) $(LINKFORSHARED) -o $@ \ ++ $(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ \ + Modules/python.o \ + $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST) + +@@ -407,8 +413,8 @@ + # Build the shared modules + sharedmods: $(BUILDPYTHON) + @case $$MAKEFLAGS in \ +- *s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \ +- *) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \ ++ *s*) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py -q build;; \ ++ *) $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' LDFLAGS='$(PY_LDFLAGS)' OPT='$(OPT)' ./$(BUILDPYTHON) -E $(srcdir)/setup.py build;; \ + esac + + # Build static library +@@ -425,18 +431,18 @@ + + libpython$(VERSION).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ +- $(BLDSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(BLDSHARED) $(PY_LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ + else \ +- $(BLDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(BLDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + fi + + libpython$(VERSION).dylib: $(LIBRARY_OBJS) +- $(CC) -dynamiclib -Wl,-single_module $(LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ ++ $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + + + libpython$(VERSION).sl: $(LIBRARY_OBJS) +- $(LDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) ++ $(LDSHARED) $(PY_LDFLAGS) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST) + + # Copy up the gdb python hooks into a position where they can be automatically + # loaded by gdb during Lib/test/test_gdb.py +@@ -475,7 +481,7 @@ + # for a shared core library; otherwise, this rule is a noop. + $(DLLLIBRARY) libpython$(VERSION).dll.a: $(LIBRARY_OBJS) + if test -n "$(DLLLIBRARY)"; then \ +- $(LDSHARED) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ ++ $(LDSHARED) $(PY_LDFLAGS) -Wl,--out-implib=$@ -o $(DLLLIBRARY) $^ \ + $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST); \ + else true; \ + fi +@@ -519,7 +525,7 @@ + $(SIGNAL_OBJS) \ + $(MODOBJS) \ + $(srcdir)/Modules/getbuildinfo.c +- $(CC) -c $(PY_CFLAGS) \ ++ $(CC) -c $(PY_CORE_CFLAGS) \ + -DSVNVERSION="\"`LC_ALL=C $(SVNVERSION)`\"" \ + -DHGVERSION="\"`LC_ALL=C $(HGVERSION)`\"" \ + -DHGTAG="\"`LC_ALL=C $(HGTAG)`\"" \ +@@ -527,7 +533,7 @@ + -o $@ $(srcdir)/Modules/getbuildinfo.c + + Modules/getpath.o: $(srcdir)/Modules/getpath.c Makefile +- $(CC) -c $(PY_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ ++ $(CC) -c $(PY_CORE_CFLAGS) -DPYTHONPATH='"$(PYTHONPATH)"' \ + -DPREFIX='"$(prefix)"' \ + -DEXEC_PREFIX='"$(exec_prefix)"' \ + -DVERSION='"$(VERSION)"' \ +@@ -535,7 +541,7 @@ + -o $@ $(srcdir)/Modules/getpath.c + + Modules/python.o: $(srcdir)/Modules/python.c +- $(MAINCC) -c $(PY_CFLAGS) -o $@ $(srcdir)/Modules/python.c ++ $(MAINCC) -c $(PY_CORE_CFLAGS) -o $@ $(srcdir)/Modules/python.c + + + # Use a stamp file to prevent make -j invoking pgen twice +@@ -546,7 +552,7 @@ + -touch Parser/pgen.stamp + + $(PGEN): $(PGENOBJS) +- $(CC) $(OPT) $(LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) ++ $(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN) + + Parser/grammar.o: $(srcdir)/Parser/grammar.c \ + $(srcdir)/Include/token.h \ +@@ -566,10 +572,10 @@ + Python/compile.o Python/symtable.o Python/ast.o: $(GRAMMAR_H) $(AST_H) + + Python/getplatform.o: $(srcdir)/Python/getplatform.c +- $(CC) -c $(PY_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c ++ $(CC) -c $(PY_CORE_CFLAGS) -DPLATFORM='"$(MACHDEP)"' -o $@ $(srcdir)/Python/getplatform.c + + Python/importdl.o: $(srcdir)/Python/importdl.c +- $(CC) -c $(PY_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c ++ $(CC) -c $(PY_CORE_CFLAGS) -I$(DLINCLDIR) -o $@ $(srcdir)/Python/importdl.c + + Objects/unicodectype.o: $(srcdir)/Objects/unicodectype.c \ + $(srcdir)/Objects/unicodetype_db.h +@@ -1144,7 +1150,7 @@ + + # Some make's put the object file in the current directory + .c.o: +- $(CC) -c $(PY_CFLAGS) -o $@ $< ++ $(CC) -c $(PY_CORE_CFLAGS) -o $@ $< + + # Run reindent on the library + reindent: +Index: b/Modules/makesetup +=================================================================== +--- a/Modules/makesetup ++++ b/Modules/makesetup +@@ -219,7 +219,7 @@ + case $doconfig in + no) cc="$cc \$(CCSHARED) \$(CFLAGS) \$(CPPFLAGS)";; + *) +- cc="$cc \$(PY_CFLAGS)";; ++ cc="$cc \$(PY_CORE_CFLAGS)";; + esac + rule="$obj: $src; $cc $cpps -c $src -o $obj" + echo "$rule" >>$rulesf +Index: b/configure.in +=================================================================== +--- a/configure.in ++++ b/configure.in +@@ -507,14 +507,13 @@ + (it is also a good idea to do 'make clean' before compiling)]) + fi + +-# If the user set CFLAGS, use this instead of the automatically +-# determined setting +-preset_cflags="$CFLAGS" +-AC_PROG_CC +-if test ! -z "$preset_cflags" +-then +- CFLAGS=$preset_cflags ++# Don't let AC_PROG_CC set the default CFLAGS. It normally sets -g -O2 ++# when the compiler supports them, but we don't always want -O2, and ++# we set -g later. ++if test -z "$CFLAGS"; then ++ CFLAGS= + fi ++AC_PROG_CC + + AC_SUBST(CXX) + AC_SUBST(MAINCC) +Index: b/Lib/distutils/sysconfig.py +=================================================================== +--- a/Lib/distutils/sysconfig.py ++++ b/Lib/distutils/sysconfig.py +@@ -283,11 +283,19 @@ + done[n] = v + + # do variable interpolation here +- while notdone: +- for name in notdone.keys(): ++ variables = list(notdone.keys()) ++ ++ # Variables with a 'PY_' prefix in the makefile. These need to ++ # be made available without that prefix through sysconfig. ++ # Special care is needed to ensure that variable expansion works, even ++ # if the expansion uses the name without a prefix. ++ renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') ++ ++ while len(variables) > 0: ++ for name in tuple(variables): + value = notdone[name] + m = _findvar1_rx.search(value) or _findvar2_rx.search(value) +- if m: ++ if m is not None: + n = m.group(1) + found = True + if n in done: +@@ -298,25 +306,47 @@ + elif n in os.environ: + # do it like make: fall back to environment + item = os.environ[n] ++ ++ elif n in renamed_variables: ++ if name.startswith('PY_') and name[3:] in renamed_variables: ++ item = "" ++ ++ elif 'PY_' + n in notdone: ++ found = False ++ ++ else: ++ item = str(done['PY_' + n]) ++ + else: + done[n] = item = "" ++ + if found: + after = value[m.end():] + value = value[:m.start()] + item + after + if "$" in after: + notdone[name] = value + else: +- try: value = int(value) ++ try: ++ value = int(value) + except ValueError: + done[name] = value.strip() + else: + done[name] = value +- del notdone[name] +- else: +- # bogus variable reference; just drop it since we can't deal +- del notdone[name] ++ variables.remove(name) ++ ++ if name.startswith('PY_') \ ++ and name[3:] in renamed_variables: + +- fp.close() ++ name = name[3:] ++ if name not in done: ++ done[name] = value ++ ++ ++ else: ++ # bogus variable reference (e.g. "prefix=$/opt/python"); ++ # just drop it since we can't deal ++ done[name] = value ++ variables.remove(name) + + # strip spurious spaces + for k, v in done.items(): --- python2.7-2.7.2.orig/debian/patches/plat-linux2_alpha.diff +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/patches/issue9012a.diff +++ python2.7-2.7.2/debian/patches/issue9012a.diff @@ -0,0 +1,13 @@ +# DP: Link _math.o only once to the static library. + +--- a/Modules/Setup.dist ++++ b/Modules/Setup.dist +@@ -169,7 +169,7 @@ + # Modules that should always be present (non UNIX dependent): + + #array arraymodule.c # array objects +-#cmath cmathmodule.c _math.c # -lm # complex math library functions ++#cmath cmathmodule.c # -lm # complex math library functions + #math mathmodule.c _math.c # -lm # math library functions, e.g. sin() + #_struct _struct.c # binary structure packing/unpacking + #time timemodule.c # -lm # time operations and variables --- python2.7-2.7.2.orig/debian/patches/hurd-disable-nonworking-constants.diff +++ python2.7-2.7.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 +@@ -9193,12 +9193,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 +@@ -4815,9 +4815,11 @@ + #ifdef SO_OOBINLINE + PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE); + #endif ++#ifndef __GNU__ + #ifdef SO_REUSEPORT + PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT); + #endif ++#endif + #ifdef SO_SNDBUF + PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF); + #endif --- python2.7-2.7.2.orig/debian/patches/deb-setup.diff +++ python2.7-2.7.2/debian/patches/deb-setup.diff @@ -0,0 +1,17 @@ +# DP: Don't include /usr/local/include and /usr/local/lib as gcc search paths + +--- a/setup.py ++++ b/setup.py +@@ -368,9 +368,9 @@ + os.unlink(tmpfile) + + def detect_modules(self): +- # Ensure that /usr/local is always used +- 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 --- python2.7-2.7.2.orig/debian/patches/hurd-broken-poll.diff +++ python2.7-2.7.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 +@@ -1736,7 +1736,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 */ +@@ -1768,7 +1768,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) { --- python2.7-2.7.2.orig/debian/patches/makesetup-bashism.diff +++ python2.7-2.7.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 --- python2.7-2.7.2.orig/debian/source/format +++ python2.7-2.7.2/debian/source/format @@ -0,0 +1 @@ +1.0