--- python3.1-3.1.1.orig/debian/mkbinfmt.py +++ python3.1-3.1.1/debian/mkbinfmt.py @@ -0,0 +1,18 @@ +# mkbinfmt.py +import imp, sys, os.path + +magic = "".join(["\\x%.2x" % c for c in imp.get_magic()]) + +name = sys.argv[1] + +binfmt = '''\ +package %s +interpreter /usr/bin/%s +magic %s\ +''' % (name, name, magic) + +#filename = '/usr/share/binfmts/' + name +#open(filename,'w+').write(binfmt) + +sys.stdout.write(binfmt) +sys.stdout.write('\n') --- python3.1-3.1.1.orig/debian/PVER-minimal.preinst.in +++ python3.1-3.1.1/debian/PVER-minimal.preinst.in @@ -0,0 +1,26 @@ +#!/bin/sh + +set -e + +case "$1" in + install) + # remember newly installed runtime + mkdir -p /var/lib/python + touch /var/lib/python/@PVER@_installed + ;; + upgrade) + : + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +#DEBHELPER# + +exit 0 --- python3.1-3.1.1.orig/debian/README.idle-PVER.in +++ python3.1-3.1.1/debian/README.idle-PVER.in @@ -0,0 +1,14 @@ + + The Python IDLE package for Debian + ---------------------------------- + +This package contains Python @VER@'s Integrated DeveLopment Environment, IDLE. + +IDLE is included in the Python @VER@ upstream distribution (Tools/idle) and +depends on Tkinter (available as @PVER@-tk package). + +I have written a simple man page. + + + 06/16/1999 + Gregor Hoffleit --- python3.1-3.1.1.orig/debian/pyhtml2devhelp.py +++ python3.1-3.1.1/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] + + parser = PyHTMLParser(formatter.NullFormatter(), base, fn, indent=0) + print '' + version = "3.1" + print '' % (sys.version[:3], version) + print '' + parser.parse_file(fn) + print '' + + print '' + + fn = 'genindex-all.html' + parser = PyIdxHTMLParser(formatter.NullFormatter(), base, fn, indent=1) + text = file(base + '/' + fn).read() + parser.feed(text) + parser.close() + + print '' + print '' + +main() --- python3.1-3.1.1.orig/debian/pymindeps.py +++ python3.1-3.1.1/debian/pymindeps.py @@ -0,0 +1,168 @@ +#! /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 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 + 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(('cPickle', 'pickle', 'doctest')), + 'copy': set(('reprlib',)), + #'hashlib': set(('_hashlib', '_md5', '_sha', '_sha256','_sha512',)), + 'heapq': set(('doctest',)), + 'io': set(('_dummy_thread',)), + 'os': set(('nt', 'ntpath', 'os2', 'os2emxpath', 'mac', 'macpath', + 'riscos', 'riscospath', 'riscosenviron')), + 'optparse': set(('gettext',)), + 'pickle': set(('doctest',)), + 'platform': set(('tempfile',)), + #'socket': set(('_ssl',)), + 'subprocess': set(('threading',)), + } + +def main(argv): + # Parse command line + import getopt + try: + opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") + except getopt.error as msg: + print(msg) + return + + # Process options + debug = 1 + domods = 0 + addpath = [] + exclude = [] + for o, a in opts: + if o == '-d': + debug = debug + 1 + if o == '-m': + domods = 1 + if o == '-p': + addpath = addpath + a.split(os.pathsep) + if o == '-q': + debug = 0 + if o == '-x': + exclude.append(a) + + path = sys.path[:] + path = addpath + path + + if debug > 1: + print("version:", sys.version) + print("path:") + for item in path: + print(" ", repr(item)) + + #exclude = ['__builtin__', 'sys', 'os'] + exclude = [] + mf = mymf(path, debug, exclude) + for arg in args: + mf.run_script(arg) + + depgraph = reduce_depgraph(mf._depgraph) + + pprint.pprint({'depgraph':mf._depgraph, 'types':mf._types}) + +if __name__=='__main__': + main(sys.argv[1:]) --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-tut.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-tut.in @@ -0,0 +1,13 @@ +Document: @PVER@-tut +Title: Python Tutorial (v@VER@) +Author: Guido van Rossum, Fred L. Drake, Jr., editor +Abstract: This tutorial introduces the reader informally to the basic + concepts and features of the Python language and system. It helps + to have a Python interpreter handy for hands-on experience, but + all examples are self-contained, so the tutorial can be read + off-line as well. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/tutorial/index.html +Files: /usr/share/doc/@PVER@/html/tutorial/*.html --- python3.1-3.1.1.orig/debian/pydoc.1.in +++ python3.1-3.1.1/debian/pydoc.1.in @@ -0,0 +1,53 @@ +.TH PYDOC@VER@ 1 +.SH NAME +pydoc@VER@ \- the Python documentation tool +.SH SYNOPSIS +.PP +.B pydoc@VER@ +.I name +.PP +.B pydoc@VER@ -k +.I keyword +.PP +.B pydoc@VER@ -p +.I port +.PP +.B pydoc@VER@ -g +.PP +.B pydoc@VER@ -w +.I module [...] +.SH DESCRIPTION +.PP +.B pydoc@VER@ +.I name +Show text documentation on something. +.I name +may be the name of a +Python keyword, topic, function, module, or package, or a dotted +reference to a class or function within a module or module in a +package. If +.I name +contains a '/', it is used as the path to a +Python source file to document. If name is 'keywords', 'topics', +or 'modules', a listing of these things is displayed. +.PP +.B pydoc@VER@ -k +.I keyword +Search for a keyword in the synopsis lines of all available modules. +.PP +.B pydoc@VER@ -p +.I port +Start an HTTP server on the given port on the local machine. +.PP +.B pydoc@VER@ -g +Pop up a graphical interface for finding and serving documentation. +.PP +.B pydoc@VER@ -w +.I name [...] +Write out the HTML documentation for a module to a file in the current +directory. If +.I name +contains a '/', it is treated as a filename; if +it names a directory, documentation is written for all the contents. +.SH AUTHOR +Moshe Zadka, based on "pydoc --help" --- python3.1-3.1.1.orig/debian/dh_doclink +++ python3.1-3.1.1/debian/dh_doclink @@ -0,0 +1,28 @@ +#! /bin/sh + +pkg=`echo $1 | sed 's/^-p//'` +target=$2 + +ln -sf $target debian/$pkg/usr/share/doc/$pkg + +f=debian/$pkg.postinst.debhelper +if [ ! -e $f ] || [ "`grep -c '^# dh_doclink' $f`" -eq 0 ]; then +cat >> $f <> $f < + +Last change: 2001-12-14 --- python3.1-3.1.1.orig/debian/PVER.desktop.in +++ python3.1-3.1.1/debian/PVER.desktop.in @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=Python (v@VER@) +Comment=Python Interpreter (v@VER@) +Exec=/usr/bin/@PVER@ +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=true +Type=Application +Categories=Development; +StartupNotify=true +NoDisplay=true --- python3.1-3.1.1.orig/debian/sitecustomize.py.in +++ python3.1-3.1.1/debian/sitecustomize.py.in @@ -0,0 +1,7 @@ +# install the apport exception handler if available +try: + import apport_python_hook +except ImportError: + pass +else: + apport_python_hook.install() --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-lib.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-lib.in @@ -0,0 +1,15 @@ +Document: @PVER@-lib +Title: Python Library Reference (v@VER@) +Author: Guido van Rossum +Abstract: This library reference manual documents Python's standard library, + as well as many optional library modules (which may or may not be + available, depending on whether the underlying platform supports + them and on the configuration choices made at compile time). It + also documents the standard types of the language and its built-in + functions and exceptions, many of which are not or incompletely + documented in the Reference Manual. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/library/index.html +Files: /usr/share/doc/@PVER@/html/library/*.html --- python3.1-3.1.1.orig/debian/pylogo.xpm +++ python3.1-3.1.1/debian/pylogo.xpm @@ -0,0 +1,351 @@ +/* XPM */ +static char * pylogo_xpm[] = { +"32 32 316 2", +" c None", +". c #8DB0CE", +"+ c #6396BF", +"@ c #4985B7", +"# c #4181B5", +"$ c #417EB2", +"% c #417EB1", +"& c #4D83B0", +"* c #6290B6", +"= c #94B2CA", +"- c #70A1C8", +"; c #3D83BC", +"> c #3881BD", +", c #387DB6", +"' c #387CB5", +") c #387BB3", +"! c #3779B0", +"~ c #3778AE", +"{ c #3776AB", +"] c #3776AA", +"^ c #3775A9", +"/ c #4A7FAC", +"( c #709FC5", +"_ c #3A83BE", +": c #5795C7", +"< c #94B9DB", +"[ c #73A4CE", +"} c #3D80B7", +"| c #387CB4", +"1 c #377AB2", +"2 c #377AB0", +"3 c #3777AC", +"4 c #3774A7", +"5 c #3773A5", +"6 c #3C73A5", +"7 c #4586BB", +"8 c #4489C1", +"9 c #A7C7E1", +"0 c #F7F9FD", +"a c #E1E9F1", +"b c #4C89BC", +"c c #3779AF", +"d c #3778AD", +"e c #3873A5", +"f c #4B7CA4", +"g c #3982BE", +"h c #4389C1", +"i c #A6C6E1", +"j c #F6F9FC", +"k c #D6E4F0", +"l c #4A88BB", +"m c #3773A6", +"n c #366F9F", +"o c #366E9D", +"p c #376E9C", +"q c #4A8BC0", +"r c #79A7CD", +"s c #548EBD", +"t c #387AB0", +"u c #3773A4", +"v c #366D9C", +"w c #387FBA", +"x c #387DB7", +"y c #387BB4", +"z c #3775A8", +"A c #366FA0", +"B c #4981AF", +"C c #427BAA", +"D c #3772A4", +"E c #376B97", +"F c #77A3C8", +"G c #4586BC", +"H c #3882BE", +"I c #3B76A7", +"J c #3B76A6", +"K c #366E9E", +"L c #376B98", +"M c #376B96", +"N c #5681A3", +"O c #F5EEB8", +"P c #FFED60", +"Q c #FFE85B", +"R c #FFE659", +"S c #FDE55F", +"T c #5592C4", +"U c #3A83BF", +"V c #3882BD", +"W c #387FB9", +"X c #3779AE", +"Y c #366F9E", +"Z c #366C98", +"` c #376A94", +" . c #5D85A7", +".. c #F5EDB7", +"+. c #FFEA5D", +"@. c #FFE75A", +"#. c #FFE354", +"$. c #FDDD56", +"%. c #669DC8", +"&. c #3885C3", +"*. c #3884C2", +"=. c #387EB8", +"-. c #387CB6", +";. c #377AB1", +">. c #3772A3", +",. c #366D9B", +"'. c #F5EBB5", +"). c #FFE557", +"!. c #FFE455", +"~. c #FFDF50", +"{. c #FFDB4C", +"]. c #FAD862", +"^. c #8EB4D2", +"/. c #3C86C1", +"(. c #3883C0", +"_. c #3882BF", +":. c #3881BC", +"<. c #3880BB", +"[. c #3775AA", +"}. c #F5EAB3", +"|. c #FFE051", +"1. c #FFDE4F", +"2. c #FFDA4A", +"3. c #FED446", +"4. c #F5DF9D", +"5. c #77A5CA", +"6. c #3885C2", +"7. c #387BB2", +"8. c #6B8EA8", +"9. c #F8E7A1", +"0. c #FFE153", +"a. c #FFDD4E", +"b. c #FFDB4B", +"c. c #FFD746", +"d. c #FFD645", +"e. c #FFD342", +"f. c #F6DB8D", +"g. c #508DBE", +"h. c #3771A3", +"i. c #376A95", +"j. c #3D6F97", +"k. c #C3CBC2", +"l. c #FBD964", +"m. c #FFDC4D", +"n. c #FFD544", +"o. c #FFD040", +"p. c #F9CF58", +"q. c #3F83BB", +"r. c #376B95", +"s. c #3A6C95", +"t. c #4E7BA0", +"u. c #91AABC", +"v. c #F6E4A3", +"w. c #FFDA4B", +"x. c #FFD646", +"y. c #FFD443", +"z. c #FFD241", +"A. c #FFCE3D", +"B. c #FFCC3B", +"C. c #FCC83E", +"D. c #3880BC", +"E. c #3C79AC", +"F. c #5F8DB4", +"G. c #7AA0C0", +"H. c #82A6C3", +"I. c #82A3BF", +"J. c #82A2BE", +"K. c #82A1BB", +"L. c #82A1B9", +"M. c #8BA4B5", +"N. c #C1C5AE", +"O. c #F2E19F", +"P. c #FDD74C", +"Q. c #FFD94A", +"R. c #FFD343", +"S. c #FFCE3E", +"T. c #FFCB39", +"U. c #FFC937", +"V. c #FEC636", +"W. c #3D79AB", +"X. c #9DB6C6", +"Y. c #D0CFA2", +"Z. c #EFE598", +"`. c #F8EE9B", +" + c #F8EB97", +".+ c #F8E996", +"++ c #F8E894", +"@+ c #FAE489", +"#+ c #FCDB64", +"$+ c #FFDA4D", +"%+ c #FFCF3E", +"&+ c #FFCB3A", +"*+ c #FFC734", +"=+ c #FFC532", +"-+ c #3F82B7", +";+ c #387EB9", +">+ c #9EB9D0", +",+ c #F2E287", +"'+ c #FDEB69", +")+ c #FEEC60", +"!+ c #FFEB5E", +"~+ c #FFE254", +"{+ c #FFE152", +"]+ c #FFD747", +"^+ c #FFC633", +"/+ c #FCC235", +"(+ c #578FBE", +"_+ c #6996BC", +":+ c #DED9A8", +"<+ c #FEEC62", +"[+ c #FFE658", +"}+ c #FFDF51", +"|+ c #FFDE50", +"1+ c #FFD03F", +"2+ c #FFCD3C", +"3+ c #FFC431", +"4+ c #FFBF2C", +"5+ c #FAC244", +"6+ c #85AACA", +"7+ c #A1BBD2", +"8+ c #F7E47C", +"9+ c #FFE456", +"0+ c #FFC735", +"a+ c #FFBC29", +"b+ c #F7D280", +"c+ c #9DBAD2", +"d+ c #3B7CB2", +"e+ c #ABC2D6", +"f+ c #FDEB7B", +"g+ c #FFC12E", +"h+ c #FDBD30", +"i+ c #F4DEA8", +"j+ c #5F91BA", +"k+ c #ABC1D4", +"l+ c #FDEE7E", +"m+ c #FFE253", +"n+ c #FFCC3C", +"o+ c #FFBA27", +"p+ c #FAC75B", +"q+ c #4A82B0", +"r+ c #3877AB", +"s+ c #3774A6", +"t+ c #AAC0D4", +"u+ c #FDEE7D", +"v+ c #FFEC5F", +"w+ c #FFE255", +"x+ c #FFD848", +"y+ c #FFD444", +"z+ c #FFCF3F", +"A+ c #FFBC2A", +"B+ c #FFBB28", +"C+ c #FDBA32", +"D+ c #447AA8", +"E+ c #4379A7", +"F+ c #FFE95C", +"G+ c #FFE558", +"H+ c #FFE355", +"I+ c #FED84B", +"J+ c #FCD149", +"K+ c #FBCE47", +"L+ c #FBCD46", +"M+ c #FBC840", +"N+ c #FBC63E", +"O+ c #FBC037", +"P+ c #FAC448", +"Q+ c #FDD44C", +"R+ c #FCD14E", +"S+ c #FFC836", +"T+ c #FFC22F", +"U+ c #FFC02D", +"V+ c #FFE052", +"W+ c #FFC636", +"X+ c #FFCF5C", +"Y+ c #FFD573", +"Z+ c #FFC33E", +"`+ c #FEBD2D", +" @ c #FFDB4D", +".@ c #FFD949", +"+@ c #FFD545", +"@@ c #FFD140", +"#@ c #FFCB48", +"$@ c #FFF7E4", +"%@ c #FFFCF6", +"&@ c #FFE09D", +"*@ c #FFBA2E", +"=@ c #FDBE2F", +"-@ c #FFD748", +";@ c #FFCA38", +">@ c #FFC844", +",@ c #FFF2D7", +"'@ c #FFF9EC", +")@ c #FFDB94", +"!@ c #FFB92D", +"~@ c #FAC54D", +"{@ c #FDD54E", +"]@ c #FFBD2D", +"^@ c #FFC858", +"/@ c #FFD174", +"(@ c #FFBF3E", +"_@ c #FCBD3C", +":@ c #FAD66A", +"<@ c #FECD3F", +"[@ c #FFC330", +"}@ c #FFBD2A", +"|@ c #FFB724", +"1@ c #FFB521", +"2@ c #FFB526", +"3@ c #FBC457", +"4@ c #F7E09E", +"5@ c #F8D781", +"6@ c #FAC349", +"7@ c #FCC134", +"8@ c #FEBE2C", +"9@ c #FBBE3F", +"0@ c #F7CF79", +"a@ c #F5D795", +" . + @ # $ % % & * = ", +" - ; > > , ' ) ! ~ { ] ^ / ", +" ( _ : < [ } | 1 2 ~ 3 4 5 5 6 ", +" 7 8 9 0 a b 2 c d 3 { 5 5 5 e f ", +" g h i j k l c ~ { { m 5 5 n o p ", +" > > q r s t c c d 4 5 u n v v v ", +" w x ' y 2 c d d z 5 u A v v v v ", +" B C 5 D v v v v E ", +" F G H H H x ' ) c c c d I J 5 K v v L M N O P Q R S ", +" T U H V V W ' ) c c X ~ 5 5 5 Y v v Z ` ` ...+.@.#.#.$. ", +" %.&.*.> w W =.-.;.c 3 { ^ 5 5 >.o v ,.E ` ` .'.).!.#.~.{.]. ", +"^./.(._.:.<., ' ) ;.X d [.5 5 >.K v ,.E ` ` ` .}.#.|.1.{.2.3.4.", +"5.6.(.H H x ' 7.c c 3 3 4 5 D K v v ,.` ` ` ` 8.9.0.a.b.c.d.e.f.", +"g._.> <.w ' ' | 2 3 { z 5 5 h.v v v i.` ` ` j.k.l.m.{.d.n.e.o.p.", +"q.> > :.-.' 1 c c c ] 5 5 >.v v ,.r.` ` s.t.u.v.{.w.x.y.z.A.B.C.", +"D.D.w -.' 1 c c c E.F.G.H.I.J.J.K.L.L.L.M.N.O.P.Q.c.R.S.B.T.U.V.", +"D.D.=.' ' 1 c c W.X.Y.Z.`.`.`.`.`. +.+++@+#+$+Q.d.R.%+B.&+*+=+=+", +"-+;+-.' ;.2 c c >+,+'+)+P P P !+Q R ~+{+1.{.]+d.y.%+B.&+^+=+=+/+", +"(+' ' ;.c X X _+:+<+P P P P !+R [+~+}+|+{.]+n.R.1+2+&+^+=+3+4+5+", +"6+' ) ! ~ { { 7+8+P P P P !+R 9+#.{+{.w.]+y.z.S.&+0+=+=+3+4+a+b+", +"c+d+7.! d 3 z e+f+P P P !+R 9+#.{+m.{.]+y.1+B.&+0+=+=+g+4+a+h+i+", +" j+c d 3 { 4 k+l+P P !+@.9+m+1.m.{.]+y.1+n+B.*+=+=+g+a+a+o+p+ ", +" q+r+{ s+m t+u+v+@.R w+{+}+{.x+d.y+z+n+B.0+=+=+g+A+a+B+C+ ", +" * D+E+E+ +.F+G+H+}+}+{.I+J+K+L+M+M+M+M+N+O+O+O+O+P+ ", +" ).).#.{+a.{.x+Q+R+ ", +" #.m+1.a.{.x+y.o.2+B.S+=+=+T+U+O+ ", +" 0.V+{.{.x+n.o.2+B.B.W+X+Y+Z+a+`+ ", +" @{..@+@n.@@B.B.S+^+#@$@%@&@*@=@ ", +" ].-@x.y.o.%+;@S+=+=+>@,@'@)@!@~@ ", +" {@z.z+2+U.=+=+=+T+]@^@/@(@_@ ", +" :@<@U.=+=+[@4+}@|@1@2@3@ ", +" 4@5@6@7@8@a+a+9@0@a@ "}; --- python3.1-3.1.1.orig/debian/PVER.overrides.in +++ python3.1-3.1.1/debian/PVER.overrides.in @@ -0,0 +1,8 @@ +# 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 --- python3.1-3.1.1.orig/debian/idle-PVER.prerm.in +++ python3.1-3.1.1/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 --- python3.1-3.1.1.orig/debian/PVER.menu.in +++ python3.1-3.1.1/debian/PVER.menu.in @@ -0,0 +1,4 @@ +?package(@PVER@):needs="text" section="Applications/Programming"\ + title="Python (v@VER@)"\ + icon="/usr/share/pixmaps/@PVER@.xpm"\ + command="/usr/bin/python@VER@" --- python3.1-3.1.1.orig/debian/PVER-dbg.symbols.in +++ python3.1-3.1.1/debian/PVER-dbg.symbols.in @@ -0,0 +1,25 @@ +libpython@VER@_d.so.1.0 python@VER@-dbg #MINVER# +#include "libpython.symbols" + _PyDict_Dummy@Base @VER@ + _PyObject_DebugCheckAddress@Base @VER@ + _PyObject_DebugDumpAddress@Base @VER@ + _PyObject_DebugFree@Base @VER@ + _PyObject_DebugMalloc@Base @VER@ + _PyObject_DebugMallocStats@Base @VER@ + _PyObject_DebugRealloc@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@ + PyModule_Create2TraceRefs@Base @VER@ --- python3.1-3.1.1.orig/debian/compat +++ python3.1-3.1.1/debian/compat @@ -0,0 +1 @@ +5 --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-new.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-new.in @@ -0,0 +1,10 @@ +Document: @PVER@-new +Title: What's new in Python @VER@ +Author: A.M. Kuchling +Abstract: This documents lists new features and changes worth mentioning + in Python @VER@. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/whatsnew/@VER@.html +Files: /usr/share/doc/@PVER@/html/whatsnew/@VER@.html --- python3.1-3.1.1.orig/debian/PVER-minimal.postinst.in +++ python3.1-3.1.1/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 + chmod 2775 $localsite + chown root:staff $localsite + fi + #if [ ! -h $syssite ]; then + # ln -s $syslink $syssite + #fi + + if which update-binfmts >/dev/null; then + update-binfmts --import @PVER@ + fi + + ;; +esac + +if [ "$1" = configure ]; then + ( + files=$(dpkg -L @PVER@-minimal | sed -n '/^\/usr\/lib\/@PVER@\/.*\.py$/p') + @PVER@ /usr/lib/@PVER@/py_compile.py $files + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config; then + @PVER@ -O /usr/lib/@PVER@/py_compile.py $files + fi + ) + bc=no + #if [ -z "$2" ] || dpkg --compare-versions "$2" lt 2.5-3 \ + # || [ -f /var/lib/python/@PVER@_installed ]; then + # bc=yes + #fi + if ! grep -sq '^supported-versions[^#]*@PVER@' /usr/share/python/debian_defaults + then + # FIXME: byte compile anyway? + bc=no + fi + if [ "$bc" = yes ]; then + # new installation or installation of first version with hook support + if [ "$DEBIAN_FRONTEND" != noninteractive ]; then + echo "Linking and byte-compiling packages for runtime @PVER@..." + fi + version=$(dpkg -s @PVER@-minimal | awk '/^Version:/ {print $2}') + for hook in /usr/share/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 --- python3.1-3.1.1.orig/debian/PVER-dbg.symbols.i386.in +++ python3.1-3.1.1/debian/PVER-dbg.symbols.i386.in @@ -0,0 +1,28 @@ +libpython@VER@_d.so.1.0 python@VER@-dbg #MINVER# +#include "libpython.symbols" + _Py_force_double@Base @VER@ + _Py_get_387controlword@Base @VER@ + _Py_set_387controlword@Base @VER@ + _PyDict_Dummy@Base @VER@ + _PyObject_DebugCheckAddress@Base @VER@ + _PyObject_DebugDumpAddress@Base @VER@ + _PyObject_DebugFree@Base @VER@ + _PyObject_DebugMalloc@Base @VER@ + _PyObject_DebugMallocStats@Base @VER@ + _PyObject_DebugRealloc@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@ + PyModule_Create2TraceRefs@Base @VER@ --- python3.1-3.1.1.orig/debian/README.dbm +++ python3.1-3.1.1/debian/README.dbm @@ -0,0 +1,72 @@ + + Python and dbm modules on Debian + -------------------------------- + +This file documents the configuration of the dbm modules for Debian. It +gives hints at the preferred use of the dbm modules. + + +The preferred way to access dbm databases in Python is the anydbm module. +dbm databases behave like mappings (dictionaries). + +Since there exist several dbm database formats, we choose the following +layout for Python on Debian: + + * creating a new database with anydbm will create a Berkeley DB 2.X Hash + database file. This is the standard format used by libdb starting + with glibc 2.1. + + * opening an existing database with anydbm will try to guess the format + of the file (using whichdb) and then load it using one of the bsddb, + bsddb1, gdbm or dbm (only if the python-gdbm package is installed) + or dumbdbm modules. + + * The modules use the following database formats: + + - bsddb: Berkeley DB 2.X Hash (as in libc6 >=2.1 or libdb2) + - bsddb1: Berkeley DB 1.85 Hash (as in libc6 >=2.1 or libdb2) + - gdbm: GNU dbm 1.x or ndbm + - dbm: " (nearly the same as the gdbm module for us) + - dumbdbm: a hand-crafted format only used in this module + + That means that all usual formats should be readable with anydbm. + + * If you want to create a database in a format different from DB 2.X, + you can still directly use the specified module. + + * I.e. bsddb is the preferred module, and DB 2.X is the preferred format. + + * Note that the db1hash and bsddb1 modules are Debian specific. anydbm + and whichdb have been modified to support DB 2.X Hash files (see + below for details). + + + +For experts only: +---------------- + +Although bsddb employs the new DB 2.X format and uses the new Sleepycat +DB 2 library as included with glibc >= 2.1, it's still using the old +DB 1.85 API (which is still supported by DB 2). + +A more recent version 1.1 of the BSD DB module (available from +http://starship.skyport.net/robind/python/) directly uses the DB 2.X API. +It has a richer set of features. + + +On a glibc 2.1 system, bsddb is linked with -ldb, bsddb1 is linked with +-ldb1 and gdbm as well as dbm are linked with -lgdbm. + +On a glibc 2.0 system (e.g. potato for m68k or slink), bsddb will be +linked with -ldb2 while bsddb1 will be linked with -ldb (therefore +python-base here depends on libdb2). + + +db1hash and bsddb1 nearly completely identical to dbhash and bsddb. The +only difference is that bsddb is linked with the real DB 2 library, while +bsddb1 is linked with an library which provides compatibility with legacy +DB 1.85 databases. + + + July 16, 1999 + Gregor Hoffleit --- python3.1-3.1.1.orig/debian/README.Debian.in +++ python3.1-3.1.1/debian/README.Debian.in @@ -0,0 +1,8 @@ +The documentation for this package is in /usr/share/doc/@PVER@/. + +A draft of the "Debian Python Policy" can be found in + + /usr/share/doc/python + +Sometime it will be moved to /usr/share/doc/debian-policy in the +debian-policy package. --- python3.1-3.1.1.orig/debian/PVER-minimal.postrm.in +++ python3.1-3.1.1/debian/PVER-minimal.postrm.in @@ -0,0 +1,29 @@ +#! /bin/sh -e + +if [ "$1" = "remove" ]; then + + (find /usr/lib/@PVER@ -name '*.py[co]' | xargs rm -f {}) 2>/dev/null || true + + for d in `find /usr/lib/@PVER@ -depth -type d -empty 2> /dev/null`; do \ + while rmdir $d 2> /dev/null; do d=`dirname $d`; done; \ + done + + if [ -f /var/lib/python/@PVER@_installed ]; then + rm -f /var/lib/python/@PVER@_installed + rmdir --ignore-fail-on-non-empty /var/lib/python 2>/dev/null + fi + + rmdir --parents /usr/local/lib/@PVER@ || true +fi + +if [ "$1" = "purge" ]; then + for d in `find /usr/lib/@PVER@ -depth -type d -empty 2> /dev/null`; do \ + while rmdir $d 2> /dev/null; do d=`dirname $d`; done; \ + done + rm -f /etc/@PVER@/site.py /etc/@PVER@/sitecustomize.py + rmdir --ignore-fail-on-non-empty /etc/@PVER@ 2>/dev/null +fi + +#DEBHELPER# + +exit 0 --- python3.1-3.1.1.orig/debian/watch +++ python3.1-3.1.1/debian/watch @@ -0,0 +1,3 @@ +version=3 +opts=dversionmangle=s/.*\+// \ + http://www.python.org/ftp/python/2\.5(\.\d)?/Python-(2\.5[.\dabcr]*)\.tgz --- python3.1-3.1.1.orig/debian/libpython.symbols.in +++ python3.1-3.1.1/debian/libpython.symbols.in @@ -0,0 +1,1409 @@ + 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@ + PyBool_FromLong@Base @VER@ + PyBool_Type@Base @VER@ + PyBuffer_FillContiguousStrides@Base @VER@ + PyBuffer_FillInfo@Base @VER@ + PyBuffer_FromContiguous@Base @VER@ + PyBuffer_GetPointer@Base @VER@ + PyBuffer_IsContiguous@Base @VER@ + PyBuffer_Release@Base @VER@ + PyBuffer_ToContiguous@Base @VER@ + PyBufferedIOBase_Type@Base @VER@ + PyBufferedRWPair_Type@Base @VER@ + PyBufferedRandom_Type@Base @VER@ + PyBufferedReader_Type@Base @VER@ + PyBufferedWriter_Type@Base @VER@ + PyByteArrayIter_Type@Base @VER@ + PyByteArray_AsString@Base @VER@ + PyByteArray_Concat@Base @VER@ + PyByteArray_Fini@Base @VER@ + PyByteArray_FromObject@Base @VER@ + PyByteArray_FromStringAndSize@Base @VER@ + PyByteArray_Init@Base @VER@ + PyByteArray_Resize@Base @VER@ + PyByteArray_Size@Base @VER@ + PyByteArray_Type@Base @VER@ + PyBytesIO_Type@Base @VER@ + PyBytesIter_Type@Base @VER@ + PyBytes_AsString@Base @VER@ + PyBytes_AsStringAndSize@Base @VER@ + PyBytes_Concat@Base @VER@ + PyBytes_ConcatAndDel@Base @VER@ + PyBytes_DecodeEscape@Base @VER@ + PyBytes_Fini@Base @VER@ + PyBytes_FromFormat@Base @VER@ + PyBytes_FromFormatV@Base @VER@ + PyBytes_FromObject@Base @VER@ + PyBytes_FromString@Base @VER@ + PyBytes_FromStringAndSize@Base @VER@ + PyBytes_Repr@Base @VER@ + PyBytes_Size@Base @VER@ + PyBytes_Type@Base @VER@ + PyCArgObject_new@Base @VER@ + PyCArg_Type@Base @VER@ + PyCArrayType_Type@Base @VER@ + PyCArrayType_from_ctype@Base @VER@ + PyCArray_Type@Base @VER@ + PyCData_AtAddress@Base @VER@ + PyCData_FromBaseObj@Base @VER@ + PyCData_Type@Base @VER@ + PyCData_get@Base @VER@ + PyCData_set@Base @VER@ + PyCField_FromDesc@Base @VER@ + PyCField_Type@Base @VER@ + PyCFuncPtrType_Type@Base @VER@ + PyCFuncPtr_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@ + PyCPointerType_Type@Base @VER@ + PyCPointer_Type@Base @VER@ + PyCSimpleType_Type@Base @VER@ + PyCStgDict_Type@Base @VER@ + PyCStgDict_clone@Base @VER@ + PyCStructType_Type@Base @VER@ + PyCStructUnionType_update_stgdict@Base @VER@ + PyCThunk_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@ + PyClassMethodDescr_Type@Base @VER@ + PyClassMethod_New@Base @VER@ + PyClassMethod_Type@Base @VER@ + PyCode_Addr2Line@Base @VER@ + PyCode_CheckLineNumber@Base @VER@ + PyCode_New@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_KnownEncoding@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_GetItemProxy@Base @VER@ + PyDict_GetItemString@Base @VER@ + PyDict_GetItemWithError@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_SetItemProxy@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_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_CallObject@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_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_ArgError@Base @VER@ + PyExc_ArithmeticError@Base @VER@ + PyExc_AssertionError@Base @VER@ + PyExc_AttributeError@Base @VER@ + PyExc_BaseException@Base @VER@ + PyExc_BlockingIOError@Base @VER@ + PyExc_BufferError@Base @VER@ + PyExc_BytesWarning@Base @VER@ + PyExc_DeprecationWarning@Base @VER@ + PyExc_EOFError@Base @VER@ + PyExc_EnvironmentError@Base @VER@ + PyExc_Exception@Base @VER@ + PyExc_FloatingPointError@Base @VER@ + PyExc_FutureWarning@Base @VER@ + PyExc_GeneratorExit@Base @VER@ + PyExc_IOError@Base @VER@ + PyExc_ImportError@Base @VER@ + PyExc_ImportWarning@Base @VER@ + PyExc_IndentationError@Base @VER@ + PyExc_IndexError@Base @VER@ + PyExc_KeyError@Base @VER@ + PyExc_KeyboardInterrupt@Base @VER@ + PyExc_LookupError@Base @VER@ + PyExc_MemoryError@Base @VER@ + PyExc_MemoryErrorInst@Base @VER@ + PyExc_NameError@Base @VER@ + PyExc_NotImplementedError@Base @VER@ + PyExc_OSError@Base @VER@ + PyExc_OverflowError@Base @VER@ + PyExc_PendingDeprecationWarning@Base @VER@ + PyExc_RecursionErrorInst@Base @VER@ + PyExc_ReferenceError@Base @VER@ + PyExc_RuntimeError@Base @VER@ + PyExc_RuntimeWarning@Base @VER@ + PyExc_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@ + PyException_GetCause@Base @VER@ + PyException_GetContext@Base @VER@ + PyException_GetTraceback@Base @VER@ + PyException_SetCause@Base @VER@ + PyException_SetContext@Base @VER@ + PyException_SetTraceback@Base @VER@ + PyFPE_counter@Base @VER@ + PyFPE_dummy@Base @VER@ + PyFPE_jbuf@Base @VER@ + PyFileIO_Type@Base @VER@ + PyFile_FromFd@Base @VER@ + PyFile_GetLine@Base @VER@ + PyFile_NewStdPrinter@Base @VER@ + PyFile_WriteObject@Base @VER@ + PyFile_WriteString@Base @VER@ + PyFilter_Type@Base @VER@ + PyFloat_AsDouble@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_LocalsToFast@Base @VER@ + PyFrame_New@Base @VER@ + PyFrame_Type@Base @VER@ + PyFrozenSet_New@Base @VER@ + PyFrozenSet_Type@Base @VER@ + PyFunction_GetAnnotations@Base @VER@ + PyFunction_GetClosure@Base @VER@ + PyFunction_GetCode@Base @VER@ + PyFunction_GetDefaults@Base @VER@ + PyFunction_GetGlobals@Base @VER@ + PyFunction_GetKwDefaults@Base @VER@ + PyFunction_GetModule@Base @VER@ + PyFunction_New@Base @VER@ + PyFunction_SetAnnotations@Base @VER@ + PyFunction_SetClosure@Base @VER@ + PyFunction_SetDefaults@Base @VER@ + PyFunction_SetKwDefaults@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@ + PyIOBase_Type@Base @VER@ + PyImport_AddModule@Base @VER@ + PyImport_AppendInittab@Base @VER@ + PyImport_Cleanup@Base @VER@ + PyImport_ExecCodeModule@Base @VER@ + PyImport_ExecCodeModuleEx@Base @VER@ + PyImport_ExtendInittab@Base @VER@ + PyImport_FrozenModules@Base @VER@ + PyImport_GetImporter@Base @VER@ + PyImport_GetMagicNumber@Base @VER@ + PyImport_GetModuleDict@Base @VER@ + PyImport_Import@Base @VER@ + PyImport_ImportFrozenModule@Base @VER@ + PyImport_ImportModule@Base @VER@ + PyImport_ImportModuleLevel@Base @VER@ + PyImport_ImportModuleNoBlock@Base @VER@ + PyImport_Inittab@Base @VER@ + PyImport_ReloadModule@Base @VER@ + PyIncrementalNewlineDecoder_Type@Base @VER@ + PyInstanceMethod_Function@Base @VER@ + PyInstanceMethod_New@Base @VER@ + PyInstanceMethod_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@ + PyLongRangeIter_Type@Base @VER@ + PyLong_AsDouble@Base @VER@ + PyLong_AsLong@Base @VER@ + PyLong_AsLongAndOverflow@Base @VER@ + PyLong_AsLongLong@Base @VER@ + PyLong_AsSize_t@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_Fini@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@ + PyMap_Type@Base @VER@ + PyMapping_Check@Base @VER@ + PyMapping_GetItemString@Base @VER@ + PyMapping_HasKey@Base @VER@ + PyMapping_HasKeyString@Base @VER@ + PyMapping_Items@Base @VER@ + PyMapping_Keys@Base @VER@ + PyMapping_Length@Base @VER@ + PyMapping_SetItemString@Base @VER@ + PyMapping_Size@Base @VER@ + PyMapping_Values@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_GetOne@Base @VER@ + PyMember_SetOne@Base @VER@ + PyMemoryView_FromBuffer@Base @VER@ + PyMemoryView_FromObject@Base @VER@ + PyMemoryView_GetContiguous@Base @VER@ + PyMemoryView_Type@Base @VER@ + PyMethodDescr_Type@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_GetDef@Base @VER@ + PyModule_GetDict@Base @VER@ + PyModule_GetFilename@Base @VER@ + PyModule_GetName@Base @VER@ + PyModule_GetState@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_AsOff_t@Base @VER@ + PyNumber_AsSsize_t@Base @VER@ + PyNumber_Check@Base @VER@ + PyNumber_Divmod@Base @VER@ + PyNumber_Float@Base @VER@ + PyNumber_FloorDivide@Base @VER@ + PyNumber_InPlaceAdd@Base @VER@ + PyNumber_InPlaceAnd@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_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_ASCII@Base @VER@ + PyObject_AsCharBuffer@Base @VER@ + PyObject_AsFileDescriptor@Base @VER@ + PyObject_AsReadBuffer@Base @VER@ + PyObject_AsWriteBuffer@Base @VER@ + PyObject_Bytes@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_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_stgdict@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@ + PyRangeIter_Type@Base @VER@ + PyRange_Type@Base @VER@ + PyRawIOBase_Type@Base @VER@ + PyReversed_Type@Base @VER@ + PyRun_AnyFile@Base @VER@ + PyRun_AnyFileEx@Base @VER@ + PyRun_AnyFileExFlags@Base @VER@ + PyRun_AnyFileFlags@Base @VER@ + PyRun_File@Base @VER@ + PyRun_FileEx@Base @VER@ + PyRun_FileExFlags@Base @VER@ + PyRun_FileFlags@Base @VER@ + PyRun_InteractiveLoop@Base @VER@ + PyRun_InteractiveLoopFlags@Base @VER@ + PyRun_InteractiveOne@Base @VER@ + PyRun_InteractiveOneFlags@Base @VER@ + PyRun_SimpleFile@Base @VER@ + PyRun_SimpleFileEx@Base @VER@ + PyRun_SimpleFileExFlags@Base @VER@ + PyRun_SimpleString@Base @VER@ + PyRun_SimpleStringFlags@Base @VER@ + PyRun_String@Base @VER@ + PyRun_StringFlags@Base @VER@ + PySTEntry_Type@Base @VER@ + PyST_GetScope@Base @VER@ + PySeqIter_New@Base @VER@ + PySeqIter_Type@Base @VER@ + PySequence_Check@Base @VER@ + PySequence_Concat@Base @VER@ + PySequence_Contains@Base @VER@ + PySequence_Count@Base @VER@ + PySequence_DelItem@Base @VER@ + PySequence_DelSlice@Base @VER@ + PySequence_Fast@Base @VER@ + PySequence_GetItem@Base @VER@ + PySequence_GetSlice@Base @VER@ + PySequence_In@Base @VER@ + PySequence_InPlaceConcat@Base @VER@ + PySequence_InPlaceRepeat@Base @VER@ + PySequence_Index@Base @VER@ + PySequence_Length@Base @VER@ + PySequence_List@Base @VER@ + PySequence_Repeat@Base @VER@ + PySequence_SetItem@Base @VER@ + PySequence_SetSlice@Base @VER@ + PySequence_Size@Base @VER@ + PySequence_Tuple@Base @VER@ + PySetIter_Type@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@ + PySortWrapper_Type@Base @VER@ + PyState_FindModule@Base @VER@ + PyStaticMethod_New@Base @VER@ + PyStaticMethod_Type@Base @VER@ + PyStdPrinter_Type@Base @VER@ + PyStringIO_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_GetObject@Base @VER@ + PySys_HasWarnOptions@Base @VER@ + PySys_ResetWarnOptions@Base @VER@ + PySys_SetArgv@Base @VER@ + PySys_SetObject@Base @VER@ + PySys_SetPath@Base @VER@ + PySys_WriteStderr@Base @VER@ + PySys_WriteStdout@Base @VER@ + PyTextIOBase_Type@Base @VER@ + PyTextIOWrapper_Type@Base @VER@ + PyThreadState_Clear@Base @VER@ + PyThreadState_Delete@Base @VER@ + PyThreadState_DeleteCurrent@Base @VER@ + PyThreadState_Get@Base @VER@ + PyThreadState_GetDict@Base @VER@ + PyThreadState_New@Base @VER@ + PyThreadState_Next@Base @VER@ + PyThreadState_SetAsyncExc@Base @VER@ + PyThreadState_Swap@Base @VER@ + PyThread_ReInitTLS@Base @VER@ + PyThread__exit_thread@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_FindEncoding@Base @VER@ + PyTokenizer_Free@Base @VER@ + PyTokenizer_FromFile@Base @VER@ + PyTokenizer_FromString@Base @VER@ + PyTokenizer_FromUTF8@Base @VER@ + PyTokenizer_Get@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@ + PyType_stgdict@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@ + PyUnicodeIter_Type@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_Append@Base @VER@ + PyUnicodeUCS4_AppendAndDel@Base @VER@ + PyUnicodeUCS4_AsASCIIString@Base @VER@ + PyUnicodeUCS4_AsCharmapString@Base @VER@ + PyUnicodeUCS4_AsDecodedObject@Base @VER@ + PyUnicodeUCS4_AsDecodedUnicode@Base @VER@ + PyUnicodeUCS4_AsEncodedObject@Base @VER@ + PyUnicodeUCS4_AsEncodedString@Base @VER@ + PyUnicodeUCS4_AsEncodedUnicode@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_DecodeFSDefault@Base @VER@ + PyUnicodeUCS4_DecodeFSDefaultAndSize@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_FSConverter@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_IsIdentifier@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_BuildEncodingMap@Base @VER@ + PyUnicode_CompareWithASCIIString@Base @VER@ + PyUnicode_DecodeUTF7@Base @VER@ + PyUnicode_DecodeUTF7Stateful@Base @VER@ + PyUnicode_EncodeUTF7@Base @VER@ + PyUnicode_InternFromString@Base @VER@ + PyUnicode_InternImmortal@Base @VER@ + PyUnicode_InternInPlace@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@ + PyZip_Type@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_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_HasFileSystemDefaultEncoding@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_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_UNICODE_strchr@Base @VER@ + Py_UNICODE_strcmp@Base @VER@ + Py_UNICODE_strcpy@Base @VER@ + Py_UNICODE_strlen@Base @VER@ + Py_UNICODE_strncpy@Base @VER@ + Py_UnbufferedStdioFlag@Base @VER@ + Py_UniversalNewlineFgets@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@ + _PyBytes_FormatLong@Base @VER@ + _PyBytes_InsertThousandsGrouping@Base @VER@ + _PyBytes_InsertThousandsGroupingLocale@Base @VER@ + _PyBytes_Join@Base @VER@ + _PyBytes_Resize@Base @VER@ + _PyCapsule_hack@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@ + _PyFileIO_closed@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@ + _PyIOBase_check_closed@Base @VER@ + _PyIOBase_check_readable@Base @VER@ + _PyIOBase_check_seekable@Base @VER@ + _PyIOBase_check_writable@Base @VER@ + _PyIOBase_finalize@Base @VER@ + _PyIO_Module@Base @VER@ + _PyIO_empty_bytes@Base @VER@ + _PyIO_empty_str@Base @VER@ + _PyIO_find_line_ending@Base @VER@ + _PyIO_str_close@Base @VER@ + _PyIO_str_closed@Base @VER@ + _PyIO_str_decode@Base @VER@ + _PyIO_str_encode@Base @VER@ + _PyIO_str_fileno@Base @VER@ + _PyIO_str_flush@Base @VER@ + _PyIO_str_getstate@Base @VER@ + _PyIO_str_isatty@Base @VER@ + _PyIO_str_newlines@Base @VER@ + _PyIO_str_nl@Base @VER@ + _PyIO_str_read1@Base @VER@ + _PyIO_str_read@Base @VER@ + _PyIO_str_readable@Base @VER@ + _PyIO_str_readinto@Base @VER@ + _PyIO_str_readline@Base @VER@ + _PyIO_str_reset@Base @VER@ + _PyIO_str_seek@Base @VER@ + _PyIO_str_seekable@Base @VER@ + _PyIO_str_setstate@Base @VER@ + _PyIO_str_tell@Base @VER@ + _PyIO_str_truncate@Base @VER@ + _PyIO_str_writable@Base @VER@ + _PyIO_str_write@Base @VER@ + _PyIO_zero@Base @VER@ + _PyImportHooks_Init@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_ReInitLock@Base @VER@ + _PyIncrementalNewlineDecoder_decode@Base @VER@ + _PyList_Extend@Base @VER@ + _PyLong_AsByteArray@Base @VER@ + _PyLong_AsScaledDouble@Base @VER@ + _PyLong_Copy@Base @VER@ + _PyLong_DigitValue@Base @VER@ + _PyLong_Format@Base @VER@ + _PyLong_FormatAdvanced@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_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_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@ + _PyParser_Grammar@Base @VER@ + _PyParser_TokenNames@Base @VER@ + _PySequence_IterSearch@Base @VER@ + _PySet_NextEntry@Base @VER@ + _PySet_Update@Base @VER@ + _PySlice_FromIndices@Base @VER@ + _PyState_AddModule@Base @VER@ + _PySys_Init@Base @VER@ + _PyThreadState_Current@Base @VER@ + _PyThreadState_GetFrame@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_IsPrintable@Base @VER@ + _PyUnicodeUCS4_IsTitlecase@Base @VER@ + _PyUnicodeUCS4_IsUppercase@Base @VER@ + _PyUnicodeUCS4_IsWhitespace@Base @VER@ + _PyUnicodeUCS4_IsXidContinue@Base @VER@ + _PyUnicodeUCS4_IsXidStart@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_AsString@Base @VER@ + _PyUnicode_AsStringAndSize@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_InsertThousandsGrouping@Base @VER@ + _PyUnicode_InsertThousandsGroupingLocale@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_BreakPoint@Base @VER@ + _Py_BuildValue_SizeT@Base @VER@ + _Py_Bytes@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_Expr@Base @VER@ + _Py_Expression@Base @VER@ + _Py_ExtSlice@Base @VER@ + _Py_FalseStruct@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_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_Nonlocal@Base @VER@ + _Py_NotImplementedStruct@Base @VER@ + _Py_Num@Base @VER@ + _Py_PackageContext@Base @VER@ + _Py_Pass@Base @VER@ + _Py_PyAtExit@Base @VER@ + _Py_Raise@Base @VER@ + _Py_ReadyTypes@Base @VER@ + _Py_ReleaseInternedUnicodeStrings@Base @VER@ + _Py_Return@Base @VER@ + _Py_Set@Base @VER@ + _Py_SetComp@Base @VER@ + _Py_SetFileSystemEncoding@Base @VER@ + _Py_Slice@Base @VER@ + _Py_Starred@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_abstract_hack@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_arg@Base @VER@ + _Py_arguments@Base @VER@ + _Py_ascii_whitespace@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_maketrans@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_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@ + _Py_dg_dtoa@Base @VER@ + _Py_dg_freedtoa@Base @VER@ + _Py_dg_strtod@Base @VER@ + _Py_findlabel@Base @VER@ + _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@ + _Py_lower__doc__@Base @VER@ + _Py_maketrans__doc__@Base @VER@ + _Py_mergebitset@Base @VER@ + _Py_meta_grammar@Base @VER@ + _Py_newbitset@Base @VER@ + _Py_newgrammar@Base @VER@ + _Py_parse_inf_or_nan@Base @VER@ + _Py_pgen@Base @VER@ + _Py_samebitset@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@ + _Py_wreadlink@Base @VER@ + + _add_one_to_index_C@Base @VER@ + _add_one_to_index_F@Base @VER@ + asdl_int_seq_new@Base @VER@ + asdl_seq_new@Base @VER@ + +# _ctypes_add_traceback@Base @VER@ +# _ctypes_alloc_callback@Base @VER@ +# _ctypes_alloc_closure@Base @VER@ +# _ctypes_alloc_format_string@Base @VER@ +# _ctypes_callproc@Base @VER@ +# _ctypes_conversion_encoding@Base @VER@ +# _ctypes_conversion_errors@Base @VER@ +# _ctypes_extend_error@Base @VER@ +# _ctypes_free_closure@Base @VER@ +# _ctypes_get_errobj@Base @VER@ +# _ctypes_get_ffi_type@Base @VER@ +# _ctypes_get_fielddesc@Base @VER@ +# _ctypes_module_methods@Base @VER@ +# _ctypes_ptrtype_cache@Base @VER@ +# _ctypes_simple_instance@Base @VER@ +# ffi_type_double@Base @VER@ +# ffi_type_float@Base @VER@ +# ffi_type_longdouble@Base @VER@ +# ffi_type_pointer@Base @VER@ +# ffi_type_sint16@Base @VER@ +# ffi_type_sint32@Base @VER@ +# ffi_type_sint64@Base @VER@ +# ffi_type_sint8@Base @VER@ +# ffi_type_uint16@Base @VER@ +# ffi_type_uint32@Base @VER@ +# ffi_type_uint64@Base @VER@ +# ffi_type_uint8@Base @VER@ +# ffi_type_void@Base @VER@ + +# pyexpat either built as builtin or extension + +# PyExpat_XML_DefaultCurrent@Base @VER@ +# PyExpat_XML_ErrorString@Base @VER@ +# PyExpat_XML_ExpatVersion@Base @VER@ +# PyExpat_XML_ExpatVersionInfo@Base @VER@ +# PyExpat_XML_ExternalEntityParserCreate@Base @VER@ +# PyExpat_XML_FreeContentModel@Base @VER@ +# PyExpat_XML_GetBase@Base @VER@ +# PyExpat_XML_GetBuffer@Base @VER@ +# PyExpat_XML_GetCurrentByteCount@Base @VER@ +# PyExpat_XML_GetCurrentByteIndex@Base @VER@ +# PyExpat_XML_GetCurrentColumnNumber@Base @VER@ +# PyExpat_XML_GetCurrentLineNumber@Base @VER@ +# PyExpat_XML_GetErrorCode@Base @VER@ +# PyExpat_XML_GetFeatureList@Base @VER@ +# PyExpat_XML_GetIdAttributeIndex@Base @VER@ +# PyExpat_XML_GetInputContext@Base @VER@ +# PyExpat_XML_GetParsingStatus@Base @VER@ +# PyExpat_XML_GetSpecifiedAttributeCount@Base @VER@ +# PyExpat_XML_MemFree@Base @VER@ +# PyExpat_XML_MemMalloc@Base @VER@ +# PyExpat_XML_MemRealloc@Base @VER@ +# PyExpat_XML_Parse@Base @VER@ +# PyExpat_XML_ParseBuffer@Base @VER@ +# PyExpat_XML_ParserCreate@Base @VER@ +# PyExpat_XML_ParserCreateNS@Base @VER@ +# PyExpat_XML_ParserCreate_MM@Base @VER@ +# PyExpat_XML_ParserFree@Base @VER@ +# PyExpat_XML_ParserReset@Base @VER@ +# PyExpat_XML_ResumeParser@Base @VER@ +# PyExpat_XML_SetAttlistDeclHandler@Base @VER@ +# PyExpat_XML_SetBase@Base @VER@ +# PyExpat_XML_SetCdataSectionHandler@Base @VER@ +# PyExpat_XML_SetCharacterDataHandler@Base @VER@ +# PyExpat_XML_SetCommentHandler@Base @VER@ +# PyExpat_XML_SetDefaultHandler@Base @VER@ +# PyExpat_XML_SetDefaultHandlerExpand@Base @VER@ +# PyExpat_XML_SetDoctypeDeclHandler@Base @VER@ +# PyExpat_XML_SetElementDeclHandler@Base @VER@ +# PyExpat_XML_SetElementHandler@Base @VER@ +# PyExpat_XML_SetEncoding@Base @VER@ +# PyExpat_XML_SetEndCdataSectionHandler@Base @VER@ +# PyExpat_XML_SetEndDoctypeDeclHandler@Base @VER@ +# PyExpat_XML_SetEndElementHandler@Base @VER@ +# PyExpat_XML_SetEndNamespaceDeclHandler@Base @VER@ +# PyExpat_XML_SetEntityDeclHandler@Base @VER@ +# PyExpat_XML_SetExternalEntityRefHandler@Base @VER@ +# PyExpat_XML_SetExternalEntityRefHandlerArg@Base @VER@ +# PyExpat_XML_SetNamespaceDeclHandler@Base @VER@ +# PyExpat_XML_SetNotStandaloneHandler@Base @VER@ +# PyExpat_XML_SetNotationDeclHandler@Base @VER@ +# PyExpat_XML_SetParamEntityParsing@Base @VER@ +# PyExpat_XML_SetProcessingInstructionHandler@Base @VER@ +# PyExpat_XML_SetReturnNSTriplet@Base @VER@ +# PyExpat_XML_SetSkippedEntityHandler@Base @VER@ +# PyExpat_XML_SetStartCdataSectionHandler@Base @VER@ +# PyExpat_XML_SetStartDoctypeDeclHandler@Base @VER@ +# PyExpat_XML_SetStartElementHandler@Base @VER@ +# PyExpat_XML_SetStartNamespaceDeclHandler@Base @VER@ +# PyExpat_XML_SetUnknownEncodingHandler@Base @VER@ +# PyExpat_XML_SetUnparsedEntityDeclHandler@Base @VER@ +# PyExpat_XML_SetUserData@Base @VER@ +# PyExpat_XML_SetXmlDeclHandler@Base @VER@ +# PyExpat_XML_StopParser@Base @VER@ +# PyExpat_XML_UseForeignDTD@Base @VER@ +# PyExpat_XML_UseParserAsHandlerArg@Base @VER@ +# PyExpat_XmlGetUtf16InternalEncoding@Base @VER@ +# PyExpat_XmlGetUtf16InternalEncodingNS@Base @VER@ +# PyExpat_XmlGetUtf8InternalEncoding@Base @VER@ +# PyExpat_XmlGetUtf8InternalEncodingNS@Base @VER@ +# PyExpat_XmlInitEncoding@Base @VER@ +# PyExpat_XmlInitEncodingNS@Base @VER@ +# PyExpat_XmlInitUnknownEncoding@Base @VER@ +# PyExpat_XmlInitUnknownEncodingNS@Base @VER@ +# PyExpat_XmlParseXmlDecl@Base @VER@ +# PyExpat_XmlParseXmlDeclNS@Base @VER@ +# PyExpat_XmlPrologStateInit@Base @VER@ +# PyExpat_XmlPrologStateInitExternalEntity@Base @VER@ +# PyExpat_XmlSizeOfUnknownEncoding@Base @VER@ +# PyExpat_XmlUtf16Encode@Base @VER@ +# PyExpat_XmlUtf8Encode@Base @VER@ + +# PyInit__ast@Base @VER@ +# PyInit__bisect@Base @VER@ +# PyInit__codecs@Base @VER@ +# PyInit__collections@Base @VER@ +# PyInit__ctypes@Base @VER@ +# PyInit__elementtree@Base @VER@ +# PyInit__functools@Base @VER@ +# PyInit__heapq@Base @VER@ +# PyInit__io@Base @VER@ +# PyInit__locale@Base @VER@ +# PyInit__pickle@Base @VER@ +# PyInit__random@Base @VER@ +# PyInit__socket@Base @VER@ +# PyInit__sre@Base @VER@ +# PyInit__struct@Base @VER@ +# PyInit__symtable@Base @VER@ +# PyInit__thread@Base @VER@ +# PyInit__weakref@Base @VER@ +# PyInit_array@Base @VER@ +# PyInit_binascii@Base @VER@ +# PyInit_datetime@Base @VER@ +# PyInit_errno@Base @VER@ +# PyInit_fcntl@Base @VER@ +# PyInit_gc@Base @VER@ +# PyInit_grp@Base @VER@ +# PyInit_imp@Base @VER@ +# PyInit_itertools@Base @VER@ +# PyInit_math@Base @VER@ +# PyInit_operator@Base @VER@ +# PyInit_posix@Base @VER@ +# PyInit_pwd@Base @VER@ +# PyInit_pyexpat@Base @VER@ +# PyInit_select@Base @VER@ +# PyInit_signal@Base @VER@ +# PyInit_spwd@Base @VER@ +# PyInit_syslog@Base @VER@ +# PyInit_time@Base @VER@ +# PyInit_unicodedata@Base @VER@ +# PyInit_xxsubtype@Base @VER@ +# PyInit_zipimport@Base @VER@ +# PyInit_zlib@Base @VER@ --- python3.1-3.1.1.orig/debian/control +++ python3.1-3.1.1/debian/control @@ -0,0 +1,113 @@ +Source: python3.1 +Section: python +Priority: optional +Maintainer: Ubuntu Core Developers +XSBC-Original-Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5.0.51~), autoconf, libreadline6-dev, libncursesw5-dev (>= 5.3), zlib1g-dev, libdb-dev, tk8.5-dev, blt-dev (>= 2.4z), libssl-dev, sharutils, libbz2-dev, libbluetooth-dev [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], locales [!sparc], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], netbase, lsb-release, bzip2, gcc-4.4 (>= 4.4.1) +Build-Depends-Indep: python-sphinx +Build-Conflicts: libgdbm-dev +XS-Python-Version: 3.1 +Standards-Version: 3.8.2 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg3.1 +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg3.1 + +Package: python3.1 +Architecture: any +Priority: optional +Depends: python3.1-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: python3.1-doc, python3.1-profiler, binutils +Provides: python3.1-cjkcodecs, python3.1-ctypes, python3.1-elementtree, python3.1-celementtree, python3.1-wsgiref, python3.1-gdbm +XB-Python-Version: 3.1 +Description: An interactive high-level object-oriented language (version 3.1) + Version 3.1 of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: python3.1-minimal +Architecture: any +Priority: optional +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: python3.1 +Suggests: binfmt-support +Replaces: python3.1 (<< 3.1.1-0ubuntu4) +Conflicts: binfmt-support (<< 1.1.2) +XB-Python-Runtime: python3.1 +XB-Python-Version: 3.1 +Description: A minimal subset of the Python language (version 3.1) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/python3.1-minimal/README.Debian for a list of the modules + contained in this package. + +Package: libpython3.1 +Architecture: any +Section: libs +Priority: optional +Depends: python3.1 (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: python3.1 (<< 3.0~rc1) +Description: Shared Python runtime library (version 3.1) + Version 3.1 of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: python3.1-examples +Architecture: all +Depends: python3.1 (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v3.1) + Examples, Demos and Tools for Python (v3.1). These are files included in + the upstream Python distribution (v3.1). + +Package: python3.1-dev +Architecture: any +Depends: python3.1 (= ${binary:Version}), libpython3.1 (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: python3.1 (<< 3.1~rc2-1) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v3.1) + Header files, a static library and development tools for building + Python (v3.1) modules, extending the Python interpreter or embedding + Python (v3.1) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-python3.1 +Architecture: all +Depends: python3.1, python3-tk, python3.1-tk, ${misc:Depends} +Enhances: python3.1 +XB-Python-Version: 3.1 +Description: An IDE for Python (v3.1) using Tkinter + IDLE is an Integrated Development Environment for Python (v3.1). + IDLE is written using Tkinter and therefore quite platform-independent. + +Package: python3.1-doc +Section: doc +Architecture: all +Depends: libjs-jquery, ${misc:Depends} +Suggests: python3.1 +Description: Documentation for the high-level object-oriented language Python (v3.1) + These is the official set of documentation for the interactive high-level + object-oriented language Python (v3.1). All documents are provided + in HTML format. The package consists of ten documents: + . + * What's New in Python3.1 + * Tutorial + * Python Library Reference + * Macintosh Module Reference + * Python Language Reference + * Extending and Embedding Python + * Python/C API Reference + * Installing Python Modules + * Documenting Python + * Distributing Python Modules + +Package: python3.1-dbg +Section: debug +Architecture: any +Priority: extra +Depends: python3.1 (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Suggests: python3-gdbm-dbg, python3-tk-dbg +Description: Debug Build of the Python Interpreter (version 3.1) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/python3.1/lib-dynload/debug first. --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-api.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-api.in @@ -0,0 +1,13 @@ +Document: @PVER@-api +Title: Python/C API Reference Manual (v@VER@) +Author: Guido van Rossum +Abstract: This manual documents the API used by C (or C++) programmers who + want to write extension modules or embed Python. It is a + companion to *Extending and Embedding the Python Interpreter*, + which describes the general principles of extension writing but + does not document the API functions in detail. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/c-api/index.html +Files: /usr/share/doc/@PVER@/html/c-api/*.html --- python3.1-3.1.1.orig/debian/copyright +++ python3.1-3.1.1/debian/copyright @@ -0,0 +1,544 @@ +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. + + +Python License +============== + +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations (now Zope +Corporation, see http://www.zope.com). In 2001, the Python Software +Foundation (PSF, see http://www.python.org/psf/) was formed, a +non-profit organization created specifically to own Python-related +Intellectual Property. Zope Corporation is a sponsoring member of +the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.2 2.1.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2.1 2.2 2002 PSF yes + 2.2.2 2.2.1 2002 PSF yes + 2.2.3 2.2.2 2003 PSF yes + 2.3 2.2.2 2002-2003 PSF yes + 2.3.1 2.3 2002-2003 PSF yes + 2.3.2 2.3.1 2002-2003 PSF yes + 2.3.3 2.3.2 2002-2003 PSF yes + 2.3.4 2.3.3 2004 PSF yes + 2.3.5 2.3.4 2005 PSF yes + 2.4 2.3 2004 PSF yes + 2.4.1 2.4 2005 PSF yes + 2.4.2 2.4.1 2005 PSF yes + 2.4.3 2.4.2 2006 PSF yes + 2.5 2.4 2006 PSF yes + 2.5.1 2.5 2007 PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python +alone or in any derivative version, provided, however, that PSF's +License Agreement and PSF's notice of copyright, i.e., "Copyright (c) +2001, 2002, 2003, 2004, 2005, 2006, 2007 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative +version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Licenses and Acknowledgements for Incorporated Software +======================================================= + +Mersenne Twister +---------------- + +The `_random' module includes code based on a download from +`http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html'. The +following are the verbatim comments from the original code: + + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Any feedback is very welcome. + http://www.math.keio.ac.jp/matumoto/emt.html + email: matumoto@math.keio.ac.jp + + +Sockets +------- + +The `socket' module uses the functions, `getaddrinfo', and +`getnameinfo', which are coded in separate source files from the WIDE +Project, `http://www.wide.ad.jp/about/index.html'. + + Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + FOR GAI_ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON GAI_ANY THEORY OF LIABILITY, WHETHER + IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN GAI_ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + + +Floating point exception control +-------------------------------- + +The source for the `fpectl' module includes the following notice: + + --------------------------------------------------------------------- + / Copyright (c) 1996. \ + | The Regents of the University of California. | + | All rights reserved. | + | | + | Permission to use, copy, modify, and distribute this software for | + | any purpose without fee is hereby granted, provided that this en- | + | tire notice is included in all copies of any software which is or | + | includes a copy or modification of this software and in all | + | copies of the supporting documentation for such software. | + | | + | This work was produced at the University of California, Lawrence | + | Livermore National Laboratory under contract no. W-7405-ENG-48 | + | between the U.S. Department of Energy and The Regents of the | + | University of California for the operation of UC LLNL. | + | | + | DISCLAIMER | + | | + | This software was prepared as an account of work sponsored by an | + | agency of the United States Government. Neither the United States | + | Government nor the University of California nor any of their em- | + | ployees, makes any warranty, express or implied, or assumes any | + | liability or responsibility for the accuracy, completeness, or | + | usefulness of any information, apparatus, product, or process | + | disclosed, or represents that its use would not infringe | + | privately-owned rights. Reference herein to any specific commer- | + | cial products, process, or service by trade name, trademark, | + | manufacturer, or otherwise, does not necessarily constitute or | + | imply its endorsement, recommendation, or favoring by the United | + | States Government or the University of California. The views and | + | opinions of authors expressed herein do not necessarily state or | + | reflect those of the United States Government or the University | + | of California, and shall not be used for advertising or product | + \ endorsement purposes. / + --------------------------------------------------------------------- + + +Cookie management +----------------- + +The `Cookie' module contains the following notice: + + Copyright 2000 by Timothy O'Malley + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software + and its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Timothy O'Malley not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR + ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +Execution tracing +----------------- + +The `trace' module contains the following notice: + + portions copyright 2001, Autonomous Zones Industries, Inc., all rights... + err... reserved and offered to the public under the terms of the + Python 2.2 license. + Author: Zooko O'Whielacronx + http://zooko.com/ + mailto:zooko@zooko.com + + Copyright 2000, Mojam Media, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1999, Bioreason, Inc., all rights reserved. + Author: Andrew Dalke + + Copyright 1995-1997, Automatrix, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. + + Permission to use, copy, modify, and distribute this Python software and + its associated documentation for any purpose without fee is hereby + granted, provided that the above copyright notice appears in all copies, + and that both that copyright notice and this permission notice appear in + supporting documentation, and that the name of neither Automatrix, + Bioreason or Mojam Media be used in advertising or publicity pertaining + to distribution of the software without specific, written prior + permission. + + +UUencode and UUdecode functions +------------------------------- + +The `uu' module contains the following notice: + + Copyright 1994 by Lance Ellinghouse + Cathedral City, California Republic, United States of America. + All Rights Reserved + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Lance Ellinghouse + not be used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Modified by Jack Jansen, CWI, July 1995: + - Use binascii module to do the actual line-by-line conversion + between ascii and binary. This results in a 1000-fold speedup. The C + version is still 5 times faster, though. + - Arguments more compliant with python standard + + +XML Remote Procedure Calls +-------------------------- + +The `xmlrpclib' module contains the following notice: + + The XML-RPC client interface is + + Copyright (c) 1999-2002 by Secret Labs AB + Copyright (c) 1999-2002 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, + and will comply with the following terms and conditions: + + Permission to use, copy, modify, and distribute this software and + its associated documentation for any purpose and without fee is + hereby granted, provided that the above copyright notice appears in + all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Secret Labs AB or the author not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD + TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- + ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR + BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + OF THIS SOFTWARE. --- python3.1-3.1.1.orig/debian/libPVER.symbols.lpia.in +++ python3.1-3.1.1/debian/libPVER.symbols.lpia.in @@ -0,0 +1,6 @@ +libpython@VER@.so.1.0 libpython@VER@ #MINVER# +#include "libpython.symbols" + PyModule_Create2@Base @VER@ + _Py_force_double@Base @VER@ + _Py_get_387controlword@Base @VER@ + _Py_set_387controlword@Base @VER@ --- python3.1-3.1.1.orig/debian/PVER-dbg.overrides.in +++ python3.1-3.1.1/debian/PVER-dbg.overrides.in @@ -0,0 +1,2 @@ +@PVER@-dbg binary: package-name-doesnt-match-sonames +@PVER@-dbg binary: non-dev-pkg-with-shlib-symlink --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-inst.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-inst.in @@ -0,0 +1,12 @@ +Document: @PVER@-inst +Title: Installing Python Modules (v@VER@) +Author: Greg Ward +Abstract: This document describes the Python Distribution Utilities + (``Distutils'') from the end-user's point-of-view, describing how to + extend the capabilities of a standard Python installation by building + and installing third-party Python modules and extensions. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/install/index.html +Files: /usr/share/doc/@PVER@/html/install/*.html --- python3.1-3.1.1.orig/debian/control.doc +++ python3.1-3.1.1/debian/control.doc @@ -0,0 +1,26 @@ +Source: @PVER@-doc +Section: contrib/python +Priority: optional +Maintainer: Matthias Klose +Build-Depends-Indep: debhelper (>= 4.2), python2.4, libhtml-tree-perl, tetex-bin, tetex-extra, texinfo, emacs21, debiandoc-sgml, sharutils, latex2html, bzip2 +Standards-Version: 3.6.2 + +Package: @PVER@-doc +Section: contrib/doc +Architecture: all +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, some in info 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 --- python3.1-3.1.1.orig/debian/idle-PVER.postrm.in +++ python3.1-3.1.1/debian/idle-PVER.postrm.in @@ -0,0 +1,9 @@ +#! /bin/sh -e + +if [ "$1" = "purge" ]; then + rm -rf /etc/idle-@PVER@ +fi + +#DEBHELPER# + +exit 0 --- python3.1-3.1.1.orig/debian/PVER.pycentral.in +++ python3.1-3.1.1/debian/PVER.pycentral.in @@ -0,0 +1,4 @@ +[@PVER@] +runtime: @PVER@ +interpreter: /usr/bin/@PVER@ +prefix: /usr/lib/@PVER@ --- python3.1-3.1.1.orig/debian/PVER.postinst.in +++ python3.1-3.1.1/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 --- python3.1-3.1.1.orig/debian/README.python +++ python3.1-3.1.1/debian/README.python @@ -0,0 +1,153 @@ + + Python 2.x for Debian + --------------------- + +This is Python 2.x packaged for Debian. + +This document contains information specific to the Debian packages of +Python 2.x. + + + + [TODO: This document is not yet up-to-date with the packages.] + + + + + + +Currently, it features those two main topics: + + 1. Release notes for the Debian packages: + 2. Notes for developers using the Debian Python packages: + +Release notes and documentation from the upstream package are installed +in /usr/share/doc/python/. + +Up-to-date information regarding Python on Debian systems is also +available as http://www.debian.org/~flight/python/. + +There's a mailing list for discussion of issues related to Python on Debian +systems: debian-python@lists.debian.org. The list is not intended for +general Python problems, but as a forum for maintainers of Python-related +packages and interested third parties. + + + +1. Release notes for the Debian packages: + + +Results of the regression test: +------------------------------ + +The package does successfully run the regression tests for all included +modules. Seven packages are skipped since they are platform-dependent and +can't be used with Linux. + + +Noteworthy changes since the 1.4 packages: +----------------------------------------- + +- Threading support enabled. +- Tkinter for Tcl/Tk 8.x. +- New package python-zlib. +- The dbmmodule was dropped. Use bsddb instead. gdbmmodule is provided + for compatibility's sake. +- python-elisp adheres to the new emacs add-on policy; it now depends + on emacsen. python-elisp probably won't work correctly with emacs19. + Refer to /usr/doc/python-elisp/ for more information. +- Remember that 1.5 has dropped the `ni' interface in favor of a generic + `packages' concept. +- Python 1.5 regression test as additional package python-regrtest. You + don't need to install this package unless you don't trust the + maintainer ;-). +- once again, modified upstream's compileall.py and py_compile.py. + Now they support compilation of optimized byte-code (.pyo) for use + with "python -O", removal of .pyc and .pyo files where the .py source + files are missing (-d) and finally the fake of a installation directory + when .py files have to be compiled out of place for later installation + in a different directory (-i destdir, used in ./debian/rules). +- The Debian packages for python 1.4 do call + /usr/lib/python1.4/compileall.py in their postrm script. Therefore + I had to provide a link from /usr/lib/python1.5/compileall.py, otherwise + the old packages won't be removed completely. THIS IS A SILLY HACK! + + + +2. Notes for developers using the Debian python packages: + + +Embedding python: +---------------- + +The files for embedding python resp. extending the python interpreter +are included in the python-dev package. With the configuration in the +Debian GNU/Linux packages of python 1.5, you will want to use something +like + + -I/usr/include/python1.5 (e.g. for config.h) + -L/usr/lib/python1.5/config -lpython1.5 (... -lpthread) + (also for Makefile.pre.in, Setup etc.) + +Makefile.pre.in automatically gets that right. Note that unlike 1.4, +python 1.5 has only one library, libpython1.5.a. + +Currently, there's no shared version of libpython. Future version of +the Debian python packages will support this. + + +Python extension packages: +------------------------- + +According to www.python.org/doc/essays/packages.html, extension packages +should only install into /usr/lib/python1.5/site-packages/ (resp. +/usr/lib/site-python/ for packages that are definitely version independent). +No extension package should install files directly into /usr/lib/python1.5/. + +But according to the FSSTND, only Debian packages are allowed to use +/usr/lib/python1.5/. Therefore Debian Python additionally by default +searches a second hierarchy in /usr/local/lib/. These directories take +precedence over their equivalents in /usr/lib/. + +a) Locally installed Python add-ons + + /usr/local/lib/python1.5/site-packages/ + /usr/local/lib/site-python/ (version-independent modules) + +b) Python add-ons packaged for Debian + + /usr/lib/python1.5/site-packages/ + /usr/lib/site-python/ (version-independent modules) + +Note that no package must install files directly into /usr/lib/python1.5/ +or /usr/local/lib/python1.5/. Only the site-packages directory is allowed +for third-party extensions. + +Use of the new `package' scheme is strongly encouraged. The `ni' interface +is obsolete in python 1.5. + +Header files for extensions go into /usr/include/python1.5/. + + +Installing extensions for local use only: +---------------------------------------- + +Most extensions use Python's Makefile.pre.in. Note that Makefile.pre.in +by default will install files into /usr/lib/, not into /usr/local/lib/, +which is not allowed for local extensions. You'll have to change the +Makefile accordingly. Most times, "make prefix=/usr/local install" will +work. + + +Packaging python extensions for Debian: +-------------------------------------- + +Maintainers of Python extension packages should read README.maintainers. + + + + + 03/09/98 + Gregor Hoffleit + +Last change: 07/16/1999 --- python3.1-3.1.1.orig/debian/pdb.1.in +++ python3.1-3.1.1/debian/pdb.1.in @@ -0,0 +1,16 @@ +.TH PDB@VER@ 1 +.SH NAME +pdb@VER@ \- the Python debugger +.SH SYNOPSIS +.PP +.B pdb@VER@ +.I script [...] +.SH DESCRIPTION +.PP +See /usr/lib/python@VER@/pdb.doc for more information on the use +of pdb. When the debugger is started, help is available via the +help command. +.SH SEE ALSO +python@VER@(1). Chapter 9 of the Python Library Reference +(The Python Debugger). Available in the python@VER@-doc package at +/usr/share/doc/python@VER@/html/lib/module-pdb.html. --- python3.1-3.1.1.orig/debian/locale-gen +++ python3.1-3.1.1/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# --- python3.1-3.1.1.orig/debian/idle.desktop.in +++ python3.1-3.1.1/debian/idle.desktop.in @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=IDLE (using Python-@VER@) +Comment=Integrated Development Environment for Python (using Python-@VER@) +Exec=/usr/bin/idle-@PVER@ -n +Icon=/usr/share/pixmaps/@PVER@.xpm +Terminal=false +Type=Application +Categories=Application;Development; +StartupNotify=true --- python3.1-3.1.1.orig/debian/idle-PVER.overrides.in +++ python3.1-3.1.1/debian/idle-PVER.overrides.in @@ -0,0 +1,2 @@ +# icon in dependent package +idle-@PVER@ binary: menu-icon-missing --- python3.1-3.1.1.orig/debian/PVER-dbg.README.Debian.in +++ python3.1-3.1.1/debian/PVER-dbg.README.Debian.in @@ -0,0 +1,51 @@ +Contents of the @PVER@-dbg package +------------------------------------- + +For debugging python and extension modules, you may want to add the contents +of /usr/share/doc/@PVER@/gdbinit to your ~/.gdbinit file. + +@PVER@-dbg contains two sets of packages: + + - debugging symbols for the standard @PVER@ build. When this package + is installed, gdb will automatically load up the debugging symbols + from it when debugging @PVER@ or one of the included extension + modules. + + - a separate @PVER@-dbg binary, configured --with-pydebug, enabling the + additional debugging code to help debug memory management problems. + +For the latter, all extension modules have to be recompiled to +correctly load with an pydebug enabled build. + + +Debian and Ubuntu specific changes to the debug interpreter +----------------------------------------------------------- +The python2.4 and python2.5 packages in Ubuntu feisty are modified to +first look for extension modules under a different name. + + normal build: foo.so + debug build: foo_d.so foo.so + +This naming schema allows installation of the extension modules into +the same path (The naming is directly taken from the Windows builds +which already uses this naming scheme). + +See https://wiki.ubuntu.com/PyDbgBuilds for more information. + + +Using the python-dbg builds +--------------------------- + + * Call the python-dbg or the pythonX.Y-dbg binaries instead of the + python or pythonX.Y binaries. + + * Properties of the debug build are described in + /usr/share/doc/@PVER@/SpecialBuilds.txt.gz. + The debug interpreter is built with Py_DEBUG defined. + + * From SpecialBuilds.txt: This is what is generally meant by "a debug + build" of Python. Py_DEBUG implies LLTRACE, Py_REF_DEBUG, + Py_TRACE_REFS, and PYMALLOC_DEBUG (if WITH_PYMALLOC is enabled). + In addition, C assert()s are enabled (via the C way: by not defining + NDEBUG), and some routines do additional sanity checks inside + "#ifdef Py_DEBUG" blocks. --- python3.1-3.1.1.orig/debian/libPVER.overrides.in +++ python3.1-3.1.1/debian/libPVER.overrides.in @@ -0,0 +1 @@ +lib@PVER@ binary: package-name-doesnt-match-sonames --- python3.1-3.1.1.orig/debian/FAQ.html +++ python3.1-3.1.1/debian/FAQ.html @@ -0,0 +1,8997 @@ + + +The Whole Python FAQ + + + +

The Whole Python FAQ

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

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

+ +

+


+

1. General information and availability

+ + +

+


+

2. Python in the real world

+ + +

+


+

3. Building Python and Other Known Bugs

+ + +

+


+

4. Programming in Python

+ + +

+


+

5. Extending Python

+ + +

+


+

6. Python's design

+ + +

+


+

7. Using Python on non-UNIX platforms

+ + +

+


+

8. Python on Windows

+ + +
+

1. General information and availability

+ +
+

1.1. What is Python?

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

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

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

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

+ +


+

1.2. Why is it called Python?

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

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

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

+ +


+

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

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

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

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

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

+ +


+

1.4. How do I get documentation on Python?

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

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

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

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

+ +


+

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

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

+USA: +

+

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

+

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

+

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

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

+ +


+

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

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

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

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

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

+ +


+

1.7. Is there a WWW page devoted to Python?

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

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

+ +


+

1.8. Is the Python documentation available on the WWW?

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

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

+ +


+

1.9. Are there any books on Python?

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

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

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

+ +


+

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

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

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

+

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

+

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

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

+ +


+

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

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

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

+ +


+

1.12. How does the Python version numbering scheme work?

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

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

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

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

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

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

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

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

+ +


+

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

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

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

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

+ +


+

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

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

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

+ +Edit this entry / +Log info +

+ +


+

1.15. Why was Python created in the first place?

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

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

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

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

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

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

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

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

+ +


+

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

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

+The two main reasons to use Python are: +

+

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

+

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

+And remember, there is no rule six. +

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

+ +


+

1.17. What is Python good for?

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

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

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

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

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

+ +


+

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

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

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

+ +


+

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

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

+

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

+

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

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

+ +


+

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

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

+

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

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

+ +


+

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

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

+

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

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

+ +


+

2. Python in the real world

+ +
+

2.1. How many people are using Python?

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

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

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

+ +


+

2.2. Have any significant projects been done in Python?

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

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

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

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

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

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

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

+See also the next question. +

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

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

+ +


+

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

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

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

+ +


+

2.4. How stable is Python?

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

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

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

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

+ +


+

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

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

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

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

+ +


+

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

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

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

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

+ +


+

2.7. What is the future of Python?

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

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

+ +


+

2.8. What was the PSA, anyway?

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

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

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

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

+ +


+

2.9. Deleted

+

+

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

+ +


+

2.10. Deleted

+

+

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

+ +


+

2.11. Is Python Y2K (Year 2000) Compliant?

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

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

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

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

+ +


+

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

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

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

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

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

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

+

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

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

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

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

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

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

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

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

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

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

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

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

+ +


+

3. Building Python and Other Known Bugs

+ +
+

3.1. Is there a test set?

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

+

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

+

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

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

+

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

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

3.3. Link errors after rerunning the configure script.

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+

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

+

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+#readline readline.c -lreadline -ltermcap +

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

+

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

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

+ +


+

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

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

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

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

+ +


+

3.9. Trouble with prototypes on Ultrix.

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

+ +Edit this entry / +Log info +

+ +


+

3.10. Other trouble building Python on platform X.

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

+

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

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

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

+ +


+

3.11. How to configure dynamic loading on Linux.

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

+ +


+

3.13. Trouble when making modules shared on Linux.

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

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

+ +


+

3.14. [deleted]

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

3.16. Deleted

+

+

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

+ +


+

3.17. Deleted.

+

+

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

+ +


+

3.18. Compilation or link errors for the _tkinter module

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

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

3.20. [deleted]

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

+

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

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

+ +


+

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

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

+

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

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

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

+ +


+

3.26. [deleted]

+[ancient libc/linux problem was here] +

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

+ +


+

3.27. [deleted]

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

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

+ +


+

3.28. How can I test if Tkinter is working?

+Try the following: +

+

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

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

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

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

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

+ +


+

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

+(From a posting by Guido van Rossum) +

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

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

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

+

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

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

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

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

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

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

+ +


+

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

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

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

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

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

+

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

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

+ +


+

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

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

+

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

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

+ +


+

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

+Use "make clobber" instead. +

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

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

+ +


+

3.33. Submitting bug reports and patches

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

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

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

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

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

+ +


+

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

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

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

+

+in Modules/Makefile, +

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

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

+ +


+

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

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

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

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

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

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

+ +


+

3.36. relocations remain against allocatable but non-writable sections

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

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

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

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

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

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

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

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

+ +


+

4. Programming in Python

+ +
+

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

+Yes. +

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

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

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

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

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

+

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

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

+ +


+

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

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

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

+

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

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

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

+ +


+

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

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

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

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

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

+ +


+

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

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

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

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

+ +


+

4.5. [deleted]

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

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

+ +


+

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

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

+

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

+

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

+

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

+

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

+

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

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

+ +


+

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

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

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

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

+

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

+

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

+

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

+

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

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

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

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

+

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

+

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

+

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

+

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

+

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

+

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

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

+

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

+

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

+

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

+

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

+

+For an anecdote related to optimization, see +

+

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

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

+ +


+

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

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

+

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

+

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

+ +Edit this entry / +Log info +

+ +


+

4.9. How do I find the current module name?

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

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

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

+ +


+

4.12. [deleted]

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

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

+ +


+

4.13. What GUI toolkits exist for Python?

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

+Currently supported solutions: +

+Cross-platform: +

+Tk: +

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

+wxWindows: +

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

+Gtk+: +

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

+

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

+

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

+Other: +

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

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

+Platform specific: +

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

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

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

+Obsolete or minority solutions: +

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

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

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

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

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

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

+ +


+

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

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

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

+ +


+

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

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

+

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

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

+ +


+

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

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

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

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

+

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

+

+

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

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

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

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

+ +


+

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

+There are several possible reasons for this. +

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

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

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

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

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

+

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

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

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

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

+ +


+

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

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

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

+ +Edit this entry / +Log info +

+ +


+

4.19. What is a class?

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

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

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

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

+ +


+

4.20. What is a method?

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

+ +Edit this entry / +Log info +

+ +


+

4.21. What is self?

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

+ +Edit this entry / +Log info +

+ +


+

4.22. What is an unbound method?

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

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

+

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

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

+ +


+

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

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

+

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

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

+ +


+

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

+This depends on the object type. +

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

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

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

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

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

+

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

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

+

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

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

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

+ +


+

4.29. What WWW tools are there for Python?

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

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

+

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

+

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

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

+ +


+

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

+Use the standard popen2 module. For example: +

+

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

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

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

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

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

+

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

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

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

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

+ +


+

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

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

+

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

+

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

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

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

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

+ +


+

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

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

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

+

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

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

+ +


+

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

+Not as such. +

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

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

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

+

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

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

+ +


+

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

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

+

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

+

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

+

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

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

+

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

+

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

+

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

+

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

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

+ +


+

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

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

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

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

+ +


+

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

+Suppose you have the following modules: +

+foo.py: +

+

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

+

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

+

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

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

+

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

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

+

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

+

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

+

+

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

+

+These solutions are not mutually exclusive. +

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

+ +


+

4.38. How do I copy an object in Python?

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

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

+ new_l = l[:]
+
+

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

+ +


+

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

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

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

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

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

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

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

+ +


+

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

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

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

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

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

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

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

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

+ +


+

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

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

+ +Edit this entry / +Log info +

+ +


+

4.46. How do I copy a file?

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

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

+ +


+

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

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

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

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

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

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

+

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

+

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

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

+

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

+

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

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

+ +


+

4.48. What is delegation?

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

+

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

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

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

+

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

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

+ +


+

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

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

+

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

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

+

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

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

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

+

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

+

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

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

+ +


+

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

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

+

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

+

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

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

+

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

+

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

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

+ +


+

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

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

+

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

+

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

+

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

+Note that Isorted may also be computed by +

+

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

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

+ +


+

4.52. How to convert between tuples and lists?

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

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

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

+ +


+

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

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

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

+ +


+

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

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

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

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

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

+ +


+

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

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

+

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

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

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

+ +


+

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

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

+

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

+

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

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

+ +


+

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

+Did you do something like this? +

+

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

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

+

+

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

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

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

+ +


+

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

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

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

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

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

+ +


+

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

+You can sort lists of tuples. +

+

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

+In Python 2.0 this can be done like: +

+

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

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

+

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

+

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

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

+ +


+

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

+It does starting with Python 1.5. +

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

+

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

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

+ +


+

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

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

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

+

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

+

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

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

+ +


+

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

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

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

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

+ +


+

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

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

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

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

+

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

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

+

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

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

+

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

+

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

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

+ +


+

4.64. How do you remove duplicates from a list?

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

+

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

+

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

+

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

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

+ +


+

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

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

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

+

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

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

+ +


+

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

+Get fancy! +

+

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

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

+ +


+

4.67. How do I generate random numbers in Python?

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

+

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

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

+

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

+

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

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

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

+ +


+

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

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

+

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

+

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

+

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

+

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

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

+ +


+

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

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

+Quoting Fredrik Lundh from the mailinglist: +

+

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

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

+ +


+

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

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

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

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

+

+    import sys
+    print sys.builtin_module_names
+
+

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

+ +


+

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

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

+

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

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

+

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

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

+ +


+

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

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

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

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

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

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

+ +


+

4.73. How do I specify hexadecimal and octal integers?

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

+

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

+

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

+

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

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

+ +


+

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

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

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

+

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

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

+ +


+

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

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

+Where in C++ you'd write +

+

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

+

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

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

+

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

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

+ +


+

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

+Use apply. For example: +

+

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

+

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

+

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

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

+ +


+

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

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

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

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

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

+ +


+

4.78. How do I create documentation from doc strings?

+Use gendoc, by Daniel Larson. See +

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

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

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

+ +


+

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

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

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

+

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

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

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

+ +


+

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

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

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

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

+ +


+

4.81. "import crypt" fails

+[Unix] +

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

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

+ +


+

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

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

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

+ +


+

4.83. How do I freeze Tkinter applications?

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

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

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

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

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

+ +


+

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

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

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

+STATIC DATA +

+For example, +

+

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

+Caution: within a method of C, +

+

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

+

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

+

+STATIC METHODS +

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

+

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

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

+

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

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

+

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

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

+ +


+

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

+Try +

+

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

+

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

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

+ +


+

4.86. Basic thread wisdom

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

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

+

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

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

+

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

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

+

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

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

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

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

+ +


+

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

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

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

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

+

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

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

+

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

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

+ +


+

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

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

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

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

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

+

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

+

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

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

+ +


+

4.89. How do I modify a string in place?

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

+

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

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

+ +


+

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

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

+

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

+

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

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

+

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

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

+ +


+

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

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

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

+

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

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

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

+ +


+

4.92. Is there a Python tutorial?

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

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

+ +


+

4.93. Deleted

+See 4.28 +

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

+ +


+

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

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

+

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

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

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

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

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

+ +


+

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

+There are two partial substitutes. If you want to remove all trailing +whitespace, use the method string.rstrip(). Otherwise, if there is only +one line in the string, use string.splitlines()[0]. +

+

+ -----------------------------------------------------------------------
+
+
+ rstrip() is too greedy, it strips all trailing white spaces.
+ splitlines() takes ControlM as line boundary.
+ Consider these strings as input:
+   "python python    \r\n"
+   "python\rpython\r\n"
+   "python python   \r\r\r\n"
+ The results from rstrip()/splitlines() are perhaps not what we want.
+
+
+ It seems re can perform this task.
+
+

+

+ #!/usr/bin/python 
+ # requires python2                                                             
+
+
+ import re, os, StringIO
+
+
+ lines=StringIO.StringIO(
+   "The Python Programming Language\r\n"
+   "The Python Programming Language \r \r \r\r\n"
+   "The\rProgramming\rLanguage\r\n"
+   "The\rProgramming\rLanguage\r\r\r\r\n"
+   "The\r\rProgramming\r\rLanguage\r\r\r\r\n"
+ )
+
+
+ ln=re.compile("(?:[\r]?\n|\r)$") # dos:\r\n, unix:\n, mac:\r, others: unknown
+ # os.linesep does not work if someone ftps(in binary mode) a dos/mac text file
+ # to your unix box
+ #ln=re.compile(os.linesep + "$")
+
+
+ while 1:
+   s=lines.readline()
+   if not s: break
+   print "1.(%s)" % `s.rstrip()`
+   print "2.(%s)" % `ln.sub( "", s, 1)`
+   print "3.(%s)" % `s.splitlines()[0]`
+   print "4.(%s)" % `s.splitlines()`
+   print
+
+
+ lines.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 8 09:51:34 2001 by +Crystal +

+ +


+

4.96. Why is join() a string method when I'm really joining the elements of a (list, tuple, sequence)?

+Strings became much more like other standard types starting in release 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. These new methods have been widely accepted, but the one which appears to make (some) programmers feel uncomfortable is: +

+

+    ", ".join(['1', '2', '4', '8', '16'])
+
+which gives the result +

+

+    "1, 2, 4, 8, 16"
+
+There are two usual arguments against this usage. +

+The first runs along the lines of: "It looks really ugly using a method of a string literal (string constant)", to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals. Get over it! +

+The second objection is typically cast as: "I am really telling a sequence to join its members together with a string constant". Sadly, you aren't. For some reason there seems to be much less difficulty with having split() as a string method, since in that case it is easy to see that +

+

+    "1, 2, 4, 8, 16".split(", ")
+
+is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space). In this case a Unicode string returns a list of Unicode strings, an ASCII string returns a list of ASCII strings, and everyone is happy. +

+join() is a string method because in using it you are telling the separator string to iterate over an arbitrary sequence, forming string representations of each of the elements, and inserting itself between the elements' representations. This method can be used with any argument which obeys the rules for sequence objects, inluding any new classes you might define yourself. +

+Because this is a string method it can work for Unicode strings as well as plain ASCII strings. If join() were a method of the sequence types then the sequence types would have to decide which type of string to return depending on the type of the separator. +

+If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write +

+

+    string.join(['1', '2', '4', '8', '16'], ", ")
+
+You will just have to try and forget that the string module actually uses the syntax you are compaining about to implement the syntax you prefer! +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 2 15:51:58 2002 by +Steve Holden +

+ +


+

4.97. How can my code discover the name of an object?

+Generally speaking, it can't, because objects don't really have names. The assignment statement does not store the assigned value in the name but a reference to it. Essentially, assignment creates a binding of a name to a value. The same is true of def and class statements, but in that case the value is a callable. Consider the following code: +

+

+    class A:
+        pass
+
+
+    B = A
+
+
+    a = B()
+    b = a
+    print b
+    <__main__.A instance at 016D07CC>
+    print a
+    <__main__.A instance at 016D07CC>
+
+

+Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value. +

+Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 8 03:53:39 2001 by +Steve Holden +

+ +


+

4.98. Why are floating point calculations so inaccurate?

+The development version of the Python Tutorial now contains an Appendix with more info: +
+    http://www.python.org/doc/current/tut/node14.html
+
+People are often very surprised by results like this: +

+

+ >>> 1.2-1.0
+ 0.199999999999999996
+
+And think it is a bug in Python. It's not. It's a problem caused by +the internal representation of a floating point number. A floating point +number is stored as a fixed number of binary digits. +

+In decimal math, there are many numbers that can't be represented +with a fixed number of decimal digits, i.e. +1/3 = 0.3333333333....... +

+In the binary case, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. There are +a lot of numbers that can't be represented. The digits are cut off at +some point. +

+Since Python 1.6, a floating point's repr() function prints as many +digits are necessary to make eval(repr(f)) == f true for any float f. +The str() function prints the more sensible number that was probably +intended: +

+

+ >>> 0.2
+ 0.20000000000000001
+ >>> print 0.2
+ 0.2
+
+Again, this has nothing to do with Python, but with the way the +underlying C platform handles floating points, and ultimately with +the inaccuracy you'll always have when writing down numbers of fixed +number of digit strings. +

+One of the consequences of this is that it is dangerous to compare +the result of some computation to a float with == ! +Tiny inaccuracies may mean that == fails. +

+Instead try something like this: +

+

+ epsilon = 0.0000000000001 # Tiny allowed error
+ expected_result = 0.4
+
+
+ if expected_result-epsilon <= computation() <= expected_result+epsilon:
+    ...
+
+

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

+ +


+

4.99. I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?

+Don't panic! Your data are probably intact. The most frequent cause +for the error is that you tried to open an earlier Berkeley DB file +with a later version of the Berkeley DB library. +

+Many Linux systems now have all three versions of Berkeley DB +available. If you are migrating from version 1 to a newer version use +db_dump185 to dump a plain text version of the database. +If you are migrating from version 2 to version 3 use db2_dump to create +a plain text version of the database. In either case, use db_load to +create a new native database for the latest version installed on your +computer. If you have version 3 of Berkeley DB installed, you should +be able to use db2_load to create a native version 2 database. +

+You should probably move away from Berkeley DB version 1 files because +the hash file code contains known bugs that can corrupt your data. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 29 16:04:29 2001 by +Skip Montanaro +

+ +


+

4.100. What are the "best practices" for using import in a module?

+First, the standard modules are great. Use them! The standard Python library is large and varied. Using modules can save you time and effort and will reduce maintainenance cost of your code. (Other programs are dedicated to supporting and fixing bugs in the standard Python modules. Coworkers may also be familiar with themodules that you use, reducing the amount of time it takes them to understand your code.) +

+The rest of this answer is largely a matter of personal preference, but here's what some newsgroup posters said (thanks to all who responded) +

+In general, don't use +

+ from modulename import *
+
+Doing so clutters the importer's namespace. Some avoid this idiom even with the few modules that were designed to be imported in this manner. (Modules designed in this manner include Tkinter, thread, and wxPython.) +

+Import modules at the top of a file, one module per line. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports. +

+Move imports into a local scope (such as at the top of a function definition) if there are a lot of imports, and you're trying to avoid the cost (lots of initialization time) of many imports. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive (because of the one time initialization of the module) but that loading a module multiple times is virtually free (a couple of dictionary lookups). Even if the module name has gone out of scope, the module is probably available in sys.modules. Thus, there isn't really anything wrong with putting no imports at the module level (if they aren't needed) and putting all of the imports at the function level. +

+It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon says: +

+ Circular imports are fine where both modules use the "import <module>"
+ form of import. They fail when the 2nd module wants to grab a name
+ out of the first ("from module import name") and the import is at
+ the top level. That's because names in the 1st are not yet available,
+ (the first module is busy importing the 2nd).  
+
+In this case, if the 2nd module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import. +

+It may also be necessary to move imports out of the top level of code +if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option. +

+If only instances of a specific class uses a module, then it is reasonable to import the module in the class's __init__ method and then assign the module to an instance variable so that the module is always available (via that instance variable) during the life of the object. Note that to delay an import until the class is instantiated, the import must be inside a method. Putting the import inside the class but outside of any method still causes the import to occur when the module is initialized. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 4 04:44:47 2001 by +TAB +

+ +


+

4.101. Is there a tool to help find bugs or perform static analysis?

+Yes. PyChecker is a static analysis tool for finding bugs +in Python source code as well as warning about code complexity +and style. +

+You can get PyChecker from: http://pychecker.sf.net. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Aug 10 15:42:11 2001 by +Neal +

+ +


+

4.102. UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)

+This error indicates that your Python installation can handle +only 7-bit ASCII strings. There are a couple ways to fix or +workaround the problem. +

+If your programs must handle data in arbitary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For instance, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by "value" is encoded as UTF-8: +

+

+    value = unicode(value, "utf-8")
+
+will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError. +

+If you only want strings coverted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails: +

+

+    try:
+        x = unicode(value, "ascii")
+    except UnicodeError:
+        value = unicode(value, "utf-8")
+    else:
+        # value was valid ASCII data
+        pass
+
+

+If you normally use a character set encoding other than US-ASCII and only need to handle data in that encoding, the simplest way to fix the problem may be simply to set the encoding in sitecustomize.py. The following code is just a modified version of the encoding setup code from site.py with the relevant lines uncommented. +

+

+    # Set the string encoding used by the Unicode implementation.
+    # The default is 'ascii'
+    encoding = "ascii" # <= CHANGE THIS if you wish
+
+
+    # Enable to support locale aware default string encodings.
+    import locale
+    loc = locale.getdefaultlocale()
+    if loc[1]:
+        encoding = loc[1]
+    if encoding != "ascii":
+        import sys
+        sys.setdefaultencoding(encoding)
+
+

+Also note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 13 04:45:41 2002 by +Skip Montanaro +

+ +


+

4.103. Using strings to call functions/methods

+There are various techniques: +

+* Use a dictionary pre-loaded with strings and functions. The primary +advantage of this technique is that the strings do not need to match the +names of the functions. This is also the primary technique used to +emulate a case construct: +

+

+    def a():
+        pass
+
+
+    def b():
+        pass
+
+
+    dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs
+
+
+    dispatch[get_input()]()  # Note trailing parens to call function
+
+* Use the built-in function getattr(): +

+

+    import foo
+    getattr(foo, 'bar')()
+
+Note that getattr() works on any object, including classes, class +instances, modules, and so on. +

+This is used in several places in the standard library, like +this: +

+

+    class Foo:
+        def do_foo(self):
+            ...
+
+
+        def do_bar(self):
+            ...
+
+
+     f = getattr(foo_instance, 'do_' + opname)
+     f()
+
+

+* Use locals() or eval() to resolve the function name: +

+def myFunc(): +

+    print "hello"
+
+fname = "myFunc" +

+f = locals()[fname] +f() +

+f = eval(fname) +f() +

+Note: Using eval() can be dangerous. If you don't have absolute control +over the contents of the string, all sorts of things could happen... +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 08:14:58 2002 by +Erno Kuusela +

+ +


+

4.104. How fast are exceptions?

+A try/except block is extremely efficient. Actually executing an +exception is expensive. In older versions of Python (prior to 2.0), it +was common to code this idiom: +

+

+    try:
+        value = dict[key]
+    except KeyError:
+        dict[key] = getvalue(key)
+        value = dict[key]
+
+This idiom only made sense when you expected the dict to have the key +95% of the time or more; other times, you coded it like this: +

+

+    if dict.has_key(key):
+        value = dict[key]
+    else:
+        dict[key] = getvalue(key)
+        value = dict[key]
+
+In Python 2.0 and higher, of course, you can code this as +

+

+    value = dict.setdefault(key, getvalue(key))
+
+However this evaluates getvalue(key) always, regardless of whether it's needed or not. So if it's slow or has a side effect you should use one of the above variants. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 9 10:12:30 2002 by +Yeti +

+ +


+

4.105. Sharing global variables across modules

+The canonical way to share information across modules within a single +program is to create a special module (often called config or cfg). +Just import the config module in all modules of your application; the +module then becomes available as a global name. Because there is only +one instance of each module, any changes made to the module object get +reflected everywhere. For example: +

+config.py: +

+

+    pass
+
+mod.py: +

+

+    import config
+    config.x = 1
+
+main.py: +

+

+    import config
+    import mod
+    print config.x
+
+Note that using a module is also the basis for implementing the +Singleton design pattern, for the same reason. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Apr 23 23:07:19 2002 by +Aahz +

+ +


+

4.106. Why is cPickle so slow?

+Use the binary option. We'd like to make that the default, but it would +break backward compatibility: +

+

+    largeString = 'z' * (100 * 1024)
+    myPickle = cPickle.dumps(largeString, 1)
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Aug 22 19:54:25 2002 by +Aahz +

+ +


+

4.107. When importing module XXX, why do I get "undefined symbol: PyUnicodeUCS2_..." ?

+You are using a version of Python that uses a 4-byte representation for +Unicode characters, but the extension module you are importing (possibly +indirectly) was compiled using a Python that uses a 2-byte representation +for Unicode characters (the default). +

+If instead the name of the undefined symbol starts with PyUnicodeUCS4_, +the problem is the same by the relationship is reversed: Python was +built using 2-byte Unicode characters, and the extension module was +compiled using a Python with 4-byte Unicode characters. +

+This can easily occur when using pre-built extension packages. RedHat +Linux 7.x, in particular, provides a "python2" binary that is compiled +with 4-byte Unicode. This only causes the link failure if the extension +uses any of the PyUnicode_*() functions. It is also a problem if if an +extension uses any of the Unicode-related format specifiers for +Py_BuildValue (or similar) or parameter-specifications for +PyArg_ParseTuple(). +

+You can check the size of the Unicode character a Python interpreter is +using by checking the value of sys.maxunicode: +

+

+  >>> import sys
+  >>> if sys.maxunicode > 65535:
+  ...     print 'UCS4 build'
+  ... else:
+  ...     print 'UCS2 build'
+
+The only way to solve this problem is to use extension modules compiled +with a Python binary built using the same size for Unicode characters. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Aug 27 15:00:17 2002 by +Fred Drake +

+ +


+

4.108. How do I create a .pyc file?

+QUESTION: +

+I have a module and I wish to generate a .pyc file. +How do I do it? Everything I read says that generation of a .pyc file is +"automatic", but I'm not getting anywhere. +

+

+ANSWER: +

+When a module is imported for the first time (or when the source is more +recent than the current compiled file) a .pyc file containing the compiled code should be created in the +same directory as the .py file. +

+One reason that a .pyc file may not be created is permissions problems with the directory. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. +

+However, in most cases, that's not the problem. +

+Creation of a .pyc file is "automatic" if you are importing a module and Python has the +ability (permissions, free space, etc...) to write the compiled module +back to the directory. But note that running Python on a top level script is not considered an +import and so no .pyc will be created automatically. For example, if you have a top-level module abc.py that imports another module xyz.py, when you run abc, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc isn't imported. +

+If you need to create abc.pyc -- that is, to create a .pyc file for a +module that is not imported -- you can. (Look up +the py_compile and compileall modules in the Library Reference.) +

+You can manually compile any module using the "py_compile" module. One +way is to use the compile() function in that module interactively: +

+

+    >>> import py_compile
+    >>> py_compile.compile('abc.py')
+
+This will write the .pyc to the same location as abc.py (or you +can override that with the optional parameter cfile). +

+You can also automatically compile all files in a directory or +directories using the "compileall" module, which can also be run +straight from the command line. +

+You can do it from the shell (or DOS) prompt by entering: +

+       python compile.py abc.py
+
+or +
+       python compile.py *
+
+Or you can write a script to do it on a list of filenames that you enter. +

+

+     import sys
+     from py_compile import compile
+
+
+     if len(sys.argv) <= 1:
+        sys.exit(1)
+
+
+     for file in sys.argv[1:]:
+        compile(file)
+
+ACKNOWLEDGMENTS: +

+Steve Holden, David Bolen, Rich Somerfield, Oleg Broytmann, Steve Ferg +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 12 15:58:25 2003 by +Stephen Ferg +

+ +


+

5. Extending Python

+ +
+

5.1. Can I create my own functions in C?

+Yes, you can create built-in modules containing functions, +variables, exceptions and even new types in C. This is explained in +the document "Extending and Embedding the Python Interpreter" (http://www.python.org/doc/current/ext/ext.html). Also read the chapter +on dynamic loading. +

+There's more information on this in each of the Python books: +Programming Python, Internet Programming with Python, and Das Python-Buch +(in German). +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 10 05:18:57 2001 by +Fred L. Drake, Jr. +

+ +


+

5.2. Can I create my own functions in C++?

+Yes, using the C-compatibility features found in C++. Basically +you place extern "C" { ... } around the Python include files and put +extern "C" before each function that is going to be called by the +Python interpreter. Global or static C++ objects with constructors +are probably not a good idea. +

+ +Edit this entry / +Log info +

+ +


+

5.3. How can I execute arbitrary Python statements from C?

+The highest-level function to do this is PyRun_SimpleString() which takes +a single string argument which is executed in the context of module +__main__ and returns 0 for success and -1 when an exception occurred +(including SyntaxError). If you want more control, use PyRun_String(); +see the source for PyRun_SimpleString() in Python/pythonrun.c. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 20:08:14 1997 by +Bill Tutt +

+ +


+

5.4. How can I evaluate an arbitrary Python expression from C?

+Call the function PyRun_String() from the previous question with the +start symbol eval_input (Py_eval_input starting with 1.5a1); it +parses an expression, evaluates it and returns its value. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:23:18 1997 by +David Ascher +

+ +


+

5.5. How do I extract C values from a Python object?

+That depends on the object's type. If it's a tuple, +PyTupleSize(o) returns its length and PyTuple_GetItem(o, i) +returns its i'th item; similar for lists with PyListSize(o) +and PyList_GetItem(o, i). For strings, PyString_Size(o) returns +its length and PyString_AsString(o) a pointer to its value +(note that Python strings may contain null bytes so strlen() +is not safe). To test which type an object is, first make sure +it isn't NULL, and then use PyString_Check(o), PyTuple_Check(o), +PyList_Check(o), etc. +

+There is also a high-level API to Python objects which is +provided by the so-called 'abstract' interface -- read +Include/abstract.h for further details. It allows for example +interfacing with any kind of Python sequence (e.g. lists and tuples) +using calls like PySequence_Length(), PySequence_GetItem(), etc.) +as well as many other useful protocols. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:34:20 1997 by +David Ascher +

+ +


+

5.6. How do I use Py_BuildValue() to create a tuple of arbitrary length?

+You can't. Use t = PyTuple_New(n) instead, and fill it with +objects using PyTuple_SetItem(t, i, o) -- note that this "eats" a +reference count of o. Similar for lists with PyList_New(n) and +PyList_SetItem(l, i, o). Note that you must set all the tuple items to +some value before you pass the tuple to Python code -- +PyTuple_New(n) initializes them to NULL, which isn't a valid Python +value. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 31 18:15:29 1997 by +Guido van Rossum +

+ +


+

5.7. How do I call an object's method from C?

+The PyObject_CallMethod() function can be used to call an arbitrary +method of an object. The parameters are the object, the name of the +method to call, a format string like that used with Py_BuildValue(), and the argument values: +

+

+    PyObject *
+    PyObject_CallMethod(PyObject *object, char *method_name,
+                        char *arg_format, ...);
+
+This works for any object that has methods -- whether built-in or +user-defined. You are responsible for eventually DECREF'ing the +return value. +

+To call, e.g., a file object's "seek" method with arguments 10, 0 +(assuming the file object pointer is "f"): +

+

+        res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
+        if (res == NULL) {
+                ... an exception occurred ...
+        }
+        else {
+                Py_DECREF(res);
+        }
+
+Note that since PyObject_CallObject() always wants a tuple for the +argument list, to call a function without arguments, pass "()" for the +format, and to call a function with one argument, surround the argument +in parentheses, e.g. "(i)". +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 6 16:15:46 2002 by +Neal Norwitz +

+ +


+

5.8. How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?

+(Due to Mark Hammond): +

+In Python code, define an object that supports the "write()" method. +Redirect sys.stdout and sys.stderr to this object. +Call print_error, or just allow the standard traceback mechanism to +work. Then, the output will go wherever your write() method sends it. +

+The easiest way to do this is to use the StringIO class in the standard +library. +

+Sample code and use for catching stdout: +

+	>>> class StdoutCatcher:
+	...  def __init__(self):
+	...   self.data = ''
+	...  def write(self, stuff):
+	...   self.data = self.data + stuff
+	...  
+	>>> import sys
+	>>> sys.stdout = StdoutCatcher()
+	>>> print 'foo'
+	>>> print 'hello world!'
+	>>> sys.stderr.write(sys.stdout.data)
+	foo
+	hello world!
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Dec 16 18:34:25 1998 by +Richard Jones +

+ +


+

5.9. How do I access a module written in Python from C?

+You can get a pointer to the module object as follows: +

+

+        module = PyImport_ImportModule("<modulename>");
+
+If the module hasn't been imported yet (i.e. it is not yet present in +sys.modules), this initializes the module; otherwise it simply returns +the value of sys.modules["<modulename>"]. Note that it doesn't enter +the module into any namespace -- it only ensures it has been +initialized and is stored in sys.modules. +

+You can then access the module's attributes (i.e. any name defined in +the module) as follows: +

+

+        attr = PyObject_GetAttrString(module, "<attrname>");
+
+Calling PyObject_SetAttrString(), to assign to variables in the module, also works. +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 22:56:40 1997 by +david ascher +

+ +


+

5.10. How do I interface to C++ objects from Python?

+Depending on your requirements, there are many approaches. To do +this manually, begin by reading the "Extending and Embedding" document +(Doc/ext.tex, see also http://www.python.org/doc/). Realize +that for the Python run-time system, there isn't a whole lot of +difference between C and C++ -- so the strategy to build a new Python +type around a C structure (pointer) type will also work for C++ +objects. +

+A useful automated approach (which also works for C) is SWIG: +http://www.swig.org/. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Oct 15 05:14:01 1999 by +Sjoerd Mullender +

+ +


+

5.11. mSQLmodule (or other old module) won't build with Python 1.5 (or later)

+Since python-1.4 "Python.h" will have the file includes needed in an +extension module. +Backward compatibility is dropped after version 1.4 and therefore +mSQLmodule.c will not build as "allobjects.h" cannot be found. +The following change in mSQLmodule.c is harmless when building it with +1.4 and necessary when doing so for later python versions: +

+Remove lines: +

+

+	#include "allobjects.h"
+	#include "modsupport.h"
+
+And insert instead: +

+

+	#include "Python.h"
+
+You may also need to add +

+

+                #include "rename2.h"
+
+if the module uses "old names". +

+This may happen with other ancient python modules as well, +and the same fix applies. +

+ +Edit this entry / +Log info + +/ Last changed on Sun Dec 21 02:03:35 1997 by +GvR +

+ +


+

5.12. I added a module using the Setup file and the make fails! Huh?

+Setup must end in a newline, if there is no newline there it gets +very sad. Aside from this possibility, maybe you have other +non-Python-specific linkage problems. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jun 24 15:54:01 1997 by +aaron watters +

+ +


+

5.13. I want to compile a Python module on my Red Hat Linux system, but some files are missing.

+Red Hat's RPM for Python doesn't include the +/usr/lib/python1.x/config/ directory, which contains various files required +for compiling Python extensions. +Install the python-devel RPM to get the necessary files. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 26 13:44:04 1999 by +A.M. Kuchling +

+ +


+

5.14. What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?

+This means that you have created an extension module named "yourmodule", but your module init function does not initialize with that name. +

+Every module init function will have a line similar to: +

+

+  module = Py_InitModule("yourmodule", yourmodule_functions);
+
+If the string passed to this function is not the same name as your extenion module, the SystemError will be raised. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 25 07:16:08 1999 by +Mark Hammond +

+ +


+

5.15. How to tell "incomplete input" from "invalid input"?

+Sometimes you want to emulate the Python interactive interpreter's +behavior, where it gives you a continuation prompt when the input +is incomplete (e.g. you typed the start of an "if" statement +or you didn't close your parentheses or triple string quotes), +but it gives you a syntax error message immediately when the input +is invalid. +

+In Python you can use the codeop module, which approximates the +parser's behavior sufficiently. IDLE uses this, for example. +

+The easiest way to do it in C is to call PyRun_InteractiveLoop() +(in a separate thread maybe) and let the Python interpreter handle +the input for you. You can also set the PyOS_ReadlineFunctionPointer +to point at your custom input function. See Modules/readline.c and +Parser/myreadline.c for more hints. +

+However sometimes you have to run the embedded Python interpreter +in the same thread as your rest application and you can't allow the +PyRun_InteractiveLoop() to stop while waiting for user input. +The one solution then is to call PyParser_ParseString() +and test for e.error equal to E_EOF (then the input is incomplete). +Sample code fragment, untested, inspired by code from Alex Farber: +

+

+  #include <Python.h>
+  #include <node.h>
+  #include <errcode.h>
+  #include <grammar.h>
+  #include <parsetok.h>
+  #include <compile.h>
+
+
+  int testcomplete(char *code)
+    /* code should end in \n */
+    /* return -1 for error, 0 for incomplete, 1 for complete */
+  {
+    node *n;
+    perrdetail e;
+
+
+    n = PyParser_ParseString(code, &_PyParser_Grammar,
+                             Py_file_input, &e);
+    if (n == NULL) {
+      if (e.error == E_EOF) 
+        return 0;
+      return -1;
+    }
+
+
+    PyNode_Free(n);
+    return 1;
+  }
+
+Another solution is trying to compile the received string with +Py_CompileString(). If it compiles fine - try to execute the returned +code object by calling PyEval_EvalCode(). Otherwise save the input for +later. If the compilation fails, find out if it's an error or just +more input is required - by extracting the message string from the +exception tuple and comparing it to the "unexpected EOF while parsing". +Here is a complete example using the GNU readline library (you may +want to ignore SIGINT while calling readline()): +

+

+  #include <stdio.h>
+  #include <readline.h>
+
+
+  #include <Python.h>
+  #include <object.h>
+  #include <compile.h>
+  #include <eval.h>
+
+
+  int main (int argc, char* argv[])
+  {
+    int i, j, done = 0;                          /* lengths of line, code */
+    char ps1[] = ">>> ";
+    char ps2[] = "... ";
+    char *prompt = ps1;
+    char *msg, *line, *code = NULL;
+    PyObject *src, *glb, *loc;
+    PyObject *exc, *val, *trb, *obj, *dum;
+
+
+    Py_Initialize ();
+    loc = PyDict_New ();
+    glb = PyDict_New ();
+    PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());
+
+
+    while (!done)
+    {
+      line = readline (prompt);
+
+
+      if (NULL == line)                          /* CTRL-D pressed */
+      {
+        done = 1;
+      }
+      else
+      {
+        i = strlen (line);
+
+
+        if (i > 0)
+          add_history (line);                    /* save non-empty lines */
+
+
+        if (NULL == code)                        /* nothing in code yet */
+          j = 0;
+        else
+          j = strlen (code);
+
+
+        code = realloc (code, i + j + 2);
+        if (NULL == code)                        /* out of memory */
+          exit (1);
+
+
+        if (0 == j)                              /* code was empty, so */
+          code[0] = '\0';                        /* keep strncat happy */
+
+
+        strncat (code, line, i);                 /* append line to code */
+        code[i + j] = '\n';                      /* append '\n' to code */
+        code[i + j + 1] = '\0';
+
+
+        src = Py_CompileString (code, "<stdin>", Py_single_input);       
+
+
+        if (NULL != src)                         /* compiled just fine - */
+        {
+          if (ps1  == prompt ||                  /* ">>> " or */
+              '\n' == code[i + j - 1])           /* "... " and double '\n' */
+          {                                               /* so execute it */
+            dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
+            Py_XDECREF (dum);
+            Py_XDECREF (src);
+            free (code);
+            code = NULL;
+            if (PyErr_Occurred ())
+              PyErr_Print ();
+            prompt = ps1;
+          }
+        }                                        /* syntax error or E_EOF? */
+        else if (PyErr_ExceptionMatches (PyExc_SyntaxError))           
+        {
+          PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */
+
+
+          if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
+              !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
+          {
+            Py_XDECREF (exc);
+            Py_XDECREF (val);
+            Py_XDECREF (trb);
+            prompt = ps2;
+          }
+          else                                   /* some other syntax error */
+          {
+            PyErr_Restore (exc, val, trb);
+            PyErr_Print ();
+            free (code);
+            code = NULL;
+            prompt = ps1;
+          }
+        }
+        else                                     /* some non-syntax error */
+        {
+          PyErr_Print ();
+          free (code);
+          code = NULL;
+          prompt = ps1;
+        }
+
+
+        free (line);
+      }
+    }
+
+
+    Py_XDECREF(glb);
+    Py_XDECREF(loc);
+    Py_Finalize();
+    exit(0);
+  }
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 15 09:47:24 2000 by +Alex Farber +

+ +


+

5.16. How do I debug an extension?

+When using gdb with dynamically loaded extensions, you can't set a +breakpoint in your extension until your extension is loaded. +

+In your .gdbinit file (or interactively), add the command +

+br _PyImport_LoadDynamicModule +

+

+$ gdb /local/bin/python +

+gdb) run myscript.py +

+gdb) continue # repeat until your extension is loaded +

+gdb) finish # so that your extension is loaded +

+gdb) br myfunction.c:50 +

+gdb) continue +

+ +Edit this entry / +Log info + +/ Last changed on Fri Oct 20 11:10:32 2000 by +Joe VanAndel +

+ +


+

5.17. How do I find undefined Linux g++ symbols, __builtin_new or __pure_virtural

+To dynamically load g++ extension modules, you must recompile python, relink python using g++ (change LINKCC in the python Modules Makefile), and link your extension module using g++ (e.g., "g++ -shared -o mymodule.so mymodule.o"). +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jan 14 18:03:51 2001 by +douglas orr +

+ +


+

5.18. How do I define and create objects corresponding to built-in/extension types

+Usually you would like to be able to inherit from a Python type when +you ask this question. The bottom line for Python 2.2 is: types and classes are miscible. You build instances by calling classes, and you can build subclasses to your heart's desire. +

+You need to be careful when instantiating immutable types like integers or strings. See http://www.amk.ca/python/2.2/, section 2, for details. +

+Prior to version 2.2, Python (like Java) insisted that there are first-class and second-class objects (the former are types, the latter classes), and never the twain shall meet. +

+The library has, however, done a good job of providing class wrappers for the more commonly desired objects (see UserDict, UserList and UserString for examples), and more are always welcome if you happen to be in the mood to write code. These wrappers still exist in Python 2.2. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 10 15:14:07 2002 by +Matthias Urlichs +

+ +


+

6. Python's design

+ +
+

6.1. Why isn't there a switch or case statement in Python?

+You can do this easily enough with a sequence of +if... elif... elif... else. There have been some proposals for switch +statement syntax, but there is no consensus (yet) on whether and how +to do range tests. +

+ +Edit this entry / +Log info +

+ +


+

6.2. Why does Python use indentation for grouping of statements?

+Basically I believe that using indentation for grouping is +extremely elegant and contributes a lot to the clarity of the average +Python program. Most people learn to love this feature after a while. +Some arguments for it: +

+Since there are no begin/end brackets there cannot be a disagreement +between grouping perceived by the parser and the human reader. I +remember long ago seeing a C fragment like this: +

+

+        if (x <= y)
+                x++;
+                y--;
+        z++;
+
+and staring a long time at it wondering why y was being decremented +even for x > y... (And I wasn't a C newbie then either.) +

+Since there are no begin/end brackets, Python is much less prone to +coding-style conflicts. In C there are loads of different ways to +place the braces (including the choice whether to place braces around +single statements in certain cases, for consistency). If you're used +to reading (and writing) code that uses one style, you will feel at +least slightly uneasy when reading (or being required to write) +another style. +Many coding styles place begin/end brackets on a line by themself. +This makes programs considerably longer and wastes valuable screen +space, making it harder to get a good overview over a program. +Ideally, a function should fit on one basic tty screen (say, 20 +lines). 20 lines of Python are worth a LOT more than 20 lines of C. +This is not solely due to the lack of begin/end brackets (the lack of +declarations also helps, and the powerful operations of course), but +it certainly helps! +

+ +Edit this entry / +Log info + +/ Last changed on Wed May 21 16:00:15 1997 by +GvR +

+ +


+

6.3. Why are Python strings immutable?

+There are two advantages. One is performance: knowing that a +string is immutable makes it easy to lay it out at construction time +-- fixed and unchanging storage requirements. (This is also one of +the reasons for the distinction between tuples and lists.) The +other is that strings in Python are considered as "elemental" as +numbers. No amount of activity will change the value 8 to anything +else, and in Python, no amount of activity will change the string +"eight" to anything else. (Adapted from Jim Roskind) +

+ +Edit this entry / +Log info +

+ +


+

6.4. Delete

+

+

+ +Edit this entry / +Log info + +/ Last changed on Tue Jan 2 03:05:25 2001 by +Moshe Zadka +

+ +


+

6.5. Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

+The major reason is history. Functions were used for those +operations that were generic for a group of types and which +were intended to work even for objects that didn't have +methods at all (e.g. numbers before type/class unification +began, or tuples). +

+It is also convenient to have a function that can readily be applied +to an amorphous collection of objects when you use the functional features of Python (map(), apply() et al). +

+In fact, implementing len(), max(), min() as a built-in function is +actually less code than implementing them as methods for each type. +One can quibble about individual cases but it's a part of Python, +and it's too late to change such things fundamentally now. The +functions have to remain to avoid massive code breakage. +

+Note that for string operations Python has moved from external functions +(the string module) to methods. However, len() is still a function. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 30 14:08:58 2002 by +Steve Holden +

+ +


+

6.6. Why can't I derive a class from built-in types (e.g. lists or files)?

+As of Python 2.2, you can derive from built-in types. For previous versions, the answer is: +

+This is caused by the relatively late addition of (user-defined) +classes to the language -- the implementation framework doesn't easily +allow it. See the answer to question 4.2 for a work-around. This +may be fixed in the (distant) future. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 23 02:53:22 2002 by +Neal Norwitz +

+ +


+

6.7. Why must 'self' be declared and used explicitly in method definitions and calls?

+So, is your current programming language C++ or Java? :-) +When classes were added to Python, this was (again) the simplest way of +implementing methods without too many changes to the interpreter. The +idea was borrowed from Modula-3. It turns out to be very useful, for +a variety of reasons. +

+First, it makes it more obvious that you are using a method or +instance attribute instead of a local variable. Reading "self.x" or +"self.meth()" makes it absolutely clear that an instance variable or +method is used even if you don't know the class definition by heart. +In C++, you can sort of tell by the lack of a local variable +declaration (assuming globals are rare or easily recognizable) -- but +in Python, there are no local variable declarations, so you'd have to +look up the class definition to be sure. +

+Second, it means that no special syntax is necessary if you want to +explicitly reference or call the method from a particular class. In +C++, if you want to use a method from base class that is overridden in +a derived class, you have to use the :: operator -- in Python you can +write baseclass.methodname(self, <argument list>). This is +particularly useful for __init__() methods, and in general in cases +where a derived class method wants to extend the base class method of +the same name and thus has to call the base class method somehow. +

+Lastly, for instance variables, it solves a syntactic problem with +assignment: since local variables in Python are (by definition!) those +variables to which a value assigned in a function body (and that +aren't explicitly declared global), there has to be some way to tell +the interpreter that an assignment was meant to assign to an instance +variable instead of to a local variable, and it should preferably be +syntactic (for efficiency reasons). C++ does this through +declarations, but Python doesn't have declarations and it would be a +pity having to introduce them just for this purpose. Using the +explicit "self.var" solves this nicely. Similarly, for using instance +variables, having to write "self.var" means that references to +unqualified names inside a method don't have to search the instance's +directories. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 12 08:01:50 2001 by +Steve Holden +

+ +


+

6.8. Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

+Answer 1: Unfortunately, the interpreter pushes at least one C stack +frame for each Python stack frame. Also, extensions can call back into +Python at almost random moments. Therefore a complete threads +implementation requires thread support for C. +

+Answer 2: Fortunately, there is Stackless Python, which has a completely redesigned interpreter loop that avoids the C stack. It's still experimental but looks very promising. Although it is binary compatible with standard Python, it's still unclear whether Stackless will make it into the core -- maybe it's just too revolutionary. Stackless Python currently lives here: http://www.stackless.com. A microthread implementation that uses it can be found here: http://world.std.com/~wware/uthread.html. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Apr 15 08:18:16 2000 by +Just van Rossum +

+ +


+

6.9. Why can't lambda forms contain statements?

+Python lambda forms cannot contain statements because Python's +syntactic framework can't handle statements nested inside expressions. +

+However, in Python, this is not a serious problem. Unlike lambda +forms in other languages, where they add functionality, Python lambdas +are only a shorthand notation if you're too lazy to define a function. +

+Functions are already first class objects in Python, and can be +declared in a local scope. Therefore the only advantage of using a +lambda form instead of a locally-defined function is that you don't need to invent a name for the function -- but that's just a local variable to which the function object (which is exactly the same type of object that a lambda form yields) is assigned! +

+ +Edit this entry / +Log info + +/ Last changed on Sun Jun 14 14:15:17 1998 by +Tim Peters +

+ +


+

6.10. [deleted]

+[lambda vs non-nested scopes used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:20:56 2002 by +Erno Kuusela +

+ +


+

6.11. [deleted]

+[recursive functions vs non-nested scopes used to be here] +

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:22:04 2002 by +Erno Kuusela +

+ +


+

6.12. Why is there no more efficient way of iterating over a dictionary than first constructing the list of keys()?

+As of Python 2.2, you can now iterate over a dictionary directly, +using the new implied dictionary iterator: +

+

+    for k in d: ...
+
+There are also methods returning iterators over the values and items: +

+

+    for k in d.iterkeys(): # same as above
+    for v in d.itervalues(): # iterate over values
+    for k, v in d.iteritems(): # iterate over items
+
+All these require that you do not modify the dictionary during the loop. +

+For previous Python versions, the following defense should do: +

+Have you tried it? I bet it's fast enough for your purposes! In +most cases such a list takes only a few percent of the space occupied +by the dictionary. Apart from the fixed header, +the list needs only 4 bytes (the size of a pointer) per +key. A dictionary uses 12 bytes per key plus between 30 and 70 +percent hash table overhead, plus the space for the keys and values. +By necessity, all keys are distinct objects, and a string object (the most +common key type) costs at least 20 bytes plus the length of the +string. Add to that the values contained in the dictionary, and you +see that 4 bytes more per item really isn't that much more memory... +

+A call to dict.keys() makes one fast scan over the dictionary +(internally, the iteration function does exist) copying the pointers +to the key objects into a pre-allocated list object of the right size. +The iteration time isn't lost (since you'll have to iterate anyway -- +unless in the majority of cases your loop terminates very prematurely +(which I doubt since you're getting the keys in random order). +

+I don't expose the dictionary iteration operation to Python +programmers because the dictionary shouldn't be modified during the +entire iteration -- if it is, there's a small chance that the +dictionary is reorganized because the hash table becomes too full, and +then the iteration may miss some items and see others twice. Exactly +because this only occurs rarely, it would lead to hidden bugs in +programs: it's easy never to have it happen during test runs if you +only insert or delete a few items per iteration -- but your users will +surely hit upon it sooner or later. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:24:08 2002 by +GvR +

+ +


+

6.13. Can Python be compiled to machine code, C or some other language?

+Not easily. Python's high level data types, dynamic typing of +objects and run-time invocation of the interpreter (using eval() or +exec) together mean that a "compiled" Python program would probably +consist mostly of calls into the Python run-time system, even for +seemingly simple operations like "x+1". +

+Several projects described in the Python newsgroup or at past +Python conferences have shown that this approach is feasible, +although the speedups reached so far are only modest (e.g. 2x). +JPython uses the same strategy for compiling to Java bytecode. +(Jim Hugunin has demonstrated that in combination with whole-program +analysis, speedups of 1000x are feasible for small demo programs. +See the website for the 1997 Python conference.) +

+Internally, Python source code is always translated into a "virtual +machine code" or "byte code" representation before it is interpreted +(by the "Python virtual machine" or "bytecode interpreter"). In order +to avoid the overhead of parsing and translating modules that rarely +change over and over again, this byte code is written on a file whose +name ends in ".pyc" whenever a module is parsed (from a file whose +name ends in ".py"). When the corresponding .py file is changed, it +is parsed and translated again and the .pyc file is rewritten. +

+There is no performance difference once the .pyc file has been loaded +(the bytecode read from the .pyc file is exactly the same as the bytecode +created by direct translation). The only difference is that loading +code from a .pyc file is faster than parsing and translating a .py +file, so the presence of precompiled .pyc files will generally improve +start-up time of Python scripts. If desired, the Lib/compileall.py +module/script can be used to force creation of valid .pyc files for a +given set of modules. +

+Note that the main script executed by Python, even if its filename +ends in .py, is not compiled to a .pyc file. It is compiled to +bytecode, but the bytecode is not saved to a file. +

+If you are looking for a way to translate Python programs in order to +distribute them in binary form, without the need to distribute the +interpreter and library as well, have a look at the freeze.py script +in the Tools/freeze directory. This creates a single binary file +incorporating your program, the Python interpreter, and those parts of +the Python library that are needed by your program. Of course, the +resulting binary will only run on the same type of platform as that +used to create it. +

+Newsflash: there are now several programs that do this, to some extent. +Look for Psyco, Pyrex, PyInline, Py2Cmod, and Weave. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:26:19 2002 by +GvR +

+ +


+

6.14. How does Python manage memory?

+The details of Python memory management depend on the implementation. +The standard Python implementation (the C implementation) uses reference +counting and another mechanism to collect reference cycles. +

+Jython relies on the Java runtime; so it uses +the JVM's garbage collector. This difference can cause some subtle +porting problems if your Python code depends on the behavior of +the reference counting implementation. +

+The reference cycle collector was added in CPython 2.0. It +periodically executes a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. A new gc module provides functions to perform a garbage collection, obtain debugging statistics, and tuning the collector's parameters. +

+The detection of cycles can be disabled when Python is compiled, if you can't afford even a tiny speed penalty or suspect that the cycle collection is buggy, by specifying the "--without-cycle-gc" switch when running the configure script. +

+Sometimes objects get stuck in "tracebacks" temporarily and hence are not deallocated when you might expect. Clear the tracebacks via +

+

+       import sys
+       sys.exc_traceback = sys.last_traceback = None
+
+Tracebacks are used for reporting errors and implementing debuggers and related things. They contain a portion of the program state extracted during the handling of an exception (usually the most recent exception). +

+In the absence of circularities and modulo tracebacks, Python programs need not explicitly manage memory. +

+Why python doesn't use a more traditional garbage collection +scheme? For one thing, unless this were +added to C as a standard feature, it's a portability pain in the ass. +And yes, I know about the Xerox library. It has bits of assembler +code for most common platforms. Not for all. And although it is +mostly transparent, it isn't completely transparent (when I once +linked Python with it, it dumped core). +

+Traditional GC also becomes a problem when Python gets embedded into +other applications. While in a stand-alone Python it may be fine to +replace the standard malloc() and free() with versions provided by the +GC library, an application embedding Python may want to have its own +substitute for malloc() and free(), and may not want Python's. Right +now, Python works with anything that implements malloc() and free() +properly. +

+In Jython, the following code (which is +fine in C Python) will probably run out of file descriptors long before +it runs out of memory: +

+

+        for file in <very long list of files>:
+                f = open(file)
+                c = f.read(1)
+
+Using the current reference counting and destructor scheme, each new +assignment to f closes the previous file. Using GC, this is not +guaranteed. Sure, you can think of ways to fix this. But it's not +off-the-shelf technology. If you want to write code that will +work with any Python implementation, you should explicitly close +the file; this will work regardless of GC: +

+

+       for file in <very long list of files>:
+                f = open(file)
+                c = f.read(1)
+                f.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Mar 21 05:35:38 2002 by +Erno Kuusela +

+ +


+

6.15. Why are there separate tuple and list data types?

+This is done so that tuples can be immutable while lists are mutable. +

+Immutable tuples are useful in situations where you need to pass a few +items to a function and don't want the function to modify the tuple; +for example, +

+

+	point1 = (120, 140)
+	point2 = (200, 300)
+	record(point1, point2)
+	draw(point1, point2)
+
+You don't want to have to think about what would happen if record() +changed the coordinates -- it can't, because the tuples are immutable. +

+On the other hand, when creating large lists dynamically, it is +absolutely crucial that they are mutable -- adding elements to a tuple +one by one requires using the concatenation operator, which makes it +quadratic in time. +

+As a general guideline, use tuples like you would use structs in C or +records in Pascal, use lists like (variable length) arrays. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:26:03 1997 by +GvR +

+ +


+

6.16. How are lists implemented?

+Despite what a Lisper might think, Python's lists are really +variable-length arrays. The implementation uses a contiguous +array of references to other objects, and keeps a pointer +to this array (as well as its length) in a list head structure. +

+This makes indexing a list (a[i]) an operation whose cost is +independent of the size of the list or the value of the index. +

+When items are appended or inserted, the array of references is resized. +Some cleverness is applied to improve the performance of appending +items repeatedly; when the array must be grown, some extra space +is allocated so the next few times don't require an actual resize. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 15:32:24 1997 by +GvR +

+ +


+

6.17. How are dictionaries implemented?

+Python's dictionaries are implemented as resizable hash tables. +

+Compared to B-trees, this gives better performance for lookup +(the most common operation by far) under most circumstances, +and the implementation is simpler. +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 23:51:14 1997 by +Vladimir Marangozov +

+ +


+

6.18. Why must dictionary keys be immutable?

+The hash table implementation of dictionaries uses a hash value +calculated from the key value to find the key. If the key were +a mutable object, its value could change, and thus its hash could +change. But since whoever changes the key object can't tell that +is incorporated in a dictionary, it can't move the entry around in +the dictionary. Then, when you try to look up the same object +in the dictionary, it won't be found, since its hash value is different; +and if you try to look up the old value, it won't be found either, +since the value of the object found in that hash bin differs. +

+If you think you need to have a dictionary indexed with a list, +try to use a tuple instead. The function tuple(l) creates a tuple +with the same entries as the list l. +

+Some unacceptable solutions that have been proposed: +

+- Hash lists by their address (object ID). This doesn't work because +if you construct a new list with the same value it won't be found; +e.g., +

+

+  d = {[1,2]: '12'}
+  print d[[1,2]]
+
+will raise a KeyError exception because the id of the [1,2] used +in the second line differs from that in the first line. +In other words, dictionary keys should be compared using '==', not using 'is'. +

+- Make a copy when using a list as a key. This doesn't work because +the list (being a mutable object) could contain a reference to itself, +and then the copying code would run into an infinite loop. +

+- Allow lists as keys but tell the user not to modify them. This would +allow a class of hard-to-track bugs in programs that I'd rather not see; +it invalidates an important invariant of dictionaries (every value in +d.keys() is usable as a key of the dictionary). +

+- Mark lists as read-only once they are used as a dictionary key. +The problem is that it's not just the top-level object that could change +its value; you could use a tuple containing a list as a key. Entering +anything as a key into a dictionary would require marking all objects +reachable from there as read-only -- and again, self-referential objects +could cause an infinite loop again (and again and again). +

+There is a trick to get around this if you need to, but +use it at your own risk: You +can wrap a mutable structure inside a class instance which +has both a __cmp__ and a __hash__ method. +

+

+   class listwrapper:
+        def __init__(self, the_list):
+              self.the_list = the_list
+        def __cmp__(self, other):
+              return self.the_list == other.the_list
+        def __hash__(self):
+              l = self.the_list
+              result = 98767 - len(l)*555
+              for i in range(len(l)):
+                   try:
+                        result = result + (hash(l[i]) % 9999999) * 1001 + i
+                   except:
+                        result = (result % 7777777) + i * 333
+              return result
+
+Note that the hash computation is complicated by the +possibility that some members of the list may be unhashable +and also by the possibility of arithmetic overflow. +

+You must make +sure that the hash value for all such wrapper objects that reside in a +dictionary (or other hash based structure), remain fixed while +the object is in the dictionary (or other structure). +

+Furthermore it must always be the case that if +o1 == o2 (ie o1.__cmp__(o2)==0) then hash(o1)==hash(o2) +(ie, o1.__hash__() == o2.__hash__()), regardless of whether +the object is in a dictionary or not. +If you fail to meet these restrictions dictionaries and other +hash based structures may misbehave! +

+In the case of listwrapper above whenever the wrapper +object is in a dictionary the wrapped list must not change +to avoid anomalies. Don't do this unless you are prepared +to think hard about the requirements and the consequences +of not meeting them correctly. You've been warned! +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 10 10:08:40 1997 by +aaron watters +

+ +


+

6.19. How the heck do you make an array in Python?

+["this", 1, "is", "an", "array"] +

+Lists are arrays in the C or Pascal sense of the word (see question +6.16). The array module also provides methods for creating arrays +of fixed types with compact representations (but they are slower to +index than lists). Also note that the Numerics extensions and others +define array-like structures with various characteristics as well. +

+To get Lisp-like lists, emulate cons cells +

+

+    lisp_list = ("like",  ("this",  ("example", None) ) )
+
+using tuples (or lists, if you want mutability). Here the analogue +of lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1]. +Only do this if you're sure you really need to (it's usually a lot +slower than using Python lists). +

+Think of Python lists as mutable heterogeneous arrays of +Python objects (say that 10 times fast :) ). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:08:27 1997 by +aaron watters +

+ +


+

6.20. Why doesn't list.sort() return the sorted list?

+In situations where performance matters, making a copy of the list +just to sort it would be wasteful. Therefore, list.sort() sorts +the list in place. In order to remind you of that fact, it does +not return the sorted list. This way, you won't be fooled into +accidentally overwriting a list when you need a sorted copy but also +need to keep the unsorted version around. +

+As a result, here's the idiom to iterate over the keys of a dictionary +in sorted order: +

+

+	keys = dict.keys()
+	keys.sort()
+	for key in keys:
+		...do whatever with dict[key]...
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Dec 2 17:01:52 1999 by +Fred L. Drake, Jr. +

+ +


+

6.21. How do you specify and enforce an interface spec in Python?

+An interfaces specification for a module as provided +by languages such as C++ and java describes the prototypes +for the methods and functions of the module. Many feel +that compile time enforcement of interface specifications +help aid in the construction of large programs. Python +does not support interface specifications directly, but many +of their advantages can be obtained by an appropriate +test discipline for components, which can often be very +easily accomplished in Python. There is also a tool, PyChecker, +which can be used to find problems due to subclassing. +

+A good test suite for a module can at +once provide a regression test and serve as a module interface +specification (even better since it also gives example usage). Look to +many of the standard libraries which often have a "script +interpretation" which provides a simple "self test." Even +modules which use complex external interfaces can often +be tested in isolation using trivial "stub" emulations of the +external interface. +

+An appropriate testing discipline (if enforced) can help +build large complex applications in Python as well as having interface +specifications would do (or better). Of course Python allows you +to get sloppy and not do it. Also you might want to design +your code with an eye to make it easily tested. +

+ +Edit this entry / +Log info + +/ Last changed on Thu May 23 03:05:29 2002 by +Neal Norwitz +

+ +


+

6.22. Why do all classes have the same type? Why do instances all have the same type?

+The Pythonic use of the word "type" is quite different from +common usage in much of the rest of the programming language +world. A "type" in Python is a description for an object's operations +as implemented in C. All classes have the same operations +implemented in C which sometimes "call back" to differing program +fragments implemented in Python, and hence all classes have the +same type. Similarly at the C level all class instances have the +same C implementation, and hence all instances have the same +type. +

+Remember that in Python usage "type" refers to a C implementation +of an object. To distinguish among instances of different classes +use Instance.__class__, and also look to 4.47. Sorry for the +terminological confusion, but at this point in Python's development +nothing can be done! +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jul 1 12:35:47 1997 by +aaron watters +

+ +


+

6.23. Why isn't all memory freed when Python exits?

+Objects referenced from Python module global name spaces are +not always deallocated when Python exits. +

+This may happen if there are circular references (see question +4.17). There are also certain bits of memory that are allocated +by the C library that are impossible to free (e.g. a tool +like Purify will complain about these). +

+But in general, Python 1.5 and beyond +(in contrast with earlier versions) is quite agressive about +cleaning up memory on exit. +

+If you want to force Python to delete certain things on deallocation +use the sys.exitfunc hook to force those deletions. For example +if you are debugging an extension module using a memory analysis +tool and you wish to make Python deallocate almost everything +you might use an exitfunc like this one: +

+

+  import sys
+
+
+  def my_exitfunc():
+       print "cleaning up"
+       import sys
+       # do order dependant deletions here
+       ...
+       # now delete everything else in arbitrary order
+       for x in sys.modules.values():
+            d = x.__dict__
+            for name in d.keys():
+                 del d[name]
+
+
+  sys.exitfunc = my_exitfunc
+
+Other exitfuncs can be less drastic, of course. +

+(In fact, this one just does what Python now already does itself; +but the example of using sys.exitfunc to force cleanups is still +useful.) +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 29 09:46:26 1998 by +GvR +

+ +


+

6.24. Why no class methods or mutable class variables?

+The notation +

+

+    instance.attribute(arg1, arg2)
+
+usually translates to the equivalent of +

+

+    Class.attribute(instance, arg1, arg2)
+
+where Class is a (super)class of instance. Similarly +

+

+    instance.attribute = value
+
+sets an attribute of an instance (overriding any attribute of a class +that instance inherits). +

+Sometimes programmers want to have +different behaviours -- they want a method which does not bind +to the instance and a class attribute which changes in place. +Python does not preclude these behaviours, but you have to +adopt a convention to implement them. One way to accomplish +this is to use "list wrappers" and global functions. +

+

+   def C_hello():
+         print "hello"
+
+
+   class C:
+        hello = [C_hello]
+        counter = [0]
+
+
+    I = C()
+
+Here I.hello[0]() acts very much like a "class method" and +I.counter[0] = 2 alters C.counter (and doesn't override it). +If you don't understand why you'd ever want to do this, that's +because you are pure of mind, and you probably never will +want to do it! This is dangerous trickery, not recommended +when avoidable. (Inspired by Tim Peter's discussion.) +

+In Python 2.2, you can do this using the new built-in operations +classmethod and staticmethod. +See http://www.python.org/2.2/descrintro.html#staticmethods +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 11 15:59:37 2001 by +GvR +

+ +


+

6.25. Why are default values sometimes shared between objects?

+It is often expected that a function CALL creates new objects for default +values. This is not what happens. Default values are created when the +function is DEFINED, that is, there is only one such object that all +functions refer to. If that object is changed, subsequent calls to the +function will refer to this changed object. By definition, immutable objects +(like numbers, strings, tuples, None) are safe from change. Changes to mutable +objects (like dictionaries, lists, class instances) is what causes the +confusion. +

+Because of this feature it is good programming practice not to use mutable +objects as default values, but to introduce them in the function. +Don't write: +

+

+	def foo(dict={}):  # XXX shared reference to one dict for all calls
+	    ...
+
+but: +
+	def foo(dict=None):
+		if dict is None:
+			dict = {} # create a new dict for local namespace
+
+See page 182 of "Internet Programming with Python" for one discussion +of this feature. Or see the top of page 144 or bottom of page 277 in +"Programming Python" for another discussion. +

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 16 07:03:35 1997 by +Case Roole +

+ +


+

6.26. Why no goto?

+Actually, you can use exceptions to provide a "structured goto" +that even works across function calls. Many feel that exceptions +can conveniently emulate all reasonable uses of the "go" or "goto" +constructs of C, Fortran, and other languages. For example: +

+

+   class label: pass # declare a label
+   try:
+        ...
+        if (condition): raise label() # goto label
+        ...
+   except label: # where to goto
+        pass
+   ...
+
+This doesn't allow you to jump into the middle of a loop, but +that's usually considered an abuse of goto anyway. Use sparingly. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Sep 10 07:16:44 1997 by +aaron watters +

+ +


+

6.27. How do you make a higher order function in Python?

+You have two choices: you can use default arguments and override +them or you can use "callable objects." For example suppose you +wanted to define linear(a,b) which returns a function f where f(x) +computes the value a*x+b. Using default arguments: +

+

+     def linear(a,b):
+         def result(x, a=a, b=b):
+             return a*x + b
+         return result
+
+Or using callable objects: +

+

+     class linear:
+        def __init__(self, a, b):
+            self.a, self.b = a,b
+        def __call__(self, x):
+            return self.a * x + self.b
+
+In both cases: +

+

+     taxes = linear(0.3,2)
+
+gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2. +

+The defaults strategy has the disadvantage that the default arguments +could be accidentally or maliciously overridden. The callable objects +approach has the disadvantage that it is a bit slower and a bit +longer. Note however that a collection of callables can share +their signature via inheritance. EG +

+

+      class exponential(linear):
+         # __init__ inherited
+         def __call__(self, x):
+             return self.a * (x ** self.b)
+
+On comp.lang.python, zenin@bawdycaste.org points out that +an object can encapsulate state for several methods in order +to emulate the "closure" concept from functional programming +languages, for example: +

+

+    class counter:
+        value = 0
+        def set(self, x): self.value = x
+        def up(self): self.value=self.value+1
+        def down(self): self.value=self.value-1
+
+
+    count = counter()
+    inc, dec, reset = count.up, count.down, count.set
+
+Here inc, dec and reset act like "functions which share the +same closure containing the variable count.value" (if you +like that way of thinking). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Sep 25 08:38:35 1998 by +Aaron Watters +

+ +


+

6.28. Why do I get a SyntaxError for a 'continue' inside a 'try'?

+This is an implementation limitation, +caused by the extremely simple-minded +way Python generates bytecode. The try block pushes something on the +"block stack" which the continue would have to pop off again. The +current code generator doesn't have the data structures around so that +'continue' can generate the right code. +

+Note that JPython doesn't have this restriction! +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 22 15:01:07 1998 by +GvR +

+ +


+

6.29. Why can't raw strings (r-strings) end with a backslash?

+More precisely, they can't end with an odd number of backslashes: +the unpaired backslash at the end escapes the closing quote character, +leaving an unterminated string. +

+Raw strings were designed to ease creating input for processors (chiefly +regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose. +

+If you're trying to build Windows pathnames, note that all Windows system calls accept forward slashes too: +

+

+    f = open("/mydir/file.txt") # works fine!
+
+If you're trying to build a pathname for a DOS command, try e.g. one of +

+

+    dir = r"\this\is\my\dos\dir" "\\"
+    dir = r"\this\is\my\dos\dir\ "[:-1]
+    dir = "\\this\\is\\my\\dos\\dir\\"
+
+

+ +Edit this entry / +Log info + +/ Last changed on Mon Jul 13 20:50:20 1998 by +Tim Peters +

+ +


+

6.30. Why can't I use an assignment in an expression?

+Many people used to C or Perl complain that they want to be able to +use e.g. this C idiom: +

+

+    while (line = readline(f)) {
+        ...do something with line...
+    }
+
+where in Python you're forced to write this: +

+

+    while 1:
+        line = f.readline()
+        if not line:
+            break
+        ...do something with line...
+
+This issue comes up in the Python newsgroup with alarming frequency +-- search Deja News for past messages about assignment expression. +The reason for not allowing assignment in Python expressions +is a common, hard-to-find bug in those other languages, +caused by this construct: +

+

+    if (x = 0) {
+        ...error handling...
+    }
+    else {
+        ...code that only works for nonzero x...
+    }
+
+Many alternatives have been proposed. Most are hacks that save some +typing but use arbitrary or cryptic syntax or keywords, +and fail the simple criterion that I use for language change proposals: +it should intuitively suggest the proper meaning to a human reader +who has not yet been introduced with the construct. +

+The earliest time something can be done about this will be with +Python 2.0 -- if it is decided that it is worth fixing. +An interesting phenomenon is that most experienced Python programmers +recognize the "while 1" idiom and don't seem to be missing the +assignment in expression construct much; it's only the newcomers +who express a strong desire to add this to the language. +

+One fairly elegant solution would be to introduce a new operator +for assignment in expressions spelled ":=" -- this avoids the "=" +instead of "==" problem. It would have the same precedence +as comparison operators but the parser would flag combination with +other comparisons (without disambiguating parentheses) as an error. +

+Finally -- there's an alternative way of spelling this that seems +attractive but is generally less robust than the "while 1" solution: +

+

+    line = f.readline()
+    while line:
+        ...do something with line...
+        line = f.readline()
+
+The problem with this is that if you change your mind about exactly +how you get the next line (e.g. you want to change it into +sys.stdin.readline()) you have to remember to change two places +in your program -- the second one hidden at the bottom of the loop. +

+ +Edit this entry / +Log info + +/ Last changed on Tue May 18 00:57:41 1999 by +Andrew Dalke +

+ +


+

6.31. Why doesn't Python have a "with" statement like some other languages?

+Basically, because such a construct would be terribly ambiguous. Thanks to Carlos Ribeiro for the following remarks: +

+Some languages, such as Object Pascal, Delphi, and C++, use static types. So it is possible to know, in an unambiguous way, what member is being assigned in a "with" clause. This is the main point - the compiler always knows the scope of every variable at compile time. +

+Python uses dynamic types. It is impossible to know in advance which +attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This would make it impossible to know, from a simple reading, what attribute is being referenced - a local one, a global one, or a member attribute. +

+For instance, take the following snippet (it is incomplete btw, just to +give you the idea): +

+

+   def with_is_broken(a):
+      with a:
+         print x
+
+The snippet assumes that "a" must have a member attribute called "x". +However, there is nothing in Python that guarantees that. What should +happen if "a" is, let us say, an integer? And if I have a global variable named "x", will it end up being used inside the with block? As you see, the dynamic nature of Python makes such choices much harder. +

+The primary benefit of "with" and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of: +

+

+    function(args).dict[index][index].a = 21
+    function(args).dict[index][index].b = 42
+    function(args).dict[index][index].c = 63
+
+would become: +

+

+    ref = function(args).dict[index][index]
+    ref.a = 21
+    ref.b = 42
+    ref.c = 63
+
+This also has the happy side-effect of increasing execution speed, since name bindings are resolved at run-time in Python, and the second method only needs to perform the resolution once. If the referenced object does not have a, b and c attributes, of course, the end result is still a run-time exception. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jan 11 14:32:58 2002 by +Steve Holden +

+ +


+

6.32. Why are colons required for if/while/def/class?

+The colon is required primarily to enhance readability (one of the +results of the experimental ABC language). Consider this: +

+

+    if a==b
+        print a
+
+versus +

+

+    if a==b:
+        print a
+
+Notice how the second one is slightly easier to read. Notice further how +a colon sets off the example in the second line of this FAQ answer; it's +a standard usage in English. Finally, the colon makes it easier for +editors with syntax highlighting. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Jun 3 07:22:57 2002 by +Matthias Urlichs +

+ +


+

6.33. Can't we get rid of the Global Interpreter Lock?

+The Global Interpreter Lock (GIL) is often seen as a hindrance to +Python's deployment on high-end multiprocessor server machines, +because a multi-threaded Python program effectively only uses +one CPU, due to the insistence that (almost) all Python code +can only run while the GIL is held. +

+Back in the days of Python 1.5, Greg Stein actually implemented +a comprehensive patch set ("free threading") +that removed the GIL, replacing it with +fine-grained locking. Unfortunately, even on Windows (where locks +are very efficient) this ran ordinary Python code about twice as +slow as the interpreter using the GIL. On Linux the performance +loss was even worse (pthread locks aren't as efficient). +

+Since then, the idea of getting rid of the GIL has occasionally +come up but nobody has found a way to deal with the expected slowdown; +Greg's free threading patch set has not been kept up-to-date for +later Python versions. +

+This doesn't mean that you can't make good use of Python on +multi-CPU machines! You just have to be creative with dividing +the work up between multiple processes rather than multiple +threads. +

+

+It has been suggested that the GIL should be a per-interpreter-state +lock rather than truly global; interpreters then wouldn't be able +to share objects. Unfortunately, this isn't likely to happen either. +

+It would be a tremendous amount of work, because many object +implementations currently have global state. E.g. small ints and +small strings are cached; these caches would have to be moved to the +interpreter state. Other object types have their own free list; these +free lists would have to be moved to the interpreter state. And so +on. +

+And I doubt that it can even be done in finite time, because the same +problem exists for 3rd party extensions. It is likely that 3rd party +extensions are being written at a faster rate than you can convert +them to store all their global state in the interpreter state. +

+And finally, once you have multiple interpreters not sharing any +state, what have you gained over running each interpreter +in a separate process? +

+ +Edit this entry / +Log info + +/ Last changed on Fri Feb 7 16:34:01 2003 by +GvR +

+ +


+

7. Using Python on non-UNIX platforms

+ +
+

7.1. Is there a Mac version of Python?

+Yes, it is maintained by Jack Jansen. See Jack's MacPython Page: +

+

+  http://www.cwi.nl/~jack/macpython.html
+
+

+ +Edit this entry / +Log info + +/ Last changed on Fri May 4 09:33:42 2001 by +GvR +

+ +


+

7.2. Are there DOS and Windows versions of Python?

+Yes. The core windows binaries are available from http://www.python.org/windows/. There is a plethora of Windows extensions available, including a large number of not-always-compatible GUI toolkits. The core binaries include the standard Tkinter GUI extension. +

+Most windows extensions can be found (or referenced) at http://www.python.org/windows/ +

+Windows 3.1/DOS support seems to have dropped off recently. You may need to settle for an old version of Python one these platforms. One such port is WPY +

+WPY: Ports to DOS, Windows 3.1(1), Windows 95, Windows NT and OS/2. +Also contains a GUI package that offers portability between Windows +(not DOS) and Unix, and native look and feel on both. +ftp://ftp.python.org/pub/python/wpy/. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Jun 2 20:21:57 1998 by +Mark Hammond +

+ +


+

7.3. Is there an OS/2 version of Python?

+Yes, see http://www.python.org/download/download_os2.html. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Sep 7 11:33:16 1999 by +GvR +

+ +


+

7.4. Is there a VMS version of Python?

+Jean-François Piéronne has ported 2.1.3 to OpenVMS. It can be found at +<http://vmspython.dyndns.org/>. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Sep 19 15:40:38 2002 by +Skip Montanaro +

+ +


+

7.5. What about IBM mainframes, or other non-UNIX platforms?

+I haven't heard about these, except I remember hearing about an +OS/9 port and a port to Vxworks (both operating systems for embedded +systems). If you're interested in any of this, go directly to the +newsgroup and ask there, you may find exactly what you need. For +example, a port to MPE/iX 5.0 on HP3000 computers was just announced, +see http://www.allegro.com/software/. +

+On the IBM mainframe side, for Z/OS there's a port of python 1.4 that goes with their open-unix package, formely OpenEdition MVS, (http://www-1.ibm.com/servers/eserver/zseries/zos/unix/python.html). On a side note, there's also a java vm ported - so, in theory, jython could run too. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Nov 18 03:18:39 2002 by +Bruno Jessen +

+ +


+

7.6. Where are the source or Makefiles for the non-UNIX versions?

+The standard sources can (almost) be used. Additional sources can +be found in the platform-specific subdirectories of the distribution. +

+ +Edit this entry / +Log info +

+ +


+

7.7. What is the status and support for the non-UNIX versions?

+I don't have access to most of these platforms, so in general I am +dependent on material submitted by volunteers. However I strive to +integrate all changes needed to get it to compile on a particular +platform back into the standard sources, so porting of the next +version to the various non-UNIX platforms should be easy. +(Note that Linux is classified as a UNIX platform here. :-) +

+Some specific platforms: +

+Windows: all versions (95, 98, ME, NT, 2000, XP) are supported, +all python.org releases come with a Windows installer. +

+MacOS: Jack Jansen does an admirable job of keeping the Mac version +up to date (both MacOS X and older versions); +see http://www.cwi.nl/~jack/macpython.html +

+For all supported platforms, see http://www.python.org/download/ +(follow the link to "Other platforms" for less common platforms) +

+ +Edit this entry / +Log info + +/ Last changed on Fri May 24 21:34:24 2002 by +GvR +

+ +


+

7.8. I have a PC version but it appears to be only a binary. Where's the library?

+If you are running any version of Windows, then you have the wrong distribution. The FAQ lists current Windows versions. Notably, Pythonwin and wpy provide fully functional installations. +

+But if you are sure you have the only distribution with a hope of working on +your system, then... +

+You still need to copy the files from the distribution directory +"python/Lib" to your system. If you don't have the full distribution, +you can get the file lib<version>.tar.gz from most ftp sites carrying +Python; this is a subset of the distribution containing just those +files, e.g. ftp://ftp.python.org/pub/python/src/lib1.4.tar.gz. +

+Once you have installed the library, you need to point sys.path to it. +Assuming the library is in C:\misc\python\lib, the following commands +will point your Python interpreter to it (note the doubled backslashes +-- you can also use single forward slashes instead): +

+

+        >>> import sys
+        >>> sys.path.insert(0, 'C:\\misc\\python\\lib')
+        >>>
+
+For a more permanent effect, set the environment variable PYTHONPATH, +as follows (talking to a DOS prompt): +

+

+        C> SET PYTHONPATH=C:\misc\python\lib
+
+

+ +Edit this entry / +Log info + +/ Last changed on Fri May 23 16:28:27 1997 by +Ken Manheimer +

+ +


+

7.9. Where's the documentation for the Mac or PC version?

+The documentation for the Unix version also applies to the Mac and +PC versions. Where applicable, differences are indicated in the text. +

+ +Edit this entry / +Log info +

+ +


+

7.10. How do I create a Python program file on the Mac or PC?

+Use an external editor. On the Mac, BBEdit seems to be a popular +no-frills text editor. I work like this: start the interpreter; edit +a module file using BBedit; import and test it in the interpreter; +edit again in BBedit; then use the built-in function reload() to +re-read the imported module; etc. In the 1.4 distribution +you will find a BBEdit extension that makes life a little easier: +it can tell the interpreter to execute the current window. +See :Mac:Tools:BBPy:README. +

+Regarding the same question for the PC, Kurt Wm. Hemr writes: "While +anyone with a pulse could certainly figure out how to do the same on +MS-Windows, I would recommend the NotGNU Emacs clone for MS-Windows. +Not only can you easily resave and "reload()" from Python after making +changes, but since WinNot auto-copies to the clipboard any text you +select, you can simply select the entire procedure (function) which +you changed in WinNot, switch to QWPython, and shift-ins to reenter +the changed program unit." +

+If you're using Windows95 or Windows NT, you should also know about +PythonWin, which provides a GUI framework, with an mouse-driven +editor, an object browser, and a GUI-based debugger. See +

+       http://www.python.org/ftp/python/pythonwin/
+
+for details. +

+ +Edit this entry / +Log info + +/ Last changed on Sun May 25 10:04:25 1997 by +GvR +

+ +


+

7.11. How can I use Tkinter on Windows 95/NT?

+Starting from Python 1.5, it's very easy -- just download and install +Python and Tcl/Tk and you're in business. See +

+

+  http://www.python.org/download/download_windows.html
+
+One warning: don't attempt to use Tkinter from PythonWin +(Mark Hammond's IDE). Use it from the command line interface +(python.exe) or the windowless interpreter (pythonw.exe). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 12 09:32:48 1998 by +GvR +

+ +


+

7.12. cgi.py (or other CGI programming) doesn't work sometimes on NT or win95!

+Be sure you have the latest python.exe, that you are using +python.exe rather than a GUI version of python and that you +have configured the server to execute +

+

+     "...\python.exe -u ..."
+
+for the cgi execution. The -u (unbuffered) option on NT and +win95 prevents the interpreter from altering newlines in the +standard input and output. Without it post/multipart requests +will seem to have the wrong length and binary (eg, GIF) +responses may get garbled (resulting in, eg, a "broken image"). +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jul 30 10:48:02 1997 by +aaron watters +

+ +


+

7.13. Why doesn't os.popen() work in PythonWin on NT?

+The reason that os.popen() doesn't work from within PythonWin is due to a bug in Microsoft's C Runtime Library (CRT). The CRT assumes you have a Win32 console attached to the process. +

+You should use the win32pipe module's popen() instead which doesn't depend on having an attached Win32 console. +

+Example: +

+ import win32pipe
+ f = win32pipe.popen('dir /c c:\\')
+ print f.readlines()
+ f.close()
+
+

+ +Edit this entry / +Log info + +/ Last changed on Thu Jul 31 15:34:09 1997 by +Bill Tutt +

+ +


+

7.14. How do I use different functionality on different platforms with the same program?

+Remember that Python is extremely dynamic and that you +can use this dynamism to configure a program at run-time to +use available functionality on different platforms. For example +you can test the sys.platform and import different modules based +on its value. +

+

+   import sys
+   if sys.platform == "win32":
+      import win32pipe
+      popen = win32pipe.popen
+   else:
+      import os
+      popen = os.popen
+
+(See FAQ 7.13 for an explanation of why you might want to +do something like this.) Also you can try to import a module +and use a fallback if the import fails: +

+

+    try:
+         import really_fast_implementation
+         choice = really_fast_implementation
+    except ImportError:
+         import slower_implementation
+         choice = slower_implementation
+
+

+ +Edit this entry / +Log info + +/ Last changed on Wed Aug 13 07:39:06 1997 by +aaron watters +

+ +


+

7.15. Is there an Amiga version of Python?

+Yes. See the AmigaPython homepage at http://www.bigfoot.com/~irmen/python.html. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Dec 14 06:53:32 1998 by +Irmen de Jong +

+ +


+

7.16. Why doesn't os.popen()/win32pipe.popen() work on Win9x?

+There is a bug in Win9x that prevents os.popen/win32pipe.popen* from working. The good news is there is a way to work around this problem. +The Microsoft Knowledge Base article that you need to lookup is: Q150956. You will find links to the knowledge base at: +http://www.microsoft.com/kb. +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 25 10:45:38 1999 by +Bill Tutt +

+ +


+

8. Python on Windows

+ +
+

8.1. Using Python for CGI on Microsoft Windows

+** Setting up the Microsoft IIS Server/Peer Server +

+On the Microsoft IIS +server or on the Win95 MS Personal Web Server +you set up python in the same way that you +would set up any other scripting engine. +

+Run regedt32 and go to: +

+HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap +

+and enter the following line (making any specific changes that your system may need) +

+.py :REG_SZ: c:\<path to python>\python.exe -u %s %s +

+This line will allow you to call your script with a simple reference like: +http://yourserver/scripts/yourscript.py +provided "scripts" is an "executable" directory for your server (which +it usually is by default). +The "-u" flag specifies unbuffered and binary mode for stdin - needed when working with binary data +

+In addition, it is recommended by people who would know that using ".py" may +not be a good idea for the file extensions when used in this context +(you might want to reserve *.py for support modules and use *.cgi or *.cgp +for "main program" scripts). +However, that issue is beyond this Windows FAQ entry. +

+

+** Apache configuration +

+In the Apache configuration file httpd.conf, add the following line at +the end of the file: +

+ScriptInterpreterSource Registry +

+Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin directory. +

+

+** Netscape Servers: +Information on this topic exists at: +http://home.netscape.com/comprod/server_central/support/fasttrack_man/programs.htm#1010870 +

+ +Edit this entry / +Log info + +/ Last changed on Wed Mar 27 12:25:54 2002 by +Gerhard Häring +

+ +


+

8.2. How to check for a keypress without blocking?

+Use the msvcrt module. This is a standard Windows-specific extensions +in Python 1.5 and beyond. It defines a function kbhit() which checks +whether a keyboard hit is present; also getch() which gets one +character without echo. Plus a few other goodies. +

+(Search for "keypress" to find an answer for Unix as well.) +

+ +Edit this entry / +Log info + +/ Last changed on Mon Mar 30 16:21:46 1998 by +GvR +

+ +


+

8.3. $PYTHONPATH

+In MS-DOS derived environments, a unix variable such as $PYTHONPATH is +set as PYTHONPATH, without the dollar sign. PYTHONPATH is useful for +specifying the location of library files. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jun 11 00:41:26 1998 by +Gvr +

+ +


+

8.4. dedent syntax errors

+The FAQ does not recommend using tabs, and Guido's Python Style Guide recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default; see +

+

+    http://www.python.org/doc/essays/styleguide.html
+
+Under any editor mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools -> Options -> Tabs, and for file type "Default" set "Tab size" and "Indent size" to 4, and select the "Insert spaces" radio button. +

+If you suspect mixed tabs and spaces are causing problems in leading whitespace, run Python with the -t switch or, run Tools/Scripts/tabnanny.py to check a directory tree in batch mode. +

+ +Edit this entry / +Log info + +/ Last changed on Mon Feb 12 15:04:14 2001 by +Steve Holden +

+ +


+

8.5. How do I emulate os.kill() in Windows?

+Use win32api: +

+

+    def kill(pid):
+        """kill function for Win32"""
+        import win32api
+        handle = win32api.OpenProcess(1, 0, pid)
+        return (0 != win32api.TerminateProcess(handle, 0))
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sat Aug 8 18:55:06 1998 by +Jeff Bauer +

+ +


+

8.6. Why does os.path.isdir() fail on NT shared directories?

+The solution appears to be always append the "\\" on +the end of shared drives. +

+

+  >>> import os
+  >>> os.path.isdir( '\\\\rorschach\\public')
+  0
+  >>> os.path.isdir( '\\\\rorschach\\public\\')
+  1
+
+[Blake Winton responds:] +I've had the same problem doing "Start >> Run" and then a +directory on a shared drive. If I use "\\rorschach\public", +it will fail, but if I use "\\rorschach\public\", it will +work. For that matter, os.stat() does the same thing (well, +it gives an error for "\\\\rorschach\\public", but you get +the idea)... +

+I've got a theory about why this happens, but it's only +a theory. NT knows the difference between shared directories, +and regular directories. "\\rorschach\public" isn't a +directory, it's _really_ an IPC abstraction. This is sort +of lended credence to by the fact that when you're mapping +a network drive, you can't map "\\rorschach\public\utils", +but only "\\rorschach\public". +

+[Clarification by funkster@midwinter.com] +It's not actually a Python +question, as Python is working just fine; it's clearing up something +a bit muddled about Windows networked drives. +

+It helps to think of share points as being like drive letters. +Example: +

+        k: is not a directory
+        k:\ is a directory
+        k:\media is a directory
+        k:\media\ is not a directory
+
+The same rules apply if you substitute "k:" with "\\conky\foo": +
+        \\conky\foo  is not a directory
+        \\conky\foo\ is a directory
+        \\conky\foo\media is a directory
+        \\conky\foo\media\ is not a directory
+
+

+ +Edit this entry / +Log info + +/ Last changed on Sun Jan 31 08:44:48 1999 by +GvR +

+ +


+

8.7. PyRun_SimpleFile() crashes on Windows but not on Unix

+I've seen a number of reports of PyRun_SimpleFile() failing +in a Windows port of an application embedding Python that worked +fine on Unix. PyRun_SimpleString() works fine on both platforms. +

+I think this happens because the application was compiled with a +different set of compiler flags than Python15.DLL. It seems that some +compiler flags affect the standard I/O library in such a way that +using different flags makes calls fail. You need to set it for +the non-debug multi-threaded DLL (/MD on the command line, or can be set via MSVC under Project Settings->C++/Code Generation then the "Use rum-time library" dropdown.) +

+Also note that you can not mix-and-match Debug and Release versions. If you wish to use the Debug Multithreaded DLL, then your module _must_ have an "_d" appended to the base name. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Nov 17 17:37:07 1999 by +Mark Hammond +

+ +


+

8.8. Import of _tkinter fails on Windows 95/98

+Sometimes, the import of _tkinter fails on Windows 95 or 98, +complaining with a message like the following: +

+

+  ImportError: DLL load failed: One of the library files needed
+  to run this application cannot be found.
+
+It could be that you haven't installed Tcl/Tk, but if you did +install Tcl/Tk, and the Wish application works correctly, +the problem may be that its installer didn't +manage to edit the autoexec.bat file correctly. It tries to add a +statement that changes the PATH environment variable to include +the Tcl/Tk 'bin' subdirectory, but sometimes this edit doesn't +quite work. Opening it with notepad usually reveals what the +problem is. +

+(One additional hint, noted by David Szafranski: you can't use +long filenames here; e.g. use C:\PROGRA~1\Tcl\bin instead of +C:\Program Files\Tcl\bin.) +

+ +Edit this entry / +Log info + +/ Last changed on Wed Dec 2 22:32:41 1998 by +GvR +

+ +


+

8.9. Can't extract the downloaded documentation on Windows

+Sometimes, when you download the documentation package to a Windows +machine using a web browser, the file extension of the saved file +ends up being .EXE. This is a mistake; the extension should be .TGZ. +

+Simply rename the downloaded file to have the .TGZ extension, and +WinZip will be able to handle it. (If your copy of WinZip doesn't, +get a newer one from http://www.winzip.com.) +

+ +Edit this entry / +Log info + +/ Last changed on Sat Nov 21 13:41:35 1998 by +GvR +

+ +


+

8.10. Can't get Py_RunSimpleFile() to work.

+This is very sensitive to the compiler vendor, version and (perhaps) +even options. If the FILE* structure in your embedding program isn't +the same as is assumed by the Python interpreter it won't work. +

+The Python 1.5.* DLLs (python15.dll) are all compiled +with MS VC++ 5.0 and with multithreading-DLL options (/MD, I think). +

+If you can't change compilers or flags, try using Py_RunSimpleString(). +A trick to get it to run an arbitrary file is to construct a call to +execfile() with the name of your file as argument. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Jan 13 10:58:14 1999 by +GvR +

+ +


+

8.11. Where is Freeze for Windows?

+("Freeze" is a program that allows you to ship a Python program +as a single stand-alone executable file. It is not a compiler, +your programs don't run any faster, but they are more easily +distributable (to platforms with the same OS and CPU). Read the +README file of the freeze program for more disclaimers.) +

+You can use freeze on Windows, but you must download the source +tree (see http://www.python.org/download/download_source.html). +This is recommended for Python 1.5.2 (and betas thereof) only; +older versions don't quite work. +

+You need the Microsoft VC++ 5.0 compiler (maybe it works with +6.0 too). You probably need to build Python -- the project files +are all in the PCbuild directory. +

+The freeze program is in the Tools\freeze subdirectory of the source +tree. +

+ +Edit this entry / +Log info + +/ Last changed on Wed Feb 17 18:47:24 1999 by +GvR +

+ +


+

8.12. Is a *.pyd file the same as a DLL?

+Yes, .pyd files are dll's. But there are a few differences. If you +have a DLL named foo.pyd, then it must have a function initfoo(). You +can then write Python "import foo", and Python will search for foo.pyd +(as well as foo.py, foo.pyc) and if it finds it, will attempt to call +initfoo() to initialize it. You do not link your .exe with foo.lib, +as that would cause Windows to require the DLL to be present. +

+Note that the search path for foo.pyd is PYTHONPATH, not the same as +the path that Windows uses to search for foo.dll. Also, foo.pyd need +not be present to run your program, whereas if you linked your program +with a dll, the dll is required. Of course, foo.pyd is required if +you want to say "import foo". In a dll, linkage is declared in the +source code with __declspec(dllexport). In a .pyd, linkage is defined +in a list of available functions. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Nov 23 02:40:08 1999 by +Jameson Quinn +

+ +


+

8.13. Missing cw3215mt.dll (or missing cw3215.dll)

+Sometimes, when using Tkinter on Windows, you get an error that +cw3215mt.dll or cw3215.dll is missing. +

+Cause: you have an old Tcl/Tk DLL built with cygwin in your path +(probably C:\Windows). You must use the Tcl/Tk DLLs from the +standard Tcl/Tk installation (Python 1.5.2 comes with one). +

+ +Edit this entry / +Log info + +/ Last changed on Fri Jun 11 00:54:13 1999 by +GvR +

+ +


+

8.14. How to make python scripts executable:

+[Blake Coverett] +

+Win2K: +

+The standard installer already associates the .py extension with a file type +(Python.File) and gives that file type an open command that runs the +interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to +make scripts executable from the command prompt as 'foo.py'. If you'd +rather be able to execute the script by simple typing 'foo' with no +extension you need to add .py to the PATHEXT environment variable. +

+WinNT: +

+The steps taken by the installed as described above allow you do run a +script with 'foo.py', but a long time bug in the NT command processor +prevents you from redirecting the input or output of any script executed in +this way. This is often important. +

+An appropriate incantation for making a Python script executable under WinNT +is to give the file an extension of .cmd and add the following as the first +line: +

+

+    @setlocal enableextensions & python -x %~f0 %* & goto :EOF
+
+Win9x: +

+[Due to Bruce Eckel] +

+

+  @echo off
+  rem = """
+  rem run python on this bat file. Needs the full path where
+  rem you keep your python files. The -x causes python to skip
+  rem the first line of the file:
+  python -x c:\aaa\Python\\"%0".bat %1 %2 %3 %4 %5 %6 %7 %8 %9
+  goto endofpython
+  rem """
+
+
+  # The python program goes here:
+
+
+  print "hello, Python"
+
+
+  # For the end of the batch file:
+  rem = """
+  :endofpython
+  rem """
+
+

+ +Edit this entry / +Log info + +/ Last changed on Tue Nov 30 10:25:17 1999 by +GvR +

+ +


+

8.15. Warning about CTL3D32 version from installer

+The Python installer issues a warning like this: +

+

+  This version uses CTL3D32.DLL whitch is not the correct version.
+  This version is used for windows NT applications only.
+
+[Tim Peters] +This is a Microsoft DLL, and a notorious +source of problems. The msg means what it says: you have the wrong version +of this DLL for your operating system. The Python installation did not +cause this -- something else you installed previous to this overwrote the +DLL that came with your OS (probably older shareware of some sort, but +there's no way to tell now). If you search for "CTL3D32" using any search +engine (AltaVista, for example), you'll find hundreds and hundreds of web +pages complaining about the same problem with all sorts of installation +programs. They'll point you to ways to get the correct version reinstalled +on your system (since Python doesn't cause this, we can't fix it). +

+David A Burton has written a little program to fix this. Go to +http://www.burtonsys.com/download.html and click on "ctl3dfix.zip" +

+ +Edit this entry / +Log info + +/ Last changed on Thu Oct 26 15:42:00 2000 by +GvR +

+ +


+

8.16. How can I embed Python into a Windows application?

+Edward K. Ream <edream@tds.net> writes +

+When '##' appears in a file name below, it is an abbreviated version number. For example, for Python 2.1.1, ## will be replaced by 21. +

+Embedding the Python interpreter in a Windows app can be summarized as +follows: +

+1. Do _not_ build Python into your .exe file directly. On Windows, +Python must be a DLL to handle importing modules that are themselves +DLL's. (This is the first key undocumented fact.) Instead, link to +python##.dll; it is typically installed in c:\Windows\System. +

+You can link to Python statically or dynamically. Linking statically +means linking against python##.lib The drawback is that your app won't +run if python##.dll does not exist on your system. +

+General note: python##.lib is the so-called "import lib" corresponding +to python.dll. It merely defines symbols for the linker. +

+Borland note: convert python##.lib to OMF format using Coff2Omf.exe +first. +

+Linking dynamically greatly simplifies link options; everything happens +at run time. Your code must load python##.dll using the Windows +LoadLibraryEx() routine. The code must also use access routines and +data in python##.dll (that is, Python's C API's) using pointers +obtained by the Windows GetProcAddress() routine. Macros can make +using these pointers transparent to any C code that calls routines in +Python's C API. +

+2. If you use SWIG, it is easy to create a Python "extension module" +that will make the app's data and methods available to Python. SWIG +will handle just about all the grungy details for you. The result is C +code that you link _into your .exe file_ (!) You do _not_ have to +create a DLL file, and this also simplifies linking. +

+3. SWIG will create an init function (a C function) whose name depends +on the name of the extension module. For example, if the name of the +module is leo, the init function will be called initleo(). If you use +SWIG shadow classes, as you should, the init function will be called +initleoc(). This initializes a mostly hidden helper class used by the +shadow class. +

+The reason you can link the C code in step 2 into your .exe file is that +calling the initialization function is equivalent to importing the +module into Python! (This is the second key undocumented fact.) +

+4. In short, you can use the following code to initialize the Python +interpreter with your extension module. +

+

+    #include "python.h"
+    ...
+    Py_Initialize();  // Initialize Python.
+    initmyAppc();  // Initialize (import) the helper class. 
+    PyRun_SimpleString("import myApp") ;  // Import the shadow class.
+
+5. There are two problems with Python's C API which will become apparent +if you use a compiler other than MSVC, the compiler used to build +python##.dll. +

+Problem 1: The so-called "Very High Level" functions that take FILE * +arguments will not work in a multi-compiler environment; each compiler's +notion of a struct FILE will be different. From an implementation +standpoint these are very _low_ level functions. +

+Problem 2: SWIG generates the following code when generating wrappers to +void functions: +

+

+    Py_INCREF(Py_None);
+    _resultobj = Py_None;
+    return _resultobj;
+
+Alas, Py_None is a macro that expands to a reference to a complex data +structure called _Py_NoneStruct inside python##.dll. Again, this code +will fail in a mult-compiler environment. Replace such code by: +

+

+    return Py_BuildValue("");
+
+It may be possible to use SWIG's %typemap command to make the change +automatically, though I have not been able to get this to work (I'm a +complete SWIG newbie). +

+6. Using a Python shell script to put up a Python interpreter window +from inside your Windows app is not a good idea; the resulting window +will be independent of your app's windowing system. Rather, you (or the +wxPythonWindow class) should create a "native" interpreter window. It +is easy to connect that window to the Python interpreter. You can +redirect Python's i/o to _any_ object that supports read and write, so +all you need is a Python object (defined in your extension module) that +contains read() and write() methods. +

+ +Edit this entry / +Log info + +/ Last changed on Thu Jan 31 16:29:34 2002 by +Victor Kryukov +

+ +


+

8.17. Setting up IIS 5 to use Python for CGI

+In order to set up Internet Information Services 5 to use Python for CGI processing, please see the following links: +

+http://www.e-coli.net/pyiis_server.html (for Win2k Server) +http://www.e-coli.net/pyiis.html (for Win2k pro) +

+ +Edit this entry / +Log info + +/ Last changed on Fri Mar 22 22:05:51 2002 by +douglas savitsky +

+ +


+

8.18. How do I run a Python program under Windows?

+This is not necessarily quite the straightforward question it appears +to be. If you are already familiar with running programs from the +Windows command line then everything will seem really easy and +obvious. If your computer experience is limited then you might need a +little more guidance. Also there are differences between Windows 95, +98, NT, ME, 2000 and XP which can add to the confusion. You might +think of this as "why I pay software support charges" if you have a +helpful and friendly administrator to help you set things up without +having to understand all this yourself. If so, then great! Show them +this page and it should be a done deal. +

+Unless you use some sort of integrated development environment (such +as PythonWin or IDLE, to name only two in a growing family) then you +will end up typing Windows commands into what is variously referred +to as a "DOS window" or "Command prompt window". Usually you can +create such a window from your Start menu (under Windows 2000 I use +"Start | Programs | Accessories | Command Prompt"). You should be +able to recognize when you have started such a window because you will +see a Windows "command prompt", which usually looks like this: +

+

+    C:\>
+
+The letter may be different, and there might be other things after it, +so you might just as easily see something like: +

+

+    D:\Steve\Projects\Python>
+
+depending on how your computer has been set up and what else you have +recently done with it. Once you have started such a window, you are +well on the way to running Python programs. +

+You need to realize that your Python scripts have to be processed by +another program, usually called the "Python interpreter". The +interpreter reads your script, "compiles" it into "Python bytecodes" +(which are instructions for an imaginary computer known as the "Python +Virtual Machine") and then executes the bytecodes to run your +program. So, how do you arrange for the interpreter to handle your +Python? +

+First, you need to make sure that your command window recognises the +word "python" as an instruction to start the interpreter. If you have +opened a command window, you should try entering the command: +

+

+    python
+
+and hitting return. If you then see something like: +

+

+    Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
+    Type "help", "copyright", "credits" or "license" for more information.
+    >>>
+
+then this part of the job has been correctly managed during Python's +installation process, and you have started the interpreter in +"interactive mode". That means you can enter Python statements or +expressions interactively and have them executed or evaluated while +you wait. This is one of Python's strongest features, but it takes a +little getting used to. Check it by entering a few expressions of your +choice and seeing the results... +

+

+    >>> print "Hello"
+    Hello
+    >>> "Hello" * 3
+    HelloHelloHello
+
+When you want to end your interactive Python session, enter a +terminator (hold the Ctrl key down while you enter a Z, then hit the +"Enter" key) to get back to your Windows command prompt. You may also +find that you have a Start-menu entry such as "Start | Programs | +Python 2.2 | Python (command line)" that results in you seeing the +">>>" prompt in a new window. If so, the window will disappear after +you enter the terminator -- Windows runs a single "python" command in +the window, which terminates when you terminate the interpreter. +

+If the "python" command, instead of displaying the interpreter prompt ">>>", gives you a message like +

+

+    'python' is not recognized as an internal or external command,
+    operable program or batch file.
+
+or +

+

+    Bad command or filename
+
+then you need to make sure that your computer knows where to find the +Python interpreter. To do this you will have to modify a setting +called the PATH, which is a just list of directories where Windows +will look for programs. Rather than just enter the right command every +time you create a command window, you should arrange for Python's +installation directory to be added to the PATH of every command window +as it starts. If you installed Python fairly recently then the command +

+

+    dir C:\py*
+
+will probably tell you where it is installed. Alternatively, perhaps +you made a note. Otherwise you will be reduced to a search of your +whole disk ... break out the Windows explorer and use "Tools | Find" +or hit the "Search" button and look for "python.exe". Suppose you +discover that Python is installed in the C:\Python22 directory (the +default at the time of writing) then you should make sure that +entering the command +

+

+    c:\Python22\python
+
+starts up the interpreter as above (and don't forget you'll need a +"CTRL-Z" and an "Enter" to get out of it). Once you have verified the +directory, you need to add it to the start-up routines your computer +goes through. For older versions of Windows the easiest way to do +this is to edit the C:\AUTOEXEC.BAT file. You would want to add a line +like the following to AUTOEXEC.BAT: +

+

+    PATH C:\Python22;%PATH%
+
+For Windows NT, 2000 and (I assume) XP, you will need to add a string +such as +

+

+    ;C:\Python22
+
+to the current setting for the PATH environment variable, which you +will find in the properties window of "My Computer" under the +"Advanced" tab. Note that if you have sufficient privilege you might +get a choice of installing the settings either for the Current User or +for System. The latter is preferred if you want everybody to be able +to run Python on the machine. +

+If you aren't confident doing any of these manipulations yourself, ask +for help! At this stage you may or may not want to reboot your system +to make absolutely sure the new setting has "taken" (don't you love +the way Windows gives you these freqeuent coffee breaks). You probably +won't need to for Windows NT, XP or 2000. You can also avoid it in +earlier versions by editing the file C:\WINDOWS\COMMAND\CMDINIT.BAT +instead of AUTOEXEC.BAT. +

+You should now be able to start a new command window, enter +

+

+    python
+
+at the "C:>" (or whatever) prompt, and see the ">>>" prompt that +indicates the Python interpreter is reading interactive commands. +

+Let's suppose you have a program called "pytest.py" in directory +"C:\Steve\Projects\Python". A session to run that program might look +like this: +

+

+    C:\> cd \Steve\Projects\Python
+    C:\Steve\Projects\Python> python pytest.py
+
+Because you added a file name to the command to start the interpreter, +when it starts up it reads the Python script in the named file, +compiles it, executes it, and terminates (so you see another "C:\>" +prompt). You might also have entered +

+

+    C:\> python \Steve\Projects\Python\pytest.py
+
+if you hadn't wanted to change your current directory. +

+Under NT, 2000 and XP you may well find that the installation process +has also arranged that the command +

+

+    pytest.py
+
+(or, if the file isn't in the current directory) +

+

+    C:\Steve\Projects\Python\pytest.py
+
+will automatically recognize the ".py" extension and run the Python +interpreter on the named file. Using this feature is fine, but some +versions of Windows have bugs which mean that this form isn't exactly +equivalent to using the interpreter explicitly, so be careful. Easier +to remember, for now, that +

+

+    python C:\Steve\Projects\Python\pytest.py
+
+works pretty close to the same, and redirection will work (more) +reliably. +

+The important things to remember are: +

+1. Start Python from the Start Menu, or make sure the PATH is set +correctly so Windows can find the Python interpreter. +

+

+    python
+
+should give you a '>>>" prompt from the Python interpreter. Don't +forget the CTRL-Z and ENTER to terminate the interpreter (and, if you +started the window from the Start Menu, make the window disappear). +

+2. Once this works, you run programs with commands: +

+

+    python {program-file}
+
+3. When you know the commands to use you can build Windows shortcuts +to run the Python interpreter on any of your scripts, naming +particular working directories, and adding them to your menus, but +that's another lessFAQ. Take a look at +

+

+    python --help
+
+if your needs are complex. +

+4. Interactive mode (where you see the ">>>" prompt) is best used +not for running programs, which are better executed as in steps 2 +and 3, but for checking that individual statements and expressions do +what you think they will, and for developing code by experiment. +

+ +Edit this entry / +Log info + +/ Last changed on Tue Aug 20 16:19:53 2002 by +GvR +

+ +


+Python home / +Python FAQ Wizard 1.0.3 / +Feedback to GvR +

Python Powered
+ + --- python3.1-3.1.1.orig/debian/libPVER.symbols.in +++ python3.1-3.1.1/debian/libPVER.symbols.in @@ -0,0 +1,3 @@ +libpython@VER@.so.1.0 libpython@VER@ #MINVER# +#include "libpython.symbols" + PyModule_Create2@Base @VER@ --- python3.1-3.1.1.orig/debian/rules +++ python3.1-3.1.1/debian/rules @@ -0,0 +1,1041 @@ +#!/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 + +export SHELL = /bin/bash + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +DEB_BUILD_ARCH ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH) +DEB_BUILD_ARCH_OS ?= $(shell dpkg-architecture -qDEB_BUILD_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 +ifeq ($(on_buildd),yes) + #ifneq (,$(findstring $(DEB_BUILD_ARCH), hppa 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) + +export VER=3.1 +export NVER=3.2 +export PVER=python3.1 +export PRIORITY=$(shell echo $(VER) | tr -d '.')0 + +PREVVER := $(shell awk '/^python/ && NR > 1 {print substr($$2,2,length($$2)-2); exit}' debian/changelog) + +# default versions are built from the python-defaults source package +# keep the definition to adjust package priorities. +DEFAULT_VERSION = no +STATIC_PYTHON=yes + +MIN_MODS := $(shell awk '/^ / && $$2 == "module" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_EXTS := $(shell awk '/^ / && $$2 == "extension" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_BUILTINS := $(shell awk '/^ / && $$2 == "builtin" { print $$1 }' \ + debian/PVER-minimal.README.Debian.in) +MIN_ENCODINGS := $(foreach i, \ + $(filter-out \ + big5% bz2% cp932.py cp949.py cp950.py euc_% \ + gb% iso2022% johab.py shift_jis% , \ + $(shell cd Lib/encodings && echo *.py)), \ + encodings/$(i)) \ + codecs.py stringprep.py + +with_tk := no +with_interp := static +#with_interp := shared + +build_target := build-all +install_target := install + +PY_INTERPRETER = /usr/bin/python$(VER) + +ifeq ($(DEFAULT_VERSION),yes) + PY_PRIO = standard + #PYSTDDEP = , python (>= $(VER)) +else + PY_PRIO = optional +endif +ifeq ($(distribution),Ubuntu) + PY_MINPRIO = required + PY_MINPRIO = optional + with_fpectl = yes +else + PY_MINPRIO = $(PY_PRIO) + with_fpectl = yes +endif + +CC = gcc + +# on alpha, use -O2 only, use -mieee +ifeq ($(DEB_BUILD_ARCH),alpha) + OPTSETTINGS = OPT="-g -O2 -mieee -Wall -Wstrict-prototypes" + OPTDEBUGSETTINGS = OPT="-g -O0 -mieee -Wall -Wstrict-prototypes" +endif +ifeq ($(DEB_BUILD_ARCH),m68k) + OPTSETTINGS = OPT="-g -O2 -Wall -Wstrict-prototypes" +endif + OPTSETTINGS = OPT="-g -O2 -Wall -Wstrict-prototypes" + +PWD := $(shell pwd) +buildd_static := $(CURDIR)/build-static +buildd_shared := $(CURDIR)/build-shared +buildd_debug := $(CURDIR)/build-debug +buildd_shdebug := $(CURDIR)/build-shdebug + +d := debian/tmp +scriptdir = usr/share/lib/python$(VER) +scriptdir = usr/share/python$(VER) +scriptdir = usr/lib/python$(VER) + +# package names and directories +p_base := $(PVER) +p_min := $(PVER)-minimal +p_lib := lib$(PVER) +p_tk := $(PVER)-tk +p_dev := $(PVER)-dev +p_exam := $(PVER)-examples +p_idle := idle-$(PVER) +p_doc := $(PVER)-doc +p_dbg := $(PVER)-dbg + +d_base := debian/$(p_base) +d_min := debian/$(p_min) +d_lib := debian/$(p_lib) +d_tk := debian/$(p_tk) +d_dev := debian/$(p_dev) +d_exam := debian/$(p_exam) +d_idle := debian/$(p_idle) +d_doc := debian/$(p_doc) +d_dbg := debian/$(p_dbg) + +ifneq (,$(findstring $(DEB_BUILD_ARCH), amd64 powerpc ppc64)) + make_build_target = +else + make_build_target = profile-opt +endif +ifeq ($(distribution),Debian) + make_build_target = +endif + +build: $(build_target) +build-all: stamp-build +stamp-build: stamp-build-static stamp-build-shared stamp-build-debug stamp-build-shared-debug stamp-mincheck stamp-check stamp-pystone stamp-pybench + touch stamp-build + +PROFILE_EXCLUDES = test_compiler test_distutils test_platform test_subprocess \ + test_multiprocessing \ + test_thread test_threaded_import test_threadedtempfile \ + test_threading test_threading_local test_threadsignals \ + test_dbm_dumb test_dbm_ndbm test_pydoc test_sundry \ + test_signal test_ioctl +# FIXME: test_mailxbox breaks, 20090703 +PROFILE_EXCLUDES += test_mailbox +# FIXME: test_xmlrpc breaks, 20090818 +PROFILE_EXCLUDES += test_xmlrpc +# FIXME: test_telnetlib uses network resources +PROFILE_EXCLUDES += test_telnetlib + +PROFILE_TASK = ../Lib/test/regrtest.py \ + -x $(sort $(TEST_EXCLUDES) $(PROFILE_EXCLUDES)) + +stamp-build-static: stamp-configure-static + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_static) \ + PROFILE_TASK='$(PROFILE_TASK)' $(make_build_target) + touch stamp-build-static + +stamp-build-shared: stamp-configure-shared + dh_testdir + $(MAKE) $(NJOBS) -C $(buildd_shared) +# : # build the shared library +# $(MAKE) $(NJOBS) -C $(buildd_shared) \ +# libpython$(VER).so + : # build a static library with PIC objects + $(MAKE) $(NJOBS) -C $(buildd_shared) \ + LIBRARY=libpython$(VER)-pic.a libpython$(VER)-pic.a + touch stamp-build-shared + +stamp-build-debug: stamp-configure-debug + dh_testdir +# not building with $(NJOBS), see issue #4279 + $(MAKE) -C $(buildd_debug) + touch stamp-build-debug + +stamp-build-shared-debug: stamp-configure-shared-debug + dh_testdir + : # build the shared debug library +# not building with $(NJOBS), see issue #4279 + $(MAKE) -C $(buildd_shdebug) \ + libpython$(VER)_d.so + touch stamp-build-shared-debug + +common_configure_args = \ + --prefix=/usr \ + --enable-ipv6 \ + --with-system-ffi \ + --with-dbmliborder=bdb \ + --with-wide-unicode \ + +ifeq ($(with_fpectl),yes) + common_configure_args += \ + --with-fpectl +endif + +stamp-configure-shared: patch-stamp + rm -rf $(buildd_shared) + mkdir -p $(buildd_shared) + cd $(buildd_shared) && \ + CC="$(CC)" $(OPTSETTINGS) \ + ../configure \ + --enable-shared \ + $(common_configure_args) + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(buildd_shared)/Modules/Setup.local + cd $(buildd_shared) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(buildd_shared)/config.c $(buildd_shared)/Modules/ + + touch stamp-configure-shared + +stamp-configure-static: patch-stamp + rm -rf $(buildd_static) + mkdir -p $(buildd_static) + cd $(buildd_static) && \ + CC="$(CC)" $(OPTSETTINGS) \ + ../configure \ + $(common_configure_args) + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist | sed 's/^#//' \ + >> $(buildd_static)/Modules/Setup.local + cd $(buildd_static) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(buildd_static)/pyconfig.h \ + > $(buildd_static)/pyconfig.h.new + touch -r $(buildd_static)/pyconfig.h $(buildd_static)/pyconfig.h.new + mv -f $(buildd_static)/pyconfig.h.new $(buildd_static)/pyconfig.h + mv $(buildd_static)/config.c $(buildd_static)/Modules/ + + touch stamp-configure-static + +stamp-configure-debug: patch-stamp + rm -rf $(buildd_debug) + mkdir -p $(buildd_debug) + cd $(buildd_debug) && \ + CC="$(CC)" $(OPTDEBUGSETTINGS) \ + ../configure \ + $(common_configure_args) \ + --with-pydebug + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist | sed 's/^#//' \ + >> $(buildd_debug)/Modules/Setup.local + cd $(buildd_debug) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(buildd_debug)/config.c $(buildd_debug)/Modules/ + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(buildd_debug)/pyconfig.h \ + > $(buildd_debug)/pyconfig.h.new + touch -r $(buildd_debug)/pyconfig.h $(buildd_debug)/pyconfig.h.new + mv -f $(buildd_debug)/pyconfig.h.new $(buildd_debug)/pyconfig.h + + touch stamp-configure-debug + +stamp-configure-shared-debug: patch-stamp + rm -rf $(buildd_shdebug) + mkdir -p $(buildd_shdebug) + cd $(buildd_shdebug) && \ + CC="$(CC)" $(OPTDEBUGSETTINGS) \ + ../configure \ + $(common_configure_args) \ + --enable-shared \ + --with-pydebug + egrep \ + "^#($$(awk '$$2 ~ /^extension$$/ {print $$1}' debian/PVER-minimal.README.Debian.in | tr '\012' '|')XX)" \ + Modules/Setup.dist \ + | sed -e 's/^#//' -e 's/-Wl,-Bdynamic//;s/-Wl,-Bstatic//' \ + >> $(buildd_shdebug)/Modules/Setup.local + cd $(buildd_shdebug) && \ + ../Modules/makesetup -c ../Modules/config.c.in -s Modules \ + Modules/Setup.config Modules/Setup.local Modules/Setup + mv $(buildd_shdebug)/config.c $(buildd_shdebug)/Modules/ + + : # apply workaround for missing os.fsync + sed 's/HAVE_SYNC/HAVE_FSYNC/g' $(buildd_shdebug)/pyconfig.h \ + > $(buildd_shdebug)/pyconfig.h.new + touch -r $(buildd_shdebug)/pyconfig.h $(buildd_shdebug)/pyconfig.h.new + mv -f $(buildd_shdebug)/pyconfig.h.new $(buildd_shdebug)/pyconfig.h + + touch stamp-configure-shared-debug + +stamp-mincheck: stamp-build-static debian/PVER-minimal.README.Debian.in + for m in $(MIN_MODS) $(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 stamp-mincheck + +TEST_RESOURCES = all +ifeq ($(on_buildd),yes) + TEST_RESOURCES := $(TEST_RESOURCES),-network,-urlfetch +endif +TESTOPTS = -w -l -u$(TEST_RESOURCES) +TEST_EXCLUDES = +TEST_EXCLUDES += test_pstats test_profile test_cprofile +ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_tcl test_codecmaps_cn test_codecmaps_hk \ + test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw \ + test_normalization test_ossaudiodev +endif +ifneq (,$(filter $(DEB_BUILD_ARCH), hppa)) + TEST_EXCLUDES += test_fork1 test_wait3 +endif +ifneq (,$(filter $(DEB_BUILD_ARCH), arm)) + TEST_EXCLUDES += test_ctypes +endif +ifneq (,$(filter $(DEB_BUILD_ARCH), arm armel m68k)) + ifeq ($(on_buildd),yes) + TEST_EXCLUDES += test_compiler + endif +endif +ifneq (,$(TEST_EXCLUDES)) + TESTOPTS += -x $(sort $(TEST_EXCLUDES)) +endif + +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 + chmod +x debian/locale-gen + debian/locale-gen + + @echo ========== test environment ============ + @env + @echo ======================================== + + @echo "BEGIN test static" + -time \ + LOCPATH=$(CURDIR)/locales \ + $(MAKE) -C $(buildd_static) test \ + TESTOPTS="$(TESTOPTS)" 2>&1 \ + | tee $(buildd_static)/test_results + @echo "END test static" + @echo "BEGIN test shared" + -time \ + LOCPATH=$(CURDIR)/locales \ + $(MAKE) -C $(buildd_shared) test \ + TESTOPTS="$(TESTOPTS)" 2>&1 \ + | tee $(buildd_shared)/test_results + @echo "END test shared" + ifeq (,$(findstring $(DEB_BUILD_ARCH), alpha)) + @echo "BEGIN test debug" + -time \ + LOCPATH=$(CURDIR)/locales \ + $(MAKE) -C $(buildd_debug) test \ + TESTOPTS="$(TESTOPTS)" 2>&1 \ + | tee $(buildd_debug)/test_results + @echo "END test debug" + endif +endif + cp -p $(buildd_static)/test_results debian/ + touch stamp-check + +stamp-pystone: + @echo "BEGIN pystone static" + cd $(buildd_static) && ./python ../Lib/test/pystone.py + cd $(buildd_static) && ./python ../Lib/test/pystone.py + @echo "END pystone static" + @echo "BEGIN pystone shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=. ./python ../Lib/test/pystone.py + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=. ./python ../Lib/test/pystone.py + @echo "END pystone shared" + @echo "BEGIN pystone debug" + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + cd $(buildd_debug) && ./python ../Lib/test/pystone.py + @echo "END pystone debug" + touch stamp-pystone + +stamp-pybench: + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log + +#ifeq (,$(filter $(DEB_BUILD_ARCH), arm armel hppa mips mipsel m68k)) + pybench_options = -C 2 -n 5 -w 4 +#endif + +stamp-pybenchx: +ifeq ($(WITHOUT_BENCH),yes) + echo "pybench run disabled for this build" > $(buildd_static)/pybench.log +else + @echo "BEGIN pybench static" + cd $(buildd_static) \ + && time ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_static) \ + && ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench static" + @echo "BEGIN pybench shared" + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=. ./python ../Tools/pybench/pybench.py -f run1.pybench $(pybench_options) + cd $(buildd_shared) \ + && LD_LIBRARY_PATH=. ./python ../Tools/pybench/pybench.py -f run2.pybench -c run1.pybench $(pybench_options) + @echo "END pybench shared" + @echo "BEGIN shared/static comparision" + $(buildd_static)/python Tools/pybench/pybench.py \ + -s $(buildd_static)/run2.pybench -c $(buildd_shared)/run2.pybench \ + | tee $(buildd_static)/pybench.log + @echo "END shared/static comparision" +endif + touch 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 -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 \ + +stamp-doc-html: + dh_testdir + $(MAKE) -C Doc html + touch stamp-doc-html + +build-doc: patch-stamp stamp-build-doc +stamp-build-doc: stamp-doc-html + touch 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 -f stamp-* + rm -f patch-stamp* pxxx + rm -f debian/test_results + + $(MAKE) -C Doc clean + sed 's/^@/#/' Makefile.pre.in | $(MAKE) -f - srcdir=. distclean + rm -rf $(buildd_static) $(buildd_shared) $(buildd_debug) $(buildd_shdebug) + find -name '*.py[co]' | xargs -r rm -f + rm -f Lib/lib2to3/*.pickle + rm -rf locales + rm -rf $(d)-dbg + + for f in debian/*.in; do \ + f2=`echo $$f | sed "s,PVER,$(PVER),g;s/@VER@/$(VER)/g;s,\.in$$,,"`; \ + if [ $$f2 != debian/control ]; then \ + rm -f $$f2; \ + fi; \ + done + dh_clean + +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 + +install: $(build_target) stamp-install +stamp-install: stamp-build control-file 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 + + : # fix some file permissions + chmod a-x $(d)/$(scriptdir)/{runpy,fractions,lib2to3/refactor,tkinter/tix}.py + +# : # move manpages to new names +# if [ -d $(d)/usr/man/man1 ]; then \ +# mkdir -p $(d)/usr/share/man +# mv $(d)/usr/man/man1/* $(d)/usr/share/man/man1/; \ +# rm -rf $(d)/usr/man/; \ +# fi + +# FIXME upstream +# mv $(d)/usr/share/man/man1/python.1 \ +# $(d)/usr/share/man/man1/python$(VER).1 + mkdir -p $(d)/usr/share/man/man1 + cp -p Misc/python.man $(d)/usr/share/man/man1/python$(VER).1 + cp -p debian/pydoc.1 $(d)/usr/share/man/man1/pydoc$(VER).1 + + : # Symlinks to /usr/bin for some tools + ln -sf ../lib/python$(VER)/pdb.py $(d)/usr/bin/pdb$(VER) + cp -p debian/pdb.1 $(d)/usr/share/man/man1/pdb$(VER).1 + + : # versioned install only + rm -f $(d)/usr/bin/python3 + rm -f $(d)/usr/bin/python3-config + + mv $(d)/usr/bin/2to3 $(d)/usr/bin/2to3-$(VER) + + : # Remove version information from the egg-info file + mv $(d)/$(scriptdir)/lib-dynload/Python-3*.egg-info \ + $(d)/$(scriptdir)/lib-dynload/Python.egg-info + + dh_installdirs -p$(p_lib) \ + $(scriptdir)/config \ + 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 \ + $(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/pydoc3 $(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/share/man/man1 \ + $(scriptdir)/lib-dynload + 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_ENCODINGS),$(scriptdir)/$(i)) \ + $(scriptdir)/site.py + +# $(foreach i,$(MIN_EXTS),$(scriptdir)/lib-dynload/$(i).so) \ +# usr/share/man/man1/python$(VER).1 \ + + rv=0; \ + for i in $(MIN_EXTS); do \ + if [ -f $(d)/$(scriptdir)/lib-dynload/$$i.so ]; then \ + echo >&2 "extension $$i not mentioned in Setup.dist"; \ + rv=1; \ + fi; \ + done; \ + exit $$rv; + + : # Install sitecustomize.py. + cp -p debian/sitecustomize.py $(d_min)/etc/$(PVER)/ + 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/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/bin/python$(VER)-config \ + usr/lib/python$(VER)/distutils/command/wininst-*.exe + + mv $(d_dev)/usr/lib/python$(VER)/config/Makefile \ + $(d)/usr/lib/python$(VER)/config/ + mv $(d_dev)/usr/include/python$(VER)/pyconfig.h \ + $(d)/usr/include/python$(VER)/ + 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 + +# : # The test framework into $(p_base), regression tests dropped + DH_COMPAT=2 dh_movefiles -p$(p_base) --sourcedir=$(d) \ + $(scriptdir)/test/{regrtest.py,support.py,__init__.py,pystone.py} + rm -rf $(d)/$(scriptdir)/test + rm -rf $(d)/$(scriptdir)/ctypes/test + rm -rf $(d)/$(scriptdir)/bsddb/test + rm -rf $(d)/$(scriptdir)/distutils/tests + rm -rf $(d)/$(scriptdir)/email/test + rm -rf $(d)/$(scriptdir)/importlib/test + rm -rf $(d)/$(scriptdir)/json/tests + rm -rf $(d)/$(scriptdir)/lib2to3/tests + rm -rf $(d)/$(scriptdir)/sqlite3/test + rm -rf $(d)/$(scriptdir)/distutils/tests + rm -rf $(d)/$(scriptdir)/lib2to3/tests + + : # IDLE + mv $(d)/usr/bin/idle3 $(d)/usr/bin/idle-python$(VER) + rm -f $(d)/usr/lib/python$(VER)/idlelib/idle.bat + dh_installdirs -p$(p_idle) \ + usr/bin \ + usr/share/man/man1 + DH_COMPAT=2 dh_movefiles -p$(p_idle) \ + usr/bin/idle-python$(VER) + cp -p debian/idle-$(PVER).1 $(d_idle)/usr/share/man/man1/ + + : # Move the demos and tools into $(p_exam)'s doc directory + dh_installdirs -p$(p_exam) \ + usr/share/doc/python$(VER)/examples + + cp -rp 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 + + : # 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 -) + rm -f $(d_base)/usr/bin/python + + : # Install menu icon + dh_installdirs -p$(p_base) usr/share/pixmaps + cp -p debian/pylogo.xpm $(d_base)/usr/share/pixmaps/$(PVER).xpm + + : # generate binfmt file + mkdir -p $(d_min)/usr/share/binfmts + $(buildd_static)/python debian/mkbinfmt.py $(PVER) \ + > $(d_min)/usr/share/binfmts/$(PVER) + + : # desktop entry + mkdir -p $(d_base)/usr/share/applications + cp -p debian/$(PVER).desktop \ + $(d_base)/usr/share/applications/$(PVER).desktop + + : # remove some things + -find debian -name .cvsignore | xargs rm -f + -find debian -name '*.py[co]' | xargs rm -f + + : # remove empty directories, when all components are in place + -find debian ! -name lib-dynload -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/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 +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/_gdbm_d.so + rm -f $(d_dbg)/usr/lib/debug/$(scriptdir)/lib-dynload/_gdbm.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 + + for i in debian/*.overrides; do \ + b=$$(basename $$i .overrides); \ + install -D -m 644 $$i debian/$$b/usr/share/lintian/overrides/$$b; \ + done + + touch stamp-install + +# Build architecture-independent files here. +binary-indep: $(install_target) $(build_target) stamp-build-doc stamp-control + dh_testdir -i + dh_testroot -i + + : # $(p_doc) package + dh_installdirs -p$(p_doc) \ + usr/share/doc/$(p_base) \ + usr/share/doc/$(p_doc) + dh_installdocs -p$(p_doc) + cp -a Doc/build/html $(d_doc)/usr/share/doc/$(p_base)/ + rm -f $(d_doc)/usr/share/doc/$(p_base)/html/_static/jquery.js + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html /usr/share/doc/$(p_doc)/html \ + /usr/share/javascript/jquery/jquery.js /usr/share/doc/$(p_base)/html/_static/jquery.js + + : # devhelp docs + python debian/pyhtml2devhelp.py \ + $(d_doc)/usr/share/doc/$(p_base)/html index.html $(VER) \ + > $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + gzip -9v $(d_doc)/usr/share/doc/$(p_base)/html/$(PVER).devhelp + dh_link -p$(p_doc) \ + /usr/share/doc/$(p_base)/html /usr/share/devhelp/books/$(PVER) + + dh_installdebconf -i $(dh_args) + dh_installexamples -i $(dh_args) + dh_installmenu -i $(dh_args) + -dh_icons -i $(dh_args) || dh_iconcache -i $(dh_args) + dh_installchangelogs -i $(dh_args) + dh_link -i $(dh_args) + dh_compress -i $(dh_args) -X.py -X.cls -X.css -X.txt -X.json -X.js -Xobjects.inv -Xgdbinit + dh_fixperms -i $(dh_args) + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + -find $(d_doc) -name '*.txt' -perm 755 -exec chmod 644 {} \; + + dh_installdeb -i $(dh_args) + dh_gencontrol -i $(dh_args) + dh_md5sums -i $(dh_args) + dh_builddeb -i $(dh_args) + +# Build architecture-dependent files here. +binary-arch: build install + dh_testdir -a + dh_testroot -a +# dh_installdebconf -a + dh_installexamples -a + dh_installmenu -a + dh_desktop -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 + rm -f $(d_base)/$(scriptdir)/lib-dynload/_gdbm.so + + dh_strip -a -N$(p_dbg) -Xdebug -Xdbg --dbg-package=$(p_dbg) + dh_link -a + dh_compress -a -X.py + dh_fixperms -a + + : # make python scripts starting with '#!' executable + for i in `find debian -mindepth 3 -type f ! -name '*.dpatch' ! -perm 755`; do \ + if head -1 $$i | grep -q '^#!'; then \ + chmod 755 $$i; \ + echo "make executable: $$i"; \ + fi; \ + done + + dh_makeshlibs -p$(p_lib) -V '$(p_lib)' + dh_makeshlibs -p$(p_dbg) -V '$(p_dbg)' +# don't include the following symbols, found in extensions +# which either can be built as builtin or extension. + sed -ri \ + -e '/^ (PyInit_|_add_one_to_index|asdl_)/d' \ + -e '/^ (PyExpat_XML_|PyExpat_Xml)/d' \ + -e '/^ (ffi_type_|_ctypes_)/d' \ + $(d_lib)/DEBIAN/symbols $(d_dbg)/DEBIAN/symbols + dh_installdeb -a + dh_shlibdeps -a + dh_gencontrol -a + dh_md5sums -a + dh_builddeb -a + +# rules to patch the unpacked files in the source directory +# --------------------------------------------------------------------------- +# various rules to unpack addons and (un)apply patches. +# - patch / apply-patches +# - unpatch / reverse-patches + +patchdir = debian/patches + +#debian_doc_patches = \ +# doc-faq \ + +# which patches should be applied? +debian_patches = \ + svn-updates \ + deb-setup \ + deb-locations \ + site-locations \ + distutils-install-layout \ + locale-module \ + distutils-link \ + distutils-sysconfig \ + test-sundry \ + tkinter-import \ + link-opt \ + debug-build \ + profile-doc \ + webbrowser \ + linecache \ + setup-modules \ + platform-lsbrelease \ + bdist-wininst-notfound \ + no-zip-on-sys.path \ + doc-nodownload \ + doc-build \ + profiled-build \ + +# svn-updates \ +# subprocess-eintr-safety \ +# pydebug-path \ + +ifeq ($(with_fpectl),yes) + debian_patches += \ + enable-fpectl +endif + +ifeq ($(DEB_BUILD_ARCH),arm) + debian_patches += arm-float +endif + +# svn-updates \ +# patchlevel \ + +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) +ifeq ($(broken_utimes),yes) + debian_patches += \ + disable-utimes +endif + +ifeq ($(distribution),Ubuntu) + debian_patches += \ + langpack-gettext +endif + +ifeq ($(DEB_BUILD_ARCH_OS),hurd) + debian_patches += \ + no-large-file-support \ + cthreads +endif + +patch: patch-stamp +apply-patches: patch-stamp + +patch-stamp: $(foreach p,$(debian_patches),patch-stamp-$(p)) + echo ""; echo "Patches applied in this version:" > pxxx + for i in $(debian_patches); do \ + echo "" >> pxxx; echo "$$i:" >> pxxx; \ + sed -n 's/^# *DP: */ /p' $(patchdir)/$$i.dpatch >> pxxx; \ + done + rm -rf autom4te.cache configure + autoconf + mv -f pxxx $@ + +reverse-patches: unpatch +unpatch: + for patch in $(debian_patches); do \ + [ -f patch-stamp-$$patch ] && patches="$$patch $$patches"; \ + done; \ + for patch in $$patches; do \ + echo "trying to revert patch $$patch ..."; \ + if sh -e $(patchdir)/$$patch.dpatch -unpatch; then \ + echo "reverted $$patch patch."; \ + rm -f patch-stamp-$$patch; \ + else \ + echo "error in reverting $$patch patch."; \ + exit 1; \ + fi; \ + done + rm -f patch-stamp + +patch-stamp-%: $(patchdir)/%.dpatch + if [ -f $@ ]; then \ + echo "$* patches already applied."; exit 1; \ + fi + sh -e $< -patch + echo "$* patches applied." > $@ + +binary: binary-indep binary-arch + +.PHONY: control-file configure build clean binary-indep binary-arch binary install + +# Local Variables: +# mode: makefile +# end: --- python3.1-3.1.1.orig/debian/PVER-doc.prerm.in +++ python3.1-3.1.1/debian/PVER-doc.prerm.in @@ -0,0 +1,17 @@ +#! /bin/sh + +set -e + +info=@INFO@ +if [ -n "$info" ] && [ -x /usr/sbin/install-info ]; then + install-info --quiet --remove /usr/share/info/@PVER@-lib.info + install-info --quiet --remove /usr/share/info/@PVER@-ref.info + install-info --quiet --remove /usr/share/info/@PVER@-api.info + install-info --quiet --remove /usr/share/info/@PVER@-ext.info + install-info --quiet --remove /usr/share/info/@PVER@-tut.info + install-info --quiet --remove /usr/share/info/@PVER@-dist.info +fi + +#DEBHELPER# + +exit 0 --- python3.1-3.1.1.orig/debian/libPVER.symbols.i386.in +++ python3.1-3.1.1/debian/libPVER.symbols.i386.in @@ -0,0 +1,6 @@ +libpython@VER@.so.1.0 libpython@VER@ #MINVER# +#include "libpython.symbols" + PyModule_Create2@Base @VER@ + _Py_force_double@Base @VER@ + _Py_get_387controlword@Base @VER@ + _Py_set_387controlword@Base @VER@ --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-doc.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-doc.in @@ -0,0 +1,19 @@ +Document: @PVER@-doc +Title: Documenting Python (v@VER@) +Author: Fred L. Drake, Jr. +Abstract: The Python language has a substantial body of documentation, much + of it contributed by various authors. The markup used for the Python + documentation is based on LATEX and requires a significant set of + macros written specifically for documenting Python. This document + describes the macros introduced to support Python documentation and + how they should be used to support a wide range of output formats. + . + This document describes the document classes and special markup used + in the Python documentation. Authors may use this guide, in + conjunction with the template files provided with the distribution, + to create or maintain whole documents or sections. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/documenting/index.html +Files: /usr/share/doc/@PVER@/html/documenting/*.html --- python3.1-3.1.1.orig/debian/changelog.shared +++ python3.1-3.1.1/debian/changelog.shared @@ -0,0 +1,3 @@ + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 5%. --- python3.1-3.1.1.orig/debian/PVER.prerm.in +++ python3.1-3.1.1/debian/PVER.prerm.in @@ -0,0 +1,23 @@ +#! /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 + +#DEBHELPER# --- python3.1-3.1.1.orig/debian/control.in +++ python3.1-3.1.1/debian/control.in @@ -0,0 +1,112 @@ +Source: @PVER@ +Section: python +Priority: optional +Maintainer: Matthias Klose +Build-Depends: debhelper (>= 5.0.51~), autoconf, libreadline6-dev, libncursesw5-dev (>= 5.3), zlib1g-dev, libdb-dev, tk8.5-dev, blt-dev (>= 2.4z), libssl-dev, sharutils, libbz2-dev, libbluetooth-dev [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], locales [!sparc], libsqlite3-dev, libffi-dev (>= 3.0.5), mime-support, libgpm2 [!hurd-i386 !kfreebsd-i386 !kfreebsd-amd64], netbase, lsb-release, bzip2, gcc-4.4 (>= 4.4.1) +Build-Depends-Indep: python-sphinx +Build-Conflicts: libgdbm-dev +XS-Python-Version: @VER@ +Standards-Version: 3.8.2 +Vcs-Browser: https://code.launchpad.net/~doko/python/pkg@VER@ +Vcs-Bzr: http://bazaar.launchpad.net/~doko/python/pkg@VER@ + +Package: @PVER@ +Architecture: any +Priority: @PRIO@ +Depends: @PVER@-minimal (= ${binary:Version}), mime-support, ${shlibs:Depends}, ${misc:Depends} +Suggests: @PVER@-doc, @PVER@-profiler, binutils +Provides: python@VER@-cjkcodecs, python@VER@-ctypes, python@VER@-elementtree, python@VER@-celementtree, python@VER@-wsgiref, @PVER@-gdbm +XB-Python-Version: @VER@ +Description: An interactive high-level object-oriented language (version @VER@) + Version @VER@ of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + +Package: @PVER@-minimal +Architecture: any +Priority: @MINPRIO@ +Depends: ${shlibs:Depends}, ${misc:Depends} +Recommends: @PVER@ +Suggests: binfmt-support +Replaces: @PVER@ (<< 3.1.1-0ubuntu4) +Conflicts: binfmt-support (<< 1.1.2) +XB-Python-Runtime: @PVER@ +XB-Python-Version: @VER@ +Description: A minimal subset of the Python language (version @VER@) + This package contains the interpreter and some essential modules. It can + be used in the boot process for some basic tasks. + See /usr/share/doc/@PVER@-minimal/README.Debian for a list of the modules + contained in this package. + +Package: lib@PVER@ +Architecture: any +Section: libs +Priority: @PRIO@ +Depends: @PVER@ (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 3.0~rc1) +Description: Shared Python runtime library (version @VER@) + Version @VER@ of the high-level, interactive object oriented language, + includes an extensive class library with lots of goodies for + network programming, system administration, sounds and graphics. + . + This package contains the shared runtime library, normally not needed + for programs using the statically linked interpreter. + +Package: @PVER@-examples +Architecture: all +Depends: @PVER@ (>= ${source:Version}), ${misc:Depends} +Description: Examples for the Python language (v@VER@) + Examples, Demos and Tools for Python (v@VER@). These are files included in + the upstream Python distribution (v@VER@). + +Package: @PVER@-dev +Architecture: any +Depends: @PVER@ (= ${binary:Version}), lib@PVER@ (= ${binary:Version}), ${shlibs:Depends}, ${misc:Depends} +Replaces: @PVER@ (<< 3.1~rc2-1) +Recommends: libc6-dev | libc-dev +Description: Header files and a static library for Python (v@VER@) + Header files, a static library and development tools for building + Python (v@VER@) modules, extending the Python interpreter or embedding + Python (v@VER@) in applications. + . + Maintainers of Python packages should read README.maintainers. + +Package: idle-@PVER@ +Architecture: all +Depends: @PVER@, python3-tk, @PVER@-tk, ${misc:Depends} +Enhances: @PVER@ +XB-Python-Version: @VER@ +Description: An 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: python3-gdbm-dbg, python3-tk-dbg +Description: Debug Build of the Python Interpreter (version @VER@) + Python interpreter configured with --pydebug. Dynamically loaded modules are + searched in /usr/lib/@PVER@/lib-dynload/debug first. --- python3.1-3.1.1.orig/debian/PVER-examples.overrides.in +++ python3.1-3.1.1/debian/PVER-examples.overrides.in @@ -0,0 +1,2 @@ +# don't care about permissions of the example files +@PVER@-examples binary: executable-not-elf-or-script --- python3.1-3.1.1.orig/debian/libpython.symbols.in.saved +++ python3.1-3.1.1/debian/libpython.symbols.in.saved @@ -0,0 +1,1384 @@ + 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@ + PyBool_FromLong@Base @VER@ + PyBool_Type@Base @VER@ + PyBuffer_FillContiguousStrides@Base @VER@ + PyBuffer_FillInfo@Base @VER@ + PyBuffer_FromContiguous@Base @VER@ + PyBuffer_GetPointer@Base @VER@ + PyBuffer_IsContiguous@Base @VER@ + PyBuffer_Release@Base @VER@ + PyBuffer_ToContiguous@Base @VER@ + PyBufferedIOBase_Type@Base @VER@ + PyBufferedRWPair_Type@Base @VER@ + PyBufferedRandom_Type@Base @VER@ + PyBufferedReader_Type@Base @VER@ + PyBufferedWriter_Type@Base @VER@ + PyByteArrayIter_Type@Base @VER@ + PyByteArray_AsString@Base @VER@ + PyByteArray_Concat@Base @VER@ + PyByteArray_Fini@Base @VER@ + PyByteArray_FromObject@Base @VER@ + PyByteArray_FromStringAndSize@Base @VER@ + PyByteArray_Init@Base @VER@ + PyByteArray_Resize@Base @VER@ + PyByteArray_Size@Base @VER@ + PyByteArray_Type@Base @VER@ + PyBytesIO_Type@Base @VER@ + PyBytesIter_Type@Base @VER@ + PyBytes_AsString@Base @VER@ + PyBytes_AsStringAndSize@Base @VER@ + PyBytes_Concat@Base @VER@ + PyBytes_ConcatAndDel@Base @VER@ + PyBytes_DecodeEscape@Base @VER@ + PyBytes_Fini@Base @VER@ + PyBytes_FromFormat@Base @VER@ + PyBytes_FromFormatV@Base @VER@ + PyBytes_FromObject@Base @VER@ + PyBytes_FromString@Base @VER@ + PyBytes_FromStringAndSize@Base @VER@ + PyBytes_Repr@Base @VER@ + PyBytes_Size@Base @VER@ + PyBytes_Type@Base @VER@ + PyCArg_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@ + PyCell_Get@Base @VER@ + PyCell_New@Base @VER@ + PyCell_Set@Base @VER@ + PyCell_Type@Base @VER@ + PyClassMethodDescr_Type@Base @VER@ + PyClassMethod_New@Base @VER@ + PyClassMethod_Type@Base @VER@ + PyCode_Addr2Line@Base @VER@ + PyCode_CheckLineNumber@Base @VER@ + PyCode_New@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_KnownEncoding@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_GetItemProxy@Base @VER@ + PyDict_GetItemString@Base @VER@ + PyDict_GetItemWithError@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_SetItemProxy@Base @VER@ + PyDict_SetItemString@Base @VER@ + PyDict_Size@Base @VER@ + PyDict_Type@Base @VER@ + PyDict_Update@Base @VER@ + PyDict_Values@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_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_CallObject@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_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_ArgError@Base @VER@ + PyExc_ArithmeticError@Base @VER@ + PyExc_AssertionError@Base @VER@ + PyExc_AttributeError@Base @VER@ + PyExc_BaseException@Base @VER@ + PyExc_BlockingIOError@Base @VER@ + PyExc_BufferError@Base @VER@ + PyExc_BytesWarning@Base @VER@ + PyExc_DeprecationWarning@Base @VER@ + PyExc_EOFError@Base @VER@ + PyExc_EnvironmentError@Base @VER@ + PyExc_Exception@Base @VER@ + PyExc_FloatingPointError@Base @VER@ + PyExc_FutureWarning@Base @VER@ + PyExc_GeneratorExit@Base @VER@ + PyExc_IOError@Base @VER@ + PyExc_ImportError@Base @VER@ + PyExc_ImportWarning@Base @VER@ + PyExc_IndentationError@Base @VER@ + PyExc_IndexError@Base @VER@ + PyExc_KeyError@Base @VER@ + PyExc_KeyboardInterrupt@Base @VER@ + PyExc_LookupError@Base @VER@ + PyExc_MemoryError@Base @VER@ + PyExc_MemoryErrorInst@Base @VER@ + PyExc_NameError@Base @VER@ + PyExc_NotImplementedError@Base @VER@ + PyExc_OSError@Base @VER@ + PyExc_OverflowError@Base @VER@ + PyExc_PendingDeprecationWarning@Base @VER@ + PyExc_RecursionErrorInst@Base @VER@ + PyExc_ReferenceError@Base @VER@ + PyExc_RuntimeError@Base @VER@ + PyExc_RuntimeWarning@Base @VER@ + PyExc_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@ + PyException_GetCause@Base @VER@ + PyException_GetContext@Base @VER@ + PyException_GetTraceback@Base @VER@ + PyException_SetCause@Base @VER@ + PyException_SetContext@Base @VER@ + PyException_SetTraceback@Base @VER@ + PyFPE_dummy@Base @VER@ + PyFileIO_Type@Base @VER@ + PyFile_FromFd@Base @VER@ + PyFile_GetLine@Base @VER@ + PyFile_NewStdPrinter@Base @VER@ + PyFile_WriteObject@Base @VER@ + PyFile_WriteString@Base @VER@ + PyFilter_Type@Base @VER@ + PyFloat_AsDouble@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_LocalsToFast@Base @VER@ + PyFrame_New@Base @VER@ + PyFrame_Type@Base @VER@ + PyFrozenSet_New@Base @VER@ + PyFrozenSet_Type@Base @VER@ + PyFunction_GetAnnotations@Base @VER@ + PyFunction_GetClosure@Base @VER@ + PyFunction_GetCode@Base @VER@ + PyFunction_GetDefaults@Base @VER@ + PyFunction_GetGlobals@Base @VER@ + PyFunction_GetKwDefaults@Base @VER@ + PyFunction_GetModule@Base @VER@ + PyFunction_New@Base @VER@ + PyFunction_SetAnnotations@Base @VER@ + PyFunction_SetClosure@Base @VER@ + PyFunction_SetDefaults@Base @VER@ + PyFunction_SetKwDefaults@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@ + PyIOBase_Type@Base @VER@ + PyImport_AddModule@Base @VER@ + PyImport_AppendInittab@Base @VER@ + PyImport_Cleanup@Base @VER@ + PyImport_ExecCodeModule@Base @VER@ + PyImport_ExecCodeModuleEx@Base @VER@ + PyImport_ExtendInittab@Base @VER@ + PyImport_FrozenModules@Base @VER@ + PyImport_GetImporter@Base @VER@ + PyImport_GetMagicNumber@Base @VER@ + PyImport_GetModuleDict@Base @VER@ + PyImport_Import@Base @VER@ + PyImport_ImportFrozenModule@Base @VER@ + PyImport_ImportModule@Base @VER@ + PyImport_ImportModuleLevel@Base @VER@ + PyImport_ImportModuleNoBlock@Base @VER@ + PyImport_Inittab@Base @VER@ + PyImport_ReloadModule@Base @VER@ + PyIncrementalNewlineDecoder_Type@Base @VER@ + PyInstanceMethod_Function@Base @VER@ + PyInstanceMethod_New@Base @VER@ + PyInstanceMethod_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@ + PyLongRangeIter_Type@Base @VER@ + PyLong_AsDouble@Base @VER@ + PyLong_AsLong@Base @VER@ + PyLong_AsLongAndOverflow@Base @VER@ + PyLong_AsLongLong@Base @VER@ + PyLong_AsSize_t@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_Fini@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@ + PyMap_Type@Base @VER@ + PyMapping_Check@Base @VER@ + PyMapping_GetItemString@Base @VER@ + PyMapping_HasKey@Base @VER@ + PyMapping_HasKeyString@Base @VER@ + PyMapping_Items@Base @VER@ + PyMapping_Keys@Base @VER@ + PyMapping_Length@Base @VER@ + PyMapping_SetItemString@Base @VER@ + PyMapping_Size@Base @VER@ + PyMapping_Values@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_GetOne@Base @VER@ + PyMember_SetOne@Base @VER@ + PyMemoryView_FromBuffer@Base @VER@ + PyMemoryView_FromObject@Base @VER@ + PyMemoryView_GetContiguous@Base @VER@ + PyMemoryView_Type@Base @VER@ + PyMethodDescr_Type@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_Create2@Base @VER@ + PyModule_GetDef@Base @VER@ + PyModule_GetDict@Base @VER@ + PyModule_GetFilename@Base @VER@ + PyModule_GetName@Base @VER@ + PyModule_GetState@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_AsOff_t@Base @VER@ + PyNumber_AsSsize_t@Base @VER@ + PyNumber_Check@Base @VER@ + PyNumber_Divmod@Base @VER@ + PyNumber_Float@Base @VER@ + PyNumber_FloorDivide@Base @VER@ + PyNumber_InPlaceAdd@Base @VER@ + PyNumber_InPlaceAnd@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_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_getsig@Base @VER@ + PyOS_mystricmp@Base @VER@ + PyOS_mystrnicmp@Base @VER@ + PyOS_setsig@Base @VER@ + PyOS_snprintf@Base @VER@ + PyOS_strtol@Base @VER@ + PyOS_strtoul@Base @VER@ + PyOS_vsnprintf@Base @VER@ + PyObject_ASCII@Base @VER@ + PyObject_AsCharBuffer@Base @VER@ + PyObject_AsFileDescriptor@Base @VER@ + PyObject_AsReadBuffer@Base @VER@ + PyObject_AsWriteBuffer@Base @VER@ + PyObject_Bytes@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_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_stgdict@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@ + PyRangeIter_Type@Base @VER@ + PyRange_Type@Base @VER@ + PyRawIOBase_Type@Base @VER@ + PyReversed_Type@Base @VER@ + PyRun_AnyFile@Base @VER@ + PyRun_AnyFileEx@Base @VER@ + PyRun_AnyFileExFlags@Base @VER@ + PyRun_AnyFileFlags@Base @VER@ + PyRun_File@Base @VER@ + PyRun_FileEx@Base @VER@ + PyRun_FileExFlags@Base @VER@ + PyRun_FileFlags@Base @VER@ + PyRun_InteractiveLoop@Base @VER@ + PyRun_InteractiveLoopFlags@Base @VER@ + PyRun_InteractiveOne@Base @VER@ + PyRun_InteractiveOneFlags@Base @VER@ + PyRun_SimpleFile@Base @VER@ + PyRun_SimpleFileEx@Base @VER@ + PyRun_SimpleFileExFlags@Base @VER@ + PyRun_SimpleString@Base @VER@ + PyRun_SimpleStringFlags@Base @VER@ + PyRun_String@Base @VER@ + PyRun_StringFlags@Base @VER@ + PySTEntry_Type@Base @VER@ + PyST_GetScope@Base @VER@ + PySeqIter_New@Base @VER@ + PySeqIter_Type@Base @VER@ + PySequence_Check@Base @VER@ + PySequence_Concat@Base @VER@ + PySequence_Contains@Base @VER@ + PySequence_Count@Base @VER@ + PySequence_DelItem@Base @VER@ + PySequence_DelSlice@Base @VER@ + PySequence_Fast@Base @VER@ + PySequence_GetItem@Base @VER@ + PySequence_GetSlice@Base @VER@ + PySequence_In@Base @VER@ + PySequence_InPlaceConcat@Base @VER@ + PySequence_InPlaceRepeat@Base @VER@ + PySequence_Index@Base @VER@ + PySequence_Length@Base @VER@ + PySequence_List@Base @VER@ + PySequence_Repeat@Base @VER@ + PySequence_SetItem@Base @VER@ + PySequence_SetSlice@Base @VER@ + PySequence_Size@Base @VER@ + PySequence_Tuple@Base @VER@ + PySetIter_Type@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@ + PySortWrapper_Type@Base @VER@ + PyState_FindModule@Base @VER@ + PyStaticMethod_New@Base @VER@ + PyStaticMethod_Type@Base @VER@ + PyStdPrinter_Type@Base @VER@ + PyStringIO_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_GetObject@Base @VER@ + PySys_HasWarnOptions@Base @VER@ + PySys_ResetWarnOptions@Base @VER@ + PySys_SetArgv@Base @VER@ + PySys_SetObject@Base @VER@ + PySys_SetPath@Base @VER@ + PySys_WriteStderr@Base @VER@ + PySys_WriteStdout@Base @VER@ + PyTextIOBase_Type@Base @VER@ + PyTextIOWrapper_Type@Base @VER@ + PyThreadState_Clear@Base @VER@ + PyThreadState_Delete@Base @VER@ + PyThreadState_DeleteCurrent@Base @VER@ + PyThreadState_Get@Base @VER@ + PyThreadState_GetDict@Base @VER@ + PyThreadState_New@Base @VER@ + PyThreadState_Next@Base @VER@ + PyThreadState_SetAsyncExc@Base @VER@ + PyThreadState_Swap@Base @VER@ + PyThread_ReInitTLS@Base @VER@ + PyThread__exit_thread@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_FindEncoding@Base @VER@ + PyTokenizer_Free@Base @VER@ + PyTokenizer_FromFile@Base @VER@ + PyTokenizer_FromString@Base @VER@ + PyTokenizer_FromUTF8@Base @VER@ + PyTokenizer_Get@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@ + PyType_stgdict@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@ + PyUnicodeIter_Type@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@ + PyUnicodeUCS2_Append@Base @VER@ + PyUnicodeUCS2_AppendAndDel@Base @VER@ + PyUnicodeUCS2_AsASCIIString@Base @VER@ + PyUnicodeUCS2_AsCharmapString@Base @VER@ + PyUnicodeUCS2_AsDecodedObject@Base @VER@ + PyUnicodeUCS2_AsDecodedUnicode@Base @VER@ + PyUnicodeUCS2_AsEncodedObject@Base @VER@ + PyUnicodeUCS2_AsEncodedString@Base @VER@ + PyUnicodeUCS2_AsEncodedUnicode@Base @VER@ + PyUnicodeUCS2_AsLatin1String@Base @VER@ + PyUnicodeUCS2_AsRawUnicodeEscapeString@Base @VER@ + PyUnicodeUCS2_AsUTF16String@Base @VER@ + PyUnicodeUCS2_AsUTF32String@Base @VER@ + PyUnicodeUCS2_AsUTF8String@Base @VER@ + PyUnicodeUCS2_AsUnicode@Base @VER@ + PyUnicodeUCS2_AsUnicodeEscapeString@Base @VER@ + PyUnicodeUCS2_AsWideChar@Base @VER@ + PyUnicodeUCS2_ClearFreelist@Base @VER@ + PyUnicodeUCS2_Compare@Base @VER@ + PyUnicodeUCS2_Concat@Base @VER@ + PyUnicodeUCS2_Contains@Base @VER@ + PyUnicodeUCS2_Count@Base @VER@ + PyUnicodeUCS2_Decode@Base @VER@ + PyUnicodeUCS2_DecodeASCII@Base @VER@ + PyUnicodeUCS2_DecodeCharmap@Base @VER@ + PyUnicodeUCS2_DecodeFSDefault@Base @VER@ + PyUnicodeUCS2_DecodeFSDefaultAndSize@Base @VER@ + PyUnicodeUCS2_DecodeLatin1@Base @VER@ + PyUnicodeUCS2_DecodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS2_DecodeUTF16@Base @VER@ + PyUnicodeUCS2_DecodeUTF16Stateful@Base @VER@ + PyUnicodeUCS2_DecodeUTF32@Base @VER@ + PyUnicodeUCS2_DecodeUTF32Stateful@Base @VER@ + PyUnicodeUCS2_DecodeUTF8@Base @VER@ + PyUnicodeUCS2_DecodeUTF8Stateful@Base @VER@ + PyUnicodeUCS2_DecodeUnicodeEscape@Base @VER@ + PyUnicodeUCS2_Encode@Base @VER@ + PyUnicodeUCS2_EncodeASCII@Base @VER@ + PyUnicodeUCS2_EncodeCharmap@Base @VER@ + PyUnicodeUCS2_EncodeDecimal@Base @VER@ + PyUnicodeUCS2_EncodeLatin1@Base @VER@ + PyUnicodeUCS2_EncodeRawUnicodeEscape@Base @VER@ + PyUnicodeUCS2_EncodeUTF16@Base @VER@ + PyUnicodeUCS2_EncodeUTF32@Base @VER@ + PyUnicodeUCS2_EncodeUTF8@Base @VER@ + PyUnicodeUCS2_EncodeUnicodeEscape@Base @VER@ + PyUnicodeUCS2_Find@Base @VER@ + PyUnicodeUCS2_Format@Base @VER@ + PyUnicodeUCS2_FromEncodedObject@Base @VER@ + PyUnicodeUCS2_FromFormat@Base @VER@ + PyUnicodeUCS2_FromFormatV@Base @VER@ + PyUnicodeUCS2_FromObject@Base @VER@ + PyUnicodeUCS2_FromOrdinal@Base @VER@ + PyUnicodeUCS2_FromString@Base @VER@ + PyUnicodeUCS2_FromStringAndSize@Base @VER@ + PyUnicodeUCS2_FromUnicode@Base @VER@ + PyUnicodeUCS2_FromWideChar@Base @VER@ + PyUnicodeUCS2_GetDefaultEncoding@Base @VER@ + PyUnicodeUCS2_GetMax@Base @VER@ + PyUnicodeUCS2_GetSize@Base @VER@ + PyUnicodeUCS2_IsIdentifier@Base @VER@ + PyUnicodeUCS2_Join@Base @VER@ + PyUnicodeUCS2_Partition@Base @VER@ + PyUnicodeUCS2_RPartition@Base @VER@ + PyUnicodeUCS2_RSplit@Base @VER@ + PyUnicodeUCS2_Replace@Base @VER@ + PyUnicodeUCS2_Resize@Base @VER@ + PyUnicodeUCS2_RichCompare@Base @VER@ + PyUnicodeUCS2_SetDefaultEncoding@Base @VER@ + PyUnicodeUCS2_Split@Base @VER@ + PyUnicodeUCS2_Splitlines@Base @VER@ + PyUnicodeUCS2_Tailmatch@Base @VER@ + PyUnicodeUCS2_Translate@Base @VER@ + PyUnicodeUCS2_TranslateCharmap@Base @VER@ + PyUnicode_BuildEncodingMap@Base @VER@ + PyUnicode_CompareWithASCIIString@Base @VER@ + PyUnicode_DecodeUTF7@Base @VER@ + PyUnicode_DecodeUTF7Stateful@Base @VER@ + PyUnicode_EncodeUTF7@Base @VER@ + PyUnicode_InternFromString@Base @VER@ + PyUnicode_InternImmortal@Base @VER@ + PyUnicode_InternInPlace@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@ + PyZip_Type@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_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_HasFileSystemDefaultEncoding@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_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_UNICODE_strchr@Base @VER@ + Py_UNICODE_strcmp@Base @VER@ + Py_UNICODE_strcpy@Base @VER@ + Py_UNICODE_strlen@Base @VER@ + Py_UNICODE_strncpy@Base @VER@ + Py_UnbufferedStdioFlag@Base @VER@ + Py_UniversalNewlineFgets@Base @VER@ + Py_UseClassExceptionsFlag@Base @VER@ + Py_VaBuildValue@Base @VER@ + Py_VerboseFlag@Base @VER@ + Py_meta_grammar@Base @VER@ + Py_pgen@Base @VER@ + SimpleType_Type@Base @VER@ + StgDict_Type@Base @VER@ + StgDict_clone@Base @VER@ + StructType_Type@Base @VER@ + StructUnionType_update_stgdict@Base @VER@ + _AddTraceback@Base @VER@ + _CallProc@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@ + _PyBytes_FormatLong@Base @VER@ + _PyBytes_InsertThousandsGrouping@Base @VER@ + _PyBytes_Join@Base @VER@ + _PyBytes_Resize@Base @VER@ + _PyCodec_Lookup@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@ + _PyFileIO_closed@Base @VER@ + _PyFloat_FormatAdvanced@Base @VER@ + _PyFloat_Init@Base @VER@ + _PyFloat_Pack4@Base @VER@ + _PyFloat_Pack8@Base @VER@ + _PyFloat_Repr@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@ + _PyIOBase_checkClosed@Base @VER@ + _PyIOBase_checkReadable@Base @VER@ + _PyIOBase_checkSeekable@Base @VER@ + _PyIOBase_checkWritable@Base @VER@ + _PyIOBase_finalize@Base @VER@ + _PyIO_Module@Base @VER@ + _PyIO_empty_bytes@Base @VER@ + _PyIO_empty_str@Base @VER@ + _PyIO_find_line_ending@Base @VER@ + _PyIO_str_close@Base @VER@ + _PyIO_str_closed@Base @VER@ + _PyIO_str_decode@Base @VER@ + _PyIO_str_encode@Base @VER@ + _PyIO_str_fileno@Base @VER@ + _PyIO_str_flush@Base @VER@ + _PyIO_str_getstate@Base @VER@ + _PyIO_str_isatty@Base @VER@ + _PyIO_str_newlines@Base @VER@ + _PyIO_str_nl@Base @VER@ + _PyIO_str_read1@Base @VER@ + _PyIO_str_read@Base @VER@ + _PyIO_str_readable@Base @VER@ + _PyIO_str_readinto@Base @VER@ + _PyIO_str_readline@Base @VER@ + _PyIO_str_reset@Base @VER@ + _PyIO_str_seek@Base @VER@ + _PyIO_str_seekable@Base @VER@ + _PyIO_str_tell@Base @VER@ + _PyIO_str_truncate@Base @VER@ + _PyIO_str_writable@Base @VER@ + _PyIO_str_write@Base @VER@ + _PyImportHooks_Init@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_ReInitLock@Base @VER@ + _PyIncrementalNewlineDecoder_decode@Base @VER@ + _PyList_Extend@Base @VER@ + _PyLong_AsByteArray@Base @VER@ + _PyLong_AsScaledDouble@Base @VER@ + _PyLong_Copy@Base @VER@ + _PyLong_DigitValue@Base @VER@ + _PyLong_Format@Base @VER@ + _PyLong_FormatAdvanced@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_optarg@Base @VER@ + _PyOS_opterr@Base @VER@ + _PyOS_optind@Base @VER@ + _PyObject_CallFunction_SizeT@Base @VER@ + _PyObject_CallMethod_SizeT@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_GetDictPtr@Base @VER@ + _PyObject_LengthHint@Base @VER@ + _PyObject_New@Base @VER@ + _PyObject_NewVar@Base @VER@ + _PyObject_NextNotImplemented@Base @VER@ + _PyObject_RealIsInstance@Base @VER@ + _PyObject_RealIsSubclass@Base @VER@ + _PyParser_Grammar@Base @VER@ + _PyParser_TokenNames@Base @VER@ + _PySequence_IterSearch@Base @VER@ + _PySet_NextEntry@Base @VER@ + _PySet_Update@Base @VER@ + _PySlice_FromIndices@Base @VER@ + _PyState_AddModule@Base @VER@ + _PySys_Init@Base @VER@ + _PyThreadState_Current@Base @VER@ + _PyThreadState_GetFrame@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@ + _PyUnicodeUCS2_AsDefaultEncodedString@Base @VER@ + _PyUnicodeUCS2_Fini@Base @VER@ + _PyUnicodeUCS2_Init@Base @VER@ + _PyUnicodeUCS2_IsAlpha@Base @VER@ + _PyUnicodeUCS2_IsDecimalDigit@Base @VER@ + _PyUnicodeUCS2_IsDigit@Base @VER@ + _PyUnicodeUCS2_IsLinebreak@Base @VER@ + _PyUnicodeUCS2_IsLowercase@Base @VER@ + _PyUnicodeUCS2_IsNumeric@Base @VER@ + _PyUnicodeUCS2_IsPrintable@Base @VER@ + _PyUnicodeUCS2_IsTitlecase@Base @VER@ + _PyUnicodeUCS2_IsUppercase@Base @VER@ + _PyUnicodeUCS2_IsWhitespace@Base @VER@ + _PyUnicodeUCS2_IsXidContinue@Base @VER@ + _PyUnicodeUCS2_IsXidStart@Base @VER@ + _PyUnicodeUCS2_ToDecimalDigit@Base @VER@ + _PyUnicodeUCS2_ToDigit@Base @VER@ + _PyUnicodeUCS2_ToLowercase@Base @VER@ + _PyUnicodeUCS2_ToNumeric@Base @VER@ + _PyUnicodeUCS2_ToTitlecase@Base @VER@ + _PyUnicodeUCS2_ToUppercase@Base @VER@ + _PyUnicode_AsString@Base @VER@ + _PyUnicode_AsStringAndSize@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_InsertThousandsGrouping@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_BreakPoint@Base @VER@ + _Py_BuildValue_SizeT@Base @VER@ + _Py_Bytes@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_Expr@Base @VER@ + _Py_Expression@Base @VER@ + _Py_ExtSlice@Base @VER@ + _Py_FalseStruct@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_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_Nonlocal@Base @VER@ + _Py_NotImplementedStruct@Base @VER@ + _Py_Num@Base @VER@ + _Py_PackageContext@Base @VER@ + _Py_Pass@Base @VER@ + _Py_PyAtExit@Base @VER@ + _Py_Raise@Base @VER@ + _Py_ReadyTypes@Base @VER@ + _Py_ReleaseInternedUnicodeStrings@Base @VER@ + _Py_Return@Base @VER@ + _Py_Set@Base @VER@ + _Py_SetComp@Base @VER@ + _Py_SetFileSystemEncoding@Base @VER@ + _Py_Slice@Base @VER@ + _Py_Starred@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_abstract_hack@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_arg@Base @VER@ + _Py_arguments@Base @VER@ + _Py_ascii_whitespace@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_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@ + _Py_findlabel@Base @VER@ + _Py_force_double@Base @VER@ + _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@ + _Py_lower__doc__@Base @VER@ + _Py_mergebitset@Base @VER@ + _Py_meta_grammar@Base @VER@ + _Py_newbitset@Base @VER@ + _Py_newgrammar@Base @VER@ + _Py_pgen@Base @VER@ + _Py_samebitset@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@ + _Py_wreadlink@Base @VER@ + + _add_one_to_index_C@Base @VER@ + _add_one_to_index_F@Base @VER@ + asdl_int_seq_new@Base @VER@ + asdl_seq_new@Base @VER@ + +# PyInit__ast@Base @VER@ +# PyInit__bisect@Base @VER@ +# PyInit__codecs@Base @VER@ +# PyInit__collections@Base @VER@ +# PyInit__ctypes@Base @VER@ +# PyInit__elementtree@Base @VER@ +# PyInit__functools@Base @VER@ +# PyInit__heapq@Base @VER@ +# PyInit__io@Base @VER@ +# PyInit__locale@Base @VER@ +# PyInit__pickle@Base @VER@ +# PyInit__random@Base @VER@ +# PyInit__socket@Base @VER@ +# PyInit__sre@Base @VER@ +# PyInit__struct@Base @VER@ +# PyInit__symtable@Base @VER@ +# PyInit__thread@Base @VER@ +# PyInit__weakref@Base @VER@ +# PyInit_array@Base @VER@ +# PyInit_binascii@Base @VER@ +# PyInit_datetime@Base @VER@ +# PyInit_errno@Base @VER@ +# PyInit_fcntl@Base @VER@ +# PyInit_gc@Base @VER@ +# PyInit_grp@Base @VER@ +# PyInit_imp@Base @VER@ +# PyInit_itertools@Base @VER@ +# PyInit_math@Base @VER@ +# PyInit_operator@Base @VER@ +# PyInit_posix@Base @VER@ +# PyInit_pwd@Base @VER@ +# PyInit_pyexpat@Base @VER@ +# PyInit_select@Base @VER@ +# PyInit_signal@Base @VER@ +# PyInit_spwd@Base @VER@ +# PyInit_syslog@Base @VER@ +# PyInit_time@Base @VER@ +# PyInit_unicodedata@Base @VER@ +# PyInit_xxsubtype@Base @VER@ +# PyInit_zipimport@Base @VER@ +# PyInit_zlib@Base @VER@ + +# pyexport either built as builtin or extension + +# PyExpat_XML_DefaultCurrent@Base @VER@ +# PyExpat_XML_ErrorString@Base @VER@ +# PyExpat_XML_ExpatVersion@Base @VER@ +# PyExpat_XML_ExpatVersionInfo@Base @VER@ +# PyExpat_XML_ExternalEntityParserCreate@Base @VER@ +# PyExpat_XML_FreeContentModel@Base @VER@ +# PyExpat_XML_GetBase@Base @VER@ +# PyExpat_XML_GetBuffer@Base @VER@ +# PyExpat_XML_GetCurrentByteCount@Base @VER@ +# PyExpat_XML_GetCurrentByteIndex@Base @VER@ +# PyExpat_XML_GetCurrentColumnNumber@Base @VER@ +# PyExpat_XML_GetCurrentLineNumber@Base @VER@ +# PyExpat_XML_GetErrorCode@Base @VER@ +# PyExpat_XML_GetFeatureList@Base @VER@ +# PyExpat_XML_GetIdAttributeIndex@Base @VER@ +# PyExpat_XML_GetInputContext@Base @VER@ +# PyExpat_XML_GetParsingStatus@Base @VER@ +# PyExpat_XML_GetSpecifiedAttributeCount@Base @VER@ +# PyExpat_XML_MemFree@Base @VER@ +# PyExpat_XML_MemMalloc@Base @VER@ +# PyExpat_XML_MemRealloc@Base @VER@ +# PyExpat_XML_Parse@Base @VER@ +# PyExpat_XML_ParseBuffer@Base @VER@ +# PyExpat_XML_ParserCreate@Base @VER@ +# PyExpat_XML_ParserCreateNS@Base @VER@ +# PyExpat_XML_ParserCreate_MM@Base @VER@ +# PyExpat_XML_ParserFree@Base @VER@ +# PyExpat_XML_ParserReset@Base @VER@ +# PyExpat_XML_ResumeParser@Base @VER@ +# PyExpat_XML_SetAttlistDeclHandler@Base @VER@ +# PyExpat_XML_SetBase@Base @VER@ +# PyExpat_XML_SetCdataSectionHandler@Base @VER@ +# PyExpat_XML_SetCharacterDataHandler@Base @VER@ +# PyExpat_XML_SetCommentHandler@Base @VER@ +# PyExpat_XML_SetDefaultHandler@Base @VER@ +# PyExpat_XML_SetDefaultHandlerExpand@Base @VER@ +# PyExpat_XML_SetDoctypeDeclHandler@Base @VER@ +# PyExpat_XML_SetElementDeclHandler@Base @VER@ +# PyExpat_XML_SetElementHandler@Base @VER@ +# PyExpat_XML_SetEncoding@Base @VER@ +# PyExpat_XML_SetEndCdataSectionHandler@Base @VER@ +# PyExpat_XML_SetEndDoctypeDeclHandler@Base @VER@ +# PyExpat_XML_SetEndElementHandler@Base @VER@ +# PyExpat_XML_SetEndNamespaceDeclHandler@Base @VER@ +# PyExpat_XML_SetEntityDeclHandler@Base @VER@ +# PyExpat_XML_SetExternalEntityRefHandler@Base @VER@ +# PyExpat_XML_SetExternalEntityRefHandlerArg@Base @VER@ +# PyExpat_XML_SetNamespaceDeclHandler@Base @VER@ +# PyExpat_XML_SetNotStandaloneHandler@Base @VER@ +# PyExpat_XML_SetNotationDeclHandler@Base @VER@ +# PyExpat_XML_SetParamEntityParsing@Base @VER@ +# PyExpat_XML_SetProcessingInstructionHandler@Base @VER@ +# PyExpat_XML_SetReturnNSTriplet@Base @VER@ +# PyExpat_XML_SetSkippedEntityHandler@Base @VER@ +# PyExpat_XML_SetStartCdataSectionHandler@Base @VER@ +# PyExpat_XML_SetStartDoctypeDeclHandler@Base @VER@ +# PyExpat_XML_SetStartElementHandler@Base @VER@ +# PyExpat_XML_SetStartNamespaceDeclHandler@Base @VER@ +# PyExpat_XML_SetUnknownEncodingHandler@Base @VER@ +# PyExpat_XML_SetUnparsedEntityDeclHandler@Base @VER@ +# PyExpat_XML_SetUserData@Base @VER@ +# PyExpat_XML_SetXmlDeclHandler@Base @VER@ +# PyExpat_XML_StopParser@Base @VER@ +# PyExpat_XML_UseForeignDTD@Base @VER@ +# PyExpat_XML_UseParserAsHandlerArg@Base @VER@ +# PyExpat_XmlGetUtf16InternalEncoding@Base @VER@ +# PyExpat_XmlGetUtf16InternalEncodingNS@Base @VER@ +# PyExpat_XmlGetUtf8InternalEncoding@Base @VER@ +# PyExpat_XmlGetUtf8InternalEncodingNS@Base @VER@ +# PyExpat_XmlInitEncoding@Base @VER@ +# PyExpat_XmlInitEncodingNS@Base @VER@ +# PyExpat_XmlInitUnknownEncoding@Base @VER@ +# PyExpat_XmlInitUnknownEncodingNS@Base @VER@ +# PyExpat_XmlParseXmlDecl@Base @VER@ +# PyExpat_XmlParseXmlDeclNS@Base @VER@ +# PyExpat_XmlPrologStateInit@Base @VER@ +# PyExpat_XmlPrologStateInitExternalEntity@Base @VER@ +# PyExpat_XmlSizeOfUnknownEncoding@Base @VER@ +# PyExpat_XmlUtf16Encode@Base @VER@ +# PyExpat_XmlUtf8Encode@Base @VER@ +# template_string@Base @VER@ + +# _ctypes either built as builtin or extension + +# AllocFunctionCallback@Base @VER@ +# ArrayType_Type@Base @VER@ +# Array_Type@Base @VER@ +# CData_AtAddress@Base @VER@ +# CData_FromBaseObj@Base @VER@ +# CData_Type@Base @VER@ +# CData_get@Base @VER@ +# CData_set@Base @VER@ +# CField_FromDesc@Base @VER@ +# CField_Type@Base @VER@ +# CFuncPtrType_Type@Base @VER@ +# CFuncPtr_Type@Base @VER@ +# CThunk_Type@Base @VER@ +# CreateArrayType@Base @VER@ +# Extend_Error_Info@Base @VER@ +# FreeClosure@Base @VER@ +# GetType@Base @VER@ +# IsSimpleSubType@Base @VER@ +# MallocClosure@Base @VER@ +# PointerType_Type@Base @VER@ +# Pointer_Type@Base @VER@ +# _pagesize@Base @VER@ +# _pointer_type_cache@Base @VER@ +# alloc_format_string@Base @VER@ +# conversion_mode_encoding@Base @VER@ +# conversion_mode_errors@Base @VER@ +# ffi_type_double@Base @VER@ +# ffi_type_float@Base @VER@ +# ffi_type_longdouble@Base @VER@ +# ffi_type_pointer@Base @VER@ +# ffi_type_sint16@Base @VER@ +# ffi_type_sint32@Base @VER@ +# ffi_type_sint64@Base @VER@ +# ffi_type_sint8@Base @VER@ +# ffi_type_uint16@Base @VER@ +# ffi_type_uint32@Base @VER@ +# ffi_type_uint64@Base @VER@ +# ffi_type_uint8@Base @VER@ +# ffi_type_void@Base @VER@ +# get_error_object@Base @VER@ +# getentry@Base @VER@ +# init_callbacks_in_module@Base @VER@ +# module_methods@Base @VER@ +# new_CArgObject@Base @VER@ --- python3.1-3.1.1.orig/debian/idle-PVER.postinst.in +++ python3.1-3.1.1/debian/idle-PVER.postinst.in @@ -0,0 +1,30 @@ +#! /bin/sh -e +# +# postinst script for the Debian idle-@PVER@ package. +# Written 1998 by Gregor Hoffleit . +# + +DIRLIST="/usr/lib/python@VER@/idlelib" + +case "$1" in + configure|abort-upgrade|abort-remove|abort-deconfigure) + + for i in $DIRLIST ; do + @PVER@ /usr/lib/@PVER@/compileall.py -q $i + if grep -sq '^byte-compile[^#]*optimize' /etc/python/debian_config + then + @PVER@ -O /usr/lib/@PVER@/compileall.py -q $i + fi + done + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; + +esac + +#DEBHELPER# + +exit 0 --- python3.1-3.1.1.orig/debian/PVER-doc.postinst.in +++ python3.1-3.1.1/debian/PVER-doc.postinst.in @@ -0,0 +1,27 @@ +#! /bin/sh -e + +info=@INFO@ +if [ -n "$info" ] && [ -x /usr/sbin/install-info ]; then + install-info --quiet --section "Python" "Python" \ + --description="Python @VER@ Library Reference" \ + /usr/share/info/@PVER@-lib.info + install-info --quiet --section "Python" "Python" \ + --description="Python @VER@ Reference Manual" \ + /usr/share/info/@PVER@-ref.info + install-info --quiet --section "Python" "Python" \ + --description="Python/C @VER@ API Reference Manual" \ + /usr/share/info/@PVER@-api.info + install-info --quiet --section "Python" "Python" \ + --description="Extending & Embedding Python @VER@" \ + /usr/share/info/@PVER@-ext.info + install-info --quiet --section "Python" "Python" \ + --description="Python @VER@ Tutorial" \ + /usr/share/info/@PVER@-tut.info + install-info --quiet --section "Python" "Python" \ + --description="Distributing Python Modules (@VER@)" \ + /usr/share/info/@PVER@-dist.info +fi + +#DEBHELPER# + +exit 0 --- python3.1-3.1.1.orig/debian/README.maintainers.in +++ python3.1-3.1.1/debian/README.maintainers.in @@ -0,0 +1,88 @@ + +Hints for maintainers of Debian packages of Python extensions +------------------------------------------------------------- + +Most of the content of this README can be found in the Debian Python policy. +See /usr/share/doc/python/python-policy.txt.gz. + +Documentation Tools +------------------- + +If your package ships documentation produced in the Python +documentation format, you can generate it at build-time by +build-depending on @PVER@-dev, and you will find the +templates, tools and scripts in /usr/lib/@PVER@/doc/tools -- +adjust your build scripts accordingly. + + +Makefile.pre.in issues +---------------------- + +Python comes with a `universal Unix Makefile for Python extensions' in +/usr/lib/@PVER@/config/Makefile.pre.in (with Debian, this is included +in the python-dev package), which is used by most Python extensions. + +In general, packages using the Makefile.pre.in approach can be packaged +simply by running dh_make or by using one of debhelper's rules' templates +(see /usr/doc/debhelper/examples/). Makefile.pre.in works fine with e.g. +"make prefix=debian/tmp/usr install". + +One glitch: You may be running into the problem that Makefile.pre.in +doesn't try to create all the directories when they don't exist. Therefore, +you may have to create them manually before "make install". In most cases, +the following should work: + + ... + dh_installdirs /usr/lib/@PVER@ + $(MAKE) prefix=debian/tmp/usr install + ... + + +Byte-compilation +---------------- + +For speed reasons, Python internally compiles source files into a byte-code. +To speed up subsequent imports, it tries to save the byte-code along with +the source with an extension .pyc (resp. pyo). This will fail if the +libraries are installed in a non-writable directory, which may be the +case for /usr/lib/@PVER@/. + +Not that .pyc and .pyo files should not be relocated, since for debugging +purposes the path of the source for is hard-coded into them. + +To precompile files in batches after installation, Python has a script +compileall.py, which compiles all files in a given directory tree. The +Debian version of compileall has been enhanced to support incremental +compilation and to feature a ddir (destination dir) option. ddir is +used to compile files in debian/usr/lib/python/ when they will be +installed into /usr/lib/python/. + + +Currently, there are two ways to use compileall for Debian packages. The +first has a speed penalty, the second has a space penalty in the package. + +1.) Compiling and removing .pyc files in postinst/prerm: + + Use dh_python(1) from the debhelper packages to add commands to byte- + compile on installation and to remove the byte-compiled files on removal. + Your package has to build-depend on: debhelper (>= 4.1.67), python. + + In /usr/share/doc/@PVER@, you'll find sample.postinst and sample.prerm. + If you set the directory where the .py files are installed, these + scripts will install and remove the .pyc and .pyo files for your + package after unpacking resp. before removing the package. + +2.) Compiling the .pyc files `out of place' during installation: + + As of 1.5.1, compileall.py allows you to specify a faked installation + directory using the "-d destdir" option, so that you can precompile + the files in their temporary directory + (e.g. debian/tmp/usr/lib/python2.1/site-packages/PACKAGE). + + + + 11/02/98 + Gregor Hoffleit + + +Last modified: 2007-10-14 --- python3.1-3.1.1.orig/debian/control.stdlib +++ python3.1-3.1.1/debian/control.stdlib @@ -0,0 +1,16 @@ +Package: @PVER@-tk +Architecture: any +Depends: @PVER@ (= ${Source-Version}), ${shlibs:Depends} +Suggests: tix +XB-Python-Version: @VER@ +Description: Tkinter - Writing Tk applications with Python (v@VER@) + A module for writing portable GUI applications with Python (v@VER@) using Tk. + Also known as Tkinter. + +Package: @PVER@-gdbm +Architecture: any +Depends: @PVER@ (= ${Source-Version}), ${shlibs:Depends} +Description: GNU dbm database support for Python (v@VER@) + GNU dbm database module for Python. Install this if you want to + create or read GNU dbm database files with Python. + --- python3.1-3.1.1.orig/debian/depgraph.py +++ python3.1-3.1.1/debian/depgraph.py @@ -0,0 +1,199 @@ +#! /usr/bin/python + +# Copyright 2004 Toby Dickenson +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject +# to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +import sys, getopt, colorsys, imp, md5 + +class pydepgraphdot: + + def main(self,argv): + opts,args = getopt.getopt(argv,'',['mono']) + self.colored = 1 + for o,v in opts: + if o=='--mono': + self.colored = 0 + self.render() + + def fix(self,s): + # Convert a module name to a syntactically correct node name + return s.replace('.','_') + + def render(self): + p,t = self.get_data() + + # normalise our input data + for k,d in p.items(): + for v in d.keys(): + if not p.has_key(v): + p[v] = {} + + f = self.get_output_file() + + f.write('digraph G {\n') + #f.write('concentrate = true;\n') + #f.write('ordering = out;\n') + f.write('ranksep=1.0;\n') + f.write('node [style=filled,fontname=Helvetica,fontsize=10];\n') + allkd = p.items() + allkd.sort() + for k,d in allkd: + tk = t.get(k) + if self.use(k,tk): + allv = d.keys() + allv.sort() + for v in allv: + tv = t.get(v) + if self.use(v,tv) and not self.toocommon(v,tv): + f.write('%s -> %s' % ( self.fix(k),self.fix(v) ) ) + self.write_attributes(f,self.edge_attributes(k,v)) + f.write(';\n') + f.write(self.fix(k)) + self.write_attributes(f,self.node_attributes(k,tk)) + f.write(';\n') + f.write('}\n') + + def write_attributes(self,f,a): + if a: + f.write(' [') + f.write(','.join(a)) + f.write(']') + + def node_attributes(self,k,type): + a = [] + a.append('label="%s"' % self.label(k)) + if self.colored: + a.append('fillcolor="%s"' % self.color(k,type)) + else: + a.append('fillcolor=white') + if self.toocommon(k,type): + a.append('peripheries=2') + return a + + def edge_attributes(self,k,v): + a = [] + weight = self.weight(k,v) + if weight!=1: + a.append('weight=%d' % weight) + length = self.alien(k,v) + if length: + a.append('minlen=%d' % length) + return a + + def get_data(self): + t = eval(sys.stdin.read()) + return t['depgraph'],t['types'] + + def get_output_file(self): + return sys.stdout + + def use(self,s,type): + # Return true if this module is interesting and should be drawn. Return false + # if it should be completely omitted. This is a default policy - please override. + if s=='__main__': + return 0 + #if s in ('os','sys','time','__future__','types','re','string'): + if s in ('sys'): + # nearly all modules use all of these... more or less. They add nothing to + # our diagram. + return 0 + if s.startswith('encodings.'): + return 0 + if self.toocommon(s,type): + # A module where we dont want to draw references _to_. Dot doesnt handle these + # well, so it is probably best to not draw them at all. + return 0 + return 1 + + def toocommon(self,s,type): + # Return true if references to this module are uninteresting. Such references + # do not get drawn. This is a default policy - please override. + # + if s=='__main__': + # references *to* __main__ are never interesting. omitting them means + # that main floats to the top of the page + return 1 + #if type==imp.PKG_DIRECTORY: + # # dont draw references to packages. + # return 1 + return 0 + + def weight(self,a,b): + # Return the weight of the dependency from a to b. Higher weights + # usually have shorter straighter edges. Return 1 if it has normal weight. + # A value of 4 is usually good for ensuring that a related pair of modules + # are drawn next to each other. This is a default policy - please override. + # + if b.split('.')[-1].startswith('_'): + # A module that starts with an underscore. You need a special reason to + # import these (for example random imports _random), so draw them close + # together + return 4 + return 1 + + def alien(self,a,b): + # Return non-zero if references to this module are strange, and should be drawn + # extra-long. the value defines the length, in rank. This is also good for putting some + # vertical space between seperate subsystems. This is a default policy - please override. + # + return 0 + + def label(self,s): + # Convert a module name to a formatted node label. This is a default policy - please override. + # + return '\\.\\n'.join(s.split('.')) + + def color(self,s,type): + # Return the node color for this module name. This is a default policy - please override. + # + # Calculate a color systematically based on the hash of the module name. Modules in the + # same package have the same color. Unpackaged modules are grey + t = self.normalise_module_name_for_hash_coloring(s,type) + return self.color_from_name(t) + + def normalise_module_name_for_hash_coloring(self,s,type): + if type==imp.PKG_DIRECTORY: + return s + else: + i = s.rfind('.') + if i<0: + return '' + else: + return s[:i] + + def color_from_name(self,name): + n = md5.md5(name).digest() + hf = float(ord(n[0])+ord(n[1])*0xff)/0xffff + sf = float(ord(n[2]))/0xff + vf = float(ord(n[3]))/0xff + r,g,b = colorsys.hsv_to_rgb(hf, 0.3+0.6*sf, 0.8+0.2*vf) + return '#%02x%02x%02x' % (r*256,g*256,b*256) + + +def main(): + pydepgraphdot().main(sys.argv[1:]) + +if __name__=='__main__': + main() + + + --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-ref.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-ref.in @@ -0,0 +1,18 @@ +Document: @PVER@-ref +Title: Python Reference Manual (v@VER@) +Author: Guido van Rossum +Abstract: This reference manual describes the syntax and "core semantics" of + the language. It is terse, but attempts to be exact and complete. + The semantics of non-essential built-in object types and of the + built-in functions and modules are described in the *Python + Library Reference*. For an informal introduction to the language, + see the *Python Tutorial*. For C or C++ programmers, two + additional manuals exist: *Extending and Embedding the Python + Interpreter* describes the high-level picture of how to write a + Python extension module, and the *Python/C API Reference Manual* + describes the interfaces available to C/C++ programmers in detail. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/reference/index.html +Files: /usr/share/doc/@PVER@/html/reference/*.html --- python3.1-3.1.1.orig/debian/PVER-doc.doc-base.PVER-ext.in +++ python3.1-3.1.1/debian/PVER-doc.doc-base.PVER-ext.in @@ -0,0 +1,16 @@ +Document: @PVER@-ext +Title: Extending and Embedding the Python Interpreter (v@VER@) +Author: Guido van Rossum +Abstract: This document describes how to write modules in C or C++ to extend + the Python interpreter with new modules. Those modules can define + new functions but also new object types and their methods. The + document also describes how to embed the Python interpreter in + another application, for use as an extension language. Finally, + it shows how to compile and link extension modules so that they + can be loaded dynamically (at run time) into the interpreter, if + the underlying operating system supports this feature. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/@PVER@/html/extending/index.html +Files: /usr/share/doc/@PVER@/html/extending/*.html --- python3.1-3.1.1.orig/debian/changelog +++ python3.1-3.1.1/debian/changelog @@ -0,0 +1,1943 @@ +python3.1 (3.1.1-1ubuntu1) lucid; urgency=low + + * Update to the 3.1 release branch, 20091102. + * distutils install: Don't install into /usr/local/local, if option + --prefix=/usr/local is present. LP: #456917. + * python3.1-doc: Fix searching in local documentation. LP: #456025. + + -- Matthias Klose Mon, 02 Nov 2009 12:38:24 +0100 + +python3.1 (3.1.1-0ubuntu4) karmic; urgency=low + + * Update to the 3.1 release branch, 20091011. + * Remove /usr/local/lib/python3.1 on package removal, if empty. + * Build _hashlib as a builtin. LP: #445530. + * python3.1-doc: Don't compress the sphinx inventory. + * python3.1-doc: Fix jquery.js symlink. LP: #447370. + * Run the benchmark with -C 2 -n 5 -w 4 on all architectures. + * python3.1-dbg: Don't create debug subdirectory in /usr/local. No + separate debug directory needed anymore. + + -- Matthias Klose Sun, 11 Oct 2009 19:59:17 +0200 + +python3.1 (3.1.1-0ubuntu3) karmic; urgency=low + + * Update to the 3.1 release branch, 20090913. + * Fix title of devhelp document. LP: #423551. + + -- Matthias Klose Sun, 13 Sep 2009 23:13:51 +0200 + +python3.1 (3.1.1-0ubuntu2) karmic; urgency=low + + * Fix regeneration of configure script. + + -- Matthias Klose Wed, 19 Aug 2009 13:38:24 +0200 + +python3.1 (3.1.1-0ubuntu1) karmic; urgency=low + + * Python 3.1.1 final release. + + -- Matthias Klose Tue, 18 Aug 2009 18:00:17 +0200 + +python3.1 (3.1-1) experimental; urgency=low + + * Python 3.1 final release. + * Update to the 3.1 release branch, 20090723. + * Add explicit build dependency on tk8.5-dev. + + -- Matthias Klose Thu, 23 Jul 2009 15:20:35 +0200 + +python3.1 (3.1-0ubuntu2) karmic; urgency=low + + * Disable profile feedback based optimization on amd64 (GCC + PR gcov-profile/38292). + + -- Matthias Klose Fri, 24 Jul 2009 16:27:22 +0200 + +python3.1 (3.1-0ubuntu1) karmic; urgency=low + + * Python 3.1 final release. + * Update to the 3.1 release branch, 20090723. + * Add explicit build dependency on tk8.5-dev. + + -- Matthias Klose Thu, 23 Jul 2009 18:52:17 +0200 + +python3.1 (3.1~rc2+20090622-1) experimental; urgency=low + + [Matthias Klose] + * Python 3.1 rc2 release. Closes: #529320. + * Update to the trunk, 20090622, remove patches integrated upstream. + * Configure with --with-fpectl --with-dbmliborder=bdb --with-wide-unicode. + NOTE: The --with-wide-unicode configuration will break most extensions + built with 3.1~a1, but is consistent with python2.x configurations. + * Add symbols files for libpython3.1 and python3.1-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python3.1-minimal to avoid a warning on + startup. + * python3.1-doc: Depend on libjs-jquery, use jquery.js from this package. + Closes: #523485. + * Do not add /usr/lib/pythonXY.zip on sys.path. + * Add symbols files for libpython3.1 and python3.1-dbg, don't include symbols + from builtins, which can either be built as builtins or extensions. + * Keep an empty lib-dynload in python3.1-minimal to avoid a warning on + startup. + * Fix some lintian warnings. + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * Move the bdist_wininst files into the -dev package (only needed to build + windows installers). + * Document changes to the site directory name in the installation manual. + * Don't build a profiled binary. Closes: #521811. + + * Address issues when working with PYTHONUSERBASE and non standard prefix + (pointed out by Larry Hastings): + - distutils.sysconfig.get_python_lib(): Only return ".../dist-packages" if + prefix is the default prefix and if PYTHONUSERBASE is not set in the + environment. + - site.addusersitepackages(): Add USER_BASE/.../dist-packages to sys.path. + * Always use the `unix_prefix' scheme for setup.py install in a virtualenv + setup. LP: #339904. + * Don't make the setup.py install options --install-layout=deb and --prefix + conflict with each other. + * distutils: Always install into `/usr/local/lib/python3.1/dist-packages' + if an option `--prefix=/usr/local' is present (except for virtualenv + and PYTHONUSERBASE installations). LP: #362570. + * Always use `site-packages' as site directory name in virtualenv. + + [Marc Deslauriers] + * debian/pyhtml2devhelp.py: update for sphinx generated documentation. + * debian/rules: re-enable documentation files for devhelp. + + -- Matthias Klose Mon, 22 Jun 2009 16:18:39 +0200 + +python3.1 (3.1~a1+20090322-1) experimental; urgency=low + + * Python 3.1 alpha1 release. + * Update to the trunk, 20090322. + * Update installation schemes: LP: #338395. + - When the --prefix option is used for setup.py install, Use the + `unix_prefix' scheme. + - Use the `deb_system' scheme if --install-layout=deb is specified. + - Use the the `unix_local' scheme if neither --install-layout=deb + nor --prefix is specified. + * Use the information in /etc/lsb-release for platform.dist(). LP: #196526. + * pydoc: Fix detection of local documentation files. + * Build a shared library configured --with-pydebug. LP: #322580. + * Fix some lintian warnings. + + -- Matthias Klose Mon, 23 Mar 2009 00:01:27 +0100 + +python3.1 (3.1~~20090226-1) experimental; urgency=low + + * Python-3.1 snapshot (20090226), upload to experimental. + + -- Matthias Klose Thu, 26 Feb 2009 16:18:41 +0100 + +python3.1 (3.1~~20090222-0ubuntu1) jaunty; urgency=low + + * Python-3.1 snapshot (20090222). + * Build the _dbm extension using the Berkeley DB backend. + + -- Matthias Klose Sun, 22 Feb 2009 12:58:58 +0100 + +python3.0 (3.0.1-0ubuntu4) jaunty; urgency=low + + * Don't build-depend on locales on sparc. Currently not installable. + + -- Matthias Klose Sun, 22 Feb 2009 12:48:38 +0100 + +python3.0 (3.0.1-0ubuntu3) jaunty; urgency=low + + * Update to 20090222 from the release30-maint branch. + + -- Matthias Klose Sun, 22 Feb 2009 11:09:58 +0100 + +python3.0 (3.0.1-0ubuntu2) jaunty; urgency=low + + * Allow docs to be built with Sphinx 0.5.x. + + -- Matthias Klose Tue, 17 Feb 2009 12:58:02 +0100 + +python3.0 (3.0.1-0ubuntu1) jaunty; urgency=low + + * New upstream version. + + -- Matthias Klose Mon, 16 Feb 2009 17:18:23 +0100 + +python3.0 (3.0-0ubuntu2) jaunty; urgency=low + + * Update to 20090213 from the release30-maint branch. + + -- Matthias Klose Fri, 13 Feb 2009 15:49:12 +0100 + +python3.0 (3.0-0ubuntu1) jaunty; urgency=low + + * Final Python-3.0 release. + + -- Matthias Klose Thu, 04 Dec 2008 09:00:09 +0100 + +python3.0 (3.0~rc3-0ubuntu4) jaunty; urgency=low + + * Update to 20081127 from the py3k branch. + * Ensure that all extensions from the -minimal package are statically + linked into the interpreter. LP: #301597. + * Include expat, _elementtree, datetime in -minimal to link + these extensions statically. + + -- Matthias Klose Thu, 27 Nov 2008 08:49:02 +0100 + +python3.0 (3.0~rc3-0ubuntu3) jaunty; urgency=low + + * Ignore errors when running the profile task. + + -- Matthias Klose Sun, 23 Nov 2008 15:50:17 +0100 + +python3.0 (3.0~rc3-0ubuntu2) jaunty; urgency=low + + * Don't run test_ioctl on the buildd, before the buildd chroot is fixed: + Unable to open /dev/tty. + + -- Matthias Klose Sun, 23 Nov 2008 15:28:02 +0100 + +python3.0 (3.0~rc3-0ubuntu1) jaunty; urgency=low + + * Update to the python-3.0 release candidate 3. + + -- Matthias Klose Sun, 23 Nov 2008 13:14:20 +0100 + +python3.0 (3.0~rc1+20081027-0ubuntu1) intrepid; urgency=low + + * Update to 20081027 from the py3k branch. LP: #279227. + * Fix typos and section names in doc-base files. LP: #273344. + * Build a new package libpython3.0. + * For locally installed packages, create a directory + /usr/local/lib/python3.0/dist-packages. This is the default for + installations done with distutils and setuptools. Third party stuff + packaged within the distribution goes to /usr/lib/python3.0/dist-packages. + There is no /usr/lib/python3.0/site-packages in the file system and + on sys.path. No package within the distribution must not install + anything in this location. + * distutils: Add an option --install-layout=deb, which + - installs into $prefix/dist-packages instead of $prefix/site-packages. + - doesn't encode the python version into the egg name. + + -- Matthias Klose Mon, 27 Oct 2008 23:38:42 +0100 + +python3.0 (3.0~b3+20080915-0ubuntu1) intrepid; urgency=low + + * Update to 20080915 from the py3k branch. + * Build gdbm + + -- Matthias Klose Mon, 15 Sep 2008 23:56:44 +0200 + +python3.0 (3.0~b3-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 3.0 beta3 release. + + -- Matthias Klose Sun, 24 Aug 2008 03:49:26 +0200 + +python3.0 (3.0~b2-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 3.0 beta2 release. + + -- Matthias Klose Thu, 07 Aug 2008 14:57:02 +0000 + +python3.0 (3.0~b1-0ubuntu1~ppa1) intrepid; urgency=low + + * Python 3.0 beta1 release. + + -- Matthias Klose Tue, 15 Jul 2008 16:10:52 +0200 + +python3.0 (3.0~a5+0530-0ubuntu1) intrepid; urgency=low + + * Update to snapshot taken from the py3k branch. + + -- Matthias Klose Thu, 29 May 2008 15:50:55 +0200 + +python3.0 (3.0~a1-0ubuntu2) gutsy; urgency=low + + * Disable running the benchmark. + + -- Matthias Klose Fri, 31 Aug 2007 23:22:34 +0000 + +python3.0 (3.0~a1-0ubuntu1) gutsy; urgency=low + + * First Python-3.0 alpha release. + + -- Matthias Klose Fri, 31 Aug 2007 21:26:21 +0200 + +python2.6 (2.6~alpha~pre1-~0ubuntu1~ppa1) gutsy; urgency=low + + * Snapshot build, an "how to use tilde in version numbers" upload. + * SVN 20070831. + + -- Matthias Klose Fri, 31 Aug 2007 15:56:09 +0200 + +python2.5 (2.5.2-4) unstable; urgency=low + + * Update to 20080427, taken from the 2.5 release branch. + - Fix issues #2670, #2682. + * Disable running pybench on the hppa buildd (ftbfs). + * Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, + CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + * Support parallel= in DEB_BUILD_OPTIONS (see #209008). + + -- Matthias Klose Sun, 27 Apr 2008 10:40:51 +0200 + +python2.5 (2.5.2-3) unstable; urgency=medium + + * Update to 20080416, taken from the 2.5 release branch. + - Fix CVE-2008-1721, integer signedness error in the zlib extension module. + - Fix urllib2 file descriptor happens byte-at-a-time, reverting + a fix for excessively large memory allocations when calling .read() + on a socket object wrapped with makefile(). + * Disable some regression tests on some architectures: + - arm: test_compiler, test_ctypes. + - armel: test_compiler. + - hppa: test_fork1, test_wait3. + - m68k: test_bsddb3, test_compiler. + * Build-depend on libffi-dev instead of libffi4-dev. + * Fix CVE-2008-1679, integer overflows in the imageop module. + + -- Matthias Klose Wed, 16 Apr 2008 23:37:46 +0200 + +python2.5 (2.5.2-2) unstable; urgency=low + + * Use site.addsitedir() to add directories in /usr/local to sys.path. + Addresses: #469157, #469818. + + -- Matthias Klose Sat, 08 Mar 2008 16:11:23 +0100 + +python2.5 (2.5.2-1) unstable; urgency=low + + * Python 2.5.2 release. + * Merge from Ubuntu: + - Move site customization into sitecustomize.py, don't make site.py + a config file. Addresses: #309719, #413172, #457361. + - Move site.py to python2.4-minimal, remove `addbuilddir' from site.py, + which is unnecessary for installed builds. + - python2.5-dev: Recommend libc-dev instead of suggesting it. LP: #164909. + - Fix issue 961805, Tk Text.edit_modified() fails. LP: #84720. + + -- Matthias Klose Thu, 28 Feb 2008 23:18:52 +0100 + +python2.5 (2.5.1-7) unstable; urgency=low + + * Update to 20080209, taken from the 2.5 release branch. + * Build the _bsddb extension with db-4.5 again; 4.6 is seriously + broken when used with the _bsddb extension. + * Do not run pybench on arm and armel. + * python2.5: Provide python2.5-wsgiref. + * Fix a pseudo RC report with duplicated attributes in the control + file. Closes: #464307. + + -- Matthias Klose Sun, 10 Feb 2008 00:22:57 +0100 + +python2.5 (2.5.1-6) unstable; urgency=low + + * Update to 20080102, taken from the 2.5 release branch. + - Only define _BSD_SOURCE on OpenBSD systems. Closes: #455400. + * Fix handling of packages in linecache.py (Kevin Goodsell). LP: #70902. + * Bump debhelper to v5. + * Register binfmt for .py[co] files. + * Use absolute paths when byte-compiling files. Addresses: #453346. + Closes: #413566, LP: #177722. + * CVE-2007-4965, http://bugs.python.org/issue1179: + Multiple integer overflows in the imageop module in Python 2.5.1 and + earlier allow context-dependent attackers to cause a denial of service + (application crash) and possibly obtain sensitive information (memory + contents) via crafted arguments to (1) the tovideo method, and unspecified + other vectors related to (2) imageop.c, (3) rbgimgmodule.c, and other + files, which trigger heap-based buffer overflows. + Patch prepared by Stephan Herrmann. Closes: #443333, LP: #163845. + * Register info docs when doing source only uploads. LP: #174786. + * Remove deprecated value from categories in desktop file. LP: #172874. + * python2.5-dbg: Don't include the gdbm and _tkinter extensions, now provided + in separate packages. + * Provide a symlink changelog -> NEWS. Closes: #439271. + * Fix build failure on hurd, working around poll() on systems on which it + returns an error on invalid FDs. Closes: #438914. + * Configure --with-system-ffi on all architectures. Closes: #448520. + * Fix version numbers in copyright and README files (Dan O'Huiginn). + Closes: #446682. + * Move some documents from python2.5 to python2.5-dev. + + -- Matthias Klose Wed, 02 Jan 2008 22:22:19 +0100 + +python2.5 (2.5.1-5) unstable; urgency=low + + * Build the _bsddb extension with db-4.6. + + -- Matthias Klose Fri, 17 Aug 2007 00:39:35 +0200 + +python2.5 (2.5.1-4) unstable; urgency=low + + * Update to 20070813, taken from the 2.5 release branch. + * Include plat-mac/plistlib.py (plat-mac is not in sys.path by default. + Closes: #435826. + * Use emacs22 to build the documentation in info format. Closes: #434969. + * Build-depend on db-dev (>= 4.6). Closes: #434965. + + -- Matthias Klose Mon, 13 Aug 2007 22:22:44 +0200 + +python2.5 (2.5.1-3) unstable; urgency=high + + * Support mixed-endian IEEE floating point, as found in the ARM old-ABI + (Aurelien Jarno). Closes: #434905. + + -- Matthias Klose Fri, 27 Jul 2007 20:01:35 +0200 + +python2.5 (2.5.1-2) unstable; urgency=low + + * Update to 20070717, taken from the 2.5 release branch. + * Fix reference count for sys.pydebug variable. Addresses: #431393. + * Build depend on libbluetooth-dev instead of libbluetooth2-dev. + + -- Matthias Klose Tue, 17 Jul 2007 14:09:47 +0200 + +python2.5 (2.5.1-1) unstable; urgency=low + + * Python-2.5.1 release. + * Build-depend on gcc-4.1 (>= 4.1.2-4) on alpha, powerpc, s390, sparc. + * Merge from Ubuntu: + - Add debian/patches/subprocess-eintr-safety.dpatch (LP: #87292): + - Create and use wrappers around read(), write(), and os.waitpid() in the + subprocess module which retry the operation on an EINTR (which happens + if e. g. an alarm was raised while the system call was in progress). + It is incredibly hard and inconvenient to sensibly handle this in + applications, so let's fix this at the right level. + - Patch based on original proposal of Peter <85>strand + in http://python.org/sf/1068268. + - Add two test cases. + - Change the interpreter to build and install python extensions + built with the python-dbg interpreter with a different name into + the same path (by appending `_d' to the extension name). The debug build + of the interpreter tries to first load a foo_d.so or foomodule_d.so + extension, then tries again with the normal name. + - When trying to import the profile and pstats modules, don't + exit, add a hint to the exception pointing to the python-profiler + package, don't exit. + - Keep the module version in the .egg-info name, only remove the + python version. + - python2.5-dbg: Install Misc/SpecialBuilds.txt, document the + debug changes in README.debug. + * Update to 20070425, taken from the 2.5 release branch. + + -- Matthias Klose Wed, 25 Apr 2007 22:12:50 +0200 + +python2.5 (2.5-6) unstable; urgency=medium + + * webbrowser.py: Recognize other browsers: www-browser, x-www-browser, + iceweasel, iceape. + * Move pyconfig.h from the python2.5-dev into the python2.5 package; + required by builds for pure python modules without having python2.5-dev + installed (matching the functionality in python2.4). + * Move the unicodedata module into python2.5-minimal; allows byte compilation + of UTF8 encoded files. + * Do not install anymore outdated debhelper sample scripts. + * Install Misc/SpecialBuilds.txt as python2.5-dbg document. + + -- Matthias Klose Wed, 21 Feb 2007 01:17:12 +0100 + +python2.5 (2.5-5) unstable; urgency=high + + * Do not run the python benchmark on m68k. Timer problems. + Fixes FTBFS on m68k. + * Update to 20061209, taken from the 2.5 release branch. + - Fixes building the library reference in info format. + + -- Matthias Klose Sat, 9 Dec 2006 13:40:48 +0100 + +python2.5 (2.5-4) unstable; urgency=medium + + * Update to 20061203, taken from the 2.5 release branch. + - Fixes build failures on knetfreebsd and the hurd. Closes: #397000. + * Clarify README about distutils. Closes: #396394. + * Move python2.5-config to python2.5-dev. Closes: #401451. + * Cleanup build-conflicts. Addresses: #394512. + + -- Matthias Klose Sun, 3 Dec 2006 18:22:49 +0100 + +python2.5 (2.5-3.1) unstable; urgency=low + + * Non-maintainer upload. + * python2.5-minimal depends on python-minimal (>= 2.4.4-1) because it's the + first version which lists python2.5 as an unsupported runtime (ie a + runtime that is available but for which modules are not auto-compiled). + And being listed there is required for python-central to accept the + installation of python2.5-minimal. Closes: #397006 + + -- Raphael Hertzog Wed, 22 Nov 2006 15:41:06 +0100 + +python2.5 (2.5-3) unstable; urgency=medium + + * Update to 20061029 (2.4.4 was released on 20061019), taken from + the 2.5 release branch. We do not want to have regressions in + 2.5 compared to the 2.4.4 release. + * Don't run pybench on m68k, fails in the calibration loop. Closes: #391030. + * Run the installation/removal hooks. Closes: #383292, #391036. + + -- Matthias Klose Sun, 29 Oct 2006 11:35:19 +0100 + +python2.5 (2.5-2) unstable; urgency=medium + + * Update to 20061003, taken from the 2.5 release branch. + * On arm and m68k, don't run the pybench in debug mode. + * Fix building the source within exec_prefix (Alexander Wirt). + Closes: #385336. + + -- Matthias Klose Tue, 3 Oct 2006 10:08:36 +0200 + +python2.5 (2.5-1) unstable; urgency=low + + * Python 2.5 release. + * Update to 20060926, taken from the 2.5 release branch. + * Run the Python benchmark during the build, compare the results + of the static and shared builds. + * Fix invalid html in python2.5.devhelp.gz. + * Add a python2.5 console entry to the menu (hidden by default). + * python2.5: Suggest python-profiler. + + -- Matthias Klose Tue, 26 Sep 2006 02:36:11 +0200 + +python2.5 (2.5~c1-1) unstable; urgency=low + + * Python 2.5 release candidate 1. + * Update to trunk 20060818. + + -- Matthias Klose Sat, 19 Aug 2006 19:21:05 +0200 + +python2.5 (2.5~b3-1) unstable; urgency=low + + * Build the _ctypes module for m68k-linux. + + -- Matthias Klose Fri, 11 Aug 2006 18:19:19 +0000 + +python2.5 (2.5~b3-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta3 release. + * Update to trunk 20060811. + * Rebuild the documentation. + * Fix value of sys.exec_prefix in the debug build. + * Do not build the library reference in info format; fails to build. + * Link the interpreter against the shared runtime library. With + gcc-4.1 the difference in the pystones benchmark dropped from about + 12% to about 6%. + * Install the statically linked version of the interpreter as + python2.5-static for now. + * Link the shared libpython with -O1. + + -- Matthias Klose Thu, 10 Aug 2006 14:04:48 +0000 + +python2.5 (2.4.3+2.5b2-3) unstable; urgency=low + + * Disable the testsuite on s390; don't care about "minimally configured" + buildd's. + + -- Matthias Klose Sun, 23 Jul 2006 11:45:03 +0200 + +python2.5 (2.4.3+2.5b2-2) unstable; urgency=low + + * Update to trunk 20060722. + * Merge idle-lib from idle-python2.5 into python2.5. + * Merge lib-tk from python-tk into python2.5. + * Tkinter.py: Suggest installation of python-tk package on failed + import of the _tkinter extension. + * Don't run the testsuite for the debug build on alpha. + * Don't run the test_compiler test on m68k. Just takes too long. + * Disable building ctypes on m68k (requires support for closures). + + -- Matthias Klose Sat, 22 Jul 2006 22:26:42 +0200 + +python2.5 (2.4.3+2.5b2-1) unstable; urgency=low + + * Python 2.5 beta2 release. + * Update to trunk 20060716. + * When built on a buildd, do not run the following test which try to + access the network: test_codecmaps_cn, test_codecmaps_hk, test_codecmaps_jp, + test_codecmaps_kr, test_codecmaps_tw, test_normalization. + * When built on a buildd, do not run tests requiring missing write permissions: + test_ossaudiodev. + + -- Matthias Klose Sun, 16 Jul 2006 02:53:50 +0000 + +python2.5 (2.4.3+2.5b2-0ubuntu1) edgy; urgency=low + + * Python 2.5 beta2 release. + + -- Matthias Klose Thu, 13 Jul 2006 17:16:52 +0000 + +python2.5 (2.4.3+2.5b1-1ubuntu2) edgy; urgency=low + + * Fix python-dev dependencies. + * Update to trunk 20060709. + + -- Matthias Klose Sun, 9 Jul 2006 18:50:32 +0200 + +python2.5 (2.4.3+2.5b1-1ubuntu1) edgy; urgency=low + + * Python 2.5 beta1 release. + * Update to trunk 20060623. + * Merge changes from the python2.4 packages. + * python2.5-minimal: Add _struct. + + -- Matthias Klose Fri, 23 Jun 2006 16:04:46 +0200 + +python2.5 (2.4.3+2.5a1-1) experimental; urgency=low + + * Update to trunk 20060409. + * Run testsuite for debug build as well. + * Build-depend on gcc-4.1. + + -- Matthias Klose Sun, 9 Apr 2006 22:27:05 +0200 + +python2.5 (2.4.3+2.5a1-0ubuntu1) dapper; urgency=low + + * Python 2.5 alpha1 release. + * Drop integrated patches. + * Add build dependencies on libsqlite3-dev and libffi4-dev. + * Add (build-)dependency on mime-support, libgpmg1 (test suite). + * Build using the system FFI. + * python2.5 provides python2.5-ctypes and python2.5-pysqlite2, + python2.5-elementtree. + * Move hashlib.py to python-minimal. + * Lib/hotshot/pstats.py: Error out on missing profile/pstats modules. + + -- Matthias Klose Wed, 5 Apr 2006 14:56:15 +0200 + +python2.4 (2.4.3-8ubuntu1) edgy; urgency=low + + * Resynchronize with Debian unstable. Remaining changes: + - Apply langpack-gettext patch. + - diff.gz contains pregenerated html and info docs. + - Build the -doc package from this source. + + -- Matthias Klose Thu, 22 Jun 2006 18:39:57 +0200 + +python2.4 (2.4.3-8) unstable; urgency=low + + * Remove python2.4's dependency on python-central. On installation of + the runtime, call hooks /usr/share/python/runtime.d/*.rtinstall. + On removal, call hooks /usr/share/python/runtime.d/*.rtremove. + Addresses: #372658. + * Call the rtinstall hooks only, if it's a new installation, or the first + installation using the hooks. Adresses: #373677. + + -- Matthias Klose Sun, 18 Jun 2006 00:56:13 +0200 + +python2.4 (2.4.3-7) unstable; urgency=medium + + * Reupload, depend on python-central (>= 0.4.15). + * Add build-conflict on python-xml. + + -- Matthias Klose Wed, 14 Jun 2006 18:56:57 +0200 + +python2.4 (2.4.3-6) medium; urgency=low + + * idle-python2.4: Remove the old postinst and prerm scripts. + * Name the runtime correctly in python2.4-minimal's installation + scripts. + + -- Matthias Klose Mon, 12 Jun 2006 17:39:56 +0000 + +python2.4 (2.4.3-5) unstable; urgency=low + + * python2.4-prerm: Handle the case, when python-central is not installed. + * idle-python2.4: Depend on python-tk instead of python2.4-tk. + + -- Matthias Klose Fri, 9 Jun 2006 05:17:17 +0200 + +python2.4 (2.4.3-4) unstable; urgency=low + + * SVN update up to 2006-06-07 + * Use python-central. + * Don't build the -tk and -gdbm packages from this source; now built + from the python-stdlib-extensions source. + * Remove leftover build dependency on libgmp3-dev. + * Do not build-depend on libbluetooth1-dev and libgpmg1-dev on + hurd-i386, kfreebsd-i386, kfreebsd-amd64. Closes: #365830. + * Do not run the test_tcl test; hangs for unknown reasons on at least + the following buildds: vivaldi(m68k), goedel (alpha), mayer (mipsel). + And no virtual package to file bug reports for the buildds ... + Closes: #364419. + * Move the Makefile from python2.4-dev to python2.4. Closes: #366473. + * Fix typo in pdb(1). Closes: #365772. + * New autoconf likes the mandir in /usr/share instead of /usr; work + with both locations. Closes: #367618. + + -- Matthias Klose Wed, 7 Jun 2006 21:37:20 +0200 + +python2.4 (2.4.3-3) unstable; urgency=low + + * SVN update up to 2006-04-21 + * Update locale aliases from /usr/share/X11/locale/locale.alias. + * Start idle with option -n from the desktop menu, so that the program + can be started in parallel. + * Testsuite related changes only: + - Add build dependencies mime-support, libgpmg1 (needed by test cases). + - Run the testsuite with bsddb, audio and curses resources enabled. + - Re-run the failed tests in verbose mode. + - Run the test suite for the debug build as well. + - Build depend on netbase, needed by test_socketmodule. + - Build depend on libgpmg1, needed by test_curses. + - On the buildds do not run the tests needing the network resource. + * Update python logo. + * Check for the availability of the profile and pstats modules when + importing hotshot.pstats. Closes: #334067. + * Don't build the -doc package from the python2.4 source. + * Set OPT in the installed Makefile to -O2. + + -- Matthias Klose Fri, 21 Apr 2006 19:58:43 +0200 + +python2.4 (2.4.3-2) unstable; urgency=low + + * Add (build-)dependency on mime-support. + + -- Matthias Klose Tue, 4 Apr 2006 22:21:41 +0200 + +python2.4 (2.4.3-1) unstable; urgency=low + + * Python 2.4.3 release. + + -- Matthias Klose Thu, 30 Mar 2006 23:42:37 +0200 + +python2.4 (2.4.3-0ubuntu1) dapper; urgency=low + + * Python 2.4.3 release. + - Fixed a bug that the gb18030 codec raises RuntimeError on encoding + surrogate pair area on UCS4 build. Ubuntu: #29289. + + -- Matthias Klose Thu, 30 Mar 2006 10:57:32 +0200 + +python2.4 (2.4.2+2.4.3c1-0ubuntu1) dapper; urgency=low + + * SVN update up to 2006-03-25 (2.4.3 candidate 1). + - Regenerate the documentation. + + -- Matthias Klose Mon, 27 Mar 2006 12:03:05 +0000 + +python2.4 (2.4.2-1ubuntu3) dapper; urgency=low + + * SVN update up to 2006-03-04 + - Regenerate the documentation. + - map.mmap(-1, size, ...) can return anonymous memory again on Unix. + Ubuntu #26201. + * Build-depend on libncursesw5-dev, ncursesw5 is preferred for linking. + Provides UTF-8 compliant curses bindings. + * Fix difflib where certain patterns of differences were making difflib + touch the recursion limit. + + -- Matthias Klose Sat, 4 Mar 2006 21:38:24 +0000 + +python2.4 (2.4.2-1ubuntu2) dapper; urgency=low + + * SVN update up to 2006-01-17 + - pwd is now a builtin module, remove it from python-minimal. + - Regenerate the documentation. + * python2.4-tk: Suggest tix instead of tix8.1. + * Move config/Makefile from the -dev package into the runtime package + to be able to use the bdist_wininst distutils command. Closes: #348335. + + -- Matthias Klose Tue, 17 Jan 2006 11:02:24 +0000 + +python2.4 (2.4.2-1ubuntu1) dapper; urgency=low + + * Temporarily remove build dependency on lsb-release. + + -- Matthias Klose Sun, 20 Nov 2005 17:40:18 +0100 + +python2.4 (2.4.2-1build1) dapper; urgency=low + + * Rebuild (openssl-0.9.8). + + -- Matthias Klose Sun, 20 Nov 2005 15:27:24 +0000 + +python2.4 (2.4.2-1) unstable; urgency=low + + * Python 2.4.2 release. + + -- Matthias Klose Thu, 29 Sep 2005 01:49:28 +0200 + +python2.4 (2.4.1+2.4.2rc1-1) unstable; urgency=low + + * Python 2.4.2 release candidate 1. + * Fix "Fatal Python error" from cStringIO's writelines. + Patch by Andrew Bennetts. + + -- Matthias Klose Thu, 22 Sep 2005 10:33:22 +0200 + +python2.4 (2.4.1-5) unstable; urgency=low + + * CVS update up to 2005-09-14 + - Regenerate the html and info docs. + * Add some more locale aliases. + * Fix substitution pf python version in README.python2.4-minimal. + Closes: #327487. + * On m68k, build using -O2 (closes: #326903). + * On Debian, don't configure --with-fpectl, which stopped working with + glibc-2.3.5. + + -- Matthias Klose Wed, 14 Sep 2005 17:32:56 +0200 + +python2.4 (2.4.1-4) unstable; urgency=low + + * CVS update up to 2005-09-04 + - teTeX 3.0 related fixes (closes: #322407). + - Regenerate the html and info docs. + * Add entry for IDLE in the Gnome menus. + * Don't build-depend on libbluetooth-dev on the Hurd (closes: #307037). + * Reenable the cthreads patch for the Hurd (closes: #307052). + + -- Matthias Klose Sun, 4 Sep 2005 18:31:42 +0200 + +python2.4 (2.4.1-3) unstable; urgency=low + + * Synchronise with Ubuntu: + - Build a python2.4-minimal package. + + -- Matthias Klose Tue, 12 Jul 2005 00:23:10 +0000 + +python2.4 (2.4.1-2ubuntu3) breezy; urgency=low + + * CVS update up to 2005-07-07 + * Regenerate the documentation. + + -- Matthias Klose Thu, 7 Jul 2005 09:21:28 +0200 + +python2.4 (2.4.1-2ubuntu2) breezy; urgency=low + + * CVS update up to 2005-06-15 + * Regenerate the documentation. + * Synchronize with Debian. Ubuntu 10485. + * idle-python2.4 enhances python2.4. Ubuntu 11562. + * README.Debian: Fix reference to the doc directory (closes: #311677). + + -- Matthias Klose Wed, 15 Jun 2005 08:56:57 +0200 + +python2.4 (2.4.1-2ubuntu1) breezy; urgency=low + + * Update build dependencies: + db4.2-dev -> db4.3-dev, + libreadline4-dev -> libreadline5-dev. + * python2.4-dev: Add missing templates to generate HTML docs. Ubuntu 11531. + + -- Matthias Klose Sun, 29 May 2005 00:01:05 +0200 + +python2.4 (2.4.1-2) unstable; urgency=low + + * Add the debug symbols for the python2.4, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. + * Add gdbinit example to doc directory. + + -- Matthias Klose Thu, 5 May 2005 11:12:32 +0200 + +python2.4 (2.4.1-1ubuntu2) breezy; urgency=low + + * Add the debug symbols for the python2.4, python2.4-minimal, python2.4-gdbm + and python2.4-tk packages to the python2.4-dbg package. Ubuntu 10261, + * Add gdbinit example to doc directory. + * For os.utime, use utimes(2), correctly working with glibc-2.3.5. + Ubuntu 10294. + + -- Matthias Klose Thu, 5 May 2005 09:06:07 +0200 + +python2.4 (2.4.1-1ubuntu1) breezy; urgency=low + + * Reupload as 2.4.1-1ubuntu1. + + -- Matthias Klose Thu, 14 Apr 2005 10:46:32 +0200 + +python2.4 (2.4.1-1) unstable; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 19:42:03 +0200 + +python2.4 (2.4.1-0) hoary; urgency=low + + * Python 2.4.1 release. + * Fix noise in python-doc installation/removal. + * New Python section for the info docs. + + -- Matthias Klose Wed, 30 Mar 2005 16:35:34 +0200 + +python2.4 (2.4+2.4.1rc2-2) unstable; urgency=low + + * Add the valgrind support file to /etc/python2.4 + * Build the -dbg package with -DPy_USING_MEMORY_DEBUGGER. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * Fix two typos in python(1). Addresses: #300124. + + -- Matthias Klose Sat, 19 Mar 2005 21:50:14 +0100 + +python2.4 (2.4+2.4.1rc2-1) unstable; urgency=low + + * Python 2.4.1 release candidate 2. + * Build-depend on libbluetooth1-dev. + + -- Matthias Klose Sat, 19 Mar 2005 00:57:14 +0100 + +python2.4 (2.4dfsg-2) unstable; urgency=low + + * CVS update up to 2005-03-03 + + -- Matthias Klose Thu, 3 Mar 2005 22:22:16 +0100 + +python2.4 (2.4dfsg-1ubuntu4) hoary; urgency=medium + + * Move exception finalisation later in the shutdown process - this + fixes the crash seen in bug #1165761, taken from CVS. + * codecs.StreamReader: Reset codec when seeking. Ubuntu #6972. + * Apply fix for SF1124295, fixing an obscure bit of Zope's security machinery. + * distutils: Don't add standard library dirs to library_dirs + and runtime_library_dirs. On amd64, runtime paths pointing to /usr/lib64 + aren't recognized by dpkg-shlibdeps, and the packages containing these + libraries aren't added to ${shlibs:Depends}. + * Lib/locale.py: + - correctly parse LANGUAGE as a colon separated list of languages. + - prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE to get the correct + encoding. + - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding + for glibc. + * os.py: Avoid using items() in environ.update(). Fixes #1124513. + * Python/pythonrun.c: + * Build depend on locales, generate the locales needed for the + testsuite. + * Add build dependency on libbluetooth1-dev, adding some bluetooth + functionality to the socket module. + * Lib/test/test_sundry.py: Don't fail on import of profile & pstats, + which are separated out to the python-profiler package. + * Fix typos in manpage. + + -- Matthias Klose Tue, 29 Mar 2005 13:35:53 +0200 + + +python2.4 (2.4dfsg-1ubuntu3) hoary; urgency=low + + * debian/patches/langpack-gettext.dpatch: + - langpack support for python-gettext added + + -- Michael Vogt Tue, 1 Mar 2005 13:13:36 +0100 + +python2.4 (2.4dfsg-1ubuntu2) hoary; urgency=low + + * Revert 'essential' status on python2.4-minimal. This status on + on python-minimal is sufficient (Ubuntu #6392). + + -- Matthias Klose Wed, 9 Feb 2005 23:09:42 +0100 + +python2.4 (2.4dfsg-1ubuntu1) hoary; urgency=low + + * Resyncronise with Debian. + * Mark the python2.4-minimal package as 'essential'. + + -- Matthias Klose Wed, 9 Feb 2005 13:31:09 +0100 + +python2.4 (2.4dfsg-1) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Remove the profile.py and pstats.py modules from the source package, + not having a DFSG conforming license. The modules can be found in + the python2.x-profile package in the non-free section. + Addresses: #293932. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7ubuntu1) hoary; urgency=low + + * Fix the name of the python-dbg man page. + * Resyncronise with Debian. + * Move more modules to -minimal (new code in copy.py requires these): + dis, inspect, opcode, token, tokenize. + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-7) unstable; urgency=medium + + * Add licenses and acknowledgements for incorporated software in the + debian/copyright file (addresses: #293932). + * Replace md5 implementation with one having a DFSG conforming license. + * Add missing norwegian locales (Tollef Fog Heen). + * CVS updates of the release24-maint branch upto 2005-02-08 (date of + the Python 2.3.5 release). + + -- Matthias Klose Tue, 8 Feb 2005 19:13:10 +0100 + +python2.4 (2.4-6) unstable; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Apply the pydebug-path patch. The package was already built in -5. + + -- Matthias Klose Fri, 4 Feb 2005 22:15:13 +0100 + +python2.4 (2.4-5) unstable; urgency=high + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + * CVS updates of the release24-maint branch upto 2005-02-04. + + -- Matthias Klose Fri, 4 Feb 2005 08:12:10 +0100 + +python2.4 (2.4-4) unstable; urgency=medium + + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Remove /usr/bin/smtpd.py (closes: #291049). + + -- Matthias Klose Mon, 17 Jan 2005 23:54:37 +0100 + +python2.4 (2.4-3ubuntu6) hoary; urgency=low + + * Use old-style dpatches instead of dpatch-run. + + -- Tollef Fog Heen Mon, 7 Feb 2005 15:58:05 +0100 + +python2.4 (2.4-3ubuntu5) hoary; urgency=low + + * Actually apply the patch as well (add to list of patches in + debian/rules) + + -- Tollef Fog Heen Sun, 6 Feb 2005 15:12:58 +0100 + +python2.4 (2.4-3ubuntu4) hoary; urgency=low + + * Add nb_NO and nn_NO locales to Lib/locale.py + + -- Tollef Fog Heen Sun, 6 Feb 2005 14:33:05 +0100 + +python2.4 (2.4-3ubuntu3) hoary; urgency=low + + * Fix a flaw in SimpleXMLRPCServerthat can affect any XML-RPC servers. + This affects any programs have been written that allow remote + untrusted users to do unrestricted traversal and can allow them to + access or change function internals using the im_* and func_* attributes. + References: CAN-2005-0089. + + -- Matthias Klose Wed, 2 Feb 2005 09:08:20 +0000 + +python2.4 (2.4-3ubuntu2) hoary; urgency=low + + * Build a python2.4-dbg package using --with-pydebug. Add a debug + directory /lib-dynload/debug to sys.path instead of + /lib-dynload und install the extension modules of the + debug build in this directory. + Change the module load path to load extension modules from other + site-packages/debug directories (for further details see the + README in the python2.4-dbg package). Closes: #5415. + * Update debian/copyright to the 2.4 license text (closes: #290898). + * Add operator and copy to the -minimal package. + + -- Matthias Klose Mon, 17 Jan 2005 23:19:47 +0100 + +python2.4 (2.4-3ubuntu1) hoary; urgency=low + + * Resynchronise with Debian. + * python2.4: Depend on the very same version of python2.4-minimal. + * Docment, that time.strptime currently cannot be used, if the + python-minimal package is installed without the python package. + + -- Matthias Klose Sun, 9 Jan 2005 19:35:48 +0100 + +python2.4 (2.4-3) unstable; urgency=medium + + * Build the fpectl module. + * Updated to CVS release24-maint 20050107. + + -- Matthias Klose Sat, 8 Jan 2005 19:05:21 +0100 + +python2.4 (2.4-2ubuntu5) hoary; urgency=low + + * Updated to CVS release24-maint 20050102. + * python-minimal: + - os.py: Use dict instead of UserDict, remove UserDict from -minimal. + - add pickle, threading, needed for subprocess module. + - optparse.py: conditionally import gettext, if not available, + define _ as the identity function. Patch taken from the trunk. + Avoids import of _locale, locale, gettext, copy, repr, itertools, + collections, token, tokenize. + - Add a build check to make sure that the minimal module list is + closed under dependency. + * Fix lintian warnings. + + -- Matthias Klose Sun, 2 Jan 2005 22:00:14 +0100 + +python2.4 (2.4-2ubuntu4) hoary; urgency=low + + * Add UserDict.py to the -minimal package, since os.py needs it. + + -- Colin Watson Thu, 30 Dec 2004 20:41:28 +0000 + +python2.4 (2.4-2ubuntu3) hoary; urgency=low + + * Add os.py and traceback.py to the -minimal package, get the list + of modules from the README. + + -- Matthias Klose Mon, 27 Dec 2004 08:20:45 +0100 + +python2.4 (2.4-2ubuntu2) hoary; urgency=low + + * Add compileall.py and py_compile.py to the -minimal package, not + just to the README ... + + -- Matthias Klose Sat, 25 Dec 2004 22:24:56 +0100 + +python2.4 (2.4-2ubuntu1) hoary; urgency=low + + * Separate the interpreter and a minimal subset of modules into + a python2.4-minimal package. See the README.Debian.gz in this + package. + * Move site.py to python2.4-minimal as well. + * Add documentation files for devhelp. + + -- Matthias Klose Sun, 19 Dec 2004 22:47:32 +0100 + +python2.4 (2.4-2) unstable; urgency=medium + + * Updated patch for #283108. Thanks to Jim Meyering. + + -- Matthias Klose Fri, 3 Dec 2004 17:00:16 +0100 + +python2.4 (2.4-1) unstable; urgency=low + + * Final 2.4 release. + * Flush stdout/stderr if closed (SF #1074011). + + -- Matthias Klose Wed, 1 Dec 2004 07:54:34 +0100 + +python2.4 (2.3.97-2) unstable; urgency=low + + * Don't run test_tcl, hanging on the buildds. + + -- Matthias Klose Fri, 19 Nov 2004 23:48:42 +0100 + +python2.4 (2.3.97-1) unstable; urgency=low + + * Python 2.4 Release Candidate 1. + + -- Matthias Klose Fri, 19 Nov 2004 21:27:02 +0100 + +python2.4 (2.3.96-1) experimental; urgency=low + + * Updated to CVS release24-maint 20041113. + * Build the docs in info format again. + + -- Matthias Klose Sat, 13 Nov 2004 21:21:10 +0100 + +python2.4 (2.3.95-2) experimental; urgency=low + + * Move distutils package from the python2.4-dev into the python2.4 + package. + + -- Matthias Klose Thu, 11 Nov 2004 22:56:14 +0100 + +python2.4 (2.3.95-1) experimental; urgency=low + + * Python 2.4 beta2 release. + + -- Matthias Klose Thu, 4 Nov 2004 23:43:47 +0100 + +python2.4 (2.3.94-1) experimental; urgency=low + + * Python 2.4 beta1 release. + + -- Matthias Klose Sat, 16 Oct 2004 08:33:57 +0200 + +python2.4 (2.3.93-1) experimental; urgency=low + + * Python 2.4 alpha3 release. + + -- Matthias Klose Fri, 3 Sep 2004 21:53:47 +0200 + +python2.4 (2.3.92-1) experimental; urgency=low + + * Python 2.4 alpha2 release. + + -- Matthias Klose Thu, 5 Aug 2004 23:53:18 +0200 + +python2.4 (2.3.91-1) experimental; urgency=low + + * Python 2.4 alpha1 release. + Highlights: http://www.python.org/2.4/highlights.html + + -- Matthias Klose Fri, 9 Jul 2004 17:38:54 +0200 + +python2.4 (2.3.90-1) experimental; urgency=low + + * Package HEAD branch (pre alpha ..). + + -- Matthias Klose Mon, 14 Jun 2004 23:19:57 +0200 + +python2.3 (2.3.4-1) unstable; urgency=medium + + * Final Python 2.3.4 Release. + * In the API docs, fix signature of PyModule_AddIntConstant (closes: #250826). + * locale.getdefaultlocale: don't fail with empty environment variables. + Closes: #249816. + * Include distutils/command/wininst.exe in -dev package (closes: #249006). + * Disable cthreads on the Hurd (Michael Banck). Closes: #247211. + * Add a note to pygettext(1), that this program is deprecated in favour + of xgettext, which now includes support for Python as well. + Closes: #246332. + + -- Matthias Klose Fri, 28 May 2004 22:59:42 +0200 + +python2.3 (2.3.3.91-1) unstable; urgency=low + + * Python 2.3.4 Release Candidate 1. + * Do not use the default namespace for attributes. Patch taken from the + 2.3 maintenance branch. + The xmllib module is obsolete. Use xml.sax instead. + * http://python.org/sf/945642 - fix nonblocking i/o with ssl socket. + + -- Matthias Klose Thu, 13 May 2004 21:24:52 +0200 + +python2.3 (2.3.3-7) unstable; urgency=low + + * Add a workaround for GNU libc nl_langinfo()'s returning NULL. + Closes: #239237. + Patch taken from 2.3 maintenance branch. + * threading.py: Remove calls to currentThread() in _Condition methods that + were side-effect. Side-effects were deemed unnecessary and were causing + problems at shutdown time when threads were catching exceptions at start + time and then triggering exceptions trying to call currentThread() after + gc'ed. Masked the initial exception which was deemed bad. + Closes: #195812. + * Properly support normalization of empty unicode strings. Closes: #239986. + Patch taken from 2.3 maintenance branch. + * README.maintainers: Add section where to find the documentation tools. + * Fix crash in pyexpat module (closes: #229281). + * For the Hurd, set the interpreters recursion limit to 930. + * Do not try to byte-compile the test files on installation; this + currently breaks the Hurd install. + + -- Matthias Klose Sat, 1 May 2004 07:50:46 +0200 + +python2.3 (2.3.3-6) unstable; urgency=low + + * Don't build the unversioned python{,-*} packages anymore. Now + built from the python-defaults package. + * Update to the proposed python-policy: byte-compile using -E. + * Remove python-elisp's dependency on emacs20 (closes: #232785). + * Don't build python-elisp from the python2.3 source anymore, + get it from python-mode.sf.net as a separate source package. + * python2.3-dev suggests libc-dev (closes: #231091). + * get LDSHARED and CCSHARED (like, CC, CXX, CPP, CFLAGS) from + the environment + * Set CXX in installed config/Makefile (closes: #230273). + + -- Matthias Klose Tue, 24 Feb 2004 07:07:51 +0100 + +python2.3 (2.3.3-5) unstable; urgency=low + + * Build-depend on libdb4.2-dev, instead of libdb4.1-dev. According + to the docs the file format is compatible. + + -- Matthias Klose Mon, 12 Jan 2004 10:37:45 +0100 + +python2.3 (2.3.3-4) unstable; urgency=low + + * Fix broken _bsddb module. setup.py picked up the wrong library. + + -- Matthias Klose Sun, 4 Jan 2004 11:30:00 +0100 + +python2.3 (2.3.3-3) unstable; urgency=low + + * Fix typo in patch (closes: #224797, #226064). + + -- Matthias Klose Sun, 4 Jan 2004 09:23:21 +0100 + +python2.3 (2.3.3-2) unstable; urgency=medium + + * Lib/email/Charset: use locale unaware function to lower case of locale + name (closes: #224797). + * Update python-mode to version from python-mode.sf.net. Fixes highlighting + problems (closes: #223520). + * Backport from mainline: Add IPV6_ socket options from RFCs 3493 and 3542. + + -- Matthias Klose Fri, 2 Jan 2004 14:03:26 +0100 + +python2.3 (2.3.3-1) unstable; urgency=low + + * New upstream release. + * Copy the templates, tools and scripts from the Doc dir in the source + to /usr/share/lib/python2.3/doc in the python2.3-dev package. Needed + for packages building documentation like python does (closes: #207337). + + -- Matthias Klose Fri, 19 Dec 2003 10:57:39 +0100 + +python2.3 (2.3.2.91-1) unstable; urgency=low + + * New upstream version (2.3.3 release candidate). + * Update python-mode.el (closes: #158811, #159630). + Closing unreproducible report (closes: #159628). + + -- Matthias Klose Sat, 6 Dec 2003 14:41:14 +0100 + +python2.3 (2.3.2-7) unstable; urgency=low + + * Put the conflict in the correct direction. python2.3 (2.3.2-6) doesn't + conflict with python (<= 2.3.2-5) but python (2.3.2-6) conflicts with + python2.3 (<= 2.3.2-5) (thanks to Brian May). Really closes #221791. + + -- Matthias Klose Fri, 21 Nov 2003 00:20:02 +0100 + +python2.3 (2.3.2-6) unstable; urgency=low + + * Add conflicts with older python{,2.3} packages to fix overwrite + errors (closes: #221791). + + -- Matthias Klose Thu, 20 Nov 2003 07:24:36 +0100 + +python2.3 (2.3.2-5) unstable; urgency=low + + * Updated to CVS release23-maint 20031119. + * Re-upgrade the dependency of python2.3 on python (>= 2.3) to + a dependency (closes: #221523). + + -- Matthias Klose Wed, 19 Nov 2003 00:30:27 +0100 + +python2.3 (2.3.2-4) unstable; urgency=low + + * Don't build-depend on latex2html (moved to non-free), but keep + the prebuilt docs in debian/patches (closes: #221347). + * Fix typos in the library reference (closes: #220510, #220954). + * Fix typo in python-elisp's autoloading code (closes: #220308). + * Update proposed python policy: private modules can be installed + into /usr/lib/ (arch dependent) and into /usr/share/ + (arch independent). + + -- Matthias Klose Tue, 18 Nov 2003 00:41:39 +0100 + +python2.3 (2.3.2-3) unstable; urgency=low + + * Downgrade the dependency of python2.3 on python (>= 2.3) to + a recommendation. + * Fix path to interpreter in binfmt file. + * Fix segfault in unicodedata module (closes: #218697). + * Adjust python-elisp autoload code (closes: #219821). + + -- Matthias Klose Sun, 9 Nov 2003 19:43:37 +0100 + +python2.3 (2.3.2-2) unstable; urgency=medium + + * Fix broken doc link (closes: #214217). + * Disable wrongly detected large file support for GNU/Hurd. + * Really fix the FTBFS for the binary-indep target (closes: #214303). + + -- Matthias Klose Mon, 6 Oct 2003 07:54:58 +0200 + +python2.3 (2.3.2-1) unstable; urgency=low + + * New upstream version. + * Fix a FTBFS for the binary-indep target. + + -- Matthias Klose Sat, 4 Oct 2003 10:20:15 +0200 + +python2.3 (2.3.1-3) unstable; urgency=low + + * Fix names of codec packages in recommends. + * On alpha compile using -mieee (see #212912). + + -- Matthias Klose Sun, 28 Sep 2003 10:48:12 +0200 + +python2.3 (2.3.1-2) unstable; urgency=low + + * Update python policy draft (closes: #128911, #163785). + * Re-add os.fsync function (closes: #212672). + * Let python2.3-doc conflict with older python2.3 versions (closes: #211882). + * Add recommends for pythonX.Y-japanese-codecs, pythonX.Y-iconvcodec, + pythonX.Y-cjkcodecs, pythonX.Y-korean-codecs (closes: #207161). + * Generate binfmt file (closes: #208005). + * Add IPPROTO_IPV6 option to the socketmodule (closes: #206569). + * Bugs reported against python2.2 and fixed in python2.3: + - Crashes in idle (closes: #186887, #200084). + + -- Matthias Klose Sat, 27 Sep 2003 11:21:47 +0200 + +python2.3 (2.3.1-1) unstable; urgency=low + + * New upstream version (bug fix release). + + -- Matthias Klose Wed, 24 Sep 2003 11:27:43 +0200 + +python2.3 (2.3-4) unstable; urgency=high + + * Disable check for utimes function, which is broken in glibc-2.3.2. + Packages using distutils had '1970/01/01-01:00:01' timestamps in files. + * Bugs fixed by making python2.3 the default python version: + - Canvas.scan_dragto() takes a 3rd optional parmeter "gain". + Closes: #158168. + - New command line parsing module (closes: #38628). + - compileall.py allows compiling single files (closes: #139971). + * Bugs reported for 2.2 and fixed in 2.3: + - Idle does save files with ASCII characters (closes: #179313). + - imaplib support for prefix-quoted strings (closes: #150485). + - posixpath includes getctime (closes: #173827). + - pydoc has support for keywords (closes: #186775). + * Bugs reported for 2.1 and fixed in 2.3: + - Fix handling of "#anchor" URLs in urlparse (closes: #147844). + - Fix readline if C stdin is not a tty, even if sys.stdin is. + Closes: #131810. + * Updated to CVS release23-maint 20030810 (fixing memory leaks in + array and socket modules). + * pydoc's usage output uses the basename of the script. + * Don't explicitely remove /etc/python2.3 on purge (closes: #202864). + * python conflicts with python-xmlbase (closes: #204773). + * Add dependency python (>= 2.3) to python2.3, so make sure the + unversioned names can be used. + + -- Matthias Klose Sun, 10 Aug 2003 09:27:52 +0200 + +python2.3 (2.3-3) unstable; urgency=medium + + * Fix shlibs file. + + -- Matthias Klose Fri, 8 Aug 2003 08:45:12 +0200 + +python2.3 (2.3-2) unstable; urgency=medium + + * Make python2.3 the default python version. + + -- Matthias Klose Tue, 5 Aug 2003 22:13:22 +0200 + +python2.3 (2.3-1) unstable; urgency=low + + * Python 2.3 final release. + + -- Matthias Klose Wed, 30 Jul 2003 08:12:28 +0200 + +python2.3 (2.2.107-1rc2) unstable; urgency=medium + + * Python 2.3 release candidate 2. + * Don't compress .txt files referenced by the html docs (closes: #200298). + * Include the email/_compat* files (closes: #200349). + + -- Matthias Klose Fri, 25 Jul 2003 07:08:09 +0200 + +python2.3 (2.2.106-2beta2) unstable; urgency=medium + + * Python 2.3 beta2 release, updated to CVS 20030704. + - Fixes AssertionError in httplib (closed: #192452). + - Fixes uncaught division by zero in difflib.py (closed: #199287). + * Detect presence of setgroups(2) at configure time (closes: #199839). + * Use default gcc on arm as well. + + -- Matthias Klose Sat, 5 Jul 2003 10:21:33 +0200 + +python2.3 (2.2.105-1beta2) unstable; urgency=low + + * Python 2.3 beta2 release. + - Includes merged idle fork. + - Fixed socket.setdefaulttimeout(). Closes: #189380. + - socket.ssl works with _socketobj. Closes: #196082. + * Do not link libtix to the _tkinter module. It's loaded via + 'package require tix' at runtime. python2.3-tkinter now + suggests tix8.1 instead. + * On arm, use gcc-3.2 to build. + * Add -fno-strict-aliasing rules to OPT to avoid warnings + "dereferencing type-punned pointer will break strict-aliasing rules", + when building with gcc-3.3. + + -- Matthias Klose Mon, 30 Jun 2003 00:19:32 +0200 + +python2.3 (2.2.104-1beta1.1) unstable; urgency=low + + * Non-maintainer upload with maintainer consent. + * debian/control (Build-Depends): s/libgdbmg1-dev/libgdbm-dev/. + + -- James Troup Wed, 4 Jun 2003 02:24:27 +0100 + +python2.3 (2.2.104-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030514. + - build the current documentation. + * Reenable Tix support. + + -- Matthias Klose Wed, 14 May 2003 07:38:57 +0200 + +python2.3 (2.2.103-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release, updated to CVS 20030506. + - updated due to build problems on mips/mipsel. + - keep the 2.3b1 documentation (doc build problems with cvs). + + -- Matthias Klose Wed, 7 May 2003 06:26:39 +0200 + +python2.3 (2.2.102-1beta1) unstable; urgency=low + + * Python 2.3 beta1 release. + + -- Matthias Klose Sat, 3 May 2003 22:45:16 +0200 + +python2.3 (2.2.101-1exp1) unstable; urgency=medium + + * Python 2.3 alpha2 release, updated to CVS 20030321. + * Tkinter: Catch exceptions thrown for undefined substitutions in + events (needed for tk 8.4.2). + + -- Matthias Klose Fri, 21 Mar 2003 21:32:14 +0100 + +python2.3 (2.2.100-1exp1) unstable; urgency=low + + * Python 2.3 alpha2 release, updated to CVS 20030221. + + -- Matthias Klose Fri, 21 Feb 2003 19:37:17 +0100 + +python2.3 (2.2.99-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030123. + - should fix the testsuite (and package build) failure on alpha. + * Remove build dependency on libexpat1-dev. Merge the python2.3-xmlbase + package into python2.3 (closes: #177739). + + -- Matthias Klose Thu, 23 Jan 2003 22:48:12 +0100 + +python2.3 (2.2.98-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030117. + * Build using libdb4.1. + + -- Matthias Klose Sat, 18 Jan 2003 00:14:01 +0100 + +python2.3 (2.2.97-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release updated to CVS 20030109. + * Build-Depend on g++ (>= 3:3.2). + * Python package maintainers: please wait uploading python dependent + packages until python2.2 and python2.1 are compiled using gcc-3.2. + + -- Matthias Klose Thu, 9 Jan 2003 23:56:42 +0100 + +python2.3 (2.2.96-1exp1) unstable; urgency=low + + * Python 2.3 alpha1 release (not exactly the tarball, but taken from + CVS 20030101). + - Includes support for linking with threaded tk8.4 (closes: #172714). + * Install and register whatsnew document (closes: #173859). + * Properly unregister info documentation. + + -- Matthias Klose Wed, 1 Jan 2003 17:38:54 +0100 + +python2.3 (2.2.95-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021212. + - data in unicodedate module is up to date (closes: #171061). + * Fix idle packaging (closes: #170394). + * Configure using unicode UCS-4 (closes: #171062). + This change breaks compatibility with binary modules, but what do you + expect from experimental packages ... Please recompile dependent packages. + * Don't strip binaries for now. + + -- Matthias Klose Thu, 12 Dec 2002 21:42:27 +0100 + +python2.3 (2.2.94-1exp1) unstable; urgency=low + + * Experimental packages from CVS 021120. + * Remove outdated README.dbm. + * Depend on tk8.4. + * python-elisp: Install emacsen install file with mode 644 (closes: #167718). + + -- Matthias Klose Thu, 21 Nov 2002 01:04:51 +0100 + +python2.3 (2.2.93-1exp1) unstable; urgency=medium + + * Experimental packages from CVS 021015. + * Build a static library libpython2.3-pic.a. + * Enable large file support for the Hurd (closes: #164602). + + -- Matthias Klose Tue, 15 Oct 2002 21:06:27 +0200 + +python2.3 (2.2.92-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020922. + * Fix build error on ia64 (closes: #161234). + * Build depend on gcc-3.2-3.2.1-0pre2 to fix build error on arm. + + -- Matthias Klose Sun, 22 Sep 2002 18:30:28 +0200 + +python2.3 (2.2.91-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020906. + * idle-python2.3: Fix conflict (closes: #159267). + * Fix location of python-mode.el (closes: #159564, #159619). + * Use tix8.1. + * Apply fix for distutils/ccompiler problem (closes: #159288). + + -- Matthias Klose Sat, 7 Sep 2002 09:55:07 +0200 + +python2.3 (2.2.90-1exp1) unstable; urgency=low + + * Experimental packages from CVS 020820. + * Don't build python2.3-elisp, but put the latest version into + python-elisp. + + -- Matthias Klose Thu, 22 Aug 2002 21:52:04 +0200 + +python2.2 (2.2.1-6) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-07-23. + * Enable IPv6 support (closes: #152543). + * Add python2.2-tk suggestion for python2.2 (pydoc -g). + * Fix from SF patch #527518: proxy config with user+pass authentication. + * Point pydoc to the correct location of the docs (closes: #147579). + * Remove '*.py[co]' files, when removing the python package, + not when purging (closes: #147130). + * Update to new py2texi.el version (Milan Zamazal). + + -- Matthias Klose Mon, 29 Jul 2002 23:11:32 +0200 + +python2.2 (2.2.1-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 2002-05-03. + * Build the info docs (closes: #145653). + + -- Matthias Klose Fri, 3 May 2002 22:35:46 +0200 + +python2.2 (2.2.1-4) unstable; urgency=high + + * Fix indentation errors introduced in last upload (closes: #143809). + + -- Matthias Klose Sun, 21 Apr 2002 01:00:14 +0200 + +python2.2 (2.2.1-3) unstable; urgency=high + + * Add Build-Conflicts: tcl8.0-dev, tk8.0-dev, tcl8.2-dev, tk8.2-dev. + Closes: #143534 (build a working _tkinter module, on machines, where + 8.0's tk.h gets included). + * CVS updates of the release22-maint branch upto 2002-04-20. + + -- Matthias Klose Sat, 20 Apr 2002 09:22:37 +0200 + +python2.2 (2.2.1-2) unstable; urgency=low + + * Forgot to copy the dlmodule patch from the 2.1.3 package. Really + closes: #141681. + + -- Matthias Klose Sat, 13 Apr 2002 01:28:05 +0200 + +python2.2 (2.2.1-1) unstable; urgency=high + + * Final 2.2.1 release. + * According to report #131813, the python interpreter is much faster on some + architectures, when beeing linked statically with the python library (25%). + Gregor and me tested on i386, m68k and alpha, but we could not reproduce + such a speedup (generally between 5% and 10%). But we are linking the + python executable now statically ... + * Build info docs from the tex source, merge the python-doc-info + package into the python-doc package. + * Always build the dl module. Failure in case of + sizeof(int)!=sizeof(long)!=sizeof(void*) + is delayed until dl.open is called. Closes: #141681. + + -- Matthias Klose Thu, 11 Apr 2002 00:19:19 +0200 + +python2.2 (2.2.0.92-0) unstable; urgency=low + + * Package CVS sources, omit cvs-updates.dpatch (closes: #140977). + + -- Matthias Klose Wed, 3 Apr 2002 08:20:52 +0200 + +python2.2 (2.2-6) unstable; urgency=medium + + * Update to python-2.2.1 release candidate 2 (final release scheduled + for April 10). + * Enable dl module (closes: #138992). + * Build doc files with python binary from package (closes: #139657). + * Build _tkinter module with BLT and Tix support. + * python2.2-elisp: Conflict with python2-elisp (closes: #138970). + * string.split docs updated in python-2.2.1 (closes: #129272). + + -- Matthias Klose Mon, 1 Apr 2002 13:52:36 +0200 + +python2.2 (2.2-5) unstable; urgency=low + + * CVS updates of the release22-maint branch upto 20020310 (aproaching + the first 2.2.1 release candidate). + * Stolen from HEAD: check argument of locale.nl_langinfo (closes: #137371). + + -- Matthias Klose Fri, 15 Mar 2002 01:05:59 +0100 + +python2.2 (2.2-4) unstable; urgency=medium + + * Include test/{__init__.py,README,pystone.py} in package (closes: #129013). + * Fix python-elisp conflict (closes: #129046). + * Don't compress stylesheets (closes: #133179). + * CVS updates of the release22-maint branch upto 20020310. + + -- Matthias Klose Sun, 10 Mar 2002 23:32:28 +0100 + +python2.2 (2.2-3) unstable; urgency=medium + + * Updates from the CVS python22-maint branch up to 20020107. + webbrowser.py: properly escape url's. + * The Hurd does not have large file support: disabled. + + -- Matthias Klose Mon, 7 Jan 2002 21:55:57 +0100 + +python2.2 (2.2-2) unstable; urgency=medium + + * CVS updates of the release22-maint branch upto 20011229. Fixes: + - Include TCP_CORK flag in plat-linux2 headers (fixes: #84340). + - Update CDROM.py module (fixes: #125785). + * Add missing chunk of the GNU/Hurd patch (therefore urgency medium). + * Send anonymous password when using anonftp (closes: #126814). + + -- Matthias Klose Sat, 29 Dec 2001 20:18:26 +0100 + +python2.2 (2.2-1) unstable; urgency=low + + * New upstream version: 2.2. + * Bugs fixed upstream: + - Docs for os.kill reference the signal module for constants. + - Documentation strings in the tutorial end with a period (closes: #94770). + - Tk: grid_location method moved from Grid to Misc (closes: #98338). + - mhlib.SubMessage.getbodytext takes decode parameter (closes: #31876). + - Strings in modules are locale aware (closes: #51444). + - Printable 8-bit characters in strings are correctly printed + (closes: #64354). + - Dictionary can be updated with abstract mapping object (closes: #46566). + * Make site.py a config files. + + -- Matthias Klose Sat, 22 Dec 2001 00:51:46 +0100 + +python2.2 (2.1.99c1-1) unstable; urgency=low + + * New upstream version: 2.2c1 (release candidate). + * Do not provide python2.2-base anymore. + * Install correct README.Debian for python2.2 package. Include hint + where to find Makefile.pre.in. + * Suggest installation of python-ssl. + * Remove idle config files on purge. + * Remove empty /usr/lib/python2.2 directory on purge. + + -- Matthias Klose Sat, 15 Dec 2001 17:56:27 +0100 + +python2.2 (2.1.99beta2-1) unstable; urgency=high + + * debian/rules: Reflect removal of regrtest package (closes: #122278). + Resulted in build failures on all architectures. + * Build -doc package from source. + + -- Matthias Klose Sat, 8 Dec 2001 00:38:41 +0100 + +python2.2 (2.1.99beta2-0.1) unstable; urgency=low + + * Non maintainer upload. + * New upstream version (this is 2.2beta2). + * Do not build the python-regrtest package anymore; keep the test framework + components test/regrtest.py and test/test_support.py in the python + package (closes: #119408). + + -- Gregor Hoffleit Tue, 27 Nov 2001 09:53:26 +0100 + +python2.2 (2.1.99beta1-4) unstable; urgency=low + + * Configure with --with-fpectl (closes: #118125). + * setup.py: Remove broken check for _curses_panel module (#116081). + * idle: Move config-* files to /etc and mark as conffiles (#106390). + * Move idle packages to section `devel'. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-3) unstable; urgency=low + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * README.Debian: point to draft of python-policy in the python package. + + -- Matthias Klose Wed, 31 Oct 2001 10:56:45 +0100 + +python2.2 (2.1.99beta1-2) unstable; urgency=medium + + * Fix shlibs file (was still referring to 2.1). Closes: #116810. + * Rename package python2.2-base to python2.2. + + -- Matthias Klose Wed, 24 Oct 2001 23:00:50 +0200 + +python2.2 (2.1.99beta1-1) unstable; urgency=low + + * New upstream version (beta). Call the package version 2.1.99beta1-1. + * New maintainer until the final 2.2 release. + * Updated the debian patches. + + -- Matthias Klose Sat, 20 Oct 2001 18:56:26 +0200 + +python2.1 (2.1.1-1.2) unstable; urgency=low + + * Really remove the python alternative. + + -- Matthias Klose Sat, 20 Oct 2001 15:16:56 +0200 + +python2.1 (2.1.1-1.1) unstable; urgency=low + + * README FOR PACKAGE MAINTAINERS: It is planned to remove the python2-XXX + packages from unstable and move on to python2.1. + If you repackage/adapt your modules for python2.1, don't build + python2-XXX and python2.1-XXX packages from the same source package, + so that the python2-XXX package can be removed without influencing the + python2.1-XXX package. + + See the debian-python mailing list at http://lists.debian.org/devel.html + for details and the current discussion and a draft for a debian-python + policy (August to October 2001). + + * Remove alternative for /usr/bin/python. The python-base package now + provides the default python version. + + * Regenerate control file to fix build dependencies (closes: #116190). + * Remove alternative for /usr/bin/{python,pydoc}. + * Provide a libpython2.1.so symlink in /usr/lib/python2.1/config, + so that the shared library is found when -L/usr/lib/python2.1/config + is specified. + * Conflict with old package versions, where /usr/bin/python is a real + program (closes: #115943). + * python2.1-elisp conflicts with python-elisp (closes: #115895). + * We now have 2.1 (closes: #96851, #107849, #110243). + + -- Matthias Klose Fri, 19 Oct 2001 17:34:41 +0200 + +python2.1 (2.1.1-1) unstable; urgency=low + + * Incorporated Matthias' modifications. + + -- Gregor Hoffleit Thu, 11 Oct 2001 00:16:42 +0200 + +python2.1 (2.1.1-0.2) unstable; urgency=low + + * New upstream 2.1.1. + * GPL compatible licence (fixes #84080, #102949, #110643). + * Fixed upstream (closes: #99692, #111340). + * Build in separate build directory. + * Split Debian patches into debian/patches directory. + * Build dependencies: Add libgmp3-dev, libexpat1-dev, tighten + debhelper dependency. + * debian/rules: Updated a "bit". + * python-elisp: Remove custom dependency (closes: #87783), + fix emacs path (closes: #89712), remove emacs19 dependency (#82694). + * Mention distutils in python-dev package description (closes: #108170). + * Update README.Debian (closes: #85430). + * Run versioned python in postinsts (closes: #113349). + * debian/sample.{postinst,prerm}: Change to version independent scripts. + * Use '/usr/bin/env python2.1' as interpreter for all python scripts. + * Add libssl-dev to Build-Conflicts. + * python-elisp: Add support for emacs21 (closes: #98635). + * Do not compress .py files in doc directories. + * Don't link explicitely with libc. + + -- Matthias Klose Wed, 3 Oct 2001 09:53:08 +0200 + +python2.1 (2.1.1-0.1) unstable; urgency=low + + * New upstream version (CVS branch release21-maint, will become 2.1.1): + This CVS branch will be released as 2.1.1 under a GPL compatible + license. + + -- Gregor Hoffleit Wed, 27 Jun 2001 22:47:58 +0200 + +python2 (2.1-0.1) unstable; urgency=low + + * Fixed Makefile.pre.in. + * Fixed the postinst files in order to use 2.1 (instead of 2.0). + * Mention the immanent release of 2.0.1 and 2.1.1, with a GPL + compatible license. + + -- Gregor Hoffleit Sun, 17 Jun 2001 21:05:25 +0200 + +python2 (2.1-0) unstable; urgency=low + + * New upstream version. + * Experimental packages. + + -- Gregor Hoffleit Thu, 10 May 2001 00:20:04 +0200 + +python2 (2.0-7) unstable; urgency=low + + * Rebuilt with recent tcl8.3-dev/tk8.3-dev in order to fix a + dependency problem with python2-tk (closes: #87793, #92962). + * Change postinst to create and update /usr/local/lib/python2.0 and + site-python with permissions and owner as mandated by policy: + 2775 and root:staff (closes: #89047). + * Fix to compileall.py: A superfluous argument made compileall without + options fail (cf. #92990 for python). + * Move the distutils module into python2-dev. It needs Makefile.pre.in + in order to work (closes: #89900). + * Remove build-dependency on libgdbm2-dev (which isn't built anyway). + * Add a build-dependency on libdb2-dev (cf. #90220 for python). + + -- Gregor Hoffleit Sat, 14 Apr 2001 21:07:51 +0200 + +python2 (2.0-6) unstable; urgency=low + + * Remove python-zlib package; merge it into python-base. + * Mark that README.python2 is not yet updated. + + -- Gregor Hoffleit Wed, 21 Feb 2001 12:34:18 +0100 + +python2 (2.0-5) unstable; urgency=low + + * Recompile with tcl/tk8.3 (closes: #82088). + * Modifications to README.why-python2 (closes: #82116). + * Add menu hint to idle2 menu entry. + * idle2 is renamed idle-python2 and now build correctly (closes: #82218). + * Add build-dependency on autoconf (closes: #85339). + * Build bsddbmodule as shared module (Modules/Setup.config.in), + and link libpython2.so with -lm in Makefile (closes: #86027). + * various cleanups in debian/rules, e.g. removing dh_suidregister. + * Make pdb available as /usr/bin/pdb-python2 in python2-dev + (cf. #79870 in python-base). + * Remove libgmp3 from build-dependencies, since we currently can't + build the mpzmodule for Python2 due to license problems. + + -- Gregor Hoffleit Sun, 18 Feb 2001 00:12:17 +0100 + +python2 (2.0-4) unstable; urgency=low + + * control: make python2-elisp conflict with python-elisp (it doesn't + make sense to have both of them installed, does it ?) + * include build-depend on libxmltok1-dev. + * again, build with tcl/tk8.0. + + -- Gregor Hoffleit Wed, 10 Jan 2001 23:37:01 +0100 + +python2 (2.0-3) unstable; urgency=low + + * Modules/Setup.in: Added a missing \ that made _tkinter be built + incorrectly. + * rules: on the fly, change all '#!' python scripts to use python2. + + -- Gregor Hoffleit Wed, 13 Dec 2000 20:07:24 +0100 + +python2 (2.0-2) unstable; urgency=low + + * Aaargh. Remove conflicts/provides/replaces on python-base to make + parallel installation of python-base and python2-base possible. + * Install examples into /usr/share/doc/python2 (not python) and fix + symlink to python2.0 (thanks to Rick Younie for + pointing out this). + * Rename man page to python2.1. + + -- Gregor Hoffleit Wed, 13 Dec 2000 09:31:05 +0100 + +python2 (2.0-1) unstable; urgency=low + + * New upstream version. Initial release for python2. + + -- Gregor Hoffleit Mon, 11 Dec 2000 22:39:46 +0100 --- python3.1-3.1.1.orig/debian/pygettext.1 +++ python3.1-3.1.1/debian/pygettext.1 @@ -0,0 +1,108 @@ +.TH PYGETTEXT 1 "" "pygettext 1.4" +.SH NAME +pygettext \- Python equivalent of xgettext(1) +.SH SYNOPSIS +.B pygettext +[\fIOPTIONS\fR] \fIINPUTFILE \fR... +.SH DESCRIPTION +pygettext is deprecated. The current version of xgettext supports +many languages, including Python. + +pygettext uses Python's standard tokenize module to scan Python +source code, generating .pot files identical to what GNU xgettext generates +for C and C++ code. From there, the standard GNU tools can be used. +.PP +pygettext searches only for _() by default, even though GNU xgettext +recognizes the following keywords: gettext, dgettext, dcgettext, +and gettext_noop. See the \fB\-k\fR/\fB\--keyword\fR flag below for how to +augment this. +.PP +.SH OPTIONS +.TP +\fB\-a\fR, \fB\-\-extract\-all\fR +Extract all strings. +.TP +\fB\-d\fR, \fB\-\-default\-domain\fR=\fINAME\fR +Rename the default output file from messages.pot to name.pot. +.TP +\fB\-E\fR, \fB\-\-escape\fR +Replace non-ASCII characters with octal escape sequences. +.TP +\fB\-D\fR, \fB\-\-docstrings\fR +Extract module, class, method, and function docstrings. +These do not need to be wrapped in _() markers, and in fact cannot +be for Python to consider them docstrings. (See also the \fB\-X\fR option). +.TP +\fB\-h\fR, \fB\-\-help\fR +Print this help message and exit. +.TP +\fB\-k\fR, \fB\-\-keyword\fR=\fIWORD\fR +Keywords to look for in addition to the default set, which are: _ +.IP +You can have multiple \fB\-k\fR flags on the command line. +.TP +\fB\-K\fR, \fB\-\-no\-default\-keywords\fR +Disable the default set of keywords (see above). +Any keywords explicitly added with the \fB\-k\fR/\fB\--keyword\fR option +are still recognized. +.TP +\fB\-\-no\-location\fR +Do not write filename/lineno location comments. +.TP +\fB\-n\fR, \fB\-\-add\-location\fR +Write filename/lineno location comments indicating where each +extracted string is found in the source. These lines appear before +each msgid. The style of comments is controlled by the +\fB\-S\fR/\fB\--style\fR option. This is the default. +.TP +\fB\-o\fR, \fB\-\-output\fR=\fIFILENAME\fR +Rename the default output file from messages.pot to FILENAME. +If FILENAME is `-' then the output is sent to standard out. +.TP +\fB\-p\fR, \fB\-\-output\-dir\fR=\fIDIR\fR +Output files will be placed in directory DIR. +.TP +\fB\-S\fR, \fB\-\-style\fR=\fISTYLENAME\fR +Specify which style to use for location comments. +Two styles are supported: +.RS +.IP \(bu 4 +Solaris # File: filename, line: line-number +.IP \(bu 4 +GNU #: filename:line +.RE +.IP +The style name is case insensitive. +GNU style is the default. +.TP +\fB\-v\fR, \fB\-\-verbose\fR +Print the names of the files being processed. +.TP +\fB\-V\fR, \fB\-\-version\fR +Print the version of pygettext and exit. +.TP +\fB\-w\fR, \fB\-\-width\fR=\fICOLUMNS\fR +Set width of output to columns. +.TP +\fB\-x\fR, \fB\-\-exclude\-file\fR=\fIFILENAME\fR +Specify a file that contains a list of strings that are not be +extracted from the input files. Each string to be excluded must +appear on a line by itself in the file. +.TP +\fB\-X\fR, \fB\-\-no\-docstrings\fR=\fIFILENAME\fR +Specify a file that contains a list of files (one per line) that +should not have their docstrings extracted. This is only useful in +conjunction with the \fB\-D\fR option above. +.PP +If `INPUTFILE' is -, standard input is read. +.SH BUGS +pygettext attempts to be option and feature compatible with GNU xgettext +where ever possible. However some options are still missing or are not fully +implemented. Also, xgettext's use of command line switches with option +arguments is broken, and in these cases, pygettext just defines additional +switches. +.SH AUTHOR +pygettext is written by Barry Warsaw . +.PP +Joonas Paalasmaa put this manual page together +based on "pygettext --help". --- python3.1-3.1.1.orig/debian/patches/svn-updates.dpatch +++ python3.1-3.1.1/debian/patches/svn-updates.dpatch @@ -0,0 +1,27235 @@ +#! /bin/sh -e + +# DP: SVN updates of the trunk (until 2009-11-02). + +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 + autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + rm -f configure + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +# svn diff http://svn.python.org/projects/python/tags/r311 http://svn.python.org/projects/python/branches/release31-maint +# svn diff http://svn.python.org/projects/python/tags/r31 http://svn.python.org/projects/python/trunk +# diff -urN --exclude=.svn Python-3.1 svn + +Index: Python/codecs.c +=================================================================== +--- Python/codecs.c (.../tags/r311) (Revision 76056) ++++ Python/codecs.c (.../branches/release31-maint) (Revision 76056) +@@ -957,7 +957,9 @@ + { + "strict_errors", + strict_errors, +- METH_O ++ METH_O, ++ PyDoc_STR("Implements the 'strict' error handling, which " ++ "raises a UnicodeError on coding errors.") + } + }, + { +@@ -965,7 +967,9 @@ + { + "ignore_errors", + ignore_errors, +- METH_O ++ METH_O, ++ PyDoc_STR("Implements the 'ignore' error handling, which " ++ "ignores malformed data and continues.") + } + }, + { +@@ -973,7 +977,9 @@ + { + "replace_errors", + replace_errors, +- METH_O ++ METH_O, ++ PyDoc_STR("Implements the 'replace' error handling, which " ++ "replaces malformed data with a replacement marker.") + } + }, + { +@@ -981,7 +987,10 @@ + { + "xmlcharrefreplace_errors", + xmlcharrefreplace_errors, +- METH_O ++ METH_O, ++ PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " ++ "which replaces an unencodable character with the " ++ "appropriate XML character reference.") + } + }, + { +@@ -989,7 +998,10 @@ + { + "backslashreplace_errors", + backslashreplace_errors, +- METH_O ++ METH_O, ++ PyDoc_STR("Implements the 'backslashreplace' error handling, " ++ "which replaces an unencodable character with a " ++ "backslashed escape sequence.") + } + }, + { +Index: Python/ceval.c +=================================================================== +--- Python/ceval.c (.../tags/r311) (Revision 76056) ++++ Python/ceval.c (.../branches/release31-maint) (Revision 76056) +@@ -51,11 +51,29 @@ + ((long*)(v))[1] = tb; + } + +-#else /* this is for linux/x86 (and probably any other GCC/x86 combo) */ ++#elif defined(__i386__) + ++/* this is for linux/x86 (and probably any other GCC/x86 combo) */ ++ + #define READ_TIMESTAMP(val) \ + __asm__ __volatile__("rdtsc" : "=A" (val)) + ++#elif defined(__x86_64__) ++ ++/* for gcc/x86_64, the "A" constraint in DI mode means *either* rax *or* rdx; ++ not edx:eax as it does for i386. Since rdtsc puts its result in edx:eax ++ even in 64-bit mode, we need to use "a" and "d" for the lower and upper ++ 32-bit pieces of the result. */ ++ ++#define READ_TIMESTAMP(val) \ ++ __asm__ __volatile__("rdtsc" : \ ++ "=a" (((int*)&(val))[0]), "=d" (((int*)&(val))[1])); ++ ++ ++#else ++ ++#error "Don't know how to implement timestamp counter for this architecture" ++ + #endif + + void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, +Index: Python/ast.c +=================================================================== +--- Python/ast.c (.../tags/r311) (Revision 76056) ++++ Python/ast.c (.../branches/release31-maint) (Revision 76056) +@@ -2105,6 +2105,19 @@ + return NULL; + if(!set_context(c, expr1, Store, ch)) + return NULL; ++ /* set_context checks that most expressions are not the left side. ++ Augmented assignments can only have a name, a subscript, or an ++ attribute on the left, though, so we have to explicitly check for ++ those. */ ++ switch (expr1->kind) { ++ case Name_kind: ++ case Attribute_kind: ++ case Subscript_kind: ++ break; ++ default: ++ ast_error(ch, "illegal expression for augmented assignment"); ++ return NULL; ++ } + + ch = CHILD(n, 2); + if (TYPE(ch) == testlist) +@@ -3204,10 +3217,11 @@ + u = NULL; + } else { + /* check for integer overflow */ +- if (len > PY_SIZE_MAX / 4) ++ if (len > PY_SIZE_MAX / 6) + return NULL; +- /* "\XX" may become "\u005c\uHHLL" (12 bytes) */ +- u = PyBytes_FromStringAndSize((char *)NULL, len * 4); ++ /* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5 ++ "\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */ ++ u = PyBytes_FromStringAndSize((char *)NULL, len * 6); + if (u == NULL) + return NULL; + p = buf = PyBytes_AsString(u); +@@ -3224,20 +3238,24 @@ + PyObject *w; + char *r; + Py_ssize_t rn, i; +- w = decode_utf8(c, &s, end, "utf-16-be"); ++ w = decode_utf8(c, &s, end, "utf-32-be"); + if (w == NULL) { + Py_DECREF(u); + return NULL; + } + r = PyBytes_AS_STRING(w); + rn = Py_SIZE(w); +- assert(rn % 2 == 0); +- for (i = 0; i < rn; i += 2) { +- sprintf(p, "\\u%02x%02x", ++ assert(rn % 4 == 0); ++ for (i = 0; i < rn; i += 4) { ++ sprintf(p, "\\U%02x%02x%02x%02x", + r[i + 0] & 0xFF, +- r[i + 1] & 0xFF); +- p += 6; ++ r[i + 1] & 0xFF, ++ r[i + 2] & 0xFF, ++ r[i + 3] & 0xFF); ++ p += 10; + } ++ /* Should be impossible to overflow */ ++ assert(p - buf <= Py_SIZE(u)); + Py_DECREF(w); + } else { + *p++ = *s++; +Index: Python/pythonrun.c +=================================================================== +--- Python/pythonrun.c (.../tags/r311) (Revision 76056) ++++ Python/pythonrun.c (.../branches/release31-maint) (Revision 76056) +@@ -18,6 +18,7 @@ + #include "eval.h" + #include "marshal.h" + #include "osdefs.h" ++#include "abstract.h" + + #ifdef HAVE_SIGNAL_H + #include +@@ -66,6 +67,7 @@ + static void err_input(perrdetail *); + static void initsigs(void); + static void call_py_exitfuncs(void); ++static void wait_for_thread_shutdown(void); + static void call_ll_exitfuncs(void); + extern void _PyUnicode_Init(void); + extern void _PyUnicode_Fini(void); +@@ -363,6 +365,8 @@ + if (!initialized) + return; + ++ wait_for_thread_shutdown(); ++ + /* The interpreter is still entirely intact at this point, and the + * exit funcs may be relying on that. In particular, if some thread + * or exit func is still waiting to do an import, the import machinery +@@ -2059,6 +2063,34 @@ + PyErr_Clear(); + } + ++/* Wait until threading._shutdown completes, provided ++ the threading module was imported in the first place. ++ The shutdown routine will wait until all non-daemon ++ "threading" threads have completed. */ ++static void ++wait_for_thread_shutdown(void) ++{ ++#ifdef WITH_THREAD ++ PyObject *result; ++ PyThreadState *tstate = PyThreadState_GET(); ++ PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, ++ "threading"); ++ if (threading == NULL) { ++ /* threading not imported */ ++ PyErr_Clear(); ++ return; ++ } ++ result = PyObject_CallMethod(threading, "_shutdown", ""); ++ if (result == NULL) { ++ PyErr_WriteUnraisable(threading); ++ } ++ else { ++ Py_DECREF(result); ++ } ++ Py_DECREF(threading); ++#endif ++} ++ + #define NEXITFUNCS 32 + static void (*exitfuncs[NEXITFUNCS])(void); + static int nexitfuncs = 0; +Index: Python/formatter_unicode.c +=================================================================== +--- Python/formatter_unicode.c (.../tags/r311) (Revision 76056) ++++ Python/formatter_unicode.c (.../branches/release31-maint) (Revision 76056) +@@ -9,6 +9,8 @@ + #define FORMAT_STRING _PyUnicode_FormatAdvanced + #define FORMAT_LONG _PyLong_FormatAdvanced + #define FORMAT_FLOAT _PyFloat_FormatAdvanced ++#ifndef WITHOUT_COMPLEX + #define FORMAT_COMPLEX _PyComplex_FormatAdvanced ++#endif + + #include "../Objects/stringlib/formatter.h" +Index: Python/import.c +=================================================================== +--- Python/import.c (.../tags/r311) (Revision 76056) ++++ Python/import.c (.../branches/release31-maint) (Revision 76056) +@@ -261,8 +261,8 @@ + static long import_lock_thread = -1; + static int import_lock_level = 0; + +-static void +-lock_import(void) ++void ++_PyImport_AcquireLock(void) + { + long me = PyThread_get_thread_ident(); + if (me == -1) +@@ -286,8 +286,8 @@ + import_lock_level = 1; + } + +-static int +-unlock_import(void) ++int ++_PyImport_ReleaseLock(void) + { + long me = PyThread_get_thread_ident(); + if (me == -1 || import_lock == NULL) +@@ -302,23 +302,16 @@ + return 1; + } + +-/* This function is called from PyOS_AfterFork to ensure that newly +- created child processes do not share locks with the parent. */ ++/* This function used to be called from PyOS_AfterFork to ensure that newly ++ created child processes do not share locks with the parent, but for some ++ reason only on AIX systems. Instead of re-initializing the lock, we now ++ acquire the import lock around fork() calls. */ + + void + _PyImport_ReInitLock(void) + { +-#ifdef _AIX +- if (import_lock != NULL) +- import_lock = PyThread_allocate_lock(); +-#endif + } + +-#else +- +-#define lock_import() +-#define unlock_import() 0 +- + #endif + + static PyObject * +@@ -335,7 +328,7 @@ + imp_acquire_lock(PyObject *self, PyObject *noargs) + { + #ifdef WITH_THREAD +- lock_import(); ++ _PyImport_AcquireLock(); + #endif + Py_INCREF(Py_None); + return Py_None; +@@ -345,7 +338,7 @@ + imp_release_lock(PyObject *self, PyObject *noargs) + { + #ifdef WITH_THREAD +- if (unlock_import() < 0) { ++ if (_PyImport_ReleaseLock() < 0) { + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); + return NULL; +@@ -2200,9 +2193,9 @@ + PyObject *fromlist, int level) + { + PyObject *result; +- lock_import(); ++ _PyImport_AcquireLock(); + result = import_module_level(name, globals, locals, fromlist, level); +- if (unlock_import() < 0) { ++ if (_PyImport_ReleaseLock() < 0) { + Py_XDECREF(result); + PyErr_SetString(PyExc_RuntimeError, + "not holding the import lock"); +Index: Python/marshal.c +=================================================================== +--- Python/marshal.c (.../tags/r311) (Revision 76056) ++++ Python/marshal.c (.../branches/release31-maint) (Revision 76056) +@@ -553,7 +553,7 @@ + r_PyLong(RFILE *p) + { + PyLongObject *ob; +- int size, i, j, md; ++ int size, i, j, md, shorts_in_top_digit; + long n; + digit d; + +@@ -566,7 +566,8 @@ + return NULL; + } + +- size = 1 + (ABS(n)-1) / PyLong_MARSHAL_RATIO; ++ size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; ++ shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; + ob = _PyLong_New(size); + if (ob == NULL) + return NULL; +@@ -583,12 +584,21 @@ + ob->ob_digit[i] = d; + } + d = 0; +- for (j=0; j < (ABS(n)-1)%PyLong_MARSHAL_RATIO + 1; j++) { ++ for (j=0; j < shorts_in_top_digit; j++) { + md = r_short(p); + if (md < 0 || md > PyLong_MARSHAL_BASE) + goto bad_digit; ++ /* topmost marshal digit should be nonzero */ ++ if (md == 0 && j == shorts_in_top_digit - 1) { ++ Py_DECREF(ob); ++ PyErr_SetString(PyExc_ValueError, ++ "bad marshal data (unnormalized long data)"); ++ return NULL; ++ } + d += (digit)md << j*PyLong_MARSHAL_SHIFT; + } ++ /* top digit should be nonzero, else the resulting PyLong won't be ++ normalized */ + ob->ob_digit[size-1] = d; + return (PyObject *)ob; + bad_digit: +Index: Python/compile.c +=================================================================== +--- Python/compile.c (.../tags/r311) (Revision 76056) ++++ Python/compile.c (.../branches/release31-maint) (Revision 76056) +@@ -909,10 +909,8 @@ + { + PyObject *t, *v; + Py_ssize_t arg; +- unsigned char *p, *q; +- Py_complex z; ++ unsigned char *p; + double d; +- int real_part_zero, imag_part_zero; + + /* necessary to make sure types aren't coerced (e.g., int and long) */ + /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ +@@ -927,7 +925,11 @@ + else + t = PyTuple_Pack(2, o, o->ob_type); + } ++#ifndef WITHOUT_COMPLEX + else if (PyComplex_Check(o)) { ++ Py_complex z; ++ int real_part_zero, imag_part_zero; ++ unsigned char *q; + /* complex case is even messier: we need to make complex(x, + 0.) different from complex(x, -0.) and complex(0., y) + different from complex(-0., y), for any x and y. In +@@ -957,6 +959,7 @@ + t = PyTuple_Pack(2, o, o->ob_type); + } + } ++#endif /* WITHOUT_COMPLEX */ + else { + t = PyTuple_Pack(2, o, o->ob_type); + } +Index: Include/py_curses.h +=================================================================== +--- Include/py_curses.h (.../tags/r311) (Revision 76056) ++++ Include/py_curses.h (.../branches/release31-maint) (Revision 76056) +@@ -10,8 +10,13 @@ + #ifdef _BSD_WCHAR_T_DEFINED_ + #define _WCHAR_T + #endif +-#endif + ++/* the following define is necessary for OS X 10.6; without it, the ++ Apple-supplied ncurses.h sets NCURSES_OPAQUE to 1, and then Python ++ can't get at the WINDOW flags field. */ ++#define NCURSES_OPAQUE 0 ++#endif /* __APPLE__ */ ++ + #ifdef __FreeBSD__ + /* + ** On FreeBSD, [n]curses.h and stdlib.h/wchar.h use different guards +Index: Include/patchlevel.h +=================================================================== +--- Include/patchlevel.h (.../tags/r311) (Revision 76056) ++++ Include/patchlevel.h (.../branches/release31-maint) (Revision 76056) +@@ -23,7 +23,7 @@ + #define PY_RELEASE_SERIAL 0 + + /* Version as a string */ +-#define PY_VERSION "3.1.1" ++#define PY_VERSION "3.1.1+" + /*--end constants--*/ + + /* Subversion Revision number of this file (not of the repository) */ +Index: Include/import.h +=================================================================== +--- Include/import.h (.../tags/r311) (Revision 76056) ++++ Include/import.h (.../branches/release31-maint) (Revision 76056) +@@ -27,6 +27,14 @@ + PyAPI_FUNC(void) PyImport_Cleanup(void); + PyAPI_FUNC(int) PyImport_ImportFrozenModule(char *); + ++#ifdef WITH_THREAD ++PyAPI_FUNC(void) _PyImport_AcquireLock(void); ++PyAPI_FUNC(int) _PyImport_ReleaseLock(void); ++#else ++#define _PyImport_AcquireLock() ++#define _PyImport_ReleaseLock() 1 ++#endif ++ + PyAPI_FUNC(struct filedescr *) _PyImport_FindModule( + const char *, PyObject *, char *, size_t, FILE **, PyObject **); + PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr *); +Index: Demo/scripts/ftpstats.py +=================================================================== +--- Demo/scripts/ftpstats.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/ftpstats.py (.../branches/release31-maint) (Revision 76056) +@@ -1,142 +0,0 @@ +-#! /usr/bin/env python +- +-# Extract statistics from ftp daemon log. +- +-# Usage: +-# ftpstats [-m maxitems] [-s search] [file] +-# -m maxitems: restrict number of items in "top-N" lists, default 25. +-# -s string: restrict statistics to lines containing this string. +-# Default file is /usr/adm/ftpd; a "-" means read standard input. +- +-# The script must be run on the host where the ftp daemon runs. +-# (At CWI this is currently buizerd.) +- +-import os +-import sys +-import re +-import string +-import getopt +- +-pat = '^([a-zA-Z0-9 :]*)!(.*)!(.*)!([<>].*)!([0-9]+)!([0-9]+)$' +-prog = re.compile(pat) +- +-def main(): +- maxitems = 25 +- search = None +- try: +- opts, args = getopt.getopt(sys.argv[1:], 'm:s:') +- except getopt.error as msg: +- print(msg) +- print('usage: ftpstats [-m maxitems] [file]') +- sys.exit(2) +- for o, a in opts: +- if o == '-m': +- maxitems = string.atoi(a) +- if o == '-s': +- search = a +- file = '/usr/adm/ftpd' +- if args: file = args[0] +- if file == '-': +- f = sys.stdin +- else: +- try: +- f = open(file, 'r') +- except IOError as msg: +- print(file, ':', msg) +- sys.exit(1) +- bydate = {} +- bytime = {} +- byfile = {} +- bydir = {} +- byhost = {} +- byuser = {} +- bytype = {} +- lineno = 0 +- try: +- while 1: +- line = f.readline() +- if not line: break +- lineno = lineno + 1 +- if search and string.find(line, search) < 0: +- continue +- if prog.match(line) < 0: +- print('Bad line', lineno, ':', repr(line)) +- continue +- items = prog.group(1, 2, 3, 4, 5, 6) +- (logtime, loguser, loghost, logfile, logbytes, +- logxxx2) = items +-## print logtime +-## print '-->', loguser +-## print '--> -->', loghost +-## print '--> --> -->', logfile +-## print '--> --> --> -->', logbytes +-## print '--> --> --> --> -->', logxxx2 +-## for i in logtime, loghost, logbytes, logxxx2: +-## if '!' in i: print '???', i +- add(bydate, logtime[-4:] + ' ' + logtime[:6], items) +- add(bytime, logtime[7:9] + ':00-59', items) +- direction, logfile = logfile[0], logfile[1:] +- # The real path probably starts at the last //... +- while 1: +- i = string.find(logfile, '//') +- if i < 0: break +- logfile = logfile[i+1:] +- add(byfile, logfile + ' ' + direction, items) +- logdir = os.path.dirname(logfile) +-## logdir = os.path.normpath(logdir) + '/.' +- while 1: +- add(bydir, logdir + ' ' + direction, items) +- dirhead = os.path.dirname(logdir) +- if dirhead == logdir: break +- logdir = dirhead +- add(byhost, loghost, items) +- add(byuser, loguser, items) +- add(bytype, direction, items) +- except KeyboardInterrupt: +- print('Interrupted at line', lineno) +- show(bytype, 'by transfer direction', maxitems) +- show(bydir, 'by directory', maxitems) +- show(byfile, 'by file', maxitems) +- show(byhost, 'by host', maxitems) +- show(byuser, 'by user', maxitems) +- showbar(bydate, 'by date') +- showbar(bytime, 'by time of day') +- +-def showbar(dict, title): +- n = len(title) +- print('='*((70-n)//2), title, '='*((71-n)//2)) +- list = [] +- for key in sorted(dict.keys()): +- n = len(str(key)) +- list.append((len(dict[key]), key)) +- maxkeylength = 0 +- maxcount = 0 +- for count, key in list: +- maxkeylength = max(maxkeylength, len(key)) +- maxcount = max(maxcount, count) +- maxbarlength = 72 - maxkeylength - 7 +- for count, key in list: +- barlength = int(round(maxbarlength*float(count)/maxcount)) +- bar = '*'*barlength +- print('%5d %-*s %s' % (count, maxkeylength, key, bar)) +- +-def show(dict, title, maxitems): +- if len(dict) > maxitems: +- title = title + ' (first %d)'%maxitems +- n = len(title) +- print('='*((70-n)//2), title, '='*((71-n)//2)) +- list = [] +- for key in dict.keys(): +- list.append((-len(dict[key]), key)) +- list.sort() +- for count, key in list[:maxitems]: +- print('%5d %s' % (-count, key)) +- +-def add(dict, key, item): +- if key in dict: +- dict[key].append(item) +- else: +- dict[key] = [item] +- +-if __name__ == "__main__": +- main() +Index: Demo/scripts/mkrcs.py +=================================================================== +--- Demo/scripts/mkrcs.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/mkrcs.py (.../branches/release31-maint) (Revision 76056) +@@ -1,61 +0,0 @@ +-#! /usr/bin/env python +- +-# A rather specialized script to make sure that a symbolic link named +-# RCS exists pointing to a real RCS directory in a parallel tree +-# referenced as RCStree in an ancestor directory. +-# (I use this because I like my RCS files to reside on a physically +-# different machine). +- +-import os +- +-def main(): +- rcstree = 'RCStree' +- rcs = 'RCS' +- if os.path.islink(rcs): +- print('%r is a symlink to %r' % (rcs, os.readlink(rcs))) +- return +- if os.path.isdir(rcs): +- print('%r is an ordinary directory' % (rcs,)) +- return +- if os.path.exists(rcs): +- print('%r is a file?!?!' % (rcs,)) +- return +- # +- p = os.getcwd() +- up = '' +- down = '' +- # Invariants: +- # (1) join(p, down) is the current directory +- # (2) up is the same directory as p +- # Ergo: +- # (3) join(up, down) is the current directory +- #print 'p =', repr(p) +- while not os.path.isdir(os.path.join(p, rcstree)): +- head, tail = os.path.split(p) +- #print 'head = %r; tail = %r' % (head, tail) +- if not tail: +- print('Sorry, no ancestor dir contains %r' % (rcstree,)) +- return +- p = head +- up = os.path.join(os.pardir, up) +- down = os.path.join(tail, down) +- #print 'p = %r; up = %r; down = %r' % (p, up, down) +- there = os.path.join(up, rcstree) +- there = os.path.join(there, down) +- there = os.path.join(there, rcs) +- if os.path.isdir(there): +- print('%r already exists' % (there, )) +- else: +- print('making %r' % (there,)) +- makedirs(there) +- print('making symlink %r -> %r' % (rcs, there)) +- os.symlink(there, rcs) +- +-def makedirs(p): +- if not os.path.isdir(p): +- head, tail = os.path.split(p) +- makedirs(head) +- os.mkdir(p, 0o777) +- +-if __name__ == "__main__": +- main() +Index: Demo/scripts/markov.py +=================================================================== +--- Demo/scripts/markov.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/markov.py (.../branches/release31-maint) (Revision 76056) +@@ -5,11 +5,10 @@ + self.histsize = histsize + self.choice = choice + self.trans = {} ++ + def add(self, state, next): +- if state not in self.trans: +- self.trans[state] = [next] +- else: +- self.trans[state].append(next) ++ self.trans.setdefault(state, []).append(next) ++ + def put(self, seq): + n = self.histsize + add = self.add +@@ -17,26 +16,29 @@ + for i in range(len(seq)): + add(seq[max(0, i-n):i], seq[i:i+1]) + add(seq[len(seq)-n:], None) ++ + def get(self): + choice = self.choice + trans = self.trans + n = self.histsize + seq = choice(trans[None]) +- while 1: ++ while True: + subseq = seq[max(0, len(seq)-n):] + options = trans[subseq] + next = choice(options) +- if not next: break +- seq = seq + next ++ if not next: ++ break ++ seq += next + return seq + ++ + def test(): +- import sys, string, random, getopt ++ import sys, random, getopt + args = sys.argv[1:] + try: +- opts, args = getopt.getopt(args, '0123456789cdw') ++ opts, args = getopt.getopt(args, '0123456789cdwq') + except getopt.error: +- print('Usage: markov [-#] [-cddqw] [file] ...') ++ print('Usage: %s [-#] [-cddqw] [file] ...' % sys.argv[0]) + print('Options:') + print('-#: 1-digit history size (default 2)') + print('-c: characters (default)') +@@ -49,16 +51,19 @@ + print('exactly one space separating words.') + print('Output consists of paragraphs separated by blank') + print('lines, where lines are no longer than 72 characters.') ++ sys.exit(2) + histsize = 2 +- do_words = 0 ++ do_words = False + debug = 1 + for o, a in opts: +- if '-0' <= o <= '-9': histsize = eval(o[1:]) +- if o == '-c': do_words = 0 +- if o == '-d': debug = debug + 1 ++ if '-0' <= o <= '-9': histsize = int(o[1:]) ++ if o == '-c': do_words = False ++ if o == '-d': debug += 1 + if o == '-q': debug = 0 +- if o == '-w': do_words = 1 +- if not args: args = ['-'] ++ if o == '-w': do_words = True ++ if not args: ++ args = ['-'] ++ + m = Markov(histsize, random.choice) + try: + for filename in args: +@@ -72,13 +77,15 @@ + if debug: print('processing', filename, '...') + text = f.read() + f.close() +- paralist = string.splitfields(text, '\n\n') ++ paralist = text.split('\n\n') + for para in paralist: + if debug > 1: print('feeding ...') +- words = string.split(para) ++ words = para.split() + if words: +- if do_words: data = tuple(words) +- else: data = string.joinfields(words, ' ') ++ if do_words: ++ data = tuple(words) ++ else: ++ data = ' '.join(words) + m.put(data) + except KeyboardInterrupt: + print('Interrupted -- continue with data read so far') +@@ -86,16 +93,19 @@ + print('No valid input files') + return + if debug: print('done.') ++ + if debug > 1: + for key in m.trans.keys(): + if key is None or len(key) < histsize: + print(repr(key), m.trans[key]) + if histsize == 0: print(repr(''), m.trans['']) + print() +- while 1: ++ while True: + data = m.get() +- if do_words: words = data +- else: words = string.split(data) ++ if do_words: ++ words = data ++ else: ++ words = data.split() + n = 0 + limit = 72 + for w in words: +@@ -103,15 +113,9 @@ + print() + n = 0 + print(w, end=' ') +- n = n + len(w) + 1 ++ n += len(w) + 1 + print() + print() + +-def tuple(list): +- if len(list) == 0: return () +- if len(list) == 1: return (list[0],) +- i = len(list)//2 +- return tuple(list[:i]) + tuple(list[i:]) +- + if __name__ == "__main__": + test() +Index: Demo/scripts/queens.py +=================================================================== +--- Demo/scripts/queens.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/queens.py (.../branches/release31-maint) (Revision 76056) +@@ -19,8 +19,8 @@ + + def reset(self): + n = self.n +- self.y = [None]*n # Where is the queen in column x +- self.row = [0]*n # Is row[y] safe? ++ self.y = [None] * n # Where is the queen in column x ++ self.row = [0] * n # Is row[y] safe? + self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? + self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? + self.nfound = 0 # Instrumentation +@@ -50,7 +50,7 @@ + self.up[x-y] = 0 + self.down[x+y] = 0 + +- silent = 0 # If set, count solutions only ++ silent = 0 # If true, count solutions only + + def display(self): + self.nfound = self.nfound + 1 +Index: Demo/scripts/lpwatch.py +=================================================================== +--- Demo/scripts/lpwatch.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/lpwatch.py (.../branches/release31-maint) (Revision 76056) +@@ -3,10 +3,9 @@ + # Watch line printer queue(s). + # Intended for BSD 4.3 lpq. + +-import posix ++import os + import sys + import time +-import string + + DEF_PRINTER = 'psc' + DEF_DELAY = 10 +@@ -14,94 +13,87 @@ + def main(): + delay = DEF_DELAY # XXX Use getopt() later + try: +- thisuser = posix.environ['LOGNAME'] ++ thisuser = os.environ['LOGNAME'] + except: +- thisuser = posix.environ['USER'] ++ thisuser = os.environ['USER'] + printers = sys.argv[1:] + if printers: + # Strip '-P' from printer names just in case + # the user specified it... +- for i in range(len(printers)): +- if printers[i][:2] == '-P': +- printers[i] = printers[i][2:] ++ for i, name in enumerate(printers): ++ if name[:2] == '-P': ++ printers[i] = name[2:] + else: +- if 'PRINTER' in posix.environ: +- printers = [posix.environ['PRINTER']] ++ if 'PRINTER' in os.environ: ++ printers = [os.environ['PRINTER']] + else: + printers = [DEF_PRINTER] +- # +- clearhome = posix.popen('clear', 'r').read() +- # +- while 1: ++ ++ clearhome = os.popen('clear', 'r').read() ++ ++ while True: + text = clearhome + for name in printers: +- text = text + makestatus(name, thisuser) + '\n' ++ text += makestatus(name, thisuser) + '\n' + print(text) + time.sleep(delay) + + def makestatus(name, thisuser): +- pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r') ++ pipe = os.popen('lpq -P' + name + ' 2>&1', 'r') + lines = [] + users = {} + aheadbytes = 0 + aheadjobs = 0 +- userseen = 0 ++ userseen = False + totalbytes = 0 + totaljobs = 0 +- while 1: +- line = pipe.readline() +- if not line: break +- fields = string.split(line) ++ for line in pipe: ++ fields = line.split() + n = len(fields) + if len(fields) >= 6 and fields[n-1] == 'bytes': +- rank = fields[0] +- user = fields[1] +- job = fields[2] ++ rank, user, job = fields[0:3] + files = fields[3:-2] +- bytes = eval(fields[n-2]) ++ bytes = int(fields[n-2]) + if user == thisuser: +- userseen = 1 ++ userseen = True + elif not userseen: +- aheadbytes = aheadbytes + bytes +- aheadjobs = aheadjobs + 1 +- totalbytes = totalbytes + bytes +- totaljobs = totaljobs + 1 +- if user in users: +- ujobs, ubytes = users[user] +- else: +- ujobs, ubytes = 0, 0 +- ujobs = ujobs + 1 +- ubytes = ubytes + bytes ++ aheadbytes += bytes ++ aheadjobs += 1 ++ totalbytes += bytes ++ totaljobs += 1 ++ ujobs, ubytes = users.get(user, (0, 0)) ++ ujobs += 1 ++ ubytes += bytes + users[user] = ujobs, ubytes + else: + if fields and fields[0] != 'Rank': +- line = string.strip(line) ++ line = line.strip() + if line == 'no entries': + line = name + ': idle' + elif line[-22:] == ' is ready and printing': + line = name + lines.append(line) +- # ++ + if totaljobs: +- line = '%d K' % ((totalbytes+1023)//1024) ++ line = '%d K' % ((totalbytes+1023) // 1024) + if totaljobs != len(users): +- line = line + ' (%d jobs)' % totaljobs ++ line += ' (%d jobs)' % totaljobs + if len(users) == 1: +- line = line + ' for %s' % (list(users.keys())[0],) ++ line += ' for %s' % next(iter(users)) + else: +- line = line + ' for %d users' % len(users) ++ line += ' for %d users' % len(users) + if userseen: + if aheadjobs == 0: +- line = line + ' (%s first)' % thisuser ++ line += ' (%s first)' % thisuser + else: +- line = line + ' (%d K before %s)' % ( +- (aheadbytes+1023)//1024, thisuser) ++ line += ' (%d K before %s)' % ( ++ (aheadbytes+1023) // 1024, thisuser) + lines.append(line) +- # ++ + sts = pipe.close() + if sts: + lines.append('lpq exit status %r' % (sts,)) +- return string.joinfields(lines, ': ') ++ return ': '.join(lines) + + if __name__ == "__main__": + try: +Index: Demo/scripts/script.py +=================================================================== +--- Demo/scripts/script.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/script.py (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,5 @@ + #! /usr/bin/env python ++ + # script.py -- Make typescript of terminal session. + # Usage: + # -a Append to typescript. +@@ -6,28 +7,36 @@ + # Author: Steen Lumholt. + + +-import os, time, sys ++import os, time, sys, getopt + import pty + + def read(fd): + data = os.read(fd, 1024) +- file.write(data) ++ script.write(data) + return data + + shell = 'sh' + filename = 'typescript' +-mode = 'w' ++mode = 'wb' + if 'SHELL' in os.environ: + shell = os.environ['SHELL'] +-if '-a' in sys.argv: +- mode = 'a' +-if '-p' in sys.argv: +- shell = 'python' + +-file = open(filename, mode) ++try: ++ opts, args = getopt.getopt(sys.argv[1:], 'ap') ++except getopt.error as msg: ++ print('%s: %s' % (sys.argv[0], msg)) ++ sys.exit(2) + ++for o, a in opts: ++ if o == '-a': ++ mode = 'ab' ++ elif o == '-p': ++ shell = 'python' ++ ++script = open(filename, mode) ++ + sys.stdout.write('Script started, file is %s\n' % filename) +-file.write('Script started on %s\n' % time.ctime(time.time())) ++script.write(('Script started on %s\n' % time.ctime(time.time())).encode()) + pty.spawn(shell, read) +-file.write('Script done on %s\n' % time.ctime(time.time())) ++script.write(('Script done on %s\n' % time.ctime(time.time())).encode()) + sys.stdout.write('Script done, file is %s\n' % filename) +Index: Demo/scripts/README +=================================================================== +--- Demo/scripts/README (.../tags/r311) (Revision 76056) ++++ Demo/scripts/README (.../branches/release31-maint) (Revision 76056) +@@ -5,15 +5,14 @@ + beer.py Print the classic 'bottles of beer' list. + eqfix.py Fix .py files to use the correct equality test operator + fact.py Factorize numbers +-find-uname.py Search for Unicode characters using regexps. ++find-uname.py Search for Unicode characters using regexps + from.py Summarize mailbox +-ftpstats.py Summarize ftp daemon log file + lpwatch.py Watch BSD line printer queues + makedir.py Like mkdir -p + markov.py Markov chain simulation of words or characters +-mboxconvvert.py Convert MH or MMDF mailboxes to unix mailbox format +-mkrcs.py Fix symlinks named RCS into parallel tree +-morse.py Produce morse code (audible or on AIFF file) ++mboxconvert.py Convert MH or MMDF mailboxes to unix mailbox format ++morse.py Produce morse code (as an AIFF file) ++newslist.py List all newsgroups on a NNTP server as HTML pages + pi.py Print all digits of pi -- given enough time and memory + pp.py Emulate some Perl command line options + primes.py Print prime numbers +Index: Demo/scripts/newslist.py +=================================================================== +--- Demo/scripts/newslist.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/newslist.py (.../branches/release31-maint) (Revision 76056) +@@ -32,22 +32,22 @@ + # fraser@europarc.xerox.com qs101@cl.cam.ac.uk + # # + ####################################################################### +-import sys,nntplib, string, marshal, time, os, posix, string ++import sys, nntplib, marshal, time, os + + ####################################################################### + # Check these variables before running! # + + # Top directory. + # Filenames which don't start with / are taken as being relative to this. +-topdir='/anfs/qsbigdisc/web/html/newspage' ++topdir = os.path.expanduser('~/newspage') + + # The name of your NNTP host + # eg. + # newshost = 'nntp-serv.cl.cam.ac.uk' + # or use following to get the name from the NNTPSERVER environment + # variable: +-# newshost = posix.environ['NNTPSERVER'] +-newshost = 'nntp-serv.cl.cam.ac.uk' ++# newshost = os.environ['NNTPSERVER'] ++newshost = 'news.example.com' + + # The filename for a local cache of the newsgroup list + treefile = 'grouptree' +@@ -81,7 +81,7 @@ + # pagelinkicon can contain html to put an icon after links to + # further pages. This helps to make important links stand out. + # Set to '' if not wanted, or '...' is quite a good one. +-pagelinkicon='... ' ++pagelinkicon = '... ' + + # --------------------------------------------------------------------- + # Less important personal preferences: +@@ -120,7 +120,7 @@ + def addtotree(tree, groups): + print('Updating tree...') + for i in groups: +- parts = string.splitfields(i,'.') ++ parts = i.split('.') + makeleaf(tree, parts) + + # Makeleaf makes a leaf and the branch leading to it if necessary +@@ -141,34 +141,38 @@ + # to those groups beginning with . + + def createpage(root, tree, p): +- filename = os.path.join(pagedir,root+'.html') ++ filename = os.path.join(pagedir, root+'.html') + if root == rootpage: + detail = '' + else: + detail = ' under ' + root +- f = open(filename,'w') +- # f.write('Content-Type: text/html\n') +- f.write('Newsgroups available' + detail + '\n') +- f.write('

Newsgroups available' + detail +'

\n') +- f.write('Back to top level

\n') +- printtree(f,tree,0,p) +- f.write('This page automatically created by \'newslist\' v. '+rcsrev+'.') +- f.write(time.ctime(time.time()) + '

') +- f.close() ++ with open(filename, 'w') as f: ++ # f.write('Content-Type: text/html\n') ++ f.write('\n\n') ++ f.write('Newsgroups available%s\n' % detail) ++ f.write('\n\n') ++ f.write('

Newsgroups available%s

\n' % detail) ++ f.write('Back to top level

\n' % ++ (httppref, rootpage)) ++ printtree(f, tree, 0, p) ++ f.write('\n

') ++ f.write("This page automatically created by 'newslist' v. %s." % ++ rcsrev) ++ f.write(time.ctime(time.time()) + '\n') ++ f.write('\n\n') + + # Printtree prints the groups as a bulleted list. Groups with + # more than subgroups will be put on a separate page. + # Other sets of subgroups are just indented. + + def printtree(f, tree, indent, p): +- global desc + l = len(tree) + +- if l > sublistsize and indent>0: ++ if l > sublistsize and indent > 0: + # Create a new page and a link to it +- f.write('

  • ') +- f.write(p[1:]+'.*') +- f.write(''+pagelinkicon+'\n') ++ f.write('
  • ' % (httppref, p[1:])) ++ f.write(p[1:] + '.*') ++ f.write('%s\n' % pagelinkicon) + createpage(p[1:], tree, p) + return + +@@ -177,67 +181,64 @@ + if l > 1: + if indent > 0: + # Create a sub-list +- f.write('
  • '+p[1:]+'\n
      ') ++ f.write('
    • %s\n
        ' % p[1:]) + else: + # Create a main list +- f.write('
          ') ++ f.write('
            ') + indent = indent + 1 + + for i in kl: + if i == '.': + # Output a newsgroup +- f.write('
          • '+ p[1:] + ' ') ++ f.write('
          • %s ' % (p[1:], p[1:])) + if p[1:] in desc: +- f.write(' '+desc[p[1:]]+'\n') ++ f.write(' %s\n' % desc[p[1:]]) + else: + f.write('\n') + else: + # Output a hierarchy +- printtree(f,tree[i], indent, p+'.'+i) ++ printtree(f, tree[i], indent, p+'.'+i) + + if l > 1: +- f.write('\n
          ') ++ f.write('\n
        ') + + # Reading descriptions file --------------------------------------- + +-# This returns an array mapping group name to its description ++# This returns a dict mapping group name to its description + + def readdesc(descfile): + global desc +- + desc = {} + + if descfile == '': + return + + try: +- d = open(descfile, 'r') +- print('Reading descriptions...') +- except (IOError): ++ with open(descfile, 'r') as d: ++ print('Reading descriptions...') ++ for l in d: ++ bits = l.split() ++ try: ++ grp = bits[0] ++ dsc = ' '.join(bits[1:]) ++ if len(dsc) > 1: ++ desc[grp] = dsc ++ except IndexError: ++ pass ++ except IOError: + print('Failed to open description file ' + descfile) + return +- l = d.readline() +- while l != '': +- bits = string.split(l) +- try: +- grp = bits[0] +- dsc = string.join(bits[1:]) +- if len(dsc)>1: +- desc[grp] = dsc +- except (IndexError): +- pass +- l = d.readline() + + # Check that ouput directory exists, ------------------------------ + # and offer to create it if not + + def checkopdir(pagedir): + if not os.path.isdir(pagedir): +- print('Directory '+pagedir+' does not exist.') ++ print('Directory %s does not exist.' % pagedir) + print('Shall I create it for you? (y/n)') + if sys.stdin.readline()[0] == 'y': + try: +- os.mkdir(pagedir,0o777) ++ os.mkdir(pagedir, 0o777) + except: + print('Sorry - failed!') + sys.exit(1) +@@ -257,23 +258,21 @@ + print('If this is the first time you have run newslist, then') + print('use the -a option to create it.') + sys.exit(1) +- treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2]) ++ treedate = '%02d%02d%02d' % (treetime[0] % 100, treetime[1], treetime[2]) + try: +- dump = open(treefile,'r') +- tree = marshal.load(dump) +- dump.close() +- except (IOError): ++ with open(treefile, 'rb') as dump: ++ tree = marshal.load(dump) ++ except IOError: + print('Cannot open local group list ' + treefile) + return (tree, treedate) + + def writelocallist(treefile, tree): + try: +- dump = open(treefile,'w') +- groups = marshal.dump(tree,dump) +- dump.close() +- print('Saved list to '+treefile+'\n') ++ with open(treefile, 'wb') as dump: ++ groups = marshal.dump(tree, dump) ++ print('Saved list to %s\n' % treefile) + except: +- print('Sorry - failed to write to local group cache '+treefile) ++ print('Sorry - failed to write to local group cache', treefile) + print('Does it (or its directory) have the correct permissions?') + sys.exit(1) + +@@ -281,18 +280,18 @@ + + def getallgroups(server): + print('Getting list of all groups...') +- treedate='010101' ++ treedate = '010101' + info = server.list()[1] + groups = [] + print('Processing...') + if skipempty: + print('\nIgnoring following empty groups:') + for i in info: +- grpname = string.split(i[0])[0] +- if skipempty and string.atoi(i[1]) < string.atoi(i[2]): +- print(grpname+' ', end=' ') ++ grpname = i[0].split()[0] ++ if skipempty and int(i[1]) < int(i[2]): ++ print(grpname.decode() + ' ', end=' ') + else: +- groups.append(grpname) ++ groups.append(grpname.decode()) + print('\n') + if skipempty: + print('(End of empty groups)') +@@ -301,42 +300,39 @@ + # Return list of new groups on server ----------------------------- + + def getnewgroups(server, treedate): +- print('Getting list of new groups since start of '+treedate+'...', end=' ') +- info = server.newgroups(treedate,'000001')[1] ++ print('Getting list of new groups since start of %s...' % treedate, end=' ') ++ info = server.newgroups(treedate, '000001')[1] + print('got %d.' % len(info)) + print('Processing...', end=' ') + groups = [] + for i in info: +- grpname = string.split(i)[0] +- groups.append(grpname) ++ grpname = i.split()[0] ++ groups.append(grpname.decode()) + print('Done') + return groups + + # Now the main program -------------------------------------------- + + def main(): +- global desc ++ tree = {} + +- tree={} +- + # Check that the output directory exists + checkopdir(pagedir) + + try: +- print('Connecting to '+newshost+'...') ++ print('Connecting to %s...' % newshost) + if sys.version[0] == '0': + s = NNTP.init(newshost) + else: + s = NNTP(newshost) +- connected = 1 ++ connected = True + except (nntplib.error_temp, nntplib.error_perm) as x: + print('Error connecting to host:', x) + print('I\'ll try to use just the local list.') +- connected = 0 ++ connected = False + + # If -a is specified, read the full list of groups from server + if connected and len(sys.argv) > 1 and sys.argv[1] == '-a': +- + groups = getallgroups(s) + + # Otherwise just read the local file and then add +Index: Demo/scripts/pi.py +=================================================================== +--- Demo/scripts/pi.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/pi.py (.../branches/release31-maint) (Revision 76056) +@@ -12,7 +12,7 @@ + + def main(): + k, a, b, a1, b1 = 2, 4, 1, 12, 4 +- while 1: ++ while True: + # Next approximation + p, q, k = k*k, 2*k+1, k+1 + a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 +@@ -25,7 +25,6 @@ + + def output(d): + # Use write() to avoid spaces between the digits +- # Use str() to avoid the 'L' + sys.stdout.write(str(d)) + # Flush so the output is seen immediately + sys.stdout.flush() +Index: Demo/scripts/unbirthday.py +=================================================================== +--- Demo/scripts/unbirthday.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/unbirthday.py (.../branches/release31-maint) (Revision 76056) +@@ -9,35 +9,27 @@ + import time + import calendar + +-def raw_input(prompt): +- sys.stdout.write(prompt) +- sys.stdout.flush() +- return sys.stdin.readline() +- + def main(): +- # Note that the range checks below also check for bad types, +- # e.g. 3.14 or (). However syntactically invalid replies +- # will raise an exception. + if sys.argv[1:]: + year = int(sys.argv[1]) + else: + year = int(input('In which year were you born? ')) +- if 0<=year<100: ++ if 0 <= year < 100: + print("I'll assume that by", year, end=' ') + year = year + 1900 + print('you mean', year, 'and not the early Christian era') +- elif not (1850<=year<=2002): ++ elif not (1850 <= year <= time.localtime()[0]): + print("It's hard to believe you were born in", year) + return +- # ++ + if sys.argv[2:]: + month = int(sys.argv[2]) + else: + month = int(input('And in which month? (1-12) ')) +- if not (1<=month<=12): ++ if not (1 <= month <= 12): + print('There is no month numbered', month) + return +- # ++ + if sys.argv[3:]: + day = int(sys.argv[3]) + else: +@@ -46,36 +38,36 @@ + maxday = 29 + else: + maxday = calendar.mdays[month] +- if not (1<=day<=maxday): ++ if not (1 <= day <= maxday): + print('There are no', day, 'days in that month!') + return +- # ++ + bdaytuple = (year, month, day) + bdaydate = mkdate(bdaytuple) + print('You were born on', format(bdaytuple)) +- # ++ + todaytuple = time.localtime()[:3] + todaydate = mkdate(todaytuple) + print('Today is', format(todaytuple)) +- # ++ + if bdaytuple > todaytuple: + print('You are a time traveler. Go back to the future!') + return +- # ++ + if bdaytuple == todaytuple: + print('You were born today. Have a nice life!') + return +- # ++ + days = todaydate - bdaydate + print('You have lived', days, 'days') +- # ++ + age = 0 + for y in range(year, todaytuple[0] + 1): + if bdaytuple < (y, month, day) <= todaytuple: + age = age + 1 +- # ++ + print('You are', age, 'years old') +- # ++ + if todaytuple[1:] == bdaytuple[1:]: + print('Congratulations! Today is your', nth(age), 'birthday') + print('Yesterday was your', end=' ') +@@ -83,8 +75,8 @@ + print('Today is your', end=' ') + print(nth(days - age), 'unbirthday') + +-def format(xxx_todo_changeme): +- (year, month, day) = xxx_todo_changeme ++def format(date): ++ (year, month, day) = date + return '%d %s %d' % (day, calendar.month_name[month], year) + + def nth(n): +@@ -93,12 +85,12 @@ + if n == 3: return '3rd' + return '%dth' % n + +-def mkdate(xxx_todo_changeme1): +- # Januari 1st, in 0 A.D. is arbitrarily defined to be day 1, ++def mkdate(date): ++ # January 1st, in 0 A.D. is arbitrarily defined to be day 1, + # even though that day never actually existed and the calendar + # was different then... +- (year, month, day) = xxx_todo_changeme1 +- days = year*365 # years, roughly ++ (year, month, day) = date ++ days = year*365 # years, roughly + days = days + (year+3)//4 # plus leap years, roughly + days = days - (year+99)//100 # minus non-leap years every century + days = days + (year+399)//400 # plus leap years every 4 centirues +Index: Demo/scripts/beer.py +=================================================================== +--- Demo/scripts/beer.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/beer.py (.../branches/release31-maint) (Revision 76056) +@@ -1,14 +1,20 @@ + #! /usr/bin/env python ++ + # By GvR, demystified after a version by Fredrik Lundh. ++ + import sys ++ + n = 100 +-if sys.argv[1:]: n = int(sys.argv[1]) ++if sys.argv[1:]: ++ n = int(sys.argv[1]) ++ + def bottle(n): + if n == 0: return "no more bottles of beer" + if n == 1: return "one bottle of beer" + return str(n) + " bottles of beer" +-for i in range(n): +- print(bottle(n-i), "on the wall,") +- print(bottle(n-i) + ".") ++ ++for i in range(n, 0, -1): ++ print(bottle(i), "on the wall,") ++ print(bottle(i) + ".") + print("Take one down, pass it around,") +- print(bottle(n-i-1), "on the wall.") ++ print(bottle(i-1), "on the wall.") +Index: Demo/scripts/fact.py +=================================================================== +--- Demo/scripts/fact.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/fact.py (.../branches/release31-maint) (Revision 76056) +@@ -9,39 +9,41 @@ + from math import sqrt + + def fact(n): +- if n < 1: raise ValueError # fact() argument should be >= 1 +- if n == 1: return [] # special case ++ if n < 1: ++ raise ValueError('fact() argument should be >= 1') ++ if n == 1: ++ return [] # special case + res = [] +- # Treat even factors special, so we can use i = i+2 later +- while n%2 == 0: ++ # Treat even factors special, so we can use i += 2 later ++ while n % 2 == 0: + res.append(2) +- n = n//2 ++ n //= 2 + # Try odd numbers up to sqrt(n) +- limit = sqrt(float(n+1)) ++ limit = sqrt(n+1) + i = 3 + while i <= limit: +- if n%i == 0: ++ if n % i == 0: + res.append(i) +- n = n//i ++ n //= i + limit = sqrt(n+1) + else: +- i = i+2 ++ i += 2 + if n != 1: + res.append(n) + return res + + def main(): + if len(sys.argv) > 1: +- for arg in sys.argv[1:]: +- n = eval(arg) +- print(n, fact(n)) ++ source = sys.argv[1:] + else: ++ source = iter(input, '') ++ for arg in source: + try: +- while 1: +- n = eval(input()) +- print(n, fact(n)) +- except EOFError: +- pass ++ n = int(arg) ++ except ValueError: ++ print(arg, 'is not an integer') ++ else: ++ print(n, fact(n)) + + if __name__ == "__main__": + main() +Index: Demo/scripts/pp.py +=================================================================== +--- Demo/scripts/pp.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/pp.py (.../branches/release31-maint) (Revision 76056) +@@ -22,7 +22,6 @@ + # - except for -n/-p, run directly from the file if at all possible + + import sys +-import string + import getopt + + FS = '' +@@ -36,7 +35,7 @@ + try: + optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') + except getopt.error as msg: +- sys.stderr.write(sys.argv[0] + ': ' + msg + '\n') ++ sys.stderr.write('%s: %s\n' % (sys.argv[0], msg)) + sys.exit(2) + + for option, optarg in optlist: +@@ -47,7 +46,7 @@ + elif option == '-d': + DFLAG = 1 + elif option == '-e': +- for line in string.splitfields(optarg, '\n'): ++ for line in optarg.split('\n'): + SCRIPT.append(line) + elif option == '-F': + FS = optarg +@@ -81,31 +80,31 @@ + elif NFLAG: + # Note that it is on purpose that AFLAG and PFLAG are + # tested dynamically each time through the loop +- prologue = [ \ +- 'LINECOUNT = 0', \ +- 'for FILE in ARGS:', \ +- ' \tif FILE == \'-\':', \ +- ' \t \tFP = sys.stdin', \ +- ' \telse:', \ +- ' \t \tFP = open(FILE, \'r\')', \ +- ' \tLINENO = 0', \ +- ' \twhile 1:', \ +- ' \t \tLINE = FP.readline()', \ +- ' \t \tif not LINE: break', \ +- ' \t \tLINENO = LINENO + 1', \ +- ' \t \tLINECOUNT = LINECOUNT + 1', \ +- ' \t \tL = LINE[:-1]', \ +- ' \t \taflag = AFLAG', \ +- ' \t \tif aflag:', \ +- ' \t \t \tif FS: F = string.splitfields(L, FS)', \ +- ' \t \t \telse: F = string.split(L)' \ ++ prologue = [ ++ 'LINECOUNT = 0', ++ 'for FILE in ARGS:', ++ ' \tif FILE == \'-\':', ++ ' \t \tFP = sys.stdin', ++ ' \telse:', ++ ' \t \tFP = open(FILE, \'r\')', ++ ' \tLINENO = 0', ++ ' \twhile 1:', ++ ' \t \tLINE = FP.readline()', ++ ' \t \tif not LINE: break', ++ ' \t \tLINENO = LINENO + 1', ++ ' \t \tLINECOUNT = LINECOUNT + 1', ++ ' \t \tL = LINE[:-1]', ++ ' \t \taflag = AFLAG', ++ ' \t \tif aflag:', ++ ' \t \t \tif FS: F = L.split(FS)', ++ ' \t \t \telse: F = L.split()' + ] +- epilogue = [ \ +- ' \t \tif not PFLAG: continue', \ +- ' \t \tif aflag:', \ +- ' \t \t \tif FS: print string.joinfields(F, FS)', \ +- ' \t \t \telse: print string.join(F)', \ +- ' \t \telse: print L', \ ++ epilogue = [ ++ ' \t \tif not PFLAG: continue', ++ ' \t \tif aflag:', ++ ' \t \t \tif FS: print(FS.join(F))', ++ ' \t \t \telse: print(\' \'.join(F))', ++ ' \t \telse: print(L)', + ] + else: + prologue = ['if 1:'] +@@ -114,18 +113,13 @@ + # Note that we indent using tabs only, so that any indentation style + # used in 'command' will come out right after re-indentation. + +-program = string.joinfields(prologue, '\n') + '\n' ++program = '\n'.join(prologue) + '\n' + for line in SCRIPT: +- program = program + (' \t \t' + line + '\n') +-program = program + (string.joinfields(epilogue, '\n') + '\n') ++ program += ' \t \t' + line + '\n' ++program += '\n'.join(epilogue) + '\n' + +-import tempfile +-fp = tempfile.NamedTemporaryFile() +-fp.write(program) +-fp.flush() +-script = open(tfn).read() + if DFLAG: + import pdb +- pdb.run(script) ++ pdb.run(program) + else: +- exec(script) ++ exec(program) +Index: Demo/scripts/find-uname.py +=================================================================== +--- Demo/scripts/find-uname.py (.../tags/r311) (Revision 76056) ++++ Demo/scripts/find-uname.py (.../branches/release31-maint) (Revision 76056) +@@ -21,20 +21,20 @@ + import re + + def main(args): +- unicode_names= [] ++ unicode_names = [] + for ix in range(sys.maxunicode+1): + try: +- unicode_names.append( (ix, unicodedata.name(chr(ix))) ) ++ unicode_names.append((ix, unicodedata.name(chr(ix)))) + except ValueError: # no name for the character + pass + for arg in args: + pat = re.compile(arg, re.I) +- matches = [(x,y) for (x,y) in unicode_names +- if pat.search(y) is not None] ++ matches = [(y,x) for (x,y) in unicode_names ++ if pat.search(y) is not None] + if matches: + print("***", arg, "matches", "***") +- for (x,y) in matches: +- print("%s (%d)" % (y,x)) ++ for match in matches: ++ print("%s (%d)" % match) + + if __name__ == "__main__": + main(sys.argv[1:]) +Index: Demo/scripts/morse.py +=================================================================== +--- Demo/scripts/morse.py (.../tags/r311) (Revision 0) ++++ Demo/scripts/morse.py (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,128 @@ ++#! /usr/bin/env python ++ ++# DAH should be three DOTs. ++# Space between DOTs and DAHs should be one DOT. ++# Space between two letters should be one DAH. ++# Space between two words should be DOT DAH DAH. ++ ++import sys, math, aifc ++from contextlib import closing ++ ++DOT = 30 ++DAH = 3 * DOT ++OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... ++ ++morsetab = { ++ 'A': '.-', 'a': '.-', ++ 'B': '-...', 'b': '-...', ++ 'C': '-.-.', 'c': '-.-.', ++ 'D': '-..', 'd': '-..', ++ 'E': '.', 'e': '.', ++ 'F': '..-.', 'f': '..-.', ++ 'G': '--.', 'g': '--.', ++ 'H': '....', 'h': '....', ++ 'I': '..', 'i': '..', ++ 'J': '.---', 'j': '.---', ++ 'K': '-.-', 'k': '-.-', ++ 'L': '.-..', 'l': '.-..', ++ 'M': '--', 'm': '--', ++ 'N': '-.', 'n': '-.', ++ 'O': '---', 'o': '---', ++ 'P': '.--.', 'p': '.--.', ++ 'Q': '--.-', 'q': '--.-', ++ 'R': '.-.', 'r': '.-.', ++ 'S': '...', 's': '...', ++ 'T': '-', 't': '-', ++ 'U': '..-', 'u': '..-', ++ 'V': '...-', 'v': '...-', ++ 'W': '.--', 'w': '.--', ++ 'X': '-..-', 'x': '-..-', ++ 'Y': '-.--', 'y': '-.--', ++ 'Z': '--..', 'z': '--..', ++ '0': '-----', ',': '--..--', ++ '1': '.----', '.': '.-.-.-', ++ '2': '..---', '?': '..--..', ++ '3': '...--', ';': '-.-.-.', ++ '4': '....-', ':': '---...', ++ '5': '.....', "'": '.----.', ++ '6': '-....', '-': '-....-', ++ '7': '--...', '/': '-..-.', ++ '8': '---..', '(': '-.--.-', ++ '9': '----.', ')': '-.--.-', ++ ' ': ' ', '_': '..--.-', ++} ++ ++nowave = b'\0' * 200 ++ ++# If we play at 44.1 kHz (which we do), then if we produce one sine ++# wave in 100 samples, we get a tone of 441 Hz. If we produce two ++# sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz ++# appears to be a nice one for playing morse code. ++def mkwave(octave): ++ sinewave = bytearray() ++ for i in range(100): ++ val = int(math.sin(math.pi * i * octave / 50.0) * 30000) ++ sinewave.extend([(val >> 8) & 255, val & 255]) ++ return bytes(sinewave) ++ ++defaultwave = mkwave(OCTAVE) ++ ++def main(): ++ import getopt ++ try: ++ opts, args = getopt.getopt(sys.argv[1:], 'o:p:') ++ except getopt.error: ++ sys.stderr.write('Usage ' + sys.argv[0] + ++ ' [ -o outfile ] [ -p octave ] [ words ] ...\n') ++ sys.exit(1) ++ wave = defaultwave ++ outfile = 'morse.aifc' ++ for o, a in opts: ++ if o == '-o': ++ outfile = a ++ if o == '-p': ++ wave = mkwave(int(a)) ++ with closing(aifc.open(outfile, 'w')) as fp: ++ fp.setframerate(44100) ++ fp.setsampwidth(2) ++ fp.setnchannels(1) ++ if args: ++ source = [' '.join(args)] ++ else: ++ source = iter(sys.stdin.readline, '') ++ for line in source: ++ mline = morse(line) ++ play(mline, fp, wave) ++ ++# Convert a string to morse code with \001 between the characters in ++# the string. ++def morse(line): ++ res = '' ++ for c in line: ++ try: ++ res += morsetab[c] + '\001' ++ except KeyError: ++ pass ++ return res ++ ++# Play a line of morse code. ++def play(line, fp, wave): ++ for c in line: ++ if c == '.': ++ sine(fp, DOT, wave) ++ elif c == '-': ++ sine(fp, DAH, wave) ++ else: # space ++ pause(fp, DAH + DOT) ++ pause(fp, DOT) ++ ++def sine(fp, length, wave): ++ for i in range(length): ++ fp.writeframesraw(wave) ++ ++def pause(fp, length): ++ for i in range(length): ++ fp.writeframesraw(nowave) ++ ++if __name__ == '__main__': ++ main() + +Eigenschaftsänderungen: Demo/scripts/morse.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:executable + + * +Hinzugefügt: svn:keywords + + Id + +Index: Demo/comparisons/sortingtest.py +=================================================================== +--- Demo/comparisons/sortingtest.py (.../tags/r311) (Revision 76056) ++++ Demo/comparisons/sortingtest.py (.../branches/release31-maint) (Revision 76056) +@@ -24,7 +24,6 @@ + # - Handles blank input lines correctly + + import re +-import string + import sys + + def main(): +@@ -32,18 +31,13 @@ + def makekey(item, prog=prog): + match = prog.match(item) + if match: +- var, num = match.group(1, 2) +- return string.atoi(num), var ++ var, num = match.groups() ++ return int(num), var + else: + # Bad input -- pretend it's a var with value 0 + return 0, item +- while 1: +- line = sys.stdin.readline() +- if not line: +- break +- items = line.split() +- items = list(map(makekey, items)) +- items.sort() ++ for line in sys.stdin: ++ items = sorted(makekey(item) for item in line.split()) + for num, var in items: + print("%s=%s" % (var, num), end=' ') + print() +Index: Demo/xml/elem_count.py +=================================================================== +--- Demo/xml/elem_count.py (.../tags/r311) (Revision 76056) ++++ Demo/xml/elem_count.py (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,10 @@ ++""" ++A simple demo that reads in an XML document and displays the number of ++elements and attributes as well as a tally of elements and attributes by name. ++""" ++ + import sys ++from collections import defaultdict + + from xml.sax import make_parser, handler + +@@ -7,16 +13,16 @@ + def __init__(self): + self._elems = 0 + self._attrs = 0 +- self._elem_types = {} +- self._attr_types = {} ++ self._elem_types = defaultdict(int) ++ self._attr_types = defaultdict(int) + + def startElement(self, name, attrs): +- self._elems = self._elems + 1 +- self._attrs = self._attrs + len(attrs) +- self._elem_types[name] = self._elem_types.get(name, 0) + 1 ++ self._elems += 1 ++ self._attrs += len(attrs) ++ self._elem_types[name] += 1 + + for name in attrs.keys(): +- self._attr_types[name] = self._attr_types.get(name, 0) + 1 ++ self._attr_types[name] += 1 + + def endDocument(self): + print("There were", self._elems, "elements.") +@@ -30,7 +36,7 @@ + for pair in self._attr_types.items(): + print("%20s %d" % pair) + +- +-parser = make_parser() +-parser.setContentHandler(FancyCounter()) +-parser.parse(sys.argv[1]) ++if __name__ == '__main__': ++ parser = make_parser() ++ parser.setContentHandler(FancyCounter()) ++ parser.parse(sys.argv[1]) +Index: Demo/xml/rss2html.py +=================================================================== +--- Demo/xml/rss2html.py (.../tags/r311) (Revision 76056) ++++ Demo/xml/rss2html.py (.../branches/release31-maint) (Revision 76056) +@@ -1,45 +1,50 @@ ++""" ++A demo that reads in an RSS XML document and emits an HTML file containing ++a list of the individual items in the feed. ++""" ++ + import sys ++import codecs + + from xml.sax import make_parser, handler + + # --- Templates + +-top = \ +-""" ++top = """\ + +- +- +- %s +- ++ ++ ++ %s ++ ++ + +- +-

        %s

        ++ ++

        %s

        + """ + +-bottom = \ +-""" ++bottom = """ +
      + +-
      +-
      +-Converted to HTML by sax_rss2html.py. +-
      ++
      ++
      ++Converted to HTML by rss2html.py. ++
      + +- +- ++ ++ + """ + + # --- The ContentHandler + + class RSSHandler(handler.ContentHandler): + +- def __init__(self, out = sys.stdout): ++ def __init__(self, out=sys.stdout): + handler.ContentHandler.__init__(self) + self._out = out + + self._text = "" + self._parent = None +- self._list_started = 0 ++ self._list_started = False + self._title = None + self._link = None + self._descr = "" +@@ -69,7 +74,7 @@ + elif name == "item": + if not self._list_started: + self._out.write("
        \n") +- self._list_started = 1 ++ self._list_started = True + + self._out.write('
      • %s %s\n' % + (self._link, self._title, self._descr)) +@@ -86,6 +91,7 @@ + + # --- Main program + +-parser = make_parser() +-parser.setContentHandler(RSSHandler()) +-parser.parse(sys.argv[1]) ++if __name__ == '__main__': ++ parser = make_parser() ++ parser.setContentHandler(RSSHandler()) ++ parser.parse(sys.argv[1]) +Index: Demo/xml/roundtrip.py +=================================================================== +--- Demo/xml/roundtrip.py (.../tags/r311) (Revision 76056) ++++ Demo/xml/roundtrip.py (.../branches/release31-maint) (Revision 76056) +@@ -3,7 +3,7 @@ + but not necessarily identical, document. + """ + +-import sys, string ++import sys + + from xml.sax import saxutils, handler, make_parser + +@@ -11,7 +11,7 @@ + + class ContentGenerator(handler.ContentHandler): + +- def __init__(self, out = sys.stdout): ++ def __init__(self, out=sys.stdout): + handler.ContentHandler.__init__(self) + self._out = out + +@@ -40,6 +40,7 @@ + + # --- The main program + +-parser = make_parser() +-parser.setContentHandler(ContentGenerator()) +-parser.parse(sys.argv[1]) ++if __name__ == '__main__': ++ parser = make_parser() ++ parser.setContentHandler(ContentGenerator()) ++ parser.parse(sys.argv[1]) +Index: configure.in +=================================================================== +--- configure.in (.../tags/r311) (Revision 76056) ++++ configure.in (.../branches/release31-maint) (Revision 76056) +@@ -101,13 +101,12 @@ + ]) + AC_SUBST(UNIVERSALSDK) + +-ARCH_RUN_32BIT= + AC_SUBST(ARCH_RUN_32BIT) + + UNIVERSAL_ARCHS="32-bit" + AC_MSG_CHECKING(for --with-universal-archs) + AC_ARG_WITH(universal-archs, +- AC_HELP_STRING(--with-universal-archs=ARCH, select architectures for universal build ("32-bit", "64-bit" or "all")), ++ AC_HELP_STRING(--with-universal-archs=ARCH, select architectures for universal build ("32-bit", "64-bit", "3-way", "intel" or "all")), + [ + AC_MSG_RESULT($withval) + UNIVERSAL_ARCHS="$withval" +@@ -226,7 +225,7 @@ + if test -z "$MACHDEP" + then + ac_sys_system=`uname -s` +- if test "$ac_sys_system" = "AIX" -o "$ac_sys_system" = "Monterey64" \ ++ if test "$ac_sys_system" = "AIX" \ + -o "$ac_sys_system" = "UnixWare" -o "$ac_sys_system" = "OpenUNIX"; then + ac_sys_release=`uname -v` + else +@@ -408,9 +407,6 @@ + case $ac_sys_system in + AIX*) CC=cc_r + without_gcc=;; +- Monterey*) +- RANLIB=: +- without_gcc=;; + *) without_gcc=no;; + esac]) + AC_MSG_RESULT($without_gcc) +@@ -532,10 +528,6 @@ + case $CC in + cc|*/cc) CC="$CC -Ae";; + esac;; +-Monterey*) +- case $CC in +- cc) CC="$CC -Wl,-Bexport";; +- esac;; + SunOS*) + # Some functions have a prototype only with that define, e.g. confstr + AC_DEFINE(__EXTENSIONS__, 1, [Defined on Solaris to see additional function prototypes.]) +@@ -596,8 +588,6 @@ + exp_extra="." + fi + LINKCC="\$(srcdir)/Modules/makexp_aix Modules/python.exp $exp_extra \$(LIBRARY); $LINKCC";; +- Monterey64*) +- LINKCC="$LINKCC -L/usr/lib/ia64l64";; + QNX*) + # qcc must be used because the other compilers do not + # support -N. +@@ -847,15 +837,6 @@ + OPT="-O" + ;; + esac +- +- # The current (beta) Monterey compiler dies with optimizations +- # XXX what is Monterey? Does it still die w/ -O? Can we get rid of this? +- case $ac_sys_system in +- Monterey*) +- OPT="" +- ;; +- esac +- + fi + + AC_SUBST(BASECFLAGS) +@@ -911,13 +892,22 @@ + + elif test "$UNIVERSAL_ARCHS" = "64-bit" ; then + UNIVERSAL_ARCH_FLAGS="-arch ppc64 -arch x86_64" ++ ARCH_RUN_32BIT="true" + + elif test "$UNIVERSAL_ARCHS" = "all" ; then + UNIVERSAL_ARCH_FLAGS="-arch i386 -arch ppc -arch ppc64 -arch x86_64" + ARCH_RUN_32BIT="arch -i386 -ppc" + ++ elif test "$UNIVERSAL_ARCHS" = "intel" ; then ++ UNIVERSAL_ARCH_FLAGS="-arch i386 -arch x86_64" ++ ARCH_RUN_32BIT="arch -i386" ++ ++ elif test "$UNIVERSAL_ARCHS" = "3-way" ; then ++ UNIVERSAL_ARCH_FLAGS="-arch i386 -arch ppc -arch x86_64" ++ ARCH_RUN_32BIT="arch -i386 -ppc" ++ + else +- AC_MSG_ERROR([proper usage is --with-universalarch=32-bit|64-bit|all]) ++ AC_MSG_ERROR([proper usage is --with-universal-arch=32-bit|64-bit|all|intel|3-way]) + + fi + +@@ -934,13 +924,32 @@ + cur_target=`sw_vers -productVersion | sed 's/\(10\.[[0-9]]*\).*/\1/'` + if test ${cur_target} '>' 10.2; then + cur_target=10.3 ++ if test ${enable_universalsdk}; then ++ if test "${UNIVERSAL_ARCHS}" = "all"; then ++ # Ensure that the default platform for a ++ # 4-way universal build is OSX 10.5, ++ # that's the first OS release where ++ # 4-way builds make sense. ++ cur_target='10.5' ++ ++ elif test "${UNIVERSAL_ARCHS}" = "3-way"; then ++ cur_target='10.5' ++ ++ elif test "${UNIVERSAL_ARCHS}" = "intel"; then ++ cur_target='10.5' ++ ++ elif test "${UNIVERSAL_ARCHS}" = "64-bit"; then ++ cur_target='10.5' ++ fi ++ else ++ if test `arch` = "i386"; then ++ # On Intel macs default to a deployment ++ # target of 10.4, that's the first OSX ++ # release with Intel support. ++ cur_target="10.4" ++ fi ++ fi + fi +- if test "${UNIVERSAL_ARCHS}" = "all"; then +- # Ensure that the default platform for a 4-way +- # universal build is OSX 10.5, that's the first +- # OS release where 4-way builds make sense. +- cur_target='10.5' +- fi + CONFIGURE_MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET-${cur_target}} + + # Make sure that MACOSX_DEPLOYMENT_TARGET is set in the +@@ -1488,6 +1497,8 @@ + ;; + esac + ++ ++ARCH_RUN_32BIT="" + AC_SUBST(LIBTOOL_CRUFT) + case $ac_sys_system/$ac_sys_release in + Darwin/@<:@01567@:>@\..*) +@@ -1495,7 +1506,7 @@ + if test "${enable_universalsdk}"; then + : + else +- LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `arch`" ++ LIBTOOL_CRUFT="${LIBTOOL_CRUFT} -arch_only `arch`" + fi + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; +@@ -1507,7 +1518,49 @@ + else + LIBTOOL_CRUFT="" + fi +- LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only `arch`" ++ AC_TRY_RUN([ ++ #include ++ int main(int argc, char*argv[]) ++ { ++ if (sizeof(long) == 4) { ++ return 0; ++ } else { ++ return 1; ++ } ++ } ++ ], ac_osx_32bit=yes, ++ ac_osx_32bit=no, ++ ac_osx_32bit=yes) ++ ++ if test "${ac_osx_32bit}" = "yes"; then ++ case `arch` in ++ i386) ++ MACOSX_DEFAULT_ARCH="i386" ++ ;; ++ ppc) ++ MACOSX_DEFAULT_ARCH="ppc" ++ ;; ++ *) ++ AC_MSG_ERROR([Unexpected output of 'arch' on OSX]) ++ ;; ++ esac ++ else ++ case `arch` in ++ i386) ++ MACOSX_DEFAULT_ARCH="x86_64" ++ ;; ++ ppc) ++ MACOSX_DEFAULT_ARCH="ppc64" ++ ;; ++ *) ++ AC_MSG_ERROR([Unexpected output of 'arch' on OSX]) ++ ;; ++ esac ++ ++ #ARCH_RUN_32BIT="true" ++ fi ++ ++ LIBTOOL_CRUFT=$LIBTOOL_CRUFT" -lSystem -lSystemStubs -arch_only ${MACOSX_DEFAULT_ARCH}" + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -install_name $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)' + LIBTOOL_CRUFT=$LIBTOOL_CRUFT' -compatibility_version $(VERSION) -current_version $(VERSION)';; + esac +@@ -1680,7 +1733,6 @@ + else LDSHARED='$(CC) -G' + fi;; + SCO_SV*) LDSHARED='$(CC) -Wl,-G,-Bexport';; +- Monterey*) LDSHARED="cc -G -dy -Bdynamic -Bexport -L/usr/lib/ia64l64";; + CYGWIN*) LDSHARED="gcc -shared -Wl,--enable-auto-image-base";; + atheos*) LDSHARED="gcc -shared";; + *) LDSHARED="ld";; +@@ -1717,7 +1769,6 @@ + then CCSHARED="-fPIC" + else CCSHARED="-Kpic -belf" + fi;; +- Monterey*) CCSHARED="-G";; + IRIX*/6*) case $CC in + *gcc*) CCSHARED="-shared";; + *) CCSHARED="";; +@@ -3517,6 +3568,10 @@ + [readline/readline.h], + AC_DEFINE(HAVE_RL_COMPLETION_APPEND_CHARACTER, 1, + [Define if you have readline 2.2]), ) ++ AC_EGREP_HEADER([extern int rl_completion_suppress_append;], ++ [readline/readline.h], ++ AC_DEFINE(HAVE_RL_COMPLETION_SUPPRESS_APPEND, 1, ++ [Define if you have rl_completion_suppress_append]), ) + fi + + # check for readline 4.0 +Index: setup.py +=================================================================== +--- setup.py (.../tags/r311) (Revision 76056) ++++ setup.py (.../branches/release31-maint) (Revision 76056) +@@ -1272,20 +1272,27 @@ + # architectures. + cflags = sysconfig.get_config_vars('CFLAGS')[0] + archs = re.findall('-arch\s+(\w+)', cflags) +- if 'x86_64' in archs or 'ppc64' in archs: +- try: +- archs.remove('x86_64') +- except ValueError: +- pass +- try: +- archs.remove('ppc64') +- except ValueError: +- pass + +- for a in archs: +- frameworks.append('-arch') +- frameworks.append(a) ++ tmpfile = os.path.join(self.build_temp, 'tk.arch') ++ if not os.path.exists(self.build_temp): ++ os.makedirs(self.build_temp) + ++ # Note: cannot use os.popen or subprocess here, that ++ # requires extensions that are not available here. ++ os.system("file %s/Tk.framework/Tk | grep 'for architecture' > %s"%(F, tmpfile)) ++ fp = open(tmpfile) ++ detected_archs = [] ++ for ln in fp: ++ a = ln.split()[-1] ++ if a in archs: ++ detected_archs.append(ln.split()[-1]) ++ fp.close() ++ os.unlink(tmpfile) ++ ++ for a in detected_archs: ++ frameworks.append('-arch') ++ frameworks.append(a) ++ + ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'], + define_macros=[('WITH_APPINIT', 1)], + include_dirs = include_dirs, +Index: Objects/bytes_methods.c +=================================================================== +--- Objects/bytes_methods.c (.../tags/r311) (Revision 76056) ++++ Objects/bytes_methods.c (.../branches/release31-maint) (Revision 76056) +@@ -427,7 +427,7 @@ + { + PyObject *frm, *to, *res = NULL; + Py_buffer bfrm, bto; +- int i; ++ Py_ssize_t i; + char *p; + + bfrm.len = -1; +@@ -452,7 +452,7 @@ + for (i = 0; i < 256; i++) + p[i] = i; + for (i = 0; i < bfrm.len; i++) { +- p[(int)((char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; ++ p[((unsigned char *)bfrm.buf)[i]] = ((char *)bto.buf)[i]; + } + + done: +Index: Objects/unicodeobject.c +=================================================================== +--- Objects/unicodeobject.c (.../tags/r311) (Revision 76056) ++++ Objects/unicodeobject.c (.../branches/release31-maint) (Revision 76056) +@@ -7708,10 +7708,10 @@ + } + + PyDoc_STRVAR(join__doc__, +- "S.join(sequence) -> str\n\ ++ "S.join(iterable) -> str\n\ + \n\ + Return a string which is the concatenation of the strings in the\n\ +-sequence. The separator between elements is S."); ++iterable. The separator between elements is S."); + + static PyObject* + unicode_join(PyObject *self, PyObject *data) +Index: Objects/listsort.txt +=================================================================== +--- Objects/listsort.txt (.../tags/r311) (Revision 76056) ++++ Objects/listsort.txt (.../branches/release31-maint) (Revision 76056) +@@ -606,7 +606,7 @@ + + def fill(n): + from random import random +- return [random() for i in xrange(n)] ++ return [random() for i in range(n)] + + def mycmp(x, y): + global ncmp +Index: Objects/rangeobject.c +=================================================================== +--- Objects/rangeobject.c (.../tags/r311) (Revision 76056) ++++ Objects/rangeobject.c (.../branches/release31-maint) (Revision 76056) +@@ -431,7 +431,7 @@ + rangeiter_new, /* tp_new */ + }; + +-/* Return number of items in range/xrange (lo, hi, step). step > 0 ++/* Return number of items in range (lo, hi, step). step > 0 + * required. Return a value < 0 if & only if the true value is too + * large to fit in a signed long. + */ +Index: Objects/funcobject.c +=================================================================== +--- Objects/funcobject.c (.../tags/r311) (Revision 76056) ++++ Objects/funcobject.c (.../branches/release31-maint) (Revision 76056) +@@ -765,12 +765,6 @@ + return -1; + if (!_PyArg_NoKeywords("classmethod", kwds)) + return -1; +- if (!PyCallable_Check(callable)) { +- PyErr_Format(PyExc_TypeError, "'%s' object is not callable", +- callable->ob_type->tp_name); +- return -1; +- } +- + Py_INCREF(callable); + cm->cm_callable = callable; + return 0; +Index: Objects/longobject.c +=================================================================== +--- Objects/longobject.c (.../tags/r311) (Revision 76056) ++++ Objects/longobject.c (.../branches/release31-maint) (Revision 76056) +@@ -1659,7 +1659,7 @@ + { + register PyLongObject *a = (PyLongObject *)aa; + PyObject *str; +- Py_ssize_t i, j, sz; ++ Py_ssize_t i, sz; + Py_ssize_t size_a; + Py_UNICODE *p; + int bits; +@@ -1680,13 +1680,14 @@ + i >>= 1; + } + i = 5; +- j = size_a*PyLong_SHIFT + bits-1; +- sz = i + j / bits; +- if (j / PyLong_SHIFT < size_a || sz < i) { ++ /* ensure we don't get signed overflow in sz calculation */ ++ if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) { + PyErr_SetString(PyExc_OverflowError, + "int is too large to format"); + return NULL; + } ++ sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits; ++ assert(sz >= 0); + str = PyUnicode_FromUnicode(NULL, sz); + if (str == NULL) + return NULL; +@@ -1719,7 +1720,7 @@ + accumbits -= basebits; + accum >>= basebits; + } while (i < size_a-1 ? accumbits >= basebits : +- accum > 0); ++ accum > 0); + } + } + else { +@@ -1734,7 +1735,8 @@ + int power = 1; + for (;;) { + twodigits newpow = powbase * (twodigits)base; +- if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */ ++ if (newpow >> PyLong_SHIFT) ++ /* doesn't fit in a digit */ + break; + powbase = (digit)newpow; + ++power; +@@ -1805,7 +1807,8 @@ + do { + } while ((*q++ = *p++) != '\0'); + q--; +- if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) { ++ if (PyUnicode_Resize(&str,(Py_ssize_t) (q - ++ PyUnicode_AS_UNICODE(str)))) { + Py_DECREF(str); + return NULL; + } +@@ -1862,7 +1865,6 @@ + for (bits_per_char = -1; n; ++bits_per_char) + n >>= 1; + /* n <- total # of bits needed, while setting p to end-of-string */ +- n = 0; + while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base) + ++p; + *str = p; +Index: Objects/bytearrayobject.c +=================================================================== +--- Objects/bytearrayobject.c (.../tags/r311) (Revision 76056) ++++ Objects/bytearrayobject.c (.../branches/release31-maint) (Revision 76056) +@@ -2552,7 +2552,7 @@ + + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, +- "cannot add more objects to bytes"); ++ "cannot add more objects to bytearray"); + return NULL; + } + if (!_getbytevalue(value, &ival)) +@@ -2587,7 +2587,7 @@ + return NULL; + if (n == PY_SSIZE_T_MAX) { + PyErr_SetString(PyExc_OverflowError, +- "cannot add more objects to bytes"); ++ "cannot add more objects to bytearray"); + return NULL; + } + if (PyByteArray_Resize((PyObject *)self, n + 1) < 0) +@@ -2688,7 +2688,7 @@ + + if (n == 0) { + PyErr_SetString(PyExc_OverflowError, +- "cannot pop an empty bytes"); ++ "cannot pop an empty bytearray"); + return NULL; + } + if (where < 0) +@@ -2705,7 +2705,7 @@ + if (PyByteArray_Resize((PyObject *)self, n - 1) < 0) + return NULL; + +- return PyLong_FromLong(value); ++ return PyLong_FromLong((unsigned char)value); + } + + PyDoc_STRVAR(remove__doc__, +@@ -2726,7 +2726,7 @@ + break; + } + if (where == n) { +- PyErr_SetString(PyExc_ValueError, "value not found in bytes"); ++ PyErr_SetString(PyExc_ValueError, "value not found in bytearray"); + return NULL; + } + if (!_canresize(self)) +Index: Objects/enumobject.c +=================================================================== +--- Objects/enumobject.c (.../tags/r311) (Revision 76056) ++++ Objects/enumobject.c (.../branches/release31-maint) (Revision 76056) +@@ -161,7 +161,7 @@ + PyDoc_STRVAR(enum_doc, + "enumerate(iterable) -> iterator for index, value of iterable\n" + "\n" +-"Return an enumerate object. iterable must be an other object that supports\n" ++"Return an enumerate object. iterable must be another object that supports\n" + "iteration. The enumerate object yields pairs containing a count (from\n" + "zero) and a value yielded by the iterable argument. enumerate is useful\n" + "for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); +Index: Objects/capsule.c +=================================================================== +--- Objects/capsule.c (.../tags/r311) (Revision 76056) ++++ Objects/capsule.c (.../branches/release31-maint) (Revision 76056) +@@ -197,7 +197,7 @@ + PyObject *object = NULL; + void *return_value = NULL; + char *trace; +- int name_length = (strlen(name) + 1) * sizeof(char); ++ size_t name_length = (strlen(name) + 1) * sizeof(char); + char *name_dup = (char *)PyMem_MALLOC(name_length); + + if (!name_dup) { +Index: Objects/classobject.c +=================================================================== +--- Objects/classobject.c (.../tags/r311) (Revision 76056) ++++ Objects/classobject.c (.../branches/release31-maint) (Revision 76056) +@@ -43,10 +43,6 @@ + PyMethod_New(PyObject *func, PyObject *self) + { + register PyMethodObject *im; +- if (!PyCallable_Check(func)) { +- PyErr_BadInternalCall(); +- return NULL; +- } + if (self == NULL) { + PyErr_BadInternalCall(); + return NULL; +Index: Misc/find_recursionlimit.py +=================================================================== +--- Misc/find_recursionlimit.py (.../tags/r311) (Revision 76056) ++++ Misc/find_recursionlimit.py (.../branches/release31-maint) (Revision 76056) +@@ -1,118 +0,0 @@ +-#! /usr/bin/env python +-"""Find the maximum recursion limit that prevents interpreter termination. +- +-This script finds the maximum safe recursion limit on a particular +-platform. If you need to change the recursion limit on your system, +-this script will tell you a safe upper bound. To use the new limit, +-call sys.setrecursionlimit(). +- +-This module implements several ways to create infinite recursion in +-Python. Different implementations end up pushing different numbers of +-C stack frames, depending on how many calls through Python's abstract +-C API occur. +- +-After each round of tests, it prints a message: +-"Limit of NNNN is fine". +- +-The highest printed value of "NNNN" is therefore the highest potentially +-safe limit for your system (which depends on the OS, architecture, but also +-the compilation flags). Please note that it is practically impossible to +-test all possible recursion paths in the interpreter, so the results of +-this test should not be trusted blindly -- although they give a good hint +-of which values are reasonable. +- +-NOTE: When the C stack space allocated by your system is exceeded due +-to excessive recursion, exact behaviour depends on the platform, although +-the interpreter will always fail in a likely brutal way: either a +-segmentation fault, a MemoryError, or just a silent abort. +- +-NB: A program that does not use __methods__ can set a higher limit. +-""" +- +-import sys +-import itertools +- +-class RecursiveBlowup1: +- def __init__(self): +- self.__init__() +- +-def test_init(): +- return RecursiveBlowup1() +- +-class RecursiveBlowup2: +- def __repr__(self): +- return repr(self) +- +-def test_repr(): +- return repr(RecursiveBlowup2()) +- +-class RecursiveBlowup4: +- def __add__(self, x): +- return x + self +- +-def test_add(): +- return RecursiveBlowup4() + RecursiveBlowup4() +- +-class RecursiveBlowup5: +- def __getattr__(self, attr): +- return getattr(self, attr) +- +-def test_getattr(): +- return RecursiveBlowup5().attr +- +-class RecursiveBlowup6: +- def __getitem__(self, item): +- return self[item - 2] + self[item - 1] +- +-def test_getitem(): +- return RecursiveBlowup6()[5] +- +-def test_recurse(): +- return test_recurse() +- +-def test_cpickle(_cache={}): +- import io +- try: +- import _pickle +- except ImportError: +- print("cannot import _pickle, skipped!") +- return +- l = None +- for n in itertools.count(): +- try: +- l = _cache[n] +- continue # Already tried and it works, let's save some time +- except KeyError: +- for i in range(100): +- l = [l] +- _pickle.Pickler(io.BytesIO(), protocol=-1).dump(l) +- _cache[n] = l +- +-def check_limit(n, test_func_name): +- sys.setrecursionlimit(n) +- if test_func_name.startswith("test_"): +- print(test_func_name[5:]) +- else: +- print(test_func_name) +- test_func = globals()[test_func_name] +- try: +- test_func() +- # AttributeError can be raised because of the way e.g. PyDict_GetItem() +- # silences all exceptions and returns NULL, which is usually interpreted +- # as "missing attribute". +- except (RuntimeError, AttributeError): +- pass +- else: +- print("Yikes!") +- +-limit = 1000 +-while 1: +- check_limit(limit, "test_recurse") +- check_limit(limit, "test_add") +- check_limit(limit, "test_repr") +- check_limit(limit, "test_init") +- check_limit(limit, "test_getattr") +- check_limit(limit, "test_getitem") +- check_limit(limit, "test_cpickle") +- print("Limit of %d is fine" % limit) +- limit = limit + 100 +Index: Misc/maintainers.rst +=================================================================== +--- Misc/maintainers.rst (.../tags/r311) (Revision 0) ++++ Misc/maintainers.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,295 @@ ++Maintainers Index ++================= ++ ++This document cross references Python Modules (first table) and platforms ++(second table) with the Tracker user names of people who are experts ++and/or resources for that module or platform. This list is intended ++to be used by issue submitters, issue triage people, and other issue ++participants to find people to add to the nosy list or to contact ++directly by email for help and decisions on feature requests and bug ++fixes. People on this list may be asked to render final judgement on a ++feature or bug. If no active maintainer is listed for a given module, ++then questionable changes should go to python-dev, while any other issues ++can and should be decided by any committer. ++ ++The last part of this document is a third table, listing broader topic ++areas in which various people have expertise. These people can also ++be contacted for help, opinions, and decisions when issues involve ++their areas. ++ ++If a listed maintainer does not respond to requests for comment for an ++extended period (three weeks or more), they should be marked as inactive ++in this list by placing the word 'inactive' in parenthesis behind their ++tracker id. They are of course free to remove that inactive mark at ++any time. ++ ++Committers should update this table as their areas of expertise widen. ++New topics may be added to the third table at will. ++ ++The existence of this list is not meant to indicate that these people ++*must* be contacted for decisions; it is, rather, a resource to be used ++by non-committers to find responsible parties, and by committers who do ++not feel qualified to make a decision in a particular context. ++ ++See also `PEP 291`_ and `PEP 360`_ for information about certain modules ++with special rules. ++ ++.. _`PEP 291`: http://www.python.org/dev/peps/pep-0291/ ++.. _`PEP 360`: http://www.python.org/dev/peps/pep-0360/ ++ ++ ++================== =========== ++Module Maintainers ++================== =========== ++__future__ ++__main__ gvanrossum ++_dummy_thread brett.cannon ++_thread ++abc ++aifc r.david.murray ++array ++ast ++asynchat josiahcarlson ++asyncore josiahcarlson ++atexit ++audioop ++base64 ++bdb ++binascii ++binhex ++bisect rhettinger ++builtins ++bz2 ++calendar ++cgi ++cgitb ++chunk ++cmath mark.dickinson ++cmd ++code ++codecs lemburg, doerwalter ++codeop ++collections rhettinger ++colorsys ++compileall ++configparser ++contextlib ++copy alexandre.vassalotti ++copyreg alexandre.vassalotti ++cProfile ++crypt ++csv ++ctypes theller ++curses andrew.kuchling ++datetime ++dbm ++decimal facundobatista, rhettinger, mark.dickinson ++difflib ++dis ++distutils tarek ++doctest tim_one (inactive) ++dummy_threading brett.cannon ++email barry ++encodings lemburg, loewis ++errno ++exceptions ++fcntl ++filecmp ++fileinput ++fnmatch ++formatter ++fpectl ++fractions mark.dickinson ++ftplib ++functools ++gc pitrou ++getopt ++getpass ++gettext loewis ++glob ++grp ++gzip ++hashlib ++heapq rhettinger ++hmac ++html ++http ++idlelib ++imaplib ++imghdr ++imp ++importlib brett.cannon ++inspect ++io pitrou, benjamin.peterson ++itertools rhettinger ++json bob.ippolito (inactive) ++keyword ++lib2to3 benjamin.peterson ++linecache ++locale loewis, lemburg ++logging vsajip ++macpath ++mailbox andrew.kuchling ++mailcap ++marshal ++math mark.dickinson ++mimetypes ++mmap ++modulefinder theller, jvr ++msilib loewis ++msvcrt ++multiprocessing jnoller ++netrc ++nis ++nntplib ++numbers ++operator ++optparse aronacher ++os loewis ++ossaudiodev ++parser ++pdb ++pickle alexandre.vassalotti, pitrou ++pickletools alexandre.vassalotti ++pipes ++pkgutil ++platform lemburg ++plistlib ++poplib ++posix ++pprint fdrake ++pstats ++pty ++pwd ++py_compile ++pybench lemburg, pitrou ++pyclbr ++pydoc ++queue ++quopri ++random rhettinger ++re effbot (inactive), pitrou ++readline ++reprlib ++resource ++rlcompleter ++runpy ncoghlan ++sched ++select ++shelve ++shlex ++shutil ++signal ++site ++smtpd ++smtplib ++sndhdr ++socket ++socketserver ++spwd ++sqlite3 ghaering ++ssl janssen ++stat ++string ++stringprep ++struct mark.dickinson ++subprocess astrand (inactive) ++sunau ++symbol ++symtable benjamin.peterson ++sys ++syslog ++tabnanny tim_one ++tarfile lars.gustaebel ++telnetlib ++tempfile ++termios ++test ++textwrap ++threading ++time brett.cannon ++timeit ++tkinter gpolo ++token georg.brandl ++tokenize ++trace ++traceback georg.brandl ++tty ++turtle gregorlingl ++types ++unicodedata loewis, lemburg, ezio.melotti ++unittest michael.foord ++urllib orsenthil ++uu ++uuid ++warnings brett.cannon ++wave ++weakref fdrake ++webbrowser georg.brandl ++winreg ++winsound effbot (inactive) ++wsgiref pje ++xdrlib ++xml loewis ++xml.etree effbot (inactive) ++xmlrpc loewis ++zipfile ++zipimport ++zlib ++================== =========== ++ ++ ++================== =========== ++Tool Maintainers ++------------------ ----------- ++pybench lemburg ++ ++ ++================== =========== ++Platform Maintainers ++------------------ ----------- ++AIX ++Cygwin jlt63 ++FreeBSD ++Linux ++Mac ronaldoussoren ++NetBSD1 ++OS2/EMX aimacintyre ++Solaris ++HP-UX ++================== =========== ++ ++ ++================== =========== ++Interest Area Maintainers ++------------------ ----------- ++algorithms ++ast/compiler ncoghlan, benjamin.peterson, brett.cannon, georg.brandl ++autoconf/makefiles ++bsd ++buildbots ++bytecode pitrou ++data formats mark.dickinson, georg.brandl ++database lemburg ++documentation georg.brandl, ezio.melotti ++GUI ++i18n lemburg ++import machinery brett.cannon, ncoghlan ++io pitrou, benjamin.peterson ++locale lemburg, loewis ++mathematics mark.dickinson, eric.smith, lemburg ++memory management tim_one, lemburg ++networking ++packaging tarek, lemburg ++py3 transition benjamin.peterson ++release management tarek, lemburg, benjamin.peterson, barry, loewis, ++ gvanrossum, anthonybaxter ++str.format eric.smith ++time and dates lemburg ++testing michael.foord, pitrou ++threads ++tracker ++unicode lemburg ++version control ++windows ++================== =========== +Index: Misc/developers.txt +=================================================================== +--- Misc/developers.txt (.../tags/r311) (Revision 76056) ++++ Misc/developers.txt (.../branches/release31-maint) (Revision 76056) +@@ -20,6 +20,9 @@ + Permissions History + ------------------- + ++- Doug Hellmann was given SVN access on September 19 2009 by GFB, at ++ suggestion of Jesse Noller, for documentation work. ++ + - Ezio Melotti was given SVN access on June 7 2009 by GFB, for work on and + fixes to the documentation. + +@@ -109,6 +112,13 @@ + - Jeffrey Yasskin was given SVN access on 9 August 2007 by NCN, + for his work on PEPs and other general patches. + ++- Mark Summerfield was given SVN access on 1 August 2007 by GFB, ++ for work on documentation. ++ ++- Armin Ronacher was given SVN access on 23 July 2007 by GFB, ++ for work on the documentation toolset. He now maintains the ++ ast module. ++ + - Senthil Kumaran was given SVN access on 16 June 2007 by MvL, + for his Summer-of-Code project, mentored by Skip Montanaro. + +Index: Misc/python.man +=================================================================== +--- Misc/python.man (.../tags/r311) (Revision 76056) ++++ Misc/python.man (.../branches/release31-maint) (Revision 76056) +@@ -368,15 +368,13 @@ + .SH INTERNET RESOURCES + Main website: http://www.python.org/ + .br +-Documentation: http://docs.python.org/ ++Documentation: http://docs.python.org/py3k/ + .br +-Community website: http://starship.python.net/ +-.br + Developer resources: http://www.python.org/dev/ + .br +-FTP: ftp://ftp.python.org/pub/python/ ++Downloads: http://python.org/download/ + .br +-Module repository: http://www.vex.net/parnassus/ ++Module repository: http://pypi.python.org/ + .br + Newsgroups: comp.lang.python, comp.lang.python.announce + .SH LICENSING +Index: Misc/HISTORY +=================================================================== +--- Misc/HISTORY (.../tags/r311) (Revision 76056) ++++ Misc/HISTORY (.../branches/release31-maint) (Revision 76056) +@@ -10435,7 +10435,7 @@ + Python code. The limit exists to prevent infinite recursion from + overflowing the C stack and causing a core dump. The default value is + 1000. The maximum safe value for a particular platform can be found +-by running Misc/find_recursionlimit.py. ++by running Tools/scripts/find_recursionlimit.py. + + New Modules and Packages + ------------------------ +Index: Misc/NEWS +=================================================================== +--- Misc/NEWS (.../tags/r311) (Revision 76056) ++++ Misc/NEWS (.../branches/release31-maint) (Revision 76056) +@@ -4,6 +4,163 @@ + + (editors: check NEWS.help for information about editing NEWS using ReST.) + ++What's New in Python 3.1.2? ++=========================== ++ ++*Release date: 20xx-xx-xx* ++ ++Core and Builtins ++----------------- ++ ++- Issue #7244: itertools.izip_longest() no longer ignores exceptions ++ raised during the formation of an output tuple. ++ ++- Issue #3297: On wide unicode builds, do not split unicode characters into ++ surrogates. ++ ++- Issue #1722344: threading._shutdown() is now called in Py_Finalize(), which ++ fixes the problem of some exceptions being thrown at shutdown when the ++ interpreter is killed. Patch by Adam Olsen. ++ ++- Issue #7065: Fix a crash in bytes.maketrans and bytearray.maketrans when ++ using byte values greater than 127. Patch by Derk Drukker. ++ ++- Issue #7019: Raise ValueError when unmarshalling bad long data, instead ++ of producing internally inconsistent Python longs. ++ ++- Issue #6990: Fix threading.local subclasses leaving old state around ++ after a reference cycle GC which could be recycled by new locals. ++ ++- Issue #6846: Fix bug where bytearray.pop() returns negative integers. ++ ++- Issue #6750: A text file opened with io.open() could duplicate its output ++ when writing from multiple threads at the same time. ++ ++ ++Library ++------- ++ ++- Issue #6896: mailbox.Maildir now invalidates its internal cache each time ++ a modification is done through it. This fixes inconsistencies and test ++ failures on systems with slightly bogus mtime behaviour. ++ ++- Issue #6665: Fix fnmatch to properly match filenames with newlines in them. ++ ++- Issue #7246 & Issue #7208: getpass now properly flushes input before ++ reading from stdin so that existing input does not confuse it and ++ lead to incorrect entry or an IOError. It also properly flushes it ++ afterwards to avoid the terminal echoing the input afterwards on ++ OSes such as Solaris. ++ ++- Issue #7233: Fix a number of two-argument Decimal methods to make ++ sure that they accept an int or long as the second argument. Also ++ fix buggy handling of large arguments (those with coefficient longer ++ than the current precision) in shift and rotate. ++ ++- Issue #7205: Fix a possible deadlock when using a BZ2File object from ++ several threads at once. ++ ++- Issue #7071: byte-compilation in Distutils is now done with respect to ++ sys.dont_write_bytecode. ++ ++- Issue #7099: Decimal.is_normal now returns True for numbers with exponent ++ larger than emax. ++ ++- Issue #7080: locale.strxfrm() raises a MemoryError on 64-bit non-Windows ++ platforms, and assorted locale fixes by Derk Drukker. ++ ++- Issue #5833: Fix extra space character in readline completion with the ++ GNU readline library version 6.0. ++ ++- Issue #6894: Fixed the issue urllib2 doesn't respect "no_proxy" environment ++ ++- Issue #7082: When falling back to the MIME 'name' parameter, the ++ correct place to look for it is the Content-Type header. ++ ++- Make tokenize.detect_coding() normalize utf-8 and iso-8859-1 variants like the ++ builtin tokenizer. ++ ++- Issue #7048: Force Decimal.logb to round its result when that result ++ is too large to fit in the current precision. ++ ++- Issue #6236, #6348: Fix various failures in the I/O library under AIX ++ and other platforms, when using a non-gcc compiler. Patch by Derk Drukker. ++ ++- Issue #6954: Fixed crash when using DISTUTILS_DEBUG flag in Distutils. ++ ++- Issue #4606: Passing 'None' if ctypes argtype is set to POINTER(...) ++ does now always result in NULL. ++ ++- Issue #5042: Structure sub-subclass does now initialize correctly ++ with base class positional arguments. ++ ++- Issue #6882: Import uuid creates zombies processes. ++ ++- Issue #6635: Fix profiler printing usage message. ++ ++- Issue #6888: pdb's alias command was broken when no arguments were given. ++ ++- Issue #6795: int(Decimal('nan')) now raises ValueError instead of ++ returning NaN or raising InvalidContext. Also, fix infinite recursion ++ in long(Decimal('nan')). ++ ++- Issue #6850: Fix bug in Decimal._parse_format_specifier for formats ++ with no type specifier. ++ ++- Issue #6239: ctypes.c_char_p return value must return bytes. ++ ++- Issue #6838: Use a list to accumulate the value instead of ++ repeatedly concatenating strings in http.client's ++ HTTPResponse._read_chunked providing a significant speed increase ++ when downloading large files servend with a Transfer-Encoding of 'chunked'. ++ ++- Have importlib raise ImportError if None is found in sys.modules for a ++ module. ++ ++- Issue #6794: Fix Decimal.compare_total and Decimal.compare_total_mag: NaN ++ payloads are now ordered by integer value rather than lexicographically. ++ ++- Issue #6163: Fixed HP-UX runtime library dir options in ++ distutils.unixcompiler. Initial patch by Sridhar Ratnakumar and ++ Michael Haubenwallner. ++ ++Extension Modules ++----------------- ++ ++- Issue #7078: Set struct.__doc__ from _struct.__doc__. ++ ++- Issue #6848: Fix curses module build failure on OS X 10.6. ++ ++Tests ++----- ++ ++- Issue #7055: test___all__ now greedily detects all modules which have an ++ __all__ attribute, rather than using a hardcoded and incomplete list. ++ ++- Issue #7058: Added save/restore for argv and os.environ to runtest_inner ++ in regrtest, with warnings if the called test modifies them. ++ ++- Issue #7042: Fix test_signal (test_itimer_virtual) failure on OS X 10.6. ++ ++Build ++----- ++ ++- Issue #6603: Change READ_TIMESTAMP macro in ceval.c so that it ++ compiles correctly under gcc on x86-64. This fixes a reported ++ problem with the --with-tsc build on x86-64. ++ ++- Issue #6802: Fix build issues on MacOSX 10.6 ++ ++- Issue #6801 : symmetric_difference_update also accepts |. ++ Thanks to Carl Chenet. ++ ++Documentation ++------------- ++ ++- Issue #6556: Fixed the Distutils configuration files location explanation ++ for Windows. ++ ++ + What's New in Python 3.1.1? + =========================== + +@@ -948,6 +1105,9 @@ + Library + ------- + ++- Issue #7066: archive_util.make_archive now restores the cwd if an error is ++ raised. Initial patch by Ezio Melotti. ++ + - Issue #6545: Removed assert statements in distutils.Extension, so the + behavior is similar when used with -O. + +Index: Misc/ACKS +=================================================================== +--- Misc/ACKS (.../tags/r311) (Revision 76056) ++++ Misc/ACKS (.../branches/release31-maint) (Revision 76056) +@@ -184,6 +184,7 @@ + Dima Dorfman + Cesar Douady + Dean Draayer ++Derk Drukker + John DuBois + Paul Dubois + Graham Dumpleton +@@ -477,6 +478,7 @@ + Graham Matthews + Dieter Maurer + Arnaud Mazin ++Kirk McDonald + Chris McDonough + Greg McFarlane + Alan McIntyre +@@ -488,6 +490,7 @@ + Lambert Meertens + Bill van Melle + Lucas Prado Melo ++Brian Merrell + Luke Mewburn + Mike Meyer + Steven Miale +@@ -536,6 +539,7 @@ + Tim O'Malley + Pascal Oberndoerfer + Jeffrey Ollie ++Adam Olsen + Grant Olson + Piet van Oostrum + Jason Orendorff +@@ -789,6 +793,7 @@ + Truida Wiedijk + Felix Wiemann + Gerry Wiener ++Frank Wierzbicki + Bryce "Zooko" Wilcox-O'Hearn + John Williams + Sue Williams +@@ -808,6 +813,7 @@ + Klaus-Juergen Wolf + Dan Wolfe + Richard Wolff ++Darren Worrall + Gordon Worley + Thomas Wouters + Heiko Wundram +Index: Misc/README +=================================================================== +--- Misc/README (.../tags/r311) (Revision 76056) ++++ Misc/README (.../branches/release31-maint) (Revision 76056) +@@ -9,24 +9,32 @@ + + ACKS Acknowledgements + AIX-NOTES Notes for building Python on AIX ++build.sh Script to build and test latest Python from the repository + cheatsheet Quick summary of Python by Ken Manheimer +-find_recursionlimit.py Script to find a value for sys.maxrecursionlimit ++developers.txt A history of who got developer permissions, and why + gdbinit Handy stuff to put in your .gdbinit file, if you use gdb + HISTORY News from previous releases -- oldest last +-HPUX-NOTES Notes about dynamic loading under HP-UX + indent.pro GNU indent profile approximating my C style ++maintainers.txt A list of maintainers for library modules + NEWS News for this release (for some meaning of "this") ++NEWS.help How to edit NEWS + Porting Mini-FAQ on porting to new platforms + PURIFY.README Information for Purify users + pymemcompat.h Memory interface compatibility file. + python.man UNIX man page for the python interpreter + python-mode.el Emacs mode for editing Python programs ++python.pc.in Package configuration info template for pkg-config + python-wing.wpr Wing IDE project file + README The file you're reading now ++README.coverity Information about running Coverity's Prevent on Python ++README.klocwork Information about running Klocwork's K7 on Python ++README.OpenBSD Help for building problems on OpenBSD + README.valgrind Information for Valgrind users, see valgrind-python.supp + RFD Request For Discussion about a Python newsgroup + RPM (Old) tools to build RPMs ++setuid-prog.c C helper program for set-uid Python scripts + SpecialBuilds.txt Describes extra symbols you can set for debug builds +-setuid-prog.c C helper program for set-uid Python scripts ++TextMate A TextMate bundle for Python development ++valgrind-python.supp Valgrind suppression file, see README.valgrind + vgrindefs Python configuration for vgrind (a generic pretty printer) +-valgrind-python.supp Valgrind suppression file, see README.valgrind ++Vim Python development utilities for the Vim editor +\ No newline at end of file +Index: Mac/BuildScript/scripts/postflight.framework +=================================================================== +--- Mac/BuildScript/scripts/postflight.framework (.../tags/r311) (Revision 76056) ++++ Mac/BuildScript/scripts/postflight.framework (.../branches/release31-maint) (Revision 76056) +@@ -6,28 +6,27 @@ + PYVER="@PYVER@" + FWK="/Library/Frameworks/Python.framework/Versions/@PYVER@" + +-"${FWK}/bin/python" -Wi \ ++"${FWK}/bin/python@PYVER@" -Wi \ + "${FWK}/lib/python${PYVER}/compileall.py" \ + -x badsyntax -x site-packages \ + "${FWK}/lib/python${PYVER}" + +-"${FWK}/bin/python" -Wi -O \ ++"${FWK}/bin/python@PYVER@" -Wi -O \ + "${FWK}/lib/python${PYVER}/compileall.py" \ + -x badsyntax -x site-packages \ + "${FWK}/lib/python${PYVER}" + +-"${FWK}/bin/python" -Wi \ ++"${FWK}/bin/python@PYVER@" -Wi \ + "${FWK}/lib/python${PYVER}/compileall.py" \ + -x badsyntax -x site-packages \ + "${FWK}/Mac/Tools" + +-"${FWK}/bin/python" -Wi -O \ ++"${FWK}/bin/python@PYVER@" -Wi -O \ + "${FWK}/lib/python${PYVER}/compileall.py" \ + -x badsyntax -x site-packages \ + "${FWK}/Mac/Tools" + +- +-chown -R admin "${FWK}" ++chgrp -R admin "${FWK}" + chmod -R g+w "${FWK}" + + exit 0 +Index: Tools/scripts/pathfix.py +=================================================================== +--- Tools/scripts/pathfix.py (.../tags/r311) (Revision 76056) ++++ Tools/scripts/pathfix.py (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,4 @@ +-#! /usr/bin/env python ++#!/usr/bin/env python3 + + # Change the #! line occurring in Python scripts. The new interpreter + # pathname must be given with a -i option. +@@ -43,8 +43,9 @@ + sys.exit(2) + for o, a in opts: + if o == '-i': +- new_interpreter = a +- if not new_interpreter or new_interpreter[0] != '/' or not args: ++ new_interpreter = a.encode() ++ if not new_interpreter or not new_interpreter.startswith(b'/') or \ ++ not args: + err('-i option or file-or-directory missing\n') + err(usage) + sys.exit(2) +@@ -61,7 +62,7 @@ + + ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$') + def ispython(name): +- return ispythonprog.match(name) >= 0 ++ return bool(ispythonprog.match(name)) + + def recursedown(dirname): + dbg('recursedown(%r)\n' % (dirname,)) +@@ -88,7 +89,7 @@ + def fix(filename): + ## dbg('fix(%r)\n' % (filename,)) + try: +- f = open(filename, 'r') ++ f = open(filename, 'rb') + except IOError as msg: + err('%s: cannot open: %r\n' % (filename, msg)) + return 1 +@@ -101,7 +102,7 @@ + head, tail = os.path.split(filename) + tempname = os.path.join(head, '@' + tail) + try: +- g = open(tempname, 'w') ++ g = open(tempname, 'wb') + except IOError as msg: + f.close() + err('%s: cannot create: %r\n' % (tempname, msg)) +@@ -139,11 +140,11 @@ + return 0 + + def fixline(line): +- if not line.startswith('#!'): ++ if not line.startswith(b'#!'): + return line +- if "python" not in line: ++ if b"python" not in line: + return line +- return '#! %s\n' % new_interpreter ++ return b'#! ' + new_interpreter + b'\n' + + if __name__ == '__main__': + main() +Index: Tools/scripts/find_recursionlimit.py +=================================================================== +--- Tools/scripts/find_recursionlimit.py (.../tags/r311) (Revision 0) ++++ Tools/scripts/find_recursionlimit.py (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,118 @@ ++#! /usr/bin/env python ++"""Find the maximum recursion limit that prevents interpreter termination. ++ ++This script finds the maximum safe recursion limit on a particular ++platform. If you need to change the recursion limit on your system, ++this script will tell you a safe upper bound. To use the new limit, ++call sys.setrecursionlimit(). ++ ++This module implements several ways to create infinite recursion in ++Python. Different implementations end up pushing different numbers of ++C stack frames, depending on how many calls through Python's abstract ++C API occur. ++ ++After each round of tests, it prints a message: ++"Limit of NNNN is fine". ++ ++The highest printed value of "NNNN" is therefore the highest potentially ++safe limit for your system (which depends on the OS, architecture, but also ++the compilation flags). Please note that it is practically impossible to ++test all possible recursion paths in the interpreter, so the results of ++this test should not be trusted blindly -- although they give a good hint ++of which values are reasonable. ++ ++NOTE: When the C stack space allocated by your system is exceeded due ++to excessive recursion, exact behaviour depends on the platform, although ++the interpreter will always fail in a likely brutal way: either a ++segmentation fault, a MemoryError, or just a silent abort. ++ ++NB: A program that does not use __methods__ can set a higher limit. ++""" ++ ++import sys ++import itertools ++ ++class RecursiveBlowup1: ++ def __init__(self): ++ self.__init__() ++ ++def test_init(): ++ return RecursiveBlowup1() ++ ++class RecursiveBlowup2: ++ def __repr__(self): ++ return repr(self) ++ ++def test_repr(): ++ return repr(RecursiveBlowup2()) ++ ++class RecursiveBlowup4: ++ def __add__(self, x): ++ return x + self ++ ++def test_add(): ++ return RecursiveBlowup4() + RecursiveBlowup4() ++ ++class RecursiveBlowup5: ++ def __getattr__(self, attr): ++ return getattr(self, attr) ++ ++def test_getattr(): ++ return RecursiveBlowup5().attr ++ ++class RecursiveBlowup6: ++ def __getitem__(self, item): ++ return self[item - 2] + self[item - 1] ++ ++def test_getitem(): ++ return RecursiveBlowup6()[5] ++ ++def test_recurse(): ++ return test_recurse() ++ ++def test_cpickle(_cache={}): ++ import io ++ try: ++ import _pickle ++ except ImportError: ++ print("cannot import _pickle, skipped!") ++ return ++ l = None ++ for n in itertools.count(): ++ try: ++ l = _cache[n] ++ continue # Already tried and it works, let's save some time ++ except KeyError: ++ for i in range(100): ++ l = [l] ++ _pickle.Pickler(io.BytesIO(), protocol=-1).dump(l) ++ _cache[n] = l ++ ++def check_limit(n, test_func_name): ++ sys.setrecursionlimit(n) ++ if test_func_name.startswith("test_"): ++ print(test_func_name[5:]) ++ else: ++ print(test_func_name) ++ test_func = globals()[test_func_name] ++ try: ++ test_func() ++ # AttributeError can be raised because of the way e.g. PyDict_GetItem() ++ # silences all exceptions and returns NULL, which is usually interpreted ++ # as "missing attribute". ++ except (RuntimeError, AttributeError): ++ pass ++ else: ++ print("Yikes!") ++ ++limit = 1000 ++while 1: ++ check_limit(limit, "test_recurse") ++ check_limit(limit, "test_add") ++ check_limit(limit, "test_repr") ++ check_limit(limit, "test_init") ++ check_limit(limit, "test_getattr") ++ check_limit(limit, "test_getitem") ++ check_limit(limit, "test_cpickle") ++ print("Limit of %d is fine" % limit) ++ limit = limit + 100 + +Eigenschaftsänderungen: Tools/scripts/find_recursionlimit.py +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native +Hinzugefügt: svn:keywords + + Author Date Id Revision + +Index: Tools/scripts/README +=================================================================== +--- Tools/scripts/README (.../tags/r311) (Revision 76056) ++++ Tools/scripts/README (.../branches/release31-maint) (Revision 76056) +@@ -19,7 +19,8 @@ + diff.py Print file diffs in context, unified, or ndiff formats + dutree.py Format du(1) output as a tree sorted by size + eptags.py Create Emacs TAGS file for Python modules +-finddiv.py A grep-like tool that looks for division operators. ++find_recursionlimit.py Find the maximum recursion limit on this machine ++finddiv.py A grep-like tool that looks for division operators + findlinksto.py Recursively find symbolic links to a given path prefix + findnocoding.py Find source files which need an encoding declaration + fixcid.py Massive identifier substitution on C source files +@@ -28,8 +29,8 @@ + fixnotice.py Fix the copyright notice in source files + fixps.py Fix Python scripts' first line (if #!) + ftpmirror.py FTP mirror script +-google.py Open a webbrowser with Google. +-gprof2html.py Transform gprof(1) output into useful HTML. ++google.py Open a webbrowser with Google ++gprof2html.py Transform gprof(1) output into useful HTML + h2py.py Translate #define's into Python assignments + idle Main program to start IDLE + ifdef.py Remove #if(n)def groups from C sources +@@ -55,9 +56,9 @@ + redemo.py Basic regular expression demonstration facility + reindent.py Change .py files to use 4-space indents. + rgrep.py Reverse grep through a file (useful for big logfiles) +-setup.py Install all scripts listed here. ++setup.py Install all scripts listed here + suff.py Sort a list of files by suffix +-svneol.py Sets svn:eol-style on all files in directory. ++svneol.py Sets svn:eol-style on all files in directory + texcheck.py Validate Python LaTeX formatting (Raymond Hettinger) + texi2html.py Convert GNU texinfo files into HTML + treesync.py Synchronize source trees (very ideosyncratic) +Index: Tools/pybench/README +=================================================================== +--- Tools/pybench/README (.../tags/r311) (Revision 76056) ++++ Tools/pybench/README (.../branches/release31-maint) (Revision 76056) +@@ -260,10 +260,7 @@ + + # Run test rounds + # +- # NOTE: Use xrange() for all test loops unless you want to face +- # a 20MB process ! +- # +- for i in xrange(self.rounds): ++ for i in range(self.rounds): + + # Repeat the operations per round to raise the run-time + # per operation significantly above the noise level of the +@@ -305,7 +302,7 @@ + a = 1 + + # Run test rounds (without actually doing any operation) +- for i in xrange(self.rounds): ++ for i in range(self.rounds): + + # Skip the actual execution of the operations, since we + # only want to measure the test's administration overhead. +Index: PC/pyconfig.h +=================================================================== +--- PC/pyconfig.h (.../tags/r311) (Revision 76056) ++++ PC/pyconfig.h (.../branches/release31-maint) (Revision 76056) +@@ -647,6 +647,11 @@ + #define HAVE_WCSCOLL 1 + #endif + ++/* Define to 1 if you have the `wcsxfrm' function. */ ++#ifndef MS_WINCE ++#define HAVE_WCSXFRM 1 ++#endif ++ + /* Define if you have the header file. */ + /* #undef HAVE_DLFCN_H */ + +Index: Doc/distutils/builtdist.rst +=================================================================== +--- Doc/distutils/builtdist.rst (.../tags/r311) (Revision 76056) ++++ Doc/distutils/builtdist.rst (.../branches/release31-maint) (Revision 76056) +@@ -429,14 +429,7 @@ + also the configuration. For details refer to Microsoft's documentation of the + :cfunc:`SHGetSpecialFolderPath` function. + +-Vista User Access Control (UAC) +-=============================== + +-Starting with Python 2.6, bdist_wininst supports a :option:`--user-access-control` +-option. The default is 'none' (meaning no UAC handling is done), and other +-valid values are 'auto' (meaning prompt for UAC elevation if Python was +-installed for all users) and 'force' (meaning always prompt for elevation) +- + .. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]]) + + This function creates a shortcut. *target* is the path to the program to be +@@ -447,3 +440,12 @@ + and *iconindex* is the index of the icon in the file *iconpath*. Again, for + details consult the Microsoft documentation for the :class:`IShellLink` + interface. ++ ++ ++Vista User Access Control (UAC) ++=============================== ++ ++Starting with Python 2.6, bdist_wininst supports a :option:`--user-access-control` ++option. The default is 'none' (meaning no UAC handling is done), and other ++valid values are 'auto' (meaning prompt for UAC elevation if Python was ++installed for all users) and 'force' (meaning always prompt for elevation). +Index: Doc/distutils/apiref.rst +=================================================================== +--- Doc/distutils/apiref.rst (.../tags/r311) (Revision 76056) ++++ Doc/distutils/apiref.rst (.../branches/release31-maint) (Revision 76056) +@@ -1095,7 +1095,10 @@ + the univeral binary status instead of the architecture of the current + processor. For 32-bit universal binaries the architecture is ``fat``, + for 64-bit universal binaries the architecture is ``fat64``, and +- for 4-way universal binaries the architecture is ``universal``. ++ for 4-way universal binaries the architecture is ``universal``. Starting ++ from Python 2.7 and Python 3.2 the architecture ``fat3`` is used for ++ a 3-way universal build (ppc, i386, x86_64) and ``intel`` is used for ++ a univeral build with the i386 and x86_64 architectures + + Examples of returned values on Mac OS X: + +@@ -1105,6 +1108,8 @@ + + * ``macosx-10.5-universal`` + ++ * ``macosx-10.6-intel`` ++ + .. % XXX isn't this also provided by some other non-distutils module? + + +@@ -1971,9 +1976,9 @@ + Subclasses of :class:`Command` must define the following methods. + + +-.. method:: Command.initialize_options()(S) ++.. method:: Command.initialize_options() + +- et default values for all the options that this command supports. Note that ++ Set default values for all the options that this command supports. Note that + these defaults may be overridden by other commands, by the setup script, by + config files, or by the command-line. Thus, this is not the place to code + dependencies between options; generally, :meth:`initialize_options` +Index: Doc/using/windows.rst +=================================================================== +--- Doc/using/windows.rst (.../tags/r311) (Revision 76056) ++++ Doc/using/windows.rst (.../branches/release31-maint) (Revision 76056) +@@ -67,7 +67,7 @@ + `ActivePython `_ + Installer with multi-platform compatibility, documentation, PyWin32 + +-`Python Enthought Edition `_ ++`Enthought Python Distribution `_ + Popular modules (such as PyWin32) with their respective documentation, tool + suite for building extensible python applications + +@@ -221,8 +221,7 @@ + * Win32 API calls + * Registry + * Event log +-* `Microsoft Foundation Classes `_ (MFC) ++* `Microsoft Foundation Classes `_ (MFC) + user interfaces + + `PythonWin `_ ++ `MingW -- Python extensions `_ + by Trent Apted et al, 2007 + + +Index: Doc/using/cmdline.rst +=================================================================== +--- Doc/using/cmdline.rst (.../tags/r311) (Revision 76056) ++++ Doc/using/cmdline.rst (.../branches/release31-maint) (Revision 76056) +@@ -8,7 +8,7 @@ + The CPython interpreter scans the command line and the environment for various + settings. + +-.. note:: ++.. impl-detail:: + + Other implementations' command line schemes may differ. See + :ref:`implementations` for further resources. +Index: Doc/using/mac.rst +=================================================================== +--- Doc/using/mac.rst (.../tags/r311) (Revision 76056) ++++ Doc/using/mac.rst (.../branches/release31-maint) (Revision 76056) +@@ -153,7 +153,7 @@ + + *PyQt* is another popular cross-platform GUI toolkit that runs natively on Mac + OS X. More information can be found at +-http://www.riverbankcomputing.co.uk/pyqt/. ++http://www.riverbankcomputing.co.uk/software/pyqt/intro. + + + Distributing Python Applications on the Mac +Index: Doc/c-api/buffer.rst +=================================================================== +--- Doc/c-api/buffer.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/buffer.rst (.../branches/release31-maint) (Revision 76056) +@@ -10,7 +10,6 @@ + + + .. index:: +- object: buffer + single: buffer interface + + Python objects implemented in C can export a "buffer interface." These +@@ -297,14 +296,25 @@ + length. Return 0 on success and -1 (with raising an error) on error. + + ++.. index:: ++ object: memoryview ++ ++ + MemoryView objects + ================== + +-A memoryview object is an extended buffer object that could replace the buffer +-object (but doesn't have to as that could be kept as a simple 1-d memoryview +-object). It, unlike :ctype:`Py_buffer`, is a Python object (exposed as +-:class:`memoryview` in :mod:`builtins`), so it can be used with Python code. ++A memoryview object exposes the C level buffer interface to Python. + ++ + .. cfunction:: PyObject* PyMemoryView_FromObject(PyObject *obj) + + Return a memoryview object from an object that defines the buffer interface. ++ ++ ++.. cfunction:: PyObject * PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) ++ ++ Return a memoryview object to a contiguous chunk of memory (in either ++ 'C' or 'F'ortran order) from an object that defines the buffer ++ interface. If memory is contiguous, the memoryview object points to the ++ original memory. Otherwise copy is made and the memoryview points to a ++ new bytes object. +Index: Doc/c-api/bytearray.rst +=================================================================== +--- Doc/c-api/bytearray.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/bytearray.rst (.../branches/release31-maint) (Revision 76056) +@@ -18,6 +18,8 @@ + This instance of :ctype:`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) + +@@ -31,6 +33,9 @@ + subtype of the bytearray type. + + ++Direct API functions ++^^^^^^^^^^^^^^^^^^^^ ++ + .. cfunction:: PyObject* PyByteArray_FromObject(PyObject *o) + + Return a new bytearray object from any object, *o*, that implements the +@@ -45,14 +50,14 @@ + failure, *NULL* is returned. + + +-.. cfunction:: Py_ssize_t PyByteArray_Size(PyObject *bytearray) ++.. cfunction:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b) + +- Return the size of *bytearray* after checking for a *NULL* pointer. ++ Concat bytearrays *a* and *b* and return a new bytearray with the result. + + +-.. cfunction:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray) ++.. cfunction:: Py_ssize_t PyByteArray_Size(PyObject *bytearray) + +- Macro version of :cfunc:`PyByteArray_Size` that doesn't do pointer checking. ++ Return the size of *bytearray* after checking for a *NULL* pointer. + + + .. cfunction:: char* PyByteArray_AsString(PyObject *bytearray) +@@ -61,16 +66,20 @@ + *NULL* pointer. + + +-.. cfunction:: char* PyByteArray_AS_STRING(PyObject *bytearray) ++.. cfunction:: int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len) + +- Macro version of :cfunc:`PyByteArray_AsString` that doesn't check pointers. ++ Resize the internal buffer of *bytearray* to *len*. + ++Macros ++^^^^^^ + +-.. cfunction:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b) ++These macros trade safety for speed and they don't check pointers. + +- Concat bytearrays *a* and *b* and return a new bytearray with the result. ++.. cfunction:: char* PyByteArray_AS_STRING(PyObject *bytearray) + ++ Macro version of :cfunc:`PyByteArray_AsString`. + +-.. cfunction:: PyObject* PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len) + +- Resize the internal buffer of *bytearray* to *len*. ++.. cfunction:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray) ++ ++ Macro version of :cfunc:`PyByteArray_Size`. +Index: Doc/c-api/init.rst +=================================================================== +--- Doc/c-api/init.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/init.rst (.../branches/release31-maint) (Revision 76056) +@@ -366,14 +366,18 @@ + check w/ Guido. + + +-.. cfunction:: void Py_SetPythonHome(char *home) ++.. cfunction:: void Py_SetPythonHome(wchar_t *home) + + Set the default "home" directory, that is, the location of the standard + Python libraries. The libraries are searched in + :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`. ++ The argument should point to a zero-terminated character string in static ++ storage whose contents will not change for the duration of the program's ++ execution. No code in the Python interpreter will change the contents of ++ this storage. + + +-.. cfunction:: char* Py_GetPythonHome() ++.. cfunction:: w_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` +@@ -516,6 +520,22 @@ + :cfunc:`Py_NewInterpreter`), but mixing multiple interpreters and the + :cfunc:`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 ++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 ++the fork, and releasing them afterwards. In addition, it resets any ++: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:`posix_atfork` would need to be used to accomplish the same thing. ++Additionally, when extending or embedding Python, calling :cfunc:`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 ++always able to. + + .. ctype:: PyInterpreterState + +Index: Doc/c-api/typeobj.rst +=================================================================== +--- Doc/c-api/typeobj.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/typeobj.rst (.../branches/release31-maint) (Revision 76056) +@@ -1052,7 +1052,6 @@ + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; +- binaryfunc nb_inplace_divide; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; +Index: Doc/c-api/conversion.rst +=================================================================== +--- Doc/c-api/conversion.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/conversion.rst (.../branches/release31-maint) (Revision 76056) +@@ -155,7 +155,7 @@ + See the Unix man page :manpage:`atof(2)` for details. + + .. deprecated:: 3.1 +- Use PyOS_string_to_double instead. ++ Use :cfunc:`PyOS_string_to_double` instead. + + + .. cfunction:: char* PyOS_stricmp(char *s1, char *s2) +Index: Doc/c-api/unicode.rst +=================================================================== +--- Doc/c-api/unicode.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/unicode.rst (.../branches/release31-maint) (Revision 76056) +@@ -476,11 +476,14 @@ + *byteorder == 0: native order + *byteorder == 1: big endian + +- and then switches if the first four bytes of the input data are a byte order mark +- (BOM) and the specified byte order is native order. This BOM is not copied into +- the resulting Unicode string. After completion, *\*byteorder* is set to the +- current byte order at the end of input data. ++ If ``*byteorder`` is zero, and the first four bytes of the input data are a ++ byte order mark (BOM), the decoder switches to this byte order and the BOM is ++ not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or ++ ``1``, any byte order mark is copied to the output. + ++ After completion, *\*byteorder* is set to the current byte order at the end ++ of input data. ++ + In a narrow build codepoints outside the BMP will be decoded as surrogate pairs. + + If *byteorder* is *NULL*, the codec starts in native order mode. +@@ -500,8 +503,7 @@ + .. cfunction:: 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*. If *byteorder* is not ``0``, output is written according to the +- following byte order:: ++ data in *s*. Output is written according to the following byte order:: + + byteorder == -1: little endian + byteorder == 0: native byte order (writes a BOM mark) +@@ -541,11 +543,15 @@ + *byteorder == 0: native order + *byteorder == 1: big endian + +- and then switches if the first two bytes of the input data are a byte order mark +- (BOM) and the specified byte order is native order. This BOM is not copied into +- the resulting Unicode string. After completion, *\*byteorder* is set to the +- current byte order at the end of input data. ++ If ``*byteorder`` is zero, and the first two bytes of the input data are a ++ byte order mark (BOM), the decoder switches to this byte order and the BOM is ++ not copied into the resulting Unicode string. If ``*byteorder`` is ``-1`` or ++ ``1``, any byte order mark is copied to the output (where it will result in ++ either a ``\ufeff`` or a ``\ufffe`` character). + ++ After completion, *\*byteorder* is set to the current byte order at the end ++ of input data. ++ + If *byteorder* is *NULL*, the codec starts in native order mode. + + Return *NULL* if an exception was raised by the codec. +@@ -563,8 +569,7 @@ + .. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) + + Return a Python bytes object holding the UTF-16 encoded value of the Unicode +- data in *s*. If *byteorder* is not ``0``, output is written according to the +- following byte order:: ++ data in *s*. Output is written according to the following byte order:: + + byteorder == -1: little endian + byteorder == 0: native byte order (writes a BOM mark) +Index: Doc/c-api/mapping.rst +=================================================================== +--- Doc/c-api/mapping.rst (.../tags/r311) (Revision 76056) ++++ Doc/c-api/mapping.rst (.../branches/release31-maint) (Revision 76056) +@@ -51,20 +51,20 @@ + .. cfunction:: 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()``. ++ This is equivalent to the Python expression ``list(o.keys())``. + + + .. cfunction:: 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()``. ++ *NULL*. This is equivalent to the Python expression ``list(o.values())``. + + + .. cfunction:: 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()``. ++ the Python expression ``list(o.items())``. + + + .. cfunction:: PyObject* PyMapping_GetItemString(PyObject *o, char *key) +Index: Doc/reference/datamodel.rst +=================================================================== +--- Doc/reference/datamodel.rst (.../tags/r311) (Revision 76056) ++++ Doc/reference/datamodel.rst (.../branches/release31-maint) (Revision 76056) +@@ -59,14 +59,17 @@ + they may be garbage-collected. An implementation is allowed to postpone garbage + collection or omit it altogether --- it is a matter of implementation quality + how garbage collection is implemented, as long as no objects are collected that +-are still reachable. (Implementation note: CPython currently uses a +-reference-counting scheme with (optional) delayed detection of cyclically linked +-garbage, which collects most objects as soon as they become unreachable, but is +-not guaranteed to collect garbage containing circular references. See the +-documentation of the :mod:`gc` module for information on controlling the +-collection of cyclic garbage. Other implementations act differently and CPython +-may change.) ++are still reachable. + ++.. impl-detail:: ++ ++ CPython currently uses a reference-counting scheme with (optional) delayed ++ detection of cyclically linked garbage, which collects most objects as soon ++ as they become unreachable, but is not guaranteed to collect garbage ++ containing circular references. See the documentation of the :mod:`gc` ++ module for information on controlling the collection of cyclic garbage. ++ Other implementations act differently and CPython may change. ++ + Note that the use of the implementation's tracing or debugging facilities may + keep objects alive that would normally be collectable. Also note that catching + an exception with a ':keyword:`try`...\ :keyword:`except`' statement may keep +@@ -666,7 +669,7 @@ + of the shared library file. + + Custom classes +- Custon class types are typically created by class definitions (see section ++ Custom class types are typically created by class definitions (see section + :ref:`class`). A class has a namespace implemented by a dictionary object. + Class attribute references are translated to lookups in this dictionary, e.g., + ``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of +@@ -864,6 +867,8 @@ + If a code object represents a function, the first item in :attr:`co_consts` is + the documentation string of the function, or ``None`` if undefined. + ++ .. _frame-objects: ++ + Frame objects + .. index:: object: frame + +@@ -1467,15 +1472,15 @@ + *__slots__*; otherwise, the class attribute would overwrite the descriptor + assignment. + ++* The action of a *__slots__* declaration is limited to the class where it is ++ defined. As a result, subclasses will have a *__dict__* unless they also define ++ *__slots__* (which must only contain names of any *additional* slots). ++ + * If a class defines a slot also defined in a base class, the instance variable + defined by the base class slot is inaccessible (except by retrieving its + descriptor directly from the base class). This renders the meaning of the + program undefined. In the future, a check may be added to prevent this. + +-* The action of a *__slots__* declaration is limited to the class where it is +- defined. As a result, subclasses will have a *__dict__* unless they also define +- *__slots__*. +- + * Nonempty *__slots__* does not work for classes derived from "variable-length" + built-in types such as :class:`int`, :class:`str` and :class:`tuple`. + +@@ -1530,7 +1535,7 @@ + + The appropriate metaclass is determined by the following precedence rules: + +-* If the ``metaclass`` keyword argument is based with the bases, it is used. ++* If the ``metaclass`` keyword argument is passed with the bases, it is used. + + * Otherwise, if there is at least one base class, its metaclass is used. + +@@ -1712,14 +1717,18 @@ + supply the following special method with a more efficient implementation, which + also does not require the object be a sequence. + +- + .. method:: object.__contains__(self, item) + +- Called to implement membership test operators. Should return true if *item* is +- in *self*, false otherwise. For mapping objects, this should consider the keys +- of the mapping rather than the values or the key-item pairs. ++ Called to implement membership test operators. Should return true if *item* ++ is in *self*, false otherwise. For mapping objects, this should consider the ++ keys of the mapping rather than the values or the key-item pairs. + ++ For objects that don't define :meth:`__contains__`, the membership test first ++ tries iteration via :meth:`__iter__`, then the old sequence iteration ++ protocol via :meth:`__getitem__`, see :ref:`this section in the language ++ reference `. + ++ + .. _numeric-types: + + Emulating numeric types +Index: Doc/reference/compound_stmts.rst +=================================================================== +--- Doc/reference/compound_stmts.rst (.../tags/r311) (Revision 76056) ++++ Doc/reference/compound_stmts.rst (.../branches/release31-maint) (Revision 76056) +@@ -608,9 +608,9 @@ + .. [#] The exception is propagated to the invocation stack only if there is no + :keyword:`finally` clause that negates the exception. + +-.. [#] 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` +- statement. ++.. [#] 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` statement. + + .. [#] A string literal appearing as the first statement in the function body is + transformed into the function's ``__doc__`` attribute and therefore the +Index: Doc/reference/expressions.rst +=================================================================== +--- Doc/reference/expressions.rst (.../tags/r311) (Revision 76056) ++++ Doc/reference/expressions.rst (.../branches/release31-maint) (Revision 76056) +@@ -639,13 +639,13 @@ + raised. Otherwise, the list of filled slots is used as the argument list for + the call. + +-.. note:: ++.. impl-detail:: + +- 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 parse their +- arguments. ++ 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 ++ parse their arguments. + + If there are more positional arguments than there are formal parameter slots, a + :exc:`TypeError` exception is raised, unless a formal parameter using the syntax +@@ -1053,6 +1053,8 @@ + supported cross-type comparisons and unsupported comparisons. For example, + ``Decimal(2) == 2`` and `2 == float(2)`` but ``Decimal(2) != float(2)``. + ++.. _membership-test-details: ++ + The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in + s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not + in s`` returns the negation of ``x in s``. All built-in sequences and set types +@@ -1069,7 +1071,12 @@ + For user-defined classes which define the :meth:`__contains__` method, ``x in + y`` is true if and only if ``y.__contains__(x)`` is true. + +-For user-defined classes which do not define :meth:`__contains__` and do define ++For user-defined classes which do not define :meth:`__contains__` but do define ++:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is ++produced while iterating over ``y``. If an exception is raised during the ++iteration, it is as if :keyword:`in` raised that exception. ++ ++Lastly, the old-style iteration protocol is tried: if a class defines + :meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative + integer index *i* such that ``x == y[i]``, and all lower integer indices do not + raise :exc:`IndexError` exception. (If any other exception is raised, it is as +Index: Doc/reference/simple_stmts.rst +=================================================================== +--- Doc/reference/simple_stmts.rst (.../tags/r311) (Revision 76056) ++++ Doc/reference/simple_stmts.rst (.../branches/release31-maint) (Revision 76056) +@@ -170,6 +170,25 @@ + perform the assignment, it raises an exception (usually but not necessarily + :exc:`AttributeError`). + ++ .. _attr-target-note: ++ ++ Note: If the object is a class instance and the attribute reference occurs on ++ both sides of the assignment operator, the RHS expression, ``a.x`` can access ++ either an instance attribute or (if no instance attribute exists) a class ++ attribute. The LHS target ``a.x`` is always set as an instance attribute, ++ creating it if necessary. Thus, the two occurrences of ``a.x`` do not ++ necessarily refer to the same attribute: if the RHS expression refers to a ++ class attribute, the LHS creates a new instance attribute as the target of the ++ assignment:: ++ ++ class Cls: ++ x = 3 # class variable ++ inst = Cls() ++ inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3 ++ ++ This description does not necessarily apply to descriptor attributes, such as ++ properties created with :func:`property`. ++ + .. index:: + pair: subscription; assignment + object: mutable +@@ -217,10 +236,12 @@ + from the length of the assigned sequence, thus changing the length of the + target sequence, if the object allows it. + +-(In the current implementation, the syntax for targets is taken to be the same +-as for expressions, and invalid syntax is rejected during the code generation +-phase, causing less detailed error messages.) ++.. impl-detail:: + ++ In the current implementation, the syntax for targets is taken to be the same ++ as for expressions, and invalid syntax is rejected during the code generation ++ phase, causing less detailed error messages. ++ + WARNING: Although the definition of assignment implies that overlaps between the + left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a`` + swaps two variables), overlaps *within* the collection of assigned-to variables +@@ -276,18 +297,10 @@ + *in-place* behavior, the binary operation performed by augmented assignment is + the same as the normal binary operations. + +-For targets which are attribute references, the initial value is retrieved with +-a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice +-that the two methods do not necessarily refer to the same variable. When +-:meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an +-instance variable. For example:: ++For targets which are attribute references, the same :ref:`caveat about class ++and instance attributes ` applies as for regular assignments. + +- class A: +- x = 3 # class variable +- a = A() +- a.x += 1 # writes a.x as 4 leaving A.x as 3 + +- + .. _assert: + + The :keyword:`assert` statement +@@ -796,7 +809,7 @@ + + The :keyword:`from` form with ``*`` may only occur in a module scope. The wild + card form of import --- ``import *`` --- is only allowed at the module level. +-Attempting to use it in class for function definitions will raise a ++Attempting to use it in class or function definitions will raise a + :exc:`SyntaxError`. + + .. index:: +@@ -924,10 +937,12 @@ + parameters or in a :keyword:`for` loop control target, :keyword:`class` + definition, function definition, or :keyword:`import` statement. + +-(The current implementation does not enforce the latter two restrictions, but +-programs should not abuse this freedom, as future implementations may enforce +-them or silently change the meaning of the program.) ++.. impl-detail:: + ++ The current implementation does not enforce the latter two restrictions, but ++ programs should not abuse this freedom, as future implementations may enforce ++ them or silently change the meaning of the program. ++ + .. index:: + builtin: exec + builtin: eval +Index: Doc/reference/executionmodel.rst +=================================================================== +--- Doc/reference/executionmodel.rst (.../tags/r311) (Revision 76056) ++++ Doc/reference/executionmodel.rst (.../branches/release31-maint) (Revision 76056) +@@ -129,7 +129,7 @@ + itself. ``__builtins__`` can be set to a user-created dictionary to create a + weak form of restricted execution. + +-.. note:: ++.. impl-detail:: + + Users should not touch ``__builtins__``; it is strictly an implementation + detail. Users wanting to override values in the built-in namespace should +Index: Doc/whatsnew/2.0.rst +=================================================================== +--- Doc/whatsnew/2.0.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/2.0.rst (.../branches/release31-maint) (Revision 76056) +@@ -572,8 +572,7 @@ + mostly by Trent Mick of ActiveState. (Confusingly, ``sys.platform`` is still + ``'win32'`` on Win64 because it seems that for ease of porting, MS Visual C++ + treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the +-Python CE page at http://starship.python.net/crew/mhammond/ce/ for more +-information. ++Python CE page at http://pythonce.sourceforge.net/ for more information. + + Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0. + Dynamic loading works, if you specify "configure --with-dyld --with-suffix=.x". +@@ -1041,8 +1040,8 @@ + to include SSL support, which adds an additional function to the :mod:`socket` + module: :func:`socket.ssl(socket, keyfile, certfile)`, which takes a socket + object and returns an SSL socket. The :mod:`httplib` and :mod:`urllib` modules +-were also changed to support "https://" URLs, though no one has implemented FTP +-or SMTP over SSL. ++were also changed to support ``https://`` URLs, though no one has implemented ++FTP or SMTP over SSL. + + The :mod:`httplib` module has been rewritten by Greg Stein to support HTTP/1.1. + Backward compatibility with the 1.5 version of :mod:`httplib` is provided, +Index: Doc/whatsnew/3.0.rst +=================================================================== +--- Doc/whatsnew/3.0.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/3.0.rst (.../branches/release31-maint) (Revision 76056) +@@ -804,8 +804,8 @@ + ``f(*args)``. + + * Removed :func:`callable`. Instead of ``callable(f)`` you can use +- ``hasattr(f, '__call__')``. The :func:`operator.isCallable` function +- is also gone. ++ ``isinstance(f, collections.Callable)``. The :func:`operator.isCallable` ++ function is also gone. + + * Removed :func:`coerce`. This function no longer serves a purpose + now that classic classes are gone. +Index: Doc/whatsnew/2.2.rst +=================================================================== +--- Doc/whatsnew/2.2.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/2.2.rst (.../branches/release31-maint) (Revision 76056) +@@ -30,7 +30,7 @@ + to the PEP for a particular new feature. + + +-.. seealso:: ++.. seealso (now defunct) + + http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm + "What's So Special About Python 2.2?" is also about the new 2.2 features, and +@@ -49,14 +49,14 @@ + complicated section of this article, I'll provide an overview of the changes and + offer some comments. + +-A long time ago I wrote a Web page (http://www.amk.ca/python/writing/warts.html) +-listing flaws in Python's design. One of the most significant flaws was that +-it's impossible to subclass Python types implemented in C. In particular, it's +-not possible to subclass built-in types, so you can't just subclass, say, lists +-in order to add a single useful method to them. The :mod:`UserList` module +-provides a class that supports all of the methods of lists and that can be +-subclassed further, but there's lots of C code that expects a regular Python +-list and won't accept a :class:`UserList` instance. ++A long time ago I wrote a Web page listing flaws in Python's design. One of the ++most significant flaws was that it's impossible to subclass Python types ++implemented in C. In particular, it's not possible to subclass built-in types, ++so you can't just subclass, say, lists in order to add a single useful method to ++them. The :mod:`UserList` module provides a class that supports all of the ++methods of lists and that can be subclassed further, but there's lots of C code ++that expects a regular Python list and won't accept a :class:`UserList` ++instance. + + Python 2.2 fixes this, and in the process adds some exciting new capabilities. + A brief summary: +Index: Doc/whatsnew/2.3.rst +=================================================================== +--- Doc/whatsnew/2.3.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/2.3.rst (.../branches/release31-maint) (Revision 76056) +@@ -1855,10 +1855,10 @@ + + .. seealso:: + +- http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c +- For the full details of the pymalloc implementation, see the comments at the top +- of the file :file:`Objects/obmalloc.c` in the Python source code. The above +- link points to the file within the SourceForge CVS browser. ++ http://svn.python.org/view/python/trunk/Objects/obmalloc.c ++ For the full details of the pymalloc implementation, see the comments at ++ the top of the file :file:`Objects/obmalloc.c` in the Python source code. ++ The above link points to the file within the python.org SVN browser. + + .. ====================================================================== + +Index: Doc/whatsnew/2.4.rst +=================================================================== +--- Doc/whatsnew/2.4.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/2.4.rst (.../branches/release31-maint) (Revision 76056) +@@ -680,9 +680,6 @@ + Written by Facundo Batista and implemented by Facundo Batista, Eric Price, + Raymond Hettinger, Aahz, and Tim Peters. + +- http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html +- A more detailed overview of the IEEE-754 representation. +- + http://www.lahey.com/float.htm + The article uses Fortran code to illustrate many of the problems that floating- + point inaccuracy can cause. +@@ -756,7 +753,7 @@ + :ctype:`double` to an ASCII string. + + The code for these functions came from the GLib library +-(http://developer.gnome.org/arch/gtk/glib.html), whose developers kindly ++(http://library.gnome.org/devel/glib/stable/), whose developers kindly + relicensed the relevant functions and donated them to the Python Software + Foundation. The :mod:`locale` module can now change the numeric locale, + letting extensions such as GTK+ produce the correct results. +Index: Doc/whatsnew/2.6.rst +=================================================================== +--- Doc/whatsnew/2.6.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/2.6.rst (.../branches/release31-maint) (Revision 76056) +@@ -1828,7 +1828,7 @@ + + The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol + available, instead of restricting itself to protocol 1. +- (Contributed by W. Barnes; :issue:`1551443`.) ++ (Contributed by W. Barnes.) + + * The :mod:`cgi` module will now read variables from the query string + of an HTTP POST request. This makes it possible to use form actions +@@ -2977,7 +2977,7 @@ + * The BerkeleyDB module now has a C API object, available as + ``bsddb.db.api``. This object can be used by other C extensions + that wish to use the :mod:`bsddb` module for their own purposes. +- (Contributed by Duncan Grisby; :issue:`1551895`.) ++ (Contributed by Duncan Grisby.) + + * The new buffer interface, previously described in + `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__, +Index: Doc/whatsnew/2.7.rst +=================================================================== +--- Doc/whatsnew/2.7.rst (.../tags/r311) (Revision 76056) ++++ Doc/whatsnew/2.7.rst (.../branches/release31-maint) (Revision 76056) +@@ -505,6 +505,13 @@ + differences. :meth:`assertDictContainsSubset` checks whether + all of the key/value pairs in *first* are found in *second*. + ++ * :meth:`assertAlmostEqual` and :meth:`assertNotAlmostEqual` short-circuit ++ (automatically pass or fail without checking decimal places) if the objects ++ are equal. ++ ++ * :meth:`loadTestsFromName` properly honors the ``suiteClass`` attribute of ++ the :class:`TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.) ++ + * A new hook, :meth:`addTypeEqualityFunc` takes a type object and a + function. The :meth:`assertEqual` method will use the function + when both of the objects being compared are of the specified type. +Index: Doc/tools/sphinxext/indexcontent.html +=================================================================== +--- Doc/tools/sphinxext/indexcontent.html (.../tags/r311) (Revision 76056) ++++ Doc/tools/sphinxext/indexcontent.html (.../branches/release31-maint) (Revision 76056) +@@ -26,6 +26,8 @@ + sharing modules with others

        + ++ + + + +Index: Doc/tools/sphinxext/pyspecific.py +=================================================================== +--- Doc/tools/sphinxext/pyspecific.py (.../tags/r311) (Revision 76056) ++++ Doc/tools/sphinxext/pyspecific.py (.../branches/release31-maint) (Revision 76056) +@@ -20,7 +20,23 @@ + Body.enum.converters['lowerroman'] = \ + Body.enum.converters['upperroman'] = lambda x: None + ++# monkey-patch HTML translator to give versionmodified paragraphs a class ++def new_visit_versionmodified(self, node): ++ self.body.append(self.starttag(node, 'p', CLASS=node['type'])) ++ text = versionlabels[node['type']] % node['version'] ++ if len(node): ++ text += ': ' ++ else: ++ text += '.' ++ self.body.append('%s' % text) + ++from sphinx.writers.html import HTMLTranslator ++from sphinx.locale import versionlabels ++HTMLTranslator.visit_versionmodified = new_visit_versionmodified ++ ++ ++# Support for marking up and linking to bugs.python.org issues ++ + def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): + issue = utils.unescape(text) + text = 'issue ' + issue +@@ -28,6 +44,34 @@ + return [refnode], [] + + ++# Support for marking up implementation details ++ ++from sphinx.util.compat import Directive ++ ++class ImplementationDetail(Directive): ++ ++ has_content = True ++ required_arguments = 0 ++ optional_arguments = 1 ++ final_argument_whitespace = True ++ ++ def run(self): ++ pnode = nodes.compound(classes=['impl-detail']) ++ content = self.content ++ add_text = nodes.strong('CPython implementation detail:', ++ 'CPython implementation detail:') ++ if self.arguments: ++ n, m = self.state.inline_text(self.arguments[0], self.lineno) ++ pnode.append(nodes.paragraph('', '', *(n + m))) ++ self.state.nested_parse(content, self.content_offset, pnode) ++ if pnode.children and isinstance(pnode[0], nodes.paragraph): ++ pnode[0].insert(0, add_text) ++ pnode[0].insert(1, nodes.Text(' ')) ++ else: ++ pnode.insert(0, nodes.paragraph('', '', add_text)) ++ return [pnode] ++ ++ + # Support for building "topic help" for pydoc + + pydoc_topic_labels = [ +@@ -94,10 +138,12 @@ + finally: + f.close() + ++ + # Support for checking for suspicious markup + + import suspicious + ++ + # Support for documenting Opcodes + + import re +@@ -120,6 +166,7 @@ + + def setup(app): + app.add_role('issue', issue_role) ++ app.add_directive('impl-detail', ImplementationDetail) + app.add_builder(PydocTopicsBuilder) + app.add_builder(suspicious.CheckSuspiciousMarkupBuilder) + app.add_description_unit('opcode', 'opcode', '%s (opcode)', +Index: Doc/tools/sphinxext/static/basic.css +=================================================================== +--- Doc/tools/sphinxext/static/basic.css (.../tags/r311) (Revision 76056) ++++ Doc/tools/sphinxext/static/basic.css (.../branches/release31-maint) (Revision 76056) +@@ -5,15 +5,6 @@ + + /* -- main layout ----------------------------------------------------------- */ + +-div.documentwrapper { +- float: left; +- width: 100%; +-} +- +-div.bodywrapper { +- margin: 0 0 0 230px; +-} +- + div.clearer { + clear: both; + } +@@ -338,6 +329,12 @@ + font-style: italic; + } + ++p.deprecated { ++ background-color: #ffe4e4; ++ border: 1px solid #f66; ++ padding: 7px ++} ++ + .system-message { + background-color: #fda; + padding: 5px; +@@ -348,6 +345,21 @@ + background-color: #ffa + } + ++.impl-detail { ++ margin-top: 10px; ++ margin-bottom: 10px; ++ padding: 7px; ++ border: 1px solid #ccc; ++} ++ ++.impl-detail .compound-first { ++ margin-top: 0; ++} ++ ++.impl-detail .compound-last { ++ margin-bottom: 0; ++} ++ + /* -- code displays --------------------------------------------------------- */ + + pre { +@@ -394,7 +406,7 @@ + vertical-align: middle; + } + +-div.math p { ++div.body div.math p { + text-align: center; + } + +@@ -408,7 +420,7 @@ + div.document, + div.documentwrapper, + div.bodywrapper { +- margin: 0; ++ margin: 0 !important; + width: 100%; + } + +Index: Doc/howto/unicode.rst +=================================================================== +--- Doc/howto/unicode.rst (.../tags/r311) (Revision 76056) ++++ Doc/howto/unicode.rst (.../branches/release31-maint) (Revision 76056) +@@ -150,9 +150,8 @@ + are more efficient and convenient. + + Encodings don't have to handle every possible Unicode character, and most +-encodings don't. For example, Python's default encoding is the 'ascii' +-encoding. The rules for converting a Unicode string into the ASCII encoding are +-simple; for each code point: ++encodings don't. The rules for converting a Unicode string into the ASCII ++encoding, for example, are simple; for each code point: + + 1. If the code point is < 128, each byte is the same as the value of the code + point. +@@ -212,12 +211,13 @@ + to reading the Unicode character tables, available at + . + +-Two other good introductory articles were written by Joel Spolsky +- and Jason Orendorff +-. If this introduction didn't make +-things clear to you, you should try reading one of these alternate articles +-before continuing. ++Another good introductory article was written by Joel Spolsky ++. ++If this introduction didn't make things clear to you, you should try reading this ++alternate article before continuing. + ++.. Jason Orendorff XXX http://www.jorendorff.com/articles/unicode/ is broken ++ + Wikipedia entries are often helpful; see the entries for "character encoding" + and UTF-8 + , for example. +@@ -403,7 +403,7 @@ + from the above output, ``'Ll'`` means 'Letter, lowercase', ``'No'`` means + "Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol, + other". See +- for a ++ for a + list of category codes. + + References +@@ -544,7 +544,7 @@ + The first list contains UTF-8-encoded filenames, and the second list contains + the Unicode versions. + +-Note that in most occasions, the Uniode APIs should be used. The bytes APIs ++Note that in most occasions, the Unicode APIs should be used. The bytes APIs + should only be used on systems where undecodable file names can be present, + i.e. Unix systems. + +Index: Doc/howto/webservers.rst +=================================================================== +--- Doc/howto/webservers.rst (.../tags/r311) (Revision 76056) ++++ Doc/howto/webservers.rst (.../branches/release31-maint) (Revision 76056) +@@ -270,8 +270,7 @@ + * lighttpd ships its own `FastCGI module + `_ as well as an `SCGI + module `_. +-* nginx also supports `FastCGI +- `_. ++* nginx also supports `FastCGI `_. + + Once you have installed and configured the module, you can test it with the + following WSGI-application:: +@@ -525,7 +524,7 @@ + informations on a web server. + + Often relational database engines like `MySQL `_ or +-`PostgreSQL `_ are used due to their good ++`PostgreSQL `_ are used due to their good + performance handling very large databases consisting of up to millions of + entries. These are *queried* using a language called `SQL + `_. Python programmers in general do not like +@@ -629,7 +628,7 @@ + It has a big, international community which has created many sites using Django. + There are also quite a lot of add-on projects which extend Django's normal + functionality. This is partly due to Django's well written `online +-documentation `_ and the `Django book ++documentation `_ and the `Django book + `_. + + +Index: Doc/tutorial/modules.rst +=================================================================== +--- Doc/tutorial/modules.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/modules.rst (.../branches/release31-maint) (Revision 76056) +@@ -107,6 +107,10 @@ + an unknown set of names into the interpreter, possibly hiding some things + you have already defined. + ++Note that in general the practice of importing ``*`` from a module or package is ++frowned upon, since it often causes poorly readable code. However, it is okay to ++use it to save typing in interactive sessions. ++ + .. note:: + + For efficiency reasons, each module is only imported once per interpreter +@@ -445,14 +449,9 @@ + + Now what happens when the user writes ``from sound.effects import *``? Ideally, + one would hope that this somehow goes out to the filesystem, finds which +-submodules are present in the package, and imports them all. Unfortunately, +-this operation does not work very well on Windows platforms, where the +-filesystem does not always have accurate information about the case of a +-filename. On these platforms, there is no guaranteed way to know whether a file +-:file:`ECHO.PY` should be imported as a module :mod:`echo`, :mod:`Echo` or +-:mod:`ECHO`. (For example, Windows 95 has the annoying practice of showing all +-file names with a capitalized first letter.) The DOS 8+3 filename restriction +-adds another interesting problem for long module names. ++submodules are present in the package, and imports them all. This could take a ++long time and importing sub-modules might have unwanted side-effects that should ++only happen when the sub-module is explicitly imported. + + The only solution is for the package author to provide an explicit index of the + package. The :keyword:`import` statement uses the following convention: if a package's +@@ -487,10 +486,9 @@ + when the ``from...import`` statement is executed. (This also works when + ``__all__`` is defined.) + +-Note that in general the practice of importing ``*`` from a module or package is +-frowned upon, since it often causes poorly readable code. However, it is okay to +-use it to save typing in interactive sessions, and certain modules are designed +-to export only names that follow certain patterns. ++Although certain modules are designed to export only names that follow certain ++patterns when you use ``import *``, it is still considered bad practise in ++production code. + + Remember, there is nothing wrong with using ``from Package import + specific_submodule``! In fact, this is the recommended notation unless the +Index: Doc/tutorial/errors.rst +=================================================================== +--- Doc/tutorial/errors.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/errors.rst (.../branches/release31-maint) (Revision 76056) +@@ -242,9 +242,10 @@ + User-defined Exceptions + ======================= + +-Programs may name their own exceptions by creating a new exception class. +-Exceptions should typically be derived from the :exc:`Exception` class, either +-directly or indirectly. For example:: ++Programs may name their own exceptions by creating a new exception class (see ++:ref:`tut-classes` for more about Python classes). Exceptions should typically ++be derived from the :exc:`Exception` class, either directly or indirectly. For ++example:: + + >>> class MyError(Exception): + ... def __init__(self, value): +Index: Doc/tutorial/classes.rst +=================================================================== +--- Doc/tutorial/classes.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/classes.rst (.../branches/release31-maint) (Revision 76056) +@@ -51,8 +51,8 @@ + + .. _tut-scopes: + +-Python Scopes and Name Spaces +-============================= ++Python Scopes and Namespaces ++============================ + + Before introducing classes, I first have to tell you something about Python's + scope rules. Class definitions play some neat tricks with namespaces, and you +@@ -87,7 +87,7 @@ + :keyword:`del` statement. For example, ``del modname.the_answer`` will remove + the attribute :attr:`the_answer` from the object named by ``modname``. + +-Name spaces are created at different moments and have different lifetimes. The ++Namespaces are created at different moments and have different lifetimes. The + namespace containing the built-in names is created when the Python interpreter + starts up, and is never deleted. The global namespace for a module is created + when the module definition is read in; normally, module namespaces also last +@@ -381,9 +381,9 @@ + attribute that is a function object, a method object is created by packing + (pointers to) the instance object and the function object just found together in + an abstract object: this is the method object. When the method object is called +-with an argument list, it is unpacked again, a new argument list is constructed +-from the instance object and the original argument list, and the function object +-is called with this new argument list. ++with an argument list, a new argument list is constructed from the instance ++object and the argument list, and the function object is called with this new ++argument list. + + + .. _tut-remarks: +Index: Doc/tutorial/inputoutput.rst +=================================================================== +--- Doc/tutorial/inputoutput.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/inputoutput.rst (.../branches/release31-maint) (Revision 76056) +@@ -126,12 +126,12 @@ + + Basic usage of the :meth:`str.format` method looks like this:: + +- >>> print('We are the {0} who say "{1}!"'.format('knights', 'Ni')) ++ >>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) + We are the knights who say "Ni!" + + The brackets and characters within them (called format fields) are replaced with +-the objects passed into the :meth:`~str.format` method. The number in the +-brackets refers to the position of the object passed into the ++the objects passed into the :meth:`~str.format` method. A number in the ++brackets can be used to refer to the position of the object passed into the + :meth:`~str.format` method. :: + + >>> print('{0} and {1}'.format('spam', 'eggs')) +@@ -152,6 +152,15 @@ + other='Georg')) + The story of Bill, Manfred, and Georg. + ++``'!a'`` (apply :func:`ascii`), ``'!s'`` (apply :func:`str`) and ``'!r'`` ++(apply :func:`repr`) can be used to convert the value before it is formatted:: ++ ++ >>> import math ++ >>> print('The value of PI is approximately {}.'.format(math.pi)) ++ The value of PI is approximately 3.14159265359. ++ >>> print('The value of PI is approximately {!r}.'.format(math.pi)) ++ The value of PI is approximately 3.141592653589793. ++ + An optional ``':'`` and format specifier can follow the field name. This allows + greater control over how the value is formatted. The following example + truncates Pi to three places after the decimal. +Index: Doc/tutorial/introduction.rst +=================================================================== +--- Doc/tutorial/introduction.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/introduction.rst (.../branches/release31-maint) (Revision 76056) +@@ -150,7 +150,6 @@ + 4.0 + >>> abs(a) # sqrt(a.real**2 + a.imag**2) + 5.0 +- >>> + + In interactive mode, the last printed expression is assigned to the variable + ``_``. This means that when you are using Python as a desk calculator, it is +@@ -164,7 +163,6 @@ + 113.0625 + >>> round(_, 2) + 113.06 +- >>> + + This variable should be treated as read-only by the user. Don't explicitly + assign a value to it --- you would create an independent local variable with the +@@ -212,12 +210,32 @@ + + Note that newlines still need to be embedded in the string using ``\n``; the + newline following the trailing backslash is discarded. This example would print +-the following:: ++the following: + ++.. code-block:: text ++ + This is a rather long string containing + several lines of text just as you would do in C. + Note that whitespace at the beginning of the line is significant. + ++Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or ++``'''``. End of lines do not need to be escaped when using triple-quotes, but ++they will be included in the string. :: ++ ++ print(""" ++ Usage: thingy [OPTIONS] ++ -h Display this usage message ++ -H hostname Hostname to connect to ++ """) ++ ++produces the following output: ++ ++.. code-block:: text ++ ++ Usage: thingy [OPTIONS] ++ -h Display this usage message ++ -H hostname Hostname to connect to ++ + If we make the string literal a "raw" string, ``\n`` sequences are not converted + to newlines, but the backslash at the end of the line, and the newline character + in the source, are both included in the string as data. Thus, the example:: +@@ -227,8 +245,10 @@ + + print(hello) + +-would print:: ++would print: + ++.. code-block:: text ++ + This is a rather long string containing\n\ + several lines of text much as you would do in C. + +Index: Doc/tutorial/interpreter.rst +=================================================================== +--- Doc/tutorial/interpreter.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/interpreter.rst (.../branches/release31-maint) (Revision 76056) +@@ -31,7 +31,7 @@ + Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on + Windows) at the primary prompt causes the interpreter to exit with a zero exit + status. If that doesn't work, you can exit the interpreter by typing the +-following commands: ``import sys; sys.exit()``. ++following command: ``quit()``. + + The interpreter's line-editing features usually aren't very sophisticated. On + Unix, whoever installed the interpreter may have enabled support for the GNU +@@ -102,12 +102,12 @@ + before printing the first prompt:: + + $ python3.1 +- Python 3.1a1 (py3k, Sep 12 2007, 12:21:02) ++ Python 3.1 (py3k, Sep 12 2007, 12:21:02) + [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 + Type "help", "copyright", "credits" or "license" for more information. + >>> + +-.. XXX update for final release of Python 3.1 ++.. XXX update for new releases + + Continuation lines are needed when entering a multi-line construct. As an + example, take a look at this :keyword:`if` statement:: +@@ -243,7 +243,7 @@ + + .. rubric:: Footnotes + +-.. [#] On Unix, the 3.1 interpreter is by default not installed with the ++.. [#] On Unix, the Python 3.x interpreter is by default not installed with the + executable named ``python``, so that it does not conflict with a + simultaneously installed Python 2.x executable. + +Index: Doc/tutorial/index.rst +=================================================================== +--- Doc/tutorial/index.rst (.../tags/r311) (Revision 76056) ++++ Doc/tutorial/index.rst (.../branches/release31-maint) (Revision 76056) +@@ -28,18 +28,17 @@ + interpreter handy for hands-on experience, but all examples are self-contained, + so the tutorial can be read off-line as well. + +-For a description of standard objects and modules, see the Python Library +-Reference document. The Python Reference Manual gives a more formal definition +-of the language. To write extensions in C or C++, read Extending and Embedding +-the Python Interpreter and Python/C API Reference. There are also several books +-covering Python in depth. ++For a description of standard objects and modules, see :ref:`library-index`. ++:ref:`reference-index` gives a more formal definition of the language. To write ++extensions in C or C++, read :ref:`extending-index` and ++:ref:`c-api-index`. There are also several books covering Python in depth. + + This tutorial does not attempt to be comprehensive and cover every single + feature, or even every commonly used feature. Instead, it introduces many of + Python's most noteworthy features, and will give you a good idea of the + language's flavor and style. After reading it, you will be able to read and + write Python modules and programs, and you will be ready to learn more about the +-various Python library modules described in the Python Library Reference. ++various Python library modules described in :ref:`library-index`. + + The :ref:`glossary` is also worth going through. + +Index: Doc/library/xmlrpc.server.rst +=================================================================== +--- Doc/library/xmlrpc.server.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xmlrpc.server.rst (.../branches/release31-maint) (Revision 76056) +@@ -13,7 +13,7 @@ + :class:`CGIXMLRPCRequestHandler`. + + +-.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]]) ++.. class:: SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True) + + Create a new server instance. This class provides methods for registration of + functions that can be called by the XML-RPC protocol. The *requestHandler* +@@ -29,7 +29,7 @@ + the *allow_reuse_address* class variable before the address is bound. + + +-.. class:: CGIXMLRPCRequestHandler([allow_none[, encoding]]) ++.. class:: CGIXMLRPCRequestHandler(allow_none=False, encoding=None) + + Create a new instance to handle XML-RPC requests in a CGI environment. The + *allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client` +@@ -53,7 +53,7 @@ + alone XML-RPC servers. + + +-.. method:: SimpleXMLRPCServer.register_function(function[, name]) ++.. method:: SimpleXMLRPCServer.register_function(function, name=None) + + Register a function that can respond to XML-RPC requests. If *name* is given, + it will be the method name associated with *function*, otherwise +@@ -62,7 +62,7 @@ + the period character. + + +-.. method:: SimpleXMLRPCServer.register_instance(instance[, allow_dotted_names]) ++.. method:: SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False) + + Register an object which is used to expose method names which have not been + registered using :meth:`register_function`. If *instance* contains a +@@ -167,7 +167,7 @@ + requests sent to Python CGI scripts. + + +-.. method:: CGIXMLRPCRequestHandler.register_function(function[, name]) ++.. method:: CGIXMLRPCRequestHandler.register_function(function, name=None) + + Register a function that can respond to XML-RPC requests. If *name* is given, + it will be the method name associated with function, otherwise +@@ -201,7 +201,7 @@ + Register the XML-RPC multicall function ``system.multicall``. + + +-.. method:: CGIXMLRPCRequestHandler.handle_request([request_text = None]) ++.. method:: CGIXMLRPCRequestHandler.handle_request(request_text=None) + + Handle a XML-RPC request. If *request_text* is given, it should be the POST + data provided by the HTTP server, otherwise the contents of stdin will be used. +@@ -229,7 +229,7 @@ + :class:`DocCGIXMLRPCRequestHandler`. + + +-.. class:: DocXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]]) ++.. class:: DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True) + + Create a new server instance. All parameters have the same meaning as for + :class:`SimpleXMLRPCServer`; *requestHandler* defaults to +Index: Doc/library/subprocess.rst +=================================================================== +--- Doc/library/subprocess.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/subprocess.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`subprocess` --- Subprocess management + =========================================== + +@@ -121,9 +120,10 @@ + + .. note:: + +- This feature is only available if Python is built with universal newline support +- (the default). Also, the newlines attribute of the file objects :attr:`stdout`, +- :attr:`stdin` and :attr:`stderr` are not updated by the :meth:`communicate` method. ++ This feature is only available if Python is built with universal newline ++ support (the default). Also, the newlines attribute of the file objects ++ :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the ++ :meth:`communicate` method. + + The *startupinfo* and *creationflags*, if given, will be passed to the + underlying CreateProcess() function. They can specify things such as appearance +@@ -510,13 +510,13 @@ + ... + rc = pipe.close() + if rc != None and rc % 256: +- print "There were some errors" ++ print("There were some errors") + ==> + process = Popen(cmd, 'w', stdin=PIPE) + ... + process.stdin.close() + if process.wait() != 0: +- print "There were some errors" ++ print("There were some errors") + + + Replacing functions from the :mod:`popen2` module +Index: Doc/library/csv.rst +=================================================================== +--- Doc/library/csv.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/csv.rst (.../branches/release31-maint) (Revision 76056) +@@ -97,7 +97,7 @@ + + >>> import csv + >>> spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ', +- ... quotechar='|', quoting=QUOTE_MINIMAL) ++ ... quotechar='|', quoting=csv.QUOTE_MINIMAL) + >>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) + >>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) + +Index: Doc/library/datetime.rst +=================================================================== +--- Doc/library/datetime.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/datetime.rst (.../branches/release31-maint) (Revision 76056) +@@ -63,6 +63,7 @@ + + + .. class:: date ++ :noindex: + + An idealized naive date, assuming the current Gregorian calendar always was, and + always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and +@@ -70,6 +71,7 @@ + + + .. class:: time ++ :noindex: + + An idealized time, independent of any particular day, assuming that every day + has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here). +@@ -78,6 +80,7 @@ + + + .. class:: datetime ++ :noindex: + + A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`, + :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`, +@@ -85,6 +88,7 @@ + + + .. class:: timedelta ++ :noindex: + + A duration expressing the difference between two :class:`date`, :class:`time`, + or :class:`datetime` instances to microsecond resolution. +@@ -229,7 +233,7 @@ + | | (-*t1.days*, -*t1.seconds*, | + | | -*t1.microseconds*), and to *t1*\* -1. (1)(4) | + +--------------------------------+-----------------------------------------------+ +-| ``abs(t)`` | equivalent to +*t* when ``t.days >= 0``, and | ++| ``abs(t)`` | equivalent to +\ *t* when ``t.days >= 0``, and| + | | to -*t* when ``t.days < 0``. (2) | + +--------------------------------+-----------------------------------------------+ + +Index: Doc/library/ctypes.rst +=================================================================== +--- Doc/library/ctypes.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/ctypes.rst (.../branches/release31-maint) (Revision 76056) +@@ -1592,7 +1592,7 @@ + The returned function prototype creates functions that use the standard C + calling convention. The function will release the GIL during the call. If + *use_errno* is set to True, the ctypes private copy of the system +- :data:`errno` variable is exchanged with the real :data:`errno` value bafore ++ :data:`errno` variable is exchanged with the real :data:`errno` value before + and after the call; *use_last_error* does the same for the Windows error + code. + +Index: Doc/library/xml.dom.rst +=================================================================== +--- Doc/library/xml.dom.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.dom.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.dom` --- The Document Object Model API + ================================================ + +@@ -96,7 +95,7 @@ + implementation supports some customization). + + +-.. function:: getDOMImplementation([name[, features]]) ++.. function:: getDOMImplementation(name=None, features=()) + + Return a suitable DOM implementation. The *name* is either well-known, the + module name of a DOM implementation, or ``None``. If it is not ``None``, imports +Index: Doc/library/textwrap.rst +=================================================================== +--- Doc/library/textwrap.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/textwrap.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`textwrap` --- Text wrapping and filling + ============================================= + +@@ -15,16 +14,17 @@ + otherwise, you should use an instance of :class:`TextWrapper` for efficiency. + + +-.. function:: wrap(text[, width[, ...]]) ++.. function:: wrap(text, width=70, **kwargs) + +- Wraps the single paragraph in *text* (a string) so every line is at most *width* +- characters long. Returns a list of output lines, without final newlines. ++ Wraps the single paragraph in *text* (a string) so every line is at most ++ *width* characters long. Returns a list of output lines, without final ++ newlines. + + Optional keyword arguments correspond to the instance attributes of + :class:`TextWrapper`, documented below. *width* defaults to ``70``. + + +-.. function:: fill(text[, width[, ...]]) ++.. function:: fill(text, width=70, **kwargs) + + Wraps the single paragraph in *text*, and returns a single string containing the + wrapped paragraph. :func:`fill` is shorthand for :: +@@ -70,11 +70,11 @@ + print(repr(dedent(s))) # prints 'hello\n world\n' + + +-.. class:: TextWrapper(...) ++.. class:: TextWrapper(**kwargs) + + The :class:`TextWrapper` constructor accepts a number of optional keyword +- arguments. Each argument corresponds to one instance attribute, so for example +- :: ++ arguments. Each keyword argument corresponds to an instance attribute, so ++ for example :: + + wrapper = TextWrapper(initial_indent="* ") + +Index: Doc/library/urllib.error.rst +=================================================================== +--- Doc/library/urllib.error.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/urllib.error.rst (.../branches/release31-maint) (Revision 76056) +@@ -39,7 +39,7 @@ + to a value found in the dictionary of codes as found in + :attr:`http.server.BaseHTTPRequestHandler.responses`. + +-.. exception:: ContentTooShortError(msg[, content]) ++.. exception:: ContentTooShortError(msg, content) + + This exception is raised when the :func:`urlretrieve` function detects that + the amount of the downloaded data is less than the expected amount (given by +Index: Doc/library/uu.rst +=================================================================== +--- Doc/library/uu.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/uu.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`uu` --- Encode and decode uuencode files + ============================================== + +@@ -25,7 +24,7 @@ + The :mod:`uu` module defines the following functions: + + +-.. function:: encode(in_file, out_file[, name[, mode]]) ++.. function:: encode(in_file, out_file, name=None, mode=None) + + Uuencode file *in_file* into file *out_file*. The uuencoded file will have + the header specifying *name* and *mode* as the defaults for the results of +@@ -33,7 +32,7 @@ + and ``0o666`` respectively. + + +-.. function:: decode(in_file[, out_file[, mode[, quiet]]]) ++.. function:: decode(in_file, out_file=None, mode=None, quiet=False) + + This call decodes uuencoded file *in_file* placing the result on file + *out_file*. If *out_file* is a pathname, *mode* is used to set the permission +Index: Doc/library/xml.sax.rst +=================================================================== +--- Doc/library/xml.sax.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.sax.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.sax` --- Support for SAX2 parsers + =========================================== + +@@ -17,7 +16,7 @@ + The convenience functions are: + + +-.. function:: make_parser([parser_list]) ++.. function:: make_parser(parser_list=[]) + + Create and return a SAX :class:`XMLReader` object. The first parser found will + be used. If *parser_list* is provided, it must be a sequence of strings which +@@ -25,7 +24,7 @@ + in *parser_list* will be used before modules in the default list of parsers. + + +-.. function:: parse(filename_or_stream, handler[, error_handler]) ++.. function:: parse(filename_or_stream, handler, error_handler=handler.ErrorHandler()) + + Create a SAX parser and use it to parse a document. The document, passed in as + *filename_or_stream*, can be a filename or a file object. The *handler* +@@ -35,7 +34,7 @@ + return value; all work must be done by the *handler* passed in. + + +-.. function:: parseString(string, handler[, error_handler]) ++.. function:: parseString(string, handler, error_handler=handler.ErrorHandler()) + + Similar to :func:`parse`, but parses from a buffer *string* received as a + parameter. +@@ -66,7 +65,7 @@ + classes. + + +-.. exception:: SAXException(msg[, exception]) ++.. exception:: SAXException(msg, exception=None) + + Encapsulate an XML error or warning. This class can contain basic error or + warning information from either the XML parser or the application: it can be +@@ -90,14 +89,14 @@ + interface as well as the :class:`SAXException` interface. + + +-.. exception:: SAXNotRecognizedException(msg[, exception]) ++.. exception:: SAXNotRecognizedException(msg, exception=None) + + Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is + confronted with an unrecognized feature or property. SAX applications and + extensions may use this class for similar purposes. + + +-.. exception:: SAXNotSupportedException(msg[, exception]) ++.. exception:: SAXNotSupportedException(msg, exception=None) + + Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is asked to + enable a feature that is not supported, or to set a property to a value that the +Index: Doc/library/stringprep.rst +=================================================================== +--- Doc/library/stringprep.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/stringprep.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`stringprep` --- Internet String Preparation + ================================================= + +Index: Doc/library/time.rst +=================================================================== +--- Doc/library/time.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/time.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`time` --- Time access and conversions + =========================================== + +Index: Doc/library/urllib.parse.rst +=================================================================== +--- Doc/library/urllib.parse.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/urllib.parse.rst (.../branches/release31-maint) (Revision 76056) +@@ -26,7 +26,7 @@ + + The :mod:`urllib.parse` module defines the following functions: + +-.. function:: urlparse(urlstring[, default_scheme[, allow_fragments]]) ++.. function:: urlparse(urlstring, default_scheme='', allow_fragments=True) + + Parse a URL into six components, returning a 6-tuple. This corresponds to the + general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. +@@ -89,7 +89,7 @@ + object. + + +-.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]]) ++.. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False) + + Parse a query string given as a string argument (data of type + :mimetype:`application/x-www-form-urlencoded`). Data are returned as a +@@ -110,7 +110,7 @@ + dictionaries into query strings. + + +-.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]]) ++.. function:: parse_qsl(qs, keep_blank_values=False, strict_parsing=False) + + Parse a query string given as a string argument (data of type + :mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of +@@ -139,7 +139,7 @@ + states that these are equivalent). + + +-.. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]]) ++.. function:: urlsplit(urlstring, default_scheme='', allow_fragments=True) + + This is similar to :func:`urlparse`, but does not split the params from the URL. + This should generally be used instead of :func:`urlparse` if the more recent URL +@@ -187,7 +187,7 @@ + with an empty query; the RFC states that these are equivalent). + + +-.. function:: urljoin(base, url[, allow_fragments]) ++.. function:: urljoin(base, url, allow_fragments=True) + + Construct a full ("absolute") URL by combining a "base URL" (*base*) with + another URL (*url*). Informally, this uses components of the base URL, in +@@ -223,10 +223,12 @@ + string. If there is no fragment identifier in *url*, return *url* unmodified + and an empty string. + +-.. function:: quote(string[, safe[, encoding[, errors]]]) + ++.. function:: quote(string, safe='/', encoding=None, errors=None) ++ + Replace special characters in *string* using the ``%xx`` escape. Letters, +- digits, and the characters ``'_.-'`` are never quoted. The optional *safe* ++ digits, and the characters ``'_.-'`` are never quoted. By default, this ++ function is intended for quoting the path section of URL. The optional *safe* + parameter specifies additional ASCII characters that should not be quoted + --- its default value is ``'/'``. + +@@ -246,7 +248,7 @@ + Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``. + + +-.. function:: quote_plus(string[, safe[, encoding[, errors]]]) ++.. function:: quote_plus(string, safe='', encoding=None, errors=None) + + Like :func:`quote`, but also replace spaces by plus signs, as required for + quoting HTML form values when building up a query string to go into a URL. +@@ -255,16 +257,18 @@ + + Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``. + +-.. function:: quote_from_bytes(bytes[, safe]) + ++.. function:: quote_from_bytes(bytes, safe='/') ++ + Like :func:`quote`, but accepts a :class:`bytes` object rather than a + :class:`str`, and does not perform string-to-bytes encoding. + + Example: ``quote_from_bytes(b'a&\xef')`` yields + ``'a%26%EF'``. + +-.. function:: unquote(string[, encoding[, errors]]) + ++.. function:: unquote(string, encoding='utf-8', errors='replace') ++ + Replace ``%xx`` escapes by their single-character equivalent. + The optional *encoding* and *errors* parameters specify how to decode + percent-encoded sequences into Unicode characters, as accepted by the +@@ -279,7 +283,7 @@ + Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``. + + +-.. function:: unquote_plus(string[, encoding[, errors]]) ++.. function:: unquote_plus(string, encoding='utf-8', errors='replace') + + Like :func:`unquote`, but also replace plus signs by spaces, as required for + unquoting HTML form values. +@@ -288,6 +292,7 @@ + + Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``. + ++ + .. function:: unquote_to_bytes(string) + + Replace ``%xx`` escapes by their single-octet equivalent, and return a +@@ -302,7 +307,7 @@ + ``b'a&\xef'``. + + +-.. function:: urlencode(query[, doseq]) ++.. function:: urlencode(query, doseq=False) + + Convert a mapping object or a sequence of two-element tuples to a "url-encoded" + string, suitable to pass to :func:`urlopen` above as the optional *data* +Index: Doc/library/inspect.rst +=================================================================== +--- Doc/library/inspect.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/inspect.rst (.../branches/release31-maint) (Revision 76056) +@@ -290,20 +290,24 @@ + + Return true if the object is a getset descriptor. + +- getsets are attributes defined in extension modules via ``PyGetSetDef`` +- structures. For Python implementations without such types, this method will +- always return ``False``. ++ .. impl-detail:: + ++ getsets are attributes defined in extension modules via ++ :ctype:`PyGetSetDef` structures. For Python implementations without such ++ types, this method will always return ``False``. + ++ + .. function:: ismemberdescriptor(object) + + Return true if the object is a member descriptor. + +- Member descriptors are attributes defined in extension modules via +- ``PyMemberDef`` structures. For Python implementations without such types, +- this method will always return ``False``. ++ .. impl-detail:: + ++ Member descriptors are attributes defined in extension modules via ++ :ctype:`PyMemberDef` structures. For Python implementations without such ++ types, this method will always return ``False``. + ++ + .. _inspect-source: + + Retrieving source code +@@ -508,7 +512,14 @@ + + Return the frame object for the caller's stack frame. + ++ .. impl-detail:: + ++ This function relies on Python stack frame support in the interpreter, ++ which isn't guaranteed to exist in all implementations of Python. If ++ running in an implementation without Python stack frame support this ++ function returns ``None``. ++ ++ + .. function:: stack(context=1) + + Return a list of frame records for the caller's stack. The first entry in the +Index: Doc/library/plistlib.rst +=================================================================== +--- Doc/library/plistlib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/plistlib.rst (.../branches/release31-maint) (Revision 76056) +@@ -18,18 +18,24 @@ + basic object types, like dictionaries, lists, numbers and strings. Usually the + top level object is a dictionary. + ++To write out and to parse a plist file, use the :func:`writePlist` and ++:func:`readPlist` functions. ++ ++To work with plist data in bytes objects, use :func:`writePlistToBytes` ++and :func:`readPlistFromBytes`. ++ + Values can be strings, integers, floats, booleans, tuples, lists, dictionaries + (but only with string keys), :class:`Data` or :class:`datetime.datetime` +-objects. String values (including dictionary keys) may be unicode strings -- ++objects. String values (including dictionary keys) have to be unicode strings -- + they will be written out as UTF-8. + + The ```` plist type is supported through the :class:`Data` class. This is +-a thin wrapper around a Python string. Use :class:`Data` if your strings ++a thin wrapper around a Python bytes object. Use :class:`Data` if your strings + contain control characters. + + .. seealso:: + +- `PList manual page ` ++ `PList manual page `_ + Apple's documentation of the file format. + + +@@ -55,26 +61,26 @@ + a container that contains objects of unsupported types. + + +-.. function:: readPlistFromString(data) ++.. function:: readPlistFromBytes(data) + +- Read a plist from a string. Return the root object. ++ Read a plist data from a bytes object. Return the root object. + + +-.. function:: writePlistToString(rootObject) ++.. function:: writePlistToBytes(rootObject) + +- Return *rootObject* as a plist-formatted string. ++ Return *rootObject* as a plist-formatted bytes object. + + + The following class is available: + + .. class:: Data(data) + +- Return a "data" wrapper object around the string *data*. This is used in +- functions converting from/to plists to represent the ```` type ++ Return a "data" wrapper object around the bytes object *data*. This is used ++ in functions converting from/to plists to represent the ```` type + available in plists. + + It has one attribute, :attr:`data`, that can be used to retrieve the Python +- string stored in it. ++ bytes object stored in it. + + + Examples +@@ -83,22 +89,20 @@ + Generating a plist:: + + pl = dict( +- aString="Doodah", +- aList=["A", "B", 12, 32.1, [1, 2, 3]], ++ aString = "Doodah", ++ aList = ["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, +- aDict=dict( +- anotherString="", +- aUnicodeValue=u'M\xe4ssig, Ma\xdf', +- aTrueValue=True, +- aFalseValue=False, ++ aDict = dict( ++ anotherString = "", ++ aThirdString = "M\xe4ssig, Ma\xdf", ++ aTrueValue = True, ++ aFalseValue = False, + ), +- someData = Data(""), +- someMoreData = Data("" * 10), ++ someData = Data(b""), ++ someMoreData = Data(b"" * 10), + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + ) +- # unicode keys are possible, but a little awkward to use: +- pl[u'\xc5benraa'] = "That was a unicode key." + writePlist(pl, fileName) + + Parsing a plist:: +Index: Doc/library/termios.rst +=================================================================== +--- Doc/library/termios.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/termios.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`termios` --- POSIX style tty control + ========================================== + +@@ -80,17 +79,17 @@ + Convenience functions for common terminal control operations. + + ++.. _termios-example: ++ + Example + ------- + +-.. _termios-example: +- + Here's a function that prompts for a password with echoing turned off. Note the + technique using a separate :func:`tcgetattr` call and a :keyword:`try` ... + :keyword:`finally` statement to ensure that the old tty attributes are restored + exactly no matter what happens:: + +- def getpass(prompt = "Password: "): ++ def getpass(prompt="Password: "): + import termios, sys + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) +Index: Doc/library/mailbox.rst +=================================================================== +--- Doc/library/mailbox.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/mailbox.rst (.../branches/release31-maint) (Revision 76056) +@@ -329,7 +329,7 @@ + Return a list of the names of all folders. + + +- .. method:: .et_folder(folder) ++ .. method:: get_folder(folder) + + Return a :class:`Maildir` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder +@@ -595,7 +595,7 @@ + `nmh - Message Handling System `_ + Home page of :program:`nmh`, an updated version of the original :program:`mh`. + +- `MH & nmh: Email for Users & Programmers `_ ++ `MH & nmh: Email for Users & Programmers `_ + A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information + on the mailbox format. + +Index: Doc/library/types.rst +=================================================================== +--- Doc/library/types.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/types.rst (.../branches/release31-maint) (Revision 76056) +@@ -77,5 +77,8 @@ + as ``datetime.timedelta.days``. This type is used as descriptor for simple C + data members which use standard conversion functions; it has the same purpose + as the :class:`property` type, but for classes defined in extension modules. +- In other implementations of Python, this type may be identical to +- ``GetSetDescriptorType``. ++ ++ .. impl-detail:: ++ ++ In other implementations of Python, this type may be identical to ++ ``GetSetDescriptorType``. +Index: Doc/library/pdb.rst +=================================================================== +--- Doc/library/pdb.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/pdb.rst (.../branches/release31-maint) (Revision 76056) +@@ -41,7 +41,7 @@ + :file:`pdb.py` can also be invoked as a script to debug other scripts. For + example:: + +- python -m pdb myscript.py ++ python3 -m pdb myscript.py + + When invoked as a script, pdb will automatically enter post-mortem debugging if + the program being debugged exits abnormally. After post-mortem debugging (or +Index: Doc/library/string.rst +=================================================================== +--- Doc/library/string.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/string.rst (.../branches/release31-maint) (Revision 76056) +@@ -194,7 +194,7 @@ + The grammar for a replacement field is as follows: + + .. productionlist:: sf +- replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}" ++ replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}" + field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")* + arg_name: (`identifier` | `integer`)? + attribute_name: `identifier` +@@ -202,7 +202,7 @@ + conversion: "r" | "s" | "a" + format_spec: + +-In less formal terms, the replacement field starts with a *field_name* that specifies ++In less formal terms, the replacement field can start with a *field_name* that specifies + the object whose value is to be formatted and inserted + into the output instead of the replacement field. + The *field_name* is optionally followed by a *conversion* field, which is +@@ -223,7 +223,7 @@ + + "First, thou shalt count to {0}" # References first positional argument + "Bring me a {}" # Implicitly references the first positional argument +- "From {} to {}" # Same as "From {0] to {1}" ++ "From {} to {}" # Same as "From {0} to {1}" + "My quest is {name}" # References keyword argument 'name' + "Weight in tons {0.weight}" # 'weight' attribute of first positional arg + "Units destroyed: {players[0]}" # First element of keyword argument 'players'. +@@ -243,6 +243,7 @@ + + "Harold's a clever {0!s}" # Calls str() on the argument first + "Bring out the holy {name!r}" # Calls repr() on the argument first ++ "More {!a}" # Calls ascii() on the argument first + + The *format_spec* field contains a specification of how the value should be + presented, including such details as field width, alignment, padding, decimal +@@ -422,15 +423,33 @@ + | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to | + | | ``NAN`` and ``inf`` to ``INF``. | + +---------+----------------------------------------------------------+ +- | ``'g'`` | General format. This prints the number as a fixed-point | +- | | number, unless the number is too large, in which case | +- | | it switches to ``'e'`` exponent notation. Infinity and | +- | | NaN values are formatted as ``inf``, ``-inf`` and | +- | | ``nan``, respectively. | ++ | ``'g'`` | General format. For a given precision ``p >= 1``, | ++ | | this rounds the number to ``p`` significant digits and | ++ | | then formats the result in either fixed-point format | ++ | | or in scientific notation, depending on its magnitude. | ++ | | | ++ | | The precise rules are as follows: suppose that the | ++ | | result formatted with presentation type ``'e'`` and | ++ | | precision ``p-1`` would have exponent ``exp``. Then | ++ | | if ``-4 <= exp < p``, the number is formatted | ++ | | with presentation type ``'f'`` and precision | ++ | | ``p-1-exp``. Otherwise, the number is formatted | ++ | | with presentation type ``'e'`` and precision ``p-1``. | ++ | | In both cases insignificant trailing zeros are removed | ++ | | from the significand, and the decimal point is also | ++ | | removed if there are no remaining digits following it. | ++ | | | ++ | | Postive and negative infinity, positive and negative | ++ | | zero, and nans, are formatted as ``inf``, ``-inf``, | ++ | | ``0``, ``-0`` and ``nan`` respectively, regardless of | ++ | | the precision. | ++ | | | ++ | | A precision of ``0`` is treated as equivalent to a | ++ | | precision of ``1``. | + +---------+----------------------------------------------------------+ + | ``'G'`` | General format. Same as ``'g'`` except switches to | +- | | ``'E'`` if the number gets to large. The representations | +- | | of infinity and NaN are uppercased, too. | ++ | | ``'E'`` if the number gets too large. The | ++ | | representations of infinity and NaN are uppercased, too. | + +---------+----------------------------------------------------------+ + | ``'n'`` | Number. This is the same as ``'g'``, except that it uses | + | | the current locale setting to insert the appropriate | +@@ -478,19 +497,19 @@ + The constructor takes a single argument which is the template string. + + +- .. method:: substitute(mapping[, **kws]) ++ .. method:: substitute(mapping, **kwds) + + Performs the template substitution, returning a new string. *mapping* is + any dictionary-like object with keys that match the placeholders in the + template. Alternatively, you can provide keyword arguments, where the +- keywords are the placeholders. When both *mapping* and *kws* are given +- and there are duplicates, the placeholders from *kws* take precedence. ++ keywords are the placeholders. When both *mapping* and *kwds* are given ++ and there are duplicates, the placeholders from *kwds* take precedence. + + +- .. method:: safe_substitute(mapping[, **kws]) ++ .. method:: safe_substitute(mapping, **kwds) + + Like :meth:`substitute`, except that if placeholders are missing from +- *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the ++ *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the + original placeholder will appear in the resulting string intact. Also, + unlike with :meth:`substitute`, any other appearances of the ``$`` will + simply return ``$`` instead of raising :exc:`ValueError`. +@@ -564,12 +583,14 @@ + Helper functions + ---------------- + +-.. function:: capwords(s) ++.. function:: capwords(s[, sep]) + +- Split the argument into words using :func:`split`, capitalize each word using +- :func:`capitalize`, and join the capitalized words using :func:`join`. Note +- that this replaces runs of whitespace characters by a single space, and removes +- leading and trailing whitespace. ++ Split the argument into words using :meth:`str.split`, capitalize each word ++ using :meth:`str.capitalize`, and join the capitalized words using ++ :meth:`str.join`. If the optional second argument *sep* is absent ++ or ``None``, runs of whitespace characters are replaced by a single space ++ and leading and trailing whitespace are removed, otherwise *sep* is used to ++ split and join the words. + + + .. function:: maketrans(frm, to) +Index: Doc/library/winsound.rst +=================================================================== +--- Doc/library/winsound.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/winsound.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`winsound` --- Sound-playing interface for Windows + ======================================================= + +@@ -31,7 +30,7 @@ + indicates an error, :exc:`RuntimeError` is raised. + + +-.. function:: MessageBeep([type=MB_OK]) ++.. function:: MessageBeep(type=MB_OK) + + Call the underlying :cfunc:`MessageBeep` function from the Platform API. This + plays a sound as specified in the registry. The *type* argument specifies which +Index: Doc/library/spwd.rst +=================================================================== +--- Doc/library/spwd.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/spwd.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`spwd` --- The shadow password database + ============================================ + +@@ -48,7 +47,7 @@ + The sp_nam and sp_pwd items are strings, all others are integers. + :exc:`KeyError` is raised if the entry asked for cannot be found. + +-It defines the following items: ++The following functions are defined: + + + .. function:: getspnam(name) +Index: Doc/library/sys.rst +=================================================================== +--- Doc/library/sys.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/sys.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`sys` --- System-specific parameters and functions + ======================================================= + +@@ -338,12 +337,12 @@ + does not have to hold true for third-party extensions as it is implementation + specific. + +- The *default* argument allows to define a value which will be returned +- if the object type does not provide means to retrieve the size and would +- cause a `TypeError`. ++ If given, *default* will be returned if the object does not provide means to ++ retrieve the size. Otherwise a `TypeError` will be raised. + +- func:`getsizeof` calls the object's __sizeof__ method and adds an additional +- garbage collector overhead if the object is managed by the garbage collector. ++ :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an ++ additional garbage collector overhead if the object is managed by the garbage ++ collector. + + + .. function:: _getframe([depth]) +@@ -353,9 +352,12 @@ + that is deeper than the call stack, :exc:`ValueError` is raised. The default + for *depth* is zero, returning the frame at the top of the call stack. + +- This function should be used for internal and specialized purposes only. ++ .. impl-detail:: + ++ This function should be used for internal and specialized purposes only. ++ It is not guaranteed to exist in all implementations of Python. + ++ + .. function:: getprofile() + + .. index:: +@@ -373,12 +375,12 @@ + + Get the trace function as set by :func:`settrace`. + +- .. note:: ++ .. impl-detail:: + + The :func:`gettrace` function is intended only for implementing debuggers, +- profilers, coverage tools and the like. Its behavior is part of the +- implementation platform, rather than part of the language definition, +- and thus may not be available in all Python implementations. ++ profilers, coverage tools and the like. Its behavior is part of the ++ implementation platform, rather than part of the language definition, and ++ thus may not be available in all Python implementations. + + + .. function:: getwindowsversion() +@@ -749,12 +751,12 @@ + + For more information on code and frame objects, refer to :ref:`types`. + +- .. note:: ++ .. impl-detail:: + + The :func:`settrace` function is intended only for implementing debuggers, +- profilers, coverage tools and the like. Its behavior is part of the +- implementation platform, rather than part of the language definition, and thus +- may not be available in all Python implementations. ++ profilers, coverage tools and the like. Its behavior is part of the ++ implementation platform, rather than part of the language definition, and ++ thus may not be available in all Python implementations. + + + .. function:: settscdump(on_flag) +Index: Doc/library/warnings.rst +=================================================================== +--- Doc/library/warnings.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/warnings.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`warnings` --- Warning control + =================================== + +@@ -131,16 +130,16 @@ + +---------------+----------------------------------------------+ + + * *message* is a string containing a regular expression that the warning message +- must match (the match is compiled to always be case-insensitive) ++ must match (the match is compiled to always be case-insensitive). + + * *category* is a class (a subclass of :exc:`Warning`) of which the warning +- category must be a subclass in order to match ++ category must be a subclass in order to match. + + * *module* is a string containing a regular expression that the module name must +- match (the match is compiled to be case-sensitive) ++ match (the match is compiled to be case-sensitive). + + * *lineno* is an integer that the line number where the warning occurred must +- match, or ``0`` to match all line numbers ++ match, or ``0`` to match all line numbers. + + Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` + class, to turn a warning into an error we simply raise ``category(message)``. +@@ -235,7 +234,7 @@ + ------------------- + + +-.. function:: warn(message[, category[, stacklevel]]) ++.. function:: warn(message, category=None, stacklevel=1) + + Issue a warning, or maybe ignore it or raise an exception. The *category* + argument, if given, must be a warning category class (see above); it defaults to +@@ -254,7 +253,7 @@ + of the warning message). + + +-.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]]) ++.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None) + + This is a low-level interface to the functionality of :func:`warn`, passing in + explicitly the message, category, filename and line number, and optionally the +@@ -271,7 +270,7 @@ + sources). + + +-.. function:: showwarning(message, category, filename, lineno[, file[, line]]) ++.. function:: showwarning(message, category, filename, lineno, file=None, line=None) + + Write a warning to a file. The default implementation calls + ``formatwarning(message, category, filename, lineno, line)`` and writes the +@@ -283,31 +282,34 @@ + try to read the line specified by *filename* and *lineno*. + + +-.. function:: formatwarning(message, category, filename, lineno[, line]) ++.. function:: formatwarning(message, category, filename, lineno, line=None) + +- Format a warning the standard way. This returns a string which may contain +- embedded newlines and ends in a newline. *line* is +- a line of source code to be included in the warning message; if *line* is not supplied, +- :func:`formatwarning` will try to read the line specified by *filename* and *lineno*. ++ Format a warning the standard way. This returns a string which may contain ++ embedded newlines and ends in a newline. *line* is a line of source code to ++ be included in the warning message; if *line* is not supplied, ++ :func:`formatwarning` will try to read the line specified by *filename* and ++ *lineno*. + + +-.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) ++.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False) + +- Insert an entry into the list of warnings filters. The entry is inserted at the +- front by default; if *append* is true, it is inserted at the end. This checks +- the types of the arguments, compiles the message and module regular expressions, +- and inserts them as a tuple in the list of warnings filters. Entries closer to ++ Insert an entry into the list of :ref:`warnings filter specifications ++ `. The entry is inserted at the front by default; if ++ *append* is true, it is inserted at the end. This checks the types of the ++ arguments, compiles the *message* and *module* regular expressions, and ++ inserts them as a tuple in the list of warnings filters. Entries closer to + the front of the list override entries later in the list, if both match a + particular warning. Omitted arguments default to a value that matches + everything. + + +-.. function:: simplefilter(action[, category[, lineno[, append]]]) ++.. function:: simplefilter(action, category=Warning, lineno=0, append=False) + +- Insert a simple entry into the list of warnings filters. The meaning of the +- function parameters is as for :func:`filterwarnings`, but regular expressions +- are not needed as the filter inserted always matches any message in any module +- as long as the category and line number match. ++ Insert a simple entry into the list of :ref:`warnings filter specifications ++ `. The meaning of the function parameters is as for ++ :func:`filterwarnings`, but regular expressions are not needed as the filter ++ inserted always matches any message in any module as long as the category and ++ line number match. + + + .. function:: resetwarnings() +@@ -320,7 +322,7 @@ + Available Context Managers + -------------------------- + +-.. class:: catch_warnings([\*, record=False, module=None]) ++.. class:: catch_warnings(\*, record=False, module=None) + + A context manager that copies and, upon exit, restores the warnings filter + and the :func:`showwarning` function. +Index: Doc/library/timeit.rst +=================================================================== +--- Doc/library/timeit.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/timeit.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`timeit` --- Measure execution time of small code snippets + =============================================================== + +@@ -18,7 +17,7 @@ + The module defines the following public class: + + +-.. class:: Timer([stmt='pass' [, setup='pass' [, timer=]]]) ++.. class:: Timer(stmt='pass', setup='pass', timer=) + + Class for timing execution speed of small code snippets. + +@@ -38,7 +37,7 @@ + little larger in this case because of the extra function calls. + + +-.. method:: Timer.print_exc([file=None]) ++.. method:: Timer.print_exc(file=None) + + Helper to print a traceback from the timed code. + +@@ -55,7 +54,7 @@ + traceback is sent; it defaults to ``sys.stderr``. + + +-.. method:: Timer.repeat([repeat=3 [, number=1000000]]) ++.. method:: Timer.repeat(repeat=3, number=1000000) + + Call :meth:`timeit` a few times. + +@@ -76,7 +75,7 @@ + and apply common sense rather than statistics. + + +-.. method:: Timer.timeit([number=1000000]) ++.. method:: Timer.timeit(number=1000000) + + Time *number* executions of the main statement. This executes the setup + statement once, and then returns the time it takes to execute the main statement +@@ -98,14 +97,14 @@ + + The module also defines two convenience functions: + +-.. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]]) ++.. function:: repeat(stmt='pass', setup='pass', timer=, repeat=3, number=1000000) + + Create a :class:`Timer` instance with the given statement, setup code and timer + function and run its :meth:`repeat` method with the given repeat count and + *number* executions. + + +-.. function:: timeit(stmt[, setup[, timer[, number=1000000]]]) ++.. function:: timeit(stmt='pass', setup='pass', timer=, number=1000000) + + Create a :class:`Timer` instance with the given statement, setup code and timer + function and run its :meth:`timeit` method with *number* executions. +Index: Doc/library/wave.rst +=================================================================== +--- Doc/library/wave.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/wave.rst (.../branches/release31-maint) (Revision 76056) +@@ -12,7 +12,7 @@ + The :mod:`wave` module defines the following function and exception: + + +-.. function:: open(file[, mode]) ++.. function:: open(file, mode=None) + + If *file* is a string, open the file by that name, other treat it as a seekable + file-like object. *mode* can be any of +Index: Doc/library/test.rst +=================================================================== +--- Doc/library/test.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/test.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`test` --- Regression tests package for Python + =================================================== + +@@ -180,7 +179,7 @@ + + + :mod:`test.support` --- Utility functions for tests +-======================================================== ++=================================================== + + .. module:: test.support + :synopsis: Support for Python regression tests. +@@ -247,7 +246,7 @@ + tests. + + +-.. function:: requires(resource[, msg]) ++.. function:: requires(resource, msg=None) + + Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the + argument to :exc:`ResourceDenied` if it is raised. Always returns true if called +@@ -372,7 +371,7 @@ + + The :mod:`test.support` module defines the following classes: + +-.. class:: TransientResource(exc[, **kwargs]) ++.. class:: TransientResource(exc, **kwargs) + + Instances are a context manager that raises :exc:`ResourceDenied` if the + specified exception type is raised. Any keyword arguments are treated as +Index: Doc/library/turtle.rst +=================================================================== +--- Doc/library/turtle.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/turtle.rst (.../branches/release31-maint) (Revision 76056) +@@ -645,7 +645,7 @@ + >>> turtle.forward(100) + >>> turtle.pos() + (64.28,76.60) +- >>> print turtle.xcor() ++ >>> print(turtle.xcor()) + 64.2787609687 + + +@@ -658,9 +658,9 @@ + >>> turtle.home() + >>> turtle.left(60) + >>> turtle.forward(100) +- >>> print turtle.pos() ++ >>> print(turtle.pos()) + (50.00,86.60) +- >>> print turtle.ycor() ++ >>> print(turtle.ycor()) + 86.6025403784 + + +Index: Doc/library/fnmatch.rst +=================================================================== +--- Doc/library/fnmatch.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/fnmatch.rst (.../branches/release31-maint) (Revision 76056) +@@ -36,11 +36,12 @@ + + .. function:: fnmatch(filename, pattern) + +- Test whether the *filename* string matches the *pattern* string, returning true +- or false. If the operating system is case-insensitive, then both parameters +- will be normalized to all lower- or upper-case before the comparison is +- performed. If you require a case-sensitive comparison regardless of whether +- that's standard for your operating system, use :func:`fnmatchcase` instead. ++ Test whether the *filename* string matches the *pattern* string, returning ++ :const:`True` or :const:`False`. If the operating system is case-insensitive, ++ then both parameters will be normalized to all lower- or upper-case before ++ the comparison is performed. :func:`fnmatchcase` can be used to perform a ++ case-sensitive comparison, regardless of whether that's standard for the ++ operating system. + + This example will print all file names in the current directory with the + extension ``.txt``:: +@@ -55,8 +56,8 @@ + + .. function:: fnmatchcase(filename, pattern) + +- Test whether *filename* matches *pattern*, returning true or false; the +- comparison is case-sensitive. ++ Test whether *filename* matches *pattern*, returning :const:`True` or ++ :const:`False`; the comparison is case-sensitive. + + + .. function:: filter(names, pattern) +@@ -77,7 +78,7 @@ + >>> regex + '.*\\.txt$' + >>> reobj = re.compile(regex) +- >>> print(reobj.match('foobar.txt')) ++ >>> reobj.match('foobar.txt') + <_sre.SRE_Match object at 0x...> + + +Index: Doc/library/ftplib.rst +=================================================================== +--- Doc/library/ftplib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/ftplib.rst (.../branches/release31-maint) (Revision 76056) +@@ -140,7 +140,8 @@ + ``'anonymous@'``. This function should be called only once for each instance, + after a connection has been established; it should not be called at all if a + host and user were given when the instance was created. Most FTP commands are +- only allowed after the client has logged in. ++ only allowed after the client has logged in. The *acct* parameter supplies ++ "accounting information"; few systems implement this. + + + .. method:: FTP.abort() +Index: Doc/library/configparser.rst +=================================================================== +--- Doc/library/configparser.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/configparser.rst (.../branches/release31-maint) (Revision 76056) +@@ -231,11 +231,13 @@ + .. method:: RawConfigParser.readfp(fp, filename=None) + + Read and parse configuration data from the file or file-like object in *fp* +- (only the :meth:`readline` method is used). If *filename* is omitted and *fp* +- has a :attr:`name` attribute, that is used for *filename*; the default is +- ````. ++ (only the :meth:`readline` method is used). The file-like object must ++ operate in text mode, i.e. return strings from :meth:`readline`. + ++ If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used ++ for *filename*; the default is ````. + ++ + .. method:: RawConfigParser.get(section, option) + + Get an *option* value for the named *section*. +@@ -279,8 +281,9 @@ + + .. method:: RawConfigParser.write(fileobject) + +- Write a representation of the configuration to the specified file object. This +- representation can be parsed by a future :meth:`read` call. ++ Write a representation of the configuration to the specified file object, ++ which must be opened in text mode (accepting strings). This representation ++ can be parsed by a future :meth:`read` call. + + + .. method:: RawConfigParser.remove_option(section, option) +@@ -298,14 +301,25 @@ + + .. method:: RawConfigParser.optionxform(option) + +- Transforms the option name *option* as found in an input file or as passed in by +- client code to the form that should be used in the internal structures. The +- default implementation returns a lower-case version of *option*; subclasses may +- override this or client code can set an attribute of this name on instances to +- affect this behavior. Setting this to :func:`str`, for example, would make +- option names case sensitive. ++ Transforms the option name *option* as found in an input file or as passed in ++ by client code to the form that should be used in the internal structures. ++ The default implementation returns a lower-case version of *option*; ++ subclasses may override this or client code can set an attribute of this name ++ on instances to affect this behavior. + ++ You don't necessarily need to subclass a ConfigParser to use this method, you ++ can also re-set it on an instance, to a function that takes a string ++ argument. Setting it to ``str``, for example, would make option names case ++ sensitive:: + ++ cfgparser = ConfigParser() ++ ... ++ cfgparser.optionxform = str ++ ++ Note that when reading configuration files, whitespace around the ++ option names are stripped before :meth:`optionxform` is called. ++ ++ + .. _configparser-objects: + + ConfigParser Objects +@@ -370,7 +384,7 @@ + config.set('Section1', 'foo', '%(bar)s is %(baz)s!') + + # Writing our configuration file to 'example.cfg' +- with open('example.cfg', 'wb') as configfile: ++ with open('example.cfg', 'w') as configfile: + config.write(configfile) + + An example of reading the configuration file again:: +Index: Doc/library/xdrlib.rst +=================================================================== +--- Doc/library/xdrlib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xdrlib.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xdrlib` --- Encode and decode XDR data + ============================================ + +Index: Doc/library/logging.rst +=================================================================== +--- Doc/library/logging.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/logging.rst (.../branches/release31-maint) (Revision 76056) +@@ -57,7 +57,7 @@ + + import logging + LOG_FILENAME = '/tmp/logging_example.out' +- logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,) ++ logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) + + logging.debug('This message should go to the log file') + +@@ -1316,6 +1316,7 @@ + 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters + + ++ + .. _network-logging: + + Sending and receiving logging events across a network +@@ -1446,7 +1447,56 @@ + 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. + 69 myapp.area2 ERROR The five boxing wizards jump quickly. + ++Using arbitrary objects as messages ++----------------------------------- + ++In the preceding sections and examples, it has been assumed that the message ++passed when logging the event is a string. However, this is not the only ++possibility. You can pass an arbitrary object as a message, and its ++:meth:`__str__` method will be called when the logging system needs to convert ++it to a string representation. In fact, if you want to, you can avoid ++computing a string representation altogether - for example, the ++:class:`SocketHandler` emits an event by pickling it and sending it over the ++wire. ++ ++Optimization ++------------ ++ ++Formatting of message arguments is deferred until it cannot be avoided. ++However, computing the arguments passed to the logging method can also be ++expensive, and you may want to avoid doing it if the logger will just throw ++away your event. To decide what to do, you can call the :meth:`isEnabledFor` ++method which takes a level argument and returns true if the event would be ++created by the Logger for that level of call. You can write code like this:: ++ ++ if logger.isEnabledFor(logging.DEBUG): ++ logger.debug("Message with %s, %s", expensive_func1(), ++ expensive_func2()) ++ ++so that if the logger's threshold is set above ``DEBUG``, the calls to ++:func:`expensive_func1` and :func:`expensive_func2` are never made. ++ ++There are other optimizations which can be made for specific applications which ++need more precise control over what logging information is collected. Here's a ++list of things you can do to avoid processing during logging which you don't ++need: ++ +++-----------------------------------------------+----------------------------------------+ ++| What you don't want to collect | How to avoid collecting it | +++===============================================+========================================+ ++| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. | +++-----------------------------------------------+----------------------------------------+ ++| Threading information. | Set ``logging.logThreads`` to ``0``. | +++-----------------------------------------------+----------------------------------------+ ++| Process information. | Set ``logging.logProcesses`` to ``0``. | +++-----------------------------------------------+----------------------------------------+ ++ ++Also note that the core logging module only includes the basic handlers. If ++you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't ++take up any memory. ++ ++.. _handler: ++ + Handler Objects + --------------- + +@@ -1561,9 +1611,9 @@ + and :meth:`flush` methods). + + +-.. class:: StreamHandler(strm=None) ++.. class:: StreamHandler(stream=None) + +- Returns a new instance of the :class:`StreamHandler` class. If *strm* is ++ Returns a new instance of the :class:`StreamHandler` class. If *stream* is + specified, the instance will use it for logging output; otherwise, *sys.stderr* + will be used. + +Index: Doc/library/socket.rst +=================================================================== +--- Doc/library/socket.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/socket.rst (.../branches/release31-maint) (Revision 76056) +@@ -565,17 +565,17 @@ + is system-dependent (usually 5). + + +-.. method:: socket.makefile([mode[, bufsize]]) ++.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, newline=None) + + .. index:: single: I/O control; buffering + + 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 +- 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 +- :func:`file` function. ++ described in :ref:`bltin-file-objects`.) The file object references a ++ :cfunc:`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 ++ arguments are interpreted the same way as by the built-in :func:`open` ++ function. + + + .. method:: socket.recv(bufsize[, flags]) +Index: Doc/library/xml.dom.pulldom.rst +=================================================================== +--- Doc/library/xml.dom.pulldom.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.dom.pulldom.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.dom.pulldom` --- Support for building partial DOM trees + ================================================================= + +@@ -11,7 +10,7 @@ + Object Model representation of a document from SAX events. + + +-.. class:: PullDOM([documentFactory]) ++.. class:: PullDOM(documentFactory=None) + + :class:`xml.sax.handler.ContentHandler` implementation that ... + +@@ -21,17 +20,17 @@ + ... + + +-.. class:: SAX2DOM([documentFactory]) ++.. class:: SAX2DOM(documentFactory=None) + + :class:`xml.sax.handler.ContentHandler` implementation that ... + + +-.. function:: parse(stream_or_string[, parser[, bufsize]]) ++.. function:: parse(stream_or_string, parser=None, bufsize=None) + + ... + + +-.. function:: parseString(string[, parser]) ++.. function:: parseString(string, parser=None) + + ... + +Index: Doc/library/zipimport.rst +=================================================================== +--- Doc/library/zipimport.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/zipimport.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`zipimport` --- Import modules from Zip archives + ===================================================== + +Index: Doc/library/trace.rst +=================================================================== +--- Doc/library/trace.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/trace.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`trace` --- Trace or track Python statement execution + ========================================================== + +@@ -80,7 +79,7 @@ + --------------------- + + +-.. class:: Trace([count=1[, trace=1[, countfuncs=0[, countcallers=0[, ignoremods=()[, ignoredirs=()[, infile=None[, outfile=None[, timing=False]]]]]]]]]) ++.. class:: Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False) + + Create an object to trace execution of a single statement or expression. All + parameters are optional. *count* enables counting of line numbers. *trace* +@@ -98,7 +97,7 @@ + Run *cmd* under control of the Trace object with the current tracing parameters. + + +-.. method:: Trace.runctx(cmd[, globals=None[, locals=None]]) ++.. method:: Trace.runctx(cmd, globals=None, locals=None) + + Run *cmd* under control of the Trace object with the current tracing parameters + in the defined global and local environments. If not defined, *globals* and +Index: Doc/library/someos.rst +=================================================================== +--- Doc/library/someos.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/someos.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + .. _someos: + + ********************************** +@@ -8,7 +7,7 @@ + The modules described in this chapter provide interfaces to operating system + features that are available on selected operating systems only. The interfaces + are generally modeled after the Unix or C interfaces but they are available on +-some other systems as well (e.g. Windows or NT). Here's an overview: ++some other systems as well (e.g. Windows). Here's an overview: + + + .. toctree:: +Index: Doc/library/doctest.rst +=================================================================== +--- Doc/library/doctest.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/doctest.rst (.../branches/release31-maint) (Revision 76056) +@@ -701,8 +701,7 @@ + + instead. Another is to do :: + +- >>> d = foo().items() +- >>> d.sort() ++ >>> d = sorted(foo().items()) + >>> d + [('Harry', 'broomstick'), ('Hermione', 'hippogryph')] + +Index: Doc/library/xml.dom.minidom.rst +=================================================================== +--- Doc/library/xml.dom.minidom.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.dom.minidom.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.dom.minidom` --- Lightweight DOM implementation + ========================================================= + +@@ -28,7 +27,7 @@ + The :func:`parse` function can take either a filename or an open file object. + + +-.. function:: parse(filename_or_file[, parser[, bufsize]]) ++.. function:: parse(filename_or_file, parser=None, bufsize=None) + + Return a :class:`Document` from the given input. *filename_or_file* may be + either a file name, or a file-like object. *parser*, if given, must be a SAX2 +@@ -40,7 +39,7 @@ + instead: + + +-.. function:: parseString(string[, parser]) ++.. function:: parseString(string, parser=None) + + Return a :class:`Document` that represents the *string*. This method creates a + :class:`StringIO` object for the string and passes that on to :func:`parse`. +@@ -126,7 +125,7 @@ + to discard children of that node. + + +-.. method:: Node.writexml(writer[, indent=""[, addindent=""[, newl=""[, encoding=""]]]]) ++.. method:: Node.writexml(writer, indent="", addindent="", newl="", encoding="") + + Write XML to the writer object. The writer should have a :meth:`write` method + which matches that of the file object interface. The *indent* parameter is the +@@ -138,7 +137,7 @@ + used to specify the encoding field of the XML header. + + +-.. method:: Node.toxml([encoding]) ++.. method:: Node.toxml(encoding=None) + + Return the XML that the DOM represents as a string. + +@@ -153,7 +152,7 @@ + encoding argument should be specified as "utf-8". + + +-.. method:: Node.toprettyxml([indent=""[, newl=""[, encoding=""]]]) ++.. method:: Node.toprettyxml(indent="", newl="", encoding="") + + Return a pretty-printed version of the document. *indent* specifies the + indentation string and defaults to a tabulator; *newl* specifies the string +Index: Doc/library/tabnanny.rst +=================================================================== +--- Doc/library/tabnanny.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/tabnanny.rst (.../branches/release31-maint) (Revision 76056) +@@ -2,8 +2,8 @@ + ====================================================== + + .. module:: tabnanny +- :synopsis: Tool for detecting white space related problems in Python source files in a +- directory tree. ++ :synopsis: Tool for detecting white space related problems in Python ++ source files in a directory tree. + .. moduleauthor:: Tim Peters + .. sectionauthor:: Peter Funk + +Index: Doc/library/tarfile.rst +=================================================================== +--- Doc/library/tarfile.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/tarfile.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,5 +1,3 @@ +-.. _tarfile-mod: +- + :mod:`tarfile` --- Read and write tar archive files + =================================================== + +Index: Doc/library/json.rst +=================================================================== +--- Doc/library/json.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/json.rst (.../branches/release31-maint) (Revision 76056) +@@ -118,7 +118,7 @@ + file-like object). + + If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not +- of a basic type (:class:`str`, :class:`unicode`, :class:`int`, ++ of a basic type (:class:`bytes`, :class:`str`, :class:`int`, + :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a + :exc:`TypeError`. + +@@ -201,13 +201,13 @@ + + .. function:: loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) + +- Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON ++ Deserialize *s* (a :class:`bytes` or :class:`str` instance containing a JSON + document) to a Python object. + +- If *s* is a :class:`str` instance and is encoded with an ASCII based encoding ++ If *s* is a :class:`bytes` instance and is encoded with an ASCII based encoding + other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be + specified. Encodings that are not ASCII based (such as UCS-2) are not +- allowed and should be decoded to :class:`unicode` first. ++ allowed and should be decoded to :class:`str` first. + + The other arguments have the same meaning as in :func:`dump`. + +Index: Doc/library/xml.etree.elementtree.rst +=================================================================== +--- Doc/library/xml.etree.elementtree.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.etree.elementtree.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.etree.ElementTree` --- The ElementTree XML API + ======================================================== + +@@ -41,7 +40,7 @@ + --------- + + +-.. function:: Comment([text]) ++.. function:: Comment(text=None) + + Comment element factory. This factory function creates a special element + that will be serialized as an XML comment. The comment string can be either +@@ -61,7 +60,7 @@ + *elem* is an element tree or an individual element. + + +-.. function:: Element(tag[, attrib][, **extra]) ++.. function:: Element(tag, attrib={}, **extra) + + Element factory. This function returns an object implementing the standard + Element interface. The exact class or type of that object is implementation +@@ -87,7 +86,7 @@ + element instance. Returns a true value if this is an element object. + + +-.. function:: iterparse(source[, events]) ++.. function:: iterparse(source, events=None) + + Parses an XML section into an element tree incrementally, and reports what's + going on to the user. *source* is a filename or file object containing XML data. +@@ -105,7 +104,7 @@ + If you need a fully populated element, look for "end" events instead. + + +-.. function:: parse(source[, parser]) ++.. function:: parse(source, parser=None) + + Parses an XML section into an element tree. *source* is a filename or file + object containing XML data. *parser* is an optional parser instance. If not +@@ -113,7 +112,7 @@ + instance. + + +-.. function:: ProcessingInstruction(target[, text]) ++.. function:: ProcessingInstruction(target, text=None) + + PI element factory. This factory function creates a special element that will + be serialized as an XML processing instruction. *target* is a string containing +@@ -121,7 +120,7 @@ + an element instance, representing a processing instruction. + + +-.. function:: SubElement(parent, tag[, attrib[, **extra]]) ++.. function:: SubElement(parent, tag, attrib={}, **extra) + + Subelement factory. This function creates an element instance, and appends it + to an existing element. +@@ -133,7 +132,7 @@ + as keyword arguments. Returns an element instance. + + +-.. function:: tostring(element[, encoding]) ++.. function:: tostring(element, encoding=None) + + Generates a string representation of an XML element, including all subelements. + *element* is an Element instance. *encoding* is the output encoding (default is +@@ -202,7 +201,7 @@ + attributes, and sets the text and tail attributes to None. + + +-.. method:: Element.get(key[, default=None]) ++.. method:: Element.get(key, default=None) + + Gets the element attribute named *key*. + +@@ -246,7 +245,7 @@ + Returns an iterable yielding all matching elements in document order. + + +-.. method:: Element.findtext(condition[, default=None]) ++.. method:: Element.findtext(condition, default=None) + + Finds text for the first subelement matching *condition*. *condition* may be a + tag name or path. Returns the text content of the first matching element, or +@@ -259,7 +258,7 @@ + Returns all subelements. The elements are returned in document order. + + +-.. method:: Element.getiterator([tag=None]) ++.. method:: Element.getiterator(tag=None) + + Creates a tree iterator with the current element as the root. The iterator + iterates over this element and all elements below it, in document (depth first) +@@ -305,7 +304,7 @@ + ------------------- + + +-.. class:: ElementTree([element,] [file]) ++.. class:: ElementTree(element=None, file=None) + + ElementTree wrapper class. This class represents an entire element hierarchy, + and adds some extra support for serialization to and from standard XML. +@@ -336,7 +335,7 @@ + order. + + +- .. method:: findtext(path[, default]) ++ .. method:: findtext(path, default=None) + + Finds the element text for the first toplevel element with given tag. + Same as getroot().findtext(path). *path* is the toplevel element to look +@@ -346,7 +345,7 @@ + found, but has no text content, this method returns an empty string. + + +- .. method:: getiterator([tag]) ++ .. method:: getiterator(tag=None) + + Creates and returns a tree iterator for the root element. The iterator + loops over all elements in this tree, in section order. *tag* is the tag +@@ -358,7 +357,7 @@ + Returns the root element for this tree. + + +- .. method:: parse(source[, parser]) ++ .. method:: parse(source, parser=None) + + Loads an external XML section into this element tree. *source* is a file + name or file object. *parser* is an optional parser instance. If not +@@ -366,7 +365,7 @@ + root element. + + +- .. method:: write(file[, encoding]) ++ .. method:: write(file, encoding=None) + + Writes the element tree to a file, as XML. *file* is a file name, or a + file object opened for writing. *encoding* [1]_ is the output encoding +@@ -406,7 +405,7 @@ + ------------- + + +-.. class:: QName(text_or_uri[, tag]) ++.. class:: QName(text_or_uri, tag=None) + + QName wrapper. This can be used to wrap a QName attribute value, in order to + get proper namespace handling on output. *text_or_uri* is a string containing +@@ -422,7 +421,7 @@ + ------------------- + + +-.. class:: TreeBuilder([element_factory]) ++.. class:: TreeBuilder(element_factory=None) + + Generic element structure builder. This builder converts a sequence of start, + data, and end method calls to a well-formed element structure. You can use this +@@ -461,7 +460,7 @@ + ---------------------- + + +-.. class:: XMLTreeBuilder([html,] [target]) ++.. class:: XMLTreeBuilder(html=0, target=None) + + Element structure builder for XML source data, based on the expat parser. *html* + are predefined HTML entities. This flag is not supported by the current +Index: Doc/library/unittest.rst +=================================================================== +--- Doc/library/unittest.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/unittest.rst (.../branches/release31-maint) (Revision 76056) +@@ -525,7 +525,7 @@ + Test cases + ~~~~~~~~~~ + +-.. class:: TestCase([methodName]) ++.. class:: TestCase(methodName='runTest') + + Instances of the :class:`TestCase` class represent the smallest testable units + in the :mod:`unittest` universe. This class is intended to be used as a base +@@ -576,7 +576,7 @@ + the outcome of the test method. The default implementation does nothing. + + +- .. method:: run([result]) ++ .. method:: run(result=None) + + Run the test, collecting the result into the test result object passed as + *result*. If *result* is omitted or :const:`None`, a temporary result +@@ -603,9 +603,9 @@ + failures. + + +- .. method:: assertTrue(expr[, msg]) +- assert_(expr[, msg]) +- failUnless(expr[, msg]) ++ .. method:: assertTrue(expr, msg=None) ++ assert_(expr, msg=None) ++ failUnless(expr, msg=None) + + Signal a test failure if *expr* is false; the explanation for the failure + will be *msg* if given, otherwise it will be :const:`None`. +@@ -614,8 +614,8 @@ + :meth:`failUnless`. + + +- .. method:: assertEqual(first, second[, msg]) +- failUnlessEqual(first, second[, msg]) ++ .. method:: assertEqual(first, second, msg=None) ++ failUnlessEqual(first, second, msg=None) + + Test that *first* and *second* are equal. If the values do not compare + equal, the test will fail with the explanation given by *msg*, or +@@ -636,8 +636,8 @@ + :meth:`failUnlessEqual`. + + +- .. method:: assertNotEqual(first, second[, msg]) +- failIfEqual(first, second[, msg]) ++ .. method:: assertNotEqual(first, second, msg=None) ++ failIfEqual(first, second, msg=None) + + Test that *first* and *second* are not equal. If the values do compare + equal, the test will fail with the explanation given by *msg*, or +@@ -650,8 +650,8 @@ + :meth:`failIfEqual`. + + +- .. method:: assertAlmostEqual(first, second[, places[, msg]]) +- failUnlessAlmostEqual(first, second[, places[, msg]]) ++ .. method:: assertAlmostEqual(first, second, *, places=7, msg=None) ++ failUnlessAlmostEqual(first, second, *, places=7, msg=None) + + Test that *first* and *second* are approximately equal by computing the + difference, rounding to the given number of decimal *places* (default 7), +@@ -666,8 +666,8 @@ + :meth:`failUnlessAlmostEqual`. + + +- .. method:: assertNotAlmostEqual(first, second[, places[, msg]]) +- failIfAlmostEqual(first, second[, places[, msg]]) ++ .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None) ++ failIfAlmostEqual(first, second, *, places=7, msg=None) + + Test that *first* and *second* are not approximately equal by computing + the difference, rounding to the given number of decimal *places* (default +@@ -708,7 +708,7 @@ + .. versionadded:: 3.1 + + +- .. method:: assertRegexpMatches(text, regexp[, msg=None]): ++ .. method:: assertRegexpMatches(text, regexp, msg=None): + + Verifies that a *regexp* search matches *text*. Fails with an error + message including the pattern and the *text*. *regexp* may be +@@ -801,8 +801,10 @@ + .. versionadded:: 3.1 + + +- .. method:: assertRaises(exception[, callable, ...]) +- failUnlessRaises(exception[, callable, ...]) ++ .. method:: assertRaises(exception, callable, *args, **kwds) ++ failUnlessRaises(exception, callable, *args, **kwds) ++ assertRaises(exception) ++ failUnlessRaises(exception) + + Test that an exception is raised when *callable* is called with any + positional or keyword arguments that are also passed to +@@ -811,8 +813,8 @@ + To catch any of a group of exceptions, a tuple containing the exception + classes may be passed as *exception*. + +- If *callable* is omitted or None, returns a context manager so that the +- code under test can be written inline rather than as a function:: ++ If only the *exception* argument is given, returns a context manager so ++ that the code under test can be written inline rather than as a function:: + + with self.failUnlessRaises(some_error_class): + do_something() +@@ -842,14 +844,14 @@ + .. versionadded:: 3.1 + + +- .. method:: assertIsNone(expr[, msg]) ++ .. method:: assertIsNone(expr, msg=None) + + This signals a test failure if *expr* is not None. + + .. versionadded:: 3.1 + + +- .. method:: assertIsNotNone(expr[, msg]) ++ .. method:: assertIsNotNone(expr, msg=None) + + The inverse of the :meth:`assertIsNone` method. + This signals a test failure if *expr* is None. +@@ -857,7 +859,7 @@ + .. versionadded:: 3.1 + + +- .. method:: assertIs(expr1, expr2[, msg]) ++ .. method:: assertIs(expr1, expr2, msg=None) + + This signals a test failure if *expr1* and *expr2* don't evaluate to the same + object. +@@ -865,7 +867,7 @@ + .. versionadded:: 3.1 + + +- .. method:: assertIsNot(expr1, expr2[, msg]) ++ .. method:: assertIsNot(expr1, expr2, msg=None) + + The inverse of the :meth:`assertIs` method. + This signals a test failure if *expr1* and *expr2* evaluate to the same +@@ -874,8 +876,8 @@ + .. versionadded:: 3.1 + + +- .. method:: assertFalse(expr[, msg]) +- failIf(expr[, msg]) ++ .. method:: assertFalse(expr, msg=None) ++ failIf(expr, msg=None) + + The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method. + This signals a test failure if *expr* is true, with *msg* or :const:`None` +@@ -885,7 +887,7 @@ + :meth:`failIf`. + + +- .. method:: fail([msg]) ++ .. method:: fail(msg=None) + + Signals a test failure unconditionally, with *msg* or :const:`None` for + the error message. +@@ -976,7 +978,7 @@ + .. versionadded:: 3.1 + + +- .. method:: addCleanup(function[, *args[, **kwargs]]) ++ .. method:: addCleanup(function, *args, **kwargs) + + Add a function to be called after :meth:`tearDown` to cleanup resources + used during the test. Functions will be called in reverse order to the +@@ -1006,7 +1008,7 @@ + .. versionadded:: 2.7 + + +-.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]]) ++.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None) + + This class implements the portion of the :class:`TestCase` interface which + allows the test runner to drive the test, but does not provide the methods which +@@ -1020,7 +1022,7 @@ + Grouping tests + ~~~~~~~~~~~~~~ + +-.. class:: TestSuite([tests]) ++.. class:: TestSuite(tests=()) + + This class represents an aggregation of individual tests cases and test suites. + The class presents the interface needed by the test runner to allow it to be run +@@ -1127,7 +1129,7 @@ + be useful when the fixtures are different and defined in subclasses. + + +- .. method:: loadTestsFromName(name[, module]) ++ .. method:: loadTestsFromName(name, module=None) + + Return a suite of all tests cases given a string specifier. + +@@ -1152,7 +1154,7 @@ + The method optionally resolves *name* relative to the given *module*. + + +- .. method:: loadTestsFromNames(names[, module]) ++ .. method:: loadTestsFromNames(names, module=None) + + Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather + than a single name. The return value is a test suite which supports all +@@ -1369,7 +1371,7 @@ + instead of repeatedly creating new instances. + + +-.. class:: TextTestRunner([stream[, descriptions[, verbosity]]]) ++.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1) + + A basic test runner implementation which prints results on standard error. It + has a few configurable parameters, but is essentially very simple. Graphical +@@ -1382,7 +1384,7 @@ + subclasses to provide a custom ``TestResult``. + + +-.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit]]]]]]) ++.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=TextTestRunner, testLoader=unittest.defaultTestLoader, exit=True) + + A command-line program that runs a set of tests; this is primarily for making + test modules conveniently executable. The simplest use for this function is to +Index: Doc/library/unicodedata.rst +=================================================================== +--- Doc/library/unicodedata.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/unicodedata.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`unicodedata` --- Unicode Database + ======================================= + +@@ -146,7 +145,7 @@ + + >>> import unicodedata + >>> unicodedata.lookup('LEFT CURLY BRACKET') +- u'{' ++ '{' + >>> unicodedata.name('/') + 'SOLIDUS' + >>> unicodedata.decimal('9') +Index: Doc/library/sqlite3.rst +=================================================================== +--- Doc/library/sqlite3.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/sqlite3.rst (.../branches/release31-maint) (Revision 76056) +@@ -79,12 +79,12 @@ + >>> c = conn.cursor() + >>> c.execute('select * from stocks order by price') + >>> for row in c: +- ... print(row) ++ ... print(row) + ... +- (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) ++ ('2006-01-05', 'BUY', 'RHAT', 100, 35.14) ++ ('2006-03-28', 'BUY', 'IBM', 1000, 45.0) ++ ('2006-04-06', 'SELL', 'IBM', 500, 53.0) ++ ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.0) + >>> + + +@@ -589,18 +589,19 @@ + + >>> r = c.fetchone() + >>> type(r) +- +- >>> r +- (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14) ++ ++ >>> tuple(r) ++ ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14) + >>> len(r) + 5 + >>> r[2] +- u'RHAT' ++ 'RHAT' + >>> r.keys() + ['date', 'trans', 'symbol', 'qty', 'price'] + >>> r['qty'] + 100.0 +- >>> for member in r: print member ++ >>> for member in r: ++ ... print(member) + ... + 2006-01-05 + BUY +@@ -647,7 +648,7 @@ + +=============+=============================================+ + | ``NULL`` | :const:`None` | + +-------------+---------------------------------------------+ +-| ``INTEGER`` | :class`int` | ++| ``INTEGER`` | :class:`int` | + +-------------+---------------------------------------------+ + | ``REAL`` | :class:`float` | + +-------------+---------------------------------------------+ +Index: Doc/library/multiprocessing.rst +=================================================================== +--- Doc/library/multiprocessing.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/multiprocessing.rst (.../branches/release31-maint) (Revision 76056) +@@ -77,14 +77,14 @@ + import os + + def info(title): +- print title +- print 'module name:', __name__ +- print 'parent process:', os.getppid() +- print 'process id:', os.getpid() ++ print(title) ++ print('module name:', __name__) ++ print('parent process:', os.getppid()) ++ print('process id:', os.getpid()) + + def f(name): + info('function f') +- print 'hello', name ++ print('hello', name) + + if __name__ == '__main__': + info('main line') +@@ -279,10 +279,10 @@ + return x*x + + if __name__ == '__main__': +- pool = Pool(processes=4) # start 4 worker processes ++ pool = Pool(processes=4) # start 4 worker processes + result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously +- print result.get(timeout=1) # prints "100" unless your computer is *very* slow +- print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]" ++ print(result.get(timeout=1)) # prints "100" unless your computer is *very* slow ++ print(pool.map(f, range(10))) # prints "[0, 1, 4,..., 81]" + + + Reference +@@ -1151,11 +1151,6 @@ + + Run the server in the current process. + +- .. method:: from_address(address, authkey) +- +- A class method which creates a manager object referring to a pre-existing +- server process which is using the given address and authentication key. +- + .. method:: get_server() + + Returns a :class:`Server` object which represents the actual server under +Index: Doc/library/xml.sax.utils.rst +=================================================================== +--- Doc/library/xml.sax.utils.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.sax.utils.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.sax.saxutils` --- SAX Utilities + ========================================= + +@@ -13,7 +12,7 @@ + or as base classes. + + +-.. function:: escape(data[, entities]) ++.. function:: escape(data, entities={}) + + Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data. + +@@ -23,7 +22,7 @@ + ``'>'`` are always escaped, even if *entities* is provided. + + +-.. function:: unescape(data[, entities]) ++.. function:: unescape(data, entities={}) + + Unescape ``'&'``, ``'<'``, and ``'>'`` in a string of data. + +@@ -33,7 +32,7 @@ + are always unescaped, even if *entities* is provided. + + +-.. function:: quoteattr(data[, entities]) ++.. function:: quoteattr(data, entities={}) + + Similar to :func:`escape`, but also prepares *data* to be used as an + attribute value. The return value is a quoted version of *data* with any +@@ -51,7 +50,7 @@ + using the reference concrete syntax. + + +-.. class:: XMLGenerator([out[, encoding]]) ++.. class:: XMLGenerator(out=None, encoding='iso-8859-1') + + This class implements the :class:`ContentHandler` interface by writing SAX + events back into an XML document. In other words, using an :class:`XMLGenerator` +@@ -69,7 +68,7 @@ + requests as they pass through. + + +-.. function:: prepare_input_source(source[, base]) ++.. function:: prepare_input_source(source, base='') + + This function takes an input source and an optional base URL and returns a fully + resolved :class:`InputSource` object ready for reading. The input source can be +Index: Doc/library/sunau.rst +=================================================================== +--- Doc/library/sunau.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/sunau.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`sunau` --- Read and write Sun AU files + ============================================ + +Index: Doc/library/symbol.rst +=================================================================== +--- Doc/library/symbol.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/symbol.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`symbol` --- Constants used with Python parse trees + ======================================================== + +Index: Doc/library/undoc.rst +=================================================================== +--- Doc/library/undoc.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/undoc.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + .. _undoc: + + ******************** +Index: Doc/library/constants.rst +=================================================================== +--- Doc/library/constants.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/constants.rst (.../branches/release31-maint) (Revision 76056) +@@ -66,7 +66,7 @@ + + Objects that when printed, print a message like "Use quit() or Ctrl-D + (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the +- specified exit code, and when . ++ specified exit code. + + .. data:: copyright + license +Index: Doc/library/xmlrpc.client.rst +=================================================================== +--- Doc/library/xmlrpc.client.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xmlrpc.client.rst (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + between conformable Python objects and XML on the wire. + + +-.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]]) ++.. class:: ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False) + + A :class:`ServerProxy` instance is an object that manages communication with a + remote XML-RPC server. The required first argument is a URI (Uniform Resource +@@ -458,7 +458,7 @@ + Convenience Functions + --------------------- + +-.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]]) ++.. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False) + + Convert *params* into an XML-RPC request. or into a response if *methodresponse* + is true. *params* can be either a tuple of arguments or an instance of the +@@ -469,7 +469,7 @@ + it via an extension, provide a true value for *allow_none*. + + +-.. function:: loads(data[, use_datetime]) ++.. function:: loads(data, use_datetime=False) + + Convert an XML-RPC request or response into Python objects, a ``(params, + methodname)``. *params* is a tuple of argument; *methodname* is a string, or +Index: Doc/library/optparse.rst +=================================================================== +--- Doc/library/optparse.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/optparse.rst (.../branches/release31-maint) (Revision 76056) +@@ -7,14 +7,14 @@ + .. sectionauthor:: Greg Ward + + +-``optparse`` is a more convenient, flexible, and powerful library for parsing +-command-line options than the old :mod:`getopt` module. ``optparse`` uses a more declarative +-style of command-line parsing: you create an instance of :class:`OptionParser`, +-populate it with options, and parse the command line. ``optparse`` allows users +-to specify options in the conventional GNU/POSIX syntax, and additionally +-generates usage and help messages for you. ++:mod:`optparse` is a more convenient, flexible, and powerful library for parsing ++command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a ++more declarative style of command-line parsing: you create an instance of ++:class:`OptionParser`, populate it with options, and parse the command ++line. :mod:`optparse` allows users to specify options in the conventional ++GNU/POSIX syntax, and additionally generates usage and help messages for you. + +-Here's an example of using ``optparse`` in a simple script:: ++Here's an example of using :mod:`optparse` in a simple script:: + + from optparse import OptionParser + [...] +@@ -32,11 +32,11 @@ + + --file=outfile -q + +-As it parses the command line, ``optparse`` sets attributes of the ``options`` +-object returned by :meth:`parse_args` based on user-supplied command-line +-values. When :meth:`parse_args` returns from parsing this command line, +-``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be +-``False``. ``optparse`` supports both long and short options, allows short ++As it parses the command line, :mod:`optparse` sets attributes of the ++``options`` object returned by :meth:`parse_args` based on user-supplied ++command-line values. When :meth:`parse_args` returns from parsing this command ++line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be ++``False``. :mod:`optparse` supports both long and short options, allows short + options to be merged together, and allows options to be associated with their + arguments in a variety of ways. Thus, the following command lines are all + equivalent to the above example:: +@@ -51,7 +51,7 @@ + -h + --help + +-and ``optparse`` will print out a brief summary of your script's options:: ++and :mod:`optparse` will print out a brief summary of your script's options:: + + usage: [options] + +@@ -82,10 +82,10 @@ + ^^^^^^^^^^^ + + argument +- a string entered on the command-line, and passed by the shell to ``execl()`` or +- ``execv()``. In Python, arguments are elements of ``sys.argv[1:]`` +- (``sys.argv[0]`` is the name of the program being executed). Unix shells also +- use the term "word". ++ a string entered on the command-line, and passed by the shell to ``execl()`` ++ or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]`` ++ (``sys.argv[0]`` is the name of the program being executed). Unix shells ++ also use the term "word". + + It is occasionally desirable to substitute an argument list other than + ``sys.argv[1:]``, so you should read "argument" as "an element of +@@ -93,14 +93,14 @@ + ``sys.argv[1:]``". + + option +- an argument used to supply extra information to guide or customize the execution +- of a program. There are many different syntaxes for options; the traditional +- Unix syntax is a hyphen ("-") followed by a single letter, e.g. ``"-x"`` or +- ``"-F"``. Also, traditional Unix syntax allows multiple options to be merged +- into a single argument, e.g. ``"-x -F"`` is equivalent to ``"-xF"``. The GNU +- project introduced ``"--"`` followed by a series of hyphen-separated words, e.g. +- ``"--file"`` or ``"--dry-run"``. These are the only two option syntaxes +- provided by :mod:`optparse`. ++ an argument used to supply extra information to guide or customize the ++ execution of a program. There are many different syntaxes for options; the ++ traditional Unix syntax is a hyphen ("-") followed by a single letter, ++ e.g. ``"-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple ++ options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent ++ to ``"-xF"``. The GNU project introduced ``"--"`` followed by a series of ++ hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the ++ only two option syntaxes provided by :mod:`optparse`. + + Some other option syntaxes that the world has seen include: + +@@ -117,15 +117,16 @@ + * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``, + ``"/file"`` + +- These option syntaxes are not supported by :mod:`optparse`, and they never will +- be. This is deliberate: the first three are non-standard on any environment, +- and the last only makes sense if you're exclusively targeting VMS, MS-DOS, +- and/or Windows. ++ These option syntaxes are not supported by :mod:`optparse`, and they never ++ will be. This is deliberate: the first three are non-standard on any ++ environment, and the last only makes sense if you're exclusively targeting ++ VMS, MS-DOS, and/or Windows. + + option argument +- an argument that follows an option, is closely associated with that option, and +- is consumed from the argument list when that option is. With :mod:`optparse`, +- option arguments may either be in a separate argument from their option:: ++ an argument that follows an option, is closely associated with that option, ++ and is consumed from the argument list when that option is. With ++ :mod:`optparse`, option arguments may either be in a separate argument from ++ their option:: + + -f foo + --file foo +@@ -135,25 +136,26 @@ + -ffoo + --file=foo + +- Typically, a given option either takes an argument or it doesn't. Lots of people +- want an "optional option arguments" feature, meaning that some options will take +- an argument if they see it, and won't if they don't. This is somewhat +- controversial, because it makes parsing ambiguous: if ``"-a"`` takes an optional +- argument and ``"-b"`` is another option entirely, how do we interpret ``"-ab"``? +- Because of this ambiguity, :mod:`optparse` does not support this feature. ++ Typically, a given option either takes an argument or it doesn't. Lots of ++ people want an "optional option arguments" feature, meaning that some options ++ will take an argument if they see it, and won't if they don't. This is ++ somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes ++ an optional argument and ``"-b"`` is another option entirely, how do we ++ interpret ``"-ab"``? Because of this ambiguity, :mod:`optparse` does not ++ support this feature. + + positional argument + something leftover in the argument list after options have been parsed, i.e. +- after options and their arguments have been parsed and removed from the argument +- list. ++ after options and their arguments have been parsed and removed from the ++ argument list. + + required option + an option that must be supplied on the command-line; note that the phrase + "required option" is self-contradictory in English. :mod:`optparse` doesn't +- prevent you from implementing required options, but doesn't give you much help +- at it either. See ``examples/required_1.py`` and ``examples/required_2.py`` in +- the :mod:`optparse` source distribution for two ways to implement required +- options with :mod:`optparse`. ++ prevent you from implementing required options, but doesn't give you much ++ help at it either. See ``examples/required_1.py`` and ++ ``examples/required_2.py`` in the :mod:`optparse` source distribution for two ++ ways to implement required options with :mod:`optparse`. + + For example, consider this hypothetical command-line:: + +@@ -282,8 +284,9 @@ + * ``args``, the list of positional arguments leftover after parsing options + + This tutorial section only covers the four most important option attributes: +-:attr:`action`, :attr:`!type`, :attr:`dest` (destination), and :attr:`help`. Of +-these, :attr:`action` is the most fundamental. ++:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest` ++(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the ++most fundamental. + + + .. _optparse-understanding-option-actions: +@@ -294,9 +297,9 @@ + Actions tell :mod:`optparse` what to do when it encounters an option on the + command line. There is a fixed set of actions hard-coded into :mod:`optparse`; + adding new actions is an advanced topic covered in section +-:ref:`optparse-extending-optparse`. Most actions tell +-:mod:`optparse` to store a value in some variable---for example, take a string +-from the command line and store it in an attribute of ``options``. ++:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store ++a value in some variable---for example, take a string from the command line and ++store it in an attribute of ``options``. + + If you don't specify an option action, :mod:`optparse` defaults to ``store``. + +@@ -334,7 +337,7 @@ + + Let's parse another fake command-line. This time, we'll jam the option argument + right up against the option: since ``"-n42"`` (one argument) is equivalent to +-``"-n 42"`` (two arguments), the code :: ++``"-n 42"`` (two arguments), the code :: + + (options, args) = parser.parse_args(["-n42"]) + print(options.num) +@@ -386,16 +389,16 @@ + + Some other actions supported by :mod:`optparse` are: + +-``store_const`` ++``"store_const"`` + store a constant value + +-``append`` ++``"append"`` + append this option's argument to a list + +-``count`` ++``"count"`` + increment a counter by one + +-``callback`` ++``"callback"`` + call a specified function + + These are covered in section :ref:`optparse-reference-guide`, Reference Guide +@@ -454,8 +457,8 @@ + + :mod:`optparse`'s ability to generate help and usage text automatically is + useful for creating user-friendly command-line interfaces. All you have to do +-is supply a :attr:`help` value for each option, and optionally a short usage +-message for your whole program. Here's an OptionParser populated with ++is supply a :attr:`~Option.help` value for each option, and optionally a short ++usage message for your whole program. Here's an OptionParser populated with + user-friendly (documented) options:: + + usage = "usage: %prog [options] arg1 arg2" +@@ -467,7 +470,7 @@ + action="store_false", dest="verbose", + help="be vewwy quiet (I'm hunting wabbits)") + parser.add_option("-f", "--filename", +- metavar="FILE", help="write output to FILE"), ++ metavar="FILE", help="write output to FILE") + parser.add_option("-m", "--mode", + default="intermediate", + help="interaction mode: novice, intermediate, " +@@ -499,12 +502,12 @@ + usage = "usage: %prog [options] arg1 arg2" + + :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the +- current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string is +- then printed before the detailed option help. ++ current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string ++ is then printed before the detailed option help. + + If you don't supply a usage string, :mod:`optparse` uses a bland but sensible +- default: ``"usage: %prog [options]"``, which is fine if your script doesn't take +- any positional arguments. ++ default: ``"usage: %prog [options]"``, which is fine if your script doesn't ++ take any positional arguments. + + * every option defines a help string, and doesn't worry about line-wrapping--- + :mod:`optparse` takes care of wrapping lines and making the help output look +@@ -518,29 +521,29 @@ + Here, "MODE" is called the meta-variable: it stands for the argument that the + user is expected to supply to :option:`-m`/:option:`--mode`. By default, + :mod:`optparse` converts the destination variable name to uppercase and uses +- that for the meta-variable. Sometimes, that's not what you want---for example, +- the :option:`--filename` option explicitly sets ``metavar="FILE"``, resulting in +- this automatically-generated option description:: ++ that for the meta-variable. Sometimes, that's not what you want---for ++ example, the :option:`--filename` option explicitly sets ``metavar="FILE"``, ++ resulting in this automatically-generated option description:: + + -f FILE, --filename=FILE + +- This is important for more than just saving space, though: the manually written +- help text uses the meta-variable "FILE" to clue the user in that there's a +- connection between the semi-formal syntax "-f FILE" and the informal semantic +- description "write output to FILE". This is a simple but effective way to make +- your help text a lot clearer and more useful for end users. ++ This is important for more than just saving space, though: the manually ++ written help text uses the meta-variable "FILE" to clue the user in that ++ there's a connection between the semi-formal syntax "-f FILE" and the informal ++ semantic description "write output to FILE". This is a simple but effective ++ way to make your help text a lot clearer and more useful for end users. + + * options that have a default value can include ``%default`` in the help + string---\ :mod:`optparse` will replace it with :func:`str` of the option's + default value. If an option has no default value (or the default value is + ``None``), ``%default`` expands to ``none``. + +-When dealing with many options, it is convenient to group these +-options for better help output. An :class:`OptionParser` can contain +-several option groups, each of which can contain several options. ++When dealing with many options, it is convenient to group these options for ++better help output. An :class:`OptionParser` can contain several option groups, ++each of which can contain several options. + +-Continuing with the parser defined above, adding an +-:class:`OptionGroup` to a parser is easy:: ++Continuing with the parser defined above, adding an :class:`OptionGroup` to a ++parser is easy:: + + group = OptionGroup(parser, "Dangerous Options", + "Caution: use these options at your own risk. " +@@ -595,17 +598,17 @@ + + There are two broad classes of errors that :mod:`optparse` has to worry about: + programmer errors and user errors. Programmer errors are usually erroneous +-calls to ``parser.add_option()``, e.g. invalid option strings, unknown option +-attributes, missing option attributes, etc. These are dealt with in the usual +-way: raise an exception (either ``optparse.OptionError`` or :exc:`TypeError`) and +-let the program crash. ++calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown ++option attributes, missing option attributes, etc. These are dealt with in the ++usual way: raise an exception (either :exc:`optparse.OptionError` or ++:exc:`TypeError`) and let the program crash. + + Handling user errors is much more important, since they are guaranteed to happen + no matter how stable your code is. :mod:`optparse` can automatically detect + some user errors, such as bad option arguments (passing ``"-n 4x"`` where + :option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end + of the command line, where :option:`-n` takes an argument of any type). Also, +-you can call ``parser.error()`` to signal an application-defined error ++you can call :func:`OptionParser.error` to signal an application-defined error + condition:: + + (options, args) = parser.parse_args() +@@ -634,7 +637,7 @@ + + :mod:`optparse`\ -generated error messages take care always to mention the + option involved in the error; be sure to do the same when calling +-``parser.error()`` from your application code. ++:func:`OptionParser.error` from your application code. + + If :mod:`optparse`'s default error-handling behaviour does not suit your needs, + you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit` +@@ -682,49 +685,51 @@ + Creating the parser + ^^^^^^^^^^^^^^^^^^^ + +-The first step in using :mod:`optparse` is to create an OptionParser instance:: ++The first step in using :mod:`optparse` is to create an OptionParser instance. + +- parser = OptionParser(...) ++.. class:: OptionParser(...) + +-The OptionParser constructor has no required arguments, but a number of optional +-keyword arguments. You should always pass them as keyword arguments, i.e. do +-not rely on the order in which the arguments are declared. ++ The OptionParser constructor has no required arguments, but a number of ++ optional keyword arguments. You should always pass them as keyword ++ arguments, i.e. do not rely on the order in which the arguments are declared. + + ``usage`` (default: ``"%prog [options]"``) +- The usage summary to print when your program is run incorrectly or with a help +- option. When :mod:`optparse` prints the usage string, it expands ``%prog`` to +- ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you passed that keyword +- argument). To suppress a usage message, pass the special value +- ``optparse.SUPPRESS_USAGE``. ++ The usage summary to print when your program is run incorrectly or with a ++ help option. When :mod:`optparse` prints the usage string, it expands ++ ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you ++ passed that keyword argument). To suppress a usage message, pass the ++ special value :data:`optparse.SUPPRESS_USAGE`. + + ``option_list`` (default: ``[]``) + A list of Option objects to populate the parser with. The options in +- ``option_list`` are added after any options in ``standard_option_list`` (a class +- attribute that may be set by OptionParser subclasses), but before any version or +- help options. Deprecated; use :meth:`add_option` after creating the parser +- instead. ++ ``option_list`` are added after any options in ``standard_option_list`` (a ++ class attribute that may be set by OptionParser subclasses), but before ++ any version or help options. Deprecated; use :meth:`add_option` after ++ creating the parser instead. + + ``option_class`` (default: optparse.Option) + Class to use when adding options to the parser in :meth:`add_option`. + + ``version`` (default: ``None``) +- A version string to print when the user supplies a version option. If you supply +- a true value for ``version``, :mod:`optparse` automatically adds a version +- option with the single option string ``"--version"``. The substring ``"%prog"`` +- is expanded the same as for ``usage``. ++ A version string to print when the user supplies a version option. If you ++ supply a true value for ``version``, :mod:`optparse` automatically adds a ++ version option with the single option string ``"--version"``. The ++ substring ``"%prog"`` is expanded the same as for ``usage``. + + ``conflict_handler`` (default: ``"error"``) +- Specifies what to do when options with conflicting option strings are added to +- the parser; see section :ref:`optparse-conflicts-between-options`. ++ Specifies what to do when options with conflicting option strings are ++ added to the parser; see section ++ :ref:`optparse-conflicts-between-options`. + + ``description`` (default: ``None``) +- A paragraph of text giving a brief overview of your program. :mod:`optparse` +- reformats this paragraph to fit the current terminal width and prints it when +- the user requests help (after ``usage``, but before the list of options). ++ A paragraph of text giving a brief overview of your program. ++ :mod:`optparse` reformats this paragraph to fit the current terminal width ++ and prints it when the user requests help (after ``usage``, but before the ++ list of options). + +- ``formatter`` (default: a new IndentedHelpFormatter) +- An instance of optparse.HelpFormatter that will be used for printing help text. +- :mod:`optparse` provides two concrete classes for this purpose: ++ ``formatter`` (default: a new :class:`IndentedHelpFormatter`) ++ An instance of optparse.HelpFormatter that will be used for printing help ++ text. :mod:`optparse` provides two concrete classes for this purpose: + IndentedHelpFormatter and TitledHelpFormatter. + + ``add_help_option`` (default: ``True``) +@@ -743,14 +748,14 @@ + ^^^^^^^^^^^^^^^^^^^^^ + + There are several ways to populate the parser with options. The preferred way +-is by using ``OptionParser.add_option()``, as shown in section ++is by using :meth:`OptionParser.add_option`, as shown in section + :ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways: + + * pass it an Option instance (as returned by :func:`make_option`) + + * pass it any combination of positional and keyword arguments that are +- acceptable to :func:`make_option` (i.e., to the Option constructor), and it will +- create the Option instance for you ++ acceptable to :func:`make_option` (i.e., to the Option constructor), and it ++ will create the Option instance for you + + The other alternative is to pass a list of pre-constructed Option instances to + the OptionParser constructor, as in:: +@@ -778,66 +783,67 @@ + e.g. :option:`-f` and :option:`--file`. You can specify any number of short or + long option strings, but you must specify at least one overall option string. + +-The canonical way to create an Option instance is with the :meth:`add_option` +-method of :class:`OptionParser`:: ++The canonical way to create an :class:`Option` instance is with the ++:meth:`add_option` method of :class:`OptionParser`. + +- parser.add_option(opt_str[, ...], attr=value, ...) ++.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...) + +-To define an option with only a short option string:: ++ To define an option with only a short option string:: + +- parser.add_option("-f", attr=value, ...) ++ parser.add_option("-f", attr=value, ...) + +-And to define an option with only a long option string:: ++ And to define an option with only a long option string:: + +- parser.add_option("--foo", attr=value, ...) ++ parser.add_option("--foo", attr=value, ...) + +-The keyword arguments define attributes of the new Option object. The most +-important option attribute is :attr:`action`, and it largely determines which +-other attributes are relevant or required. If you pass irrelevant option +-attributes, or fail to pass required ones, :mod:`optparse` raises an +-:exc:`OptionError` exception explaining your mistake. ++ The keyword arguments define attributes of the new Option object. The most ++ important option attribute is :attr:`~Option.action`, and it largely ++ determines which other attributes are relevant or required. If you pass ++ irrelevant option attributes, or fail to pass required ones, :mod:`optparse` ++ raises an :exc:`OptionError` exception explaining your mistake. + +-An option's *action* determines what :mod:`optparse` does when it encounters +-this option on the command-line. The standard option actions hard-coded into +-:mod:`optparse` are: ++ An option's *action* determines what :mod:`optparse` does when it encounters ++ this option on the command-line. The standard option actions hard-coded into ++ :mod:`optparse` are: + +-``store`` +- store this option's argument (default) ++ ``"store"`` ++ store this option's argument (default) + +-``store_const`` +- store a constant value ++ ``"store_const"`` ++ store a constant value + +-``store_true`` +- store a true value ++ ``"store_true"`` ++ store a true value + +-``store_false`` +- store a false value ++ ``"store_false"`` ++ store a false value + +-``append`` +- append this option's argument to a list ++ ``"append"`` ++ append this option's argument to a list + +-``append_const`` +- append a constant value to a list ++ ``"append_const"`` ++ append a constant value to a list + +-``count`` +- increment a counter by one ++ ``"count"`` ++ increment a counter by one + +-``callback`` +- call a specified function ++ ``"callback"`` ++ call a specified function + +-:attr:`help` +- print a usage message including all options and the documentation for them ++ ``"help"`` ++ print a usage message including all options and the documentation for them + +-(If you don't supply an action, the default is ``store``. For this action, you +-may also supply :attr:`!type` and :attr:`dest` option attributes; see below.) ++ (If you don't supply an action, the default is ``"store"``. For this action, ++ you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option ++ attributes; see :ref:`optparse-standard-option-actions`.) + + As you can see, most actions involve storing or updating a value somewhere. + :mod:`optparse` always creates a special object for this, conventionally called +-``options`` (it happens to be an instance of ``optparse.Values``). Option ++``options`` (it happens to be an instance of :class:`optparse.Values`). Option + arguments (and various other values) are stored as attributes of this object, +-according to the :attr:`dest` (destination) option attribute. ++according to the :attr:`~Option.dest` (destination) option attribute. + +-For example, when you call :: ++For example, when you call :: + + parser.parse_args() + +@@ -845,7 +851,7 @@ + + options = Values() + +-If one of the options in this parser is defined with :: ++If one of the options in this parser is defined with :: + + parser.add_option("-f", "--file", action="store", type="string", dest="filename") + +@@ -856,15 +862,99 @@ + --file=foo + --file foo + +-then :mod:`optparse`, on seeing this option, will do the equivalent of :: ++then :mod:`optparse`, on seeing this option, will do the equivalent of :: + + options.filename = "foo" + +-The :attr:`!type` and :attr:`dest` option attributes are almost as important as +-:attr:`action`, but :attr:`action` is the only one that makes sense for *all* +-options. ++The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost ++as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only ++one that makes sense for *all* options. + + ++.. _optparse-option-attributes: ++ ++Option attributes ++^^^^^^^^^^^^^^^^^ ++ ++The following option attributes may be passed as keyword arguments to ++:meth:`OptionParser.add_option`. If you pass an option attribute that is not ++relevant to a particular option, or fail to pass a required option attribute, ++:mod:`optparse` raises :exc:`OptionError`. ++ ++.. attribute:: Option.action ++ ++ (default: ``"store"``) ++ ++ Determines :mod:`optparse`'s behaviour when this option is seen on the ++ command line; the available options are documented :ref:`here ++ `. ++ ++.. attribute:: Option.type ++ ++ (default: ``"string"``) ++ ++ The argument type expected by this option (e.g., ``"string"`` or ``"int"``); ++ the available option types are documented :ref:`here ++ `. ++ ++.. attribute:: Option.dest ++ ++ (default: derived from option strings) ++ ++ If the option's action implies writing or modifying a value somewhere, this ++ tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an ++ attribute of the ``options`` object that :mod:`optparse` builds as it parses ++ the command line. ++ ++.. attribute:: Option.default ++ ++ The value to use for this option's destination if the option is not seen on ++ the command line. See also :meth:`OptionParser.set_defaults`. ++ ++.. attribute:: Option.nargs ++ ++ (default: 1) ++ ++ How many arguments of type :attr:`~Option.type` should be consumed when this ++ option is seen. If > 1, :mod:`optparse` will store a tuple of values to ++ :attr:`~Option.dest`. ++ ++.. attribute:: Option.const ++ ++ For actions that store a constant value, the constant value to store. ++ ++.. attribute:: Option.choices ++ ++ For options of type ``"choice"``, the list of strings the user may choose ++ from. ++ ++.. attribute:: Option.callback ++ ++ For options with action ``"callback"``, the callable to call when this option ++ is seen. See section :ref:`optparse-option-callbacks` for detail on the ++ arguments passed to the callable. ++ ++.. attribute:: Option.callback_args ++ Option.callback_kwargs ++ ++ Additional positional and keyword arguments to pass to ``callback`` after the ++ four standard callback arguments. ++ ++.. attribute:: Option.help ++ ++ Help text to print for this option when listing all available options after ++ the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If ++ no help text is supplied, the option will be listed without help text. To ++ hide this option, use the special value :data:`optparse.SUPPRESS_HELP`. ++ ++.. attribute:: Option.metavar ++ ++ (default: derived from option strings) ++ ++ Stand-in for the option argument(s) to use when printing help text. See ++ section :ref:`optparse-tutorial` for an example. ++ ++ + .. _optparse-standard-option-actions: + + Standard option actions +@@ -875,42 +965,45 @@ + guide :mod:`optparse`'s behaviour; a few have required attributes, which you + must specify for any option using that action. + +-* ``store`` [relevant: :attr:`!type`, :attr:`dest`, ``nargs``, ``choices``] ++* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`, ++ :attr:`~Option.nargs`, :attr:`~Option.choices`] + + The option must be followed by an argument, which is converted to a value +- according to :attr:`!type` and stored in :attr:`dest`. If ``nargs`` > 1, +- multiple arguments will be consumed from the command line; all will be converted +- according to :attr:`!type` and stored to :attr:`dest` as a tuple. See the +- "Option types" section below. ++ according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If ++ :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the ++ command line; all will be converted according to :attr:`~Option.type` and ++ stored to :attr:`~Option.dest` as a tuple. See the ++ :ref:`optparse-standard-option-types` section. + +- If ``choices`` is supplied (a list or tuple of strings), the type defaults to +- ``choice``. ++ If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type ++ defaults to ``"choice"``. + +- If :attr:`!type` is not supplied, it defaults to ``string``. ++ If :attr:`~Option.type` is not supplied, it defaults to ``"string"``. + +- If :attr:`dest` is not supplied, :mod:`optparse` derives a destination from the +- first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``). If there +- are no long option strings, :mod:`optparse` derives a destination from the first +- short option string (e.g., ``"-f"`` implies ``f``). ++ If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination ++ from the first long option string (e.g., ``"--foo-bar"`` implies ++ ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a ++ destination from the first short option string (e.g., ``"-f"`` implies ``f``). + + Example:: + + parser.add_option("-f") + parser.add_option("-p", type="float", nargs=3, dest="point") + +- As it parses the command line :: ++ As it parses the command line :: + + -f foo.txt -p 1 -3.5 4 -fbar.txt + +- :mod:`optparse` will set :: ++ :mod:`optparse` will set :: + + options.f = "foo.txt" + options.point = (1.0, -3.5, 4.0) + options.f = "bar.txt" + +-* ``store_const`` [required: ``const``; relevant: :attr:`dest`] ++* ``"store_const"`` [required: :attr:`~Option.const`; relevant: ++ :attr:`~Option.dest`] + +- The value ``const`` is stored in :attr:`dest`. ++ The value :attr:`~Option.const` is stored in :attr:`~Option.dest`. + + Example:: + +@@ -925,29 +1018,32 @@ + + options.verbose = 2 + +-* ``store_true`` [relevant: :attr:`dest`] ++* ``"store_true"`` [relevant: :attr:`~Option.dest`] + +- A special case of ``store_const`` that stores a true value to :attr:`dest`. ++ A special case of ``"store_const"`` that stores a true value to ++ :attr:`~Option.dest`. + +-* ``store_false`` [relevant: :attr:`dest`] ++* ``"store_false"`` [relevant: :attr:`~Option.dest`] + +- Like ``store_true``, but stores a false value. ++ Like ``"store_true"``, but stores a false value. + + Example:: + + parser.add_option("--clobber", action="store_true", dest="clobber") + parser.add_option("--no-clobber", action="store_false", dest="clobber") + +-* ``append`` [relevant: :attr:`!type`, :attr:`dest`, ``nargs``, ``choices``] ++* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`, ++ :attr:`~Option.nargs`, :attr:`~Option.choices`] + + The option must be followed by an argument, which is appended to the list in +- :attr:`dest`. If no default value for :attr:`dest` is supplied, an empty list +- is automatically created when :mod:`optparse` first encounters this option on +- the command-line. If ``nargs`` > 1, multiple arguments are consumed, and a +- tuple of length ``nargs`` is appended to :attr:`dest`. ++ :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is ++ supplied, an empty list is automatically created when :mod:`optparse` first ++ encounters this option on the command-line. If :attr:`~Option.nargs` > 1, ++ multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs` ++ is appended to :attr:`~Option.dest`. + +- The defaults for :attr:`!type` and :attr:`dest` are the same as for the ``store`` +- action. ++ The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as ++ for the ``"store"`` action. + + Example:: + +@@ -963,16 +1059,19 @@ + + options.tracks.append(int("4")) + +-* ``append_const`` [required: ``const``; relevant: :attr:`dest`] ++* ``"append_const"`` [required: :attr:`~Option.const`; relevant: ++ :attr:`~Option.dest`] + +- Like ``store_const``, but the value ``const`` is appended to :attr:`dest`; as +- with ``append``, :attr:`dest` defaults to ``None``, and an empty list is +- automatically created the first time the option is encountered. ++ Like ``"store_const"``, but the value :attr:`~Option.const` is appended to ++ :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to ++ ``None``, and an empty list is automatically created the first time the option ++ is encountered. + +-* ``count`` [relevant: :attr:`dest`] ++* ``"count"`` [relevant: :attr:`~Option.dest`] + +- Increment the integer stored at :attr:`dest`. If no default value is supplied, +- :attr:`dest` is set to zero before being incremented the first time. ++ Increment the integer stored at :attr:`~Option.dest`. If no default value is ++ supplied, :attr:`~Option.dest` is set to zero before being incremented the ++ first time. + + Example:: + +@@ -988,42 +1087,47 @@ + + options.verbosity += 1 + +-* ``callback`` [required: ``callback``; relevant: :attr:`!type`, ``nargs``, +- ``callback_args``, ``callback_kwargs``] ++* ``"callback"`` [required: :attr:`~Option.callback`; relevant: ++ :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`, ++ :attr:`~Option.callback_kwargs`] + +- Call the function specified by ``callback``, which is called as :: ++ Call the function specified by :attr:`~Option.callback`, which is called as :: + + func(option, opt_str, value, parser, *args, **kwargs) + + See section :ref:`optparse-option-callbacks` for more detail. + +-* :attr:`help` ++* ``"help"`` + +- Prints a complete help message for all the options in the current option parser. +- The help message is constructed from the ``usage`` string passed to +- OptionParser's constructor and the :attr:`help` string passed to every option. ++ Prints a complete help message for all the options in the current option ++ parser. The help message is constructed from the ``usage`` string passed to ++ OptionParser's constructor and the :attr:`~Option.help` string passed to every ++ option. + +- If no :attr:`help` string is supplied for an option, it will still be listed in +- the help message. To omit an option entirely, use the special value +- ``optparse.SUPPRESS_HELP``. ++ If no :attr:`~Option.help` string is supplied for an option, it will still be ++ listed in the help message. To omit an option entirely, use the special value ++ :data:`optparse.SUPPRESS_HELP`. + +- :mod:`optparse` automatically adds a :attr:`help` option to all OptionParsers, +- so you do not normally need to create one. ++ :mod:`optparse` automatically adds a :attr:`~Option.help` option to all ++ OptionParsers, so you do not normally need to create one. + + Example:: + + from optparse import OptionParser, SUPPRESS_HELP + +- parser = OptionParser() +- parser.add_option("-h", "--help", action="help"), ++ # usually, a help option is added automatically, but that can ++ # be suppressed using the add_help_option argument ++ parser = OptionParser(add_help_option=False) ++ ++ parser.add_option("-h", "--help", action="help") + parser.add_option("-v", action="store_true", dest="verbose", + help="Be moderately verbose") + parser.add_option("--file", dest="filename", +- help="Input file to read data from"), ++ help="Input file to read data from") + parser.add_option("--secret", help=SUPPRESS_HELP) + +- If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, it +- will print something like the following help message to stdout (assuming ++ If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, ++ it will print something like the following help message to stdout (assuming + ``sys.argv[0]`` is ``"foo.py"``):: + + usage: foo.py [options] +@@ -1036,97 +1140,29 @@ + After printing the help message, :mod:`optparse` terminates your process with + ``sys.exit(0)``. + +-* ``version`` ++* ``"version"`` + +- Prints the version number supplied to the OptionParser to stdout and exits. The +- version number is actually formatted and printed by the ``print_version()`` +- method of OptionParser. Generally only relevant if the ``version`` argument is +- supplied to the OptionParser constructor. As with :attr:`help` options, you +- will rarely create ``version`` options, since :mod:`optparse` automatically adds +- them when needed. ++ Prints the version number supplied to the OptionParser to stdout and exits. ++ The version number is actually formatted and printed by the ++ ``print_version()`` method of OptionParser. Generally only relevant if the ++ ``version`` argument is supplied to the OptionParser constructor. As with ++ :attr:`~Option.help` options, you will rarely create ``version`` options, ++ since :mod:`optparse` automatically adds them when needed. + + +-.. _optparse-option-attributes: +- +-Option attributes +-^^^^^^^^^^^^^^^^^ +- +-The following option attributes may be passed as keyword arguments to +-``parser.add_option()``. If you pass an option attribute that is not relevant +-to a particular option, or fail to pass a required option attribute, +-:mod:`optparse` raises :exc:`OptionError`. +- +-* :attr:`action` (default: ``"store"``) +- +- Determines :mod:`optparse`'s behaviour when this option is seen on the command +- line; the available options are documented above. +- +-* :attr:`!type` (default: ``"string"``) +- +- The argument type expected by this option (e.g., ``"string"`` or ``"int"``); the +- available option types are documented below. +- +-* :attr:`dest` (default: derived from option strings) +- +- If the option's action implies writing or modifying a value somewhere, this +- tells :mod:`optparse` where to write it: :attr:`dest` names an attribute of the +- ``options`` object that :mod:`optparse` builds as it parses the command line. +- +-* ``default`` +- +- The value to use for this option's destination if the option is not seen on the +- command line. See also ``parser.set_defaults()``. +- +-* ``nargs`` (default: 1) +- +- How many arguments of type :attr:`!type` should be consumed when this option is +- seen. If > 1, :mod:`optparse` will store a tuple of values to :attr:`dest`. +- +-* ``const`` +- +- For actions that store a constant value, the constant value to store. +- +-* ``choices`` +- +- For options of type ``"choice"``, the list of strings the user may choose from. +- +-* ``callback`` +- +- For options with action ``"callback"``, the callable to call when this option +- is seen. See section :ref:`optparse-option-callbacks` for detail on the +- arguments passed to ``callable``. +- +-* ``callback_args``, ``callback_kwargs`` +- +- Additional positional and keyword arguments to pass to ``callback`` after the +- four standard callback arguments. +- +-* :attr:`help` +- +- Help text to print for this option when listing all available options after the +- user supplies a :attr:`help` option (such as ``"--help"``). If no help text is +- supplied, the option will be listed without help text. To hide this option, use +- the special value ``SUPPRESS_HELP``. +- +-* ``metavar`` (default: derived from option strings) +- +- Stand-in for the option argument(s) to use when printing help text. See section +- :ref:`optparse-tutorial` for an example. +- +- + .. _optparse-standard-option-types: + + Standard option types + ^^^^^^^^^^^^^^^^^^^^^ + +-:mod:`optparse` has five built-in option types: ``string``, ``int``, +-``choice``, ``float`` and ``complex``. If you need to add new option types, see +-section :ref:`optparse-extending-optparse`. ++:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``, ++``"choice"``, ``"float"`` and ``"complex"``. If you need to add new ++option types, see section :ref:`optparse-extending-optparse`. + + Arguments to string options are not checked or converted in any way: the text on + the command line is stored in the destination (or passed to the callback) as-is. + +-Integer arguments (type ``int``) are parsed as follows: ++Integer arguments (type ``"int"``) are parsed as follows: + + * if the number starts with ``0x``, it is parsed as a hexadecimal number + +@@ -1137,17 +1173,18 @@ + * otherwise, the number is parsed as a decimal number + + +-The conversion is done by calling ``int()`` with the appropriate base (2, 8, 10, +-or 16). If this fails, so will :mod:`optparse`, although with a more useful ++The conversion is done by calling :func:`int` with the appropriate base (2, 8, ++10, or 16). If this fails, so will :mod:`optparse`, although with a more useful + error message. + +-``float`` and ``complex`` option arguments are converted directly with +-``float()`` and ``complex()``, with similar error-handling. ++``"float"`` and ``"complex"`` option arguments are converted directly with ++:func:`float` and :func:`complex`, with similar error-handling. + +-``choice`` options are a subtype of ``string`` options. The ``choices`` option +-attribute (a sequence of strings) defines the set of allowed option arguments. +-``optparse.check_choice()`` compares user-supplied option arguments against this +-master list and raises :exc:`OptionValueError` if an invalid string is given. ++``"choice"`` options are a subtype of ``"string"`` options. The ++:attr:`~Option.choices`` option attribute (a sequence of strings) defines the ++set of allowed option arguments. :func:`optparse.check_choice` compares ++user-supplied option arguments against this master list and raises ++:exc:`OptionValueError` if an invalid string is given. + + + .. _optparse-parsing-arguments: +@@ -1166,19 +1203,20 @@ + the list of arguments to process (default: ``sys.argv[1:]``) + + ``values`` +- object to store option arguments in (default: a new instance of optparse.Values) ++ object to store option arguments in (default: a new instance of ++ :class:`optparse.Values`) + + and the return values are + + ``options`` +- the same object that was passed in as ``options``, or the optparse.Values ++ the same object that was passed in as ``values``, or the optparse.Values + instance created by :mod:`optparse` + + ``args`` + the leftover positional arguments after all options have been processed + + The most common usage is to supply neither keyword argument. If you supply +-``options``, it will be modified with repeated ``setattr()`` calls (roughly one ++``values``, it will be modified with repeated :func:`setattr` calls (roughly one + for every option argument stored to an option destination) and returned by + :meth:`parse_args`. + +@@ -1193,39 +1231,53 @@ + Querying and manipulating your option parser + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +-The default behavior of the option parser can be customized slightly, +-and you can also poke around your option parser and see what's there. +-OptionParser provides several methods to help you out: ++The default behavior of the option parser can be customized slightly, and you ++can also poke around your option parser and see what's there. OptionParser ++provides several methods to help you out: + +-``disable_interspersed_args()`` +- Set parsing to stop on the first non-option. Use this if you have a +- command processor which runs another command which has options of +- its own and you want to make sure these options don't get +- confused. For example, each command might have a different +- set of options. ++.. method:: OptionParser.disable_interspersed_args() + +-``enable_interspersed_args()`` +- Set parsing to not stop on the first non-option, allowing +- interspersing switches with command arguments. For example, +- ``"-s arg1 --long arg2"`` would return ``["arg1", "arg2"]`` +- as the command arguments and ``-s, --long`` as options. +- This is the default behavior. ++ Set parsing to stop on the first non-option. For example, if ``"-a"`` and ++ ``"-b"`` are both simple options that take no arguments, :mod:`optparse` ++ normally accepts this syntax:: + +-``get_option(opt_str)`` +- Returns the Option instance with the option string ``opt_str``, or ``None`` if ++ prog -a arg1 -b arg2 ++ ++ and treats it as equivalent to :: ++ ++ prog -a -b arg1 arg2 ++ ++ To disable this feature, call :meth:`disable_interspersed_args`. This ++ restores traditional Unix syntax, where option parsing stops with the first ++ non-option argument. ++ ++ Use this if you have a command processor which runs another command which has ++ options of its own and you want to make sure these options don't get ++ confused. For example, each command might have a different set of options. ++ ++.. method:: OptionParser.enable_interspersed_args() ++ ++ Set parsing to not stop on the first non-option, allowing interspersing ++ switches with command arguments. This is the default behavior. ++ ++.. method:: OptionParser.get_option(opt_str) ++ ++ Returns the Option instance with the option string *opt_str*, or ``None`` if + no options have that option string. + +-``has_option(opt_str)`` +- Return true if the OptionParser has an option with option string ``opt_str`` ++.. method:: OptionParser.has_option(opt_str) ++ ++ Return true if the OptionParser has an option with option string *opt_str* + (e.g., ``"-q"`` or ``"--verbose"``). + +-``remove_option(opt_str)`` +- If the :class:`OptionParser` has an option corresponding to ``opt_str``, that option is +- removed. If that option provided any other option strings, all of those option +- strings become invalid. If ``opt_str`` does not occur in any option belonging to +- this :class:`OptionParser`, raises :exc:`ValueError`. ++.. method:: OptionParser.remove_option(opt_str) + ++ If the :class:`OptionParser` has an option corresponding to *opt_str*, that ++ option is removed. If that option provided any other option strings, all of ++ those option strings become invalid. If *opt_str* does not occur in any ++ option belonging to this :class:`OptionParser`, raises :exc:`ValueError`. + ++ + .. _optparse-conflicts-between-options: + + Conflicts between options +@@ -1253,10 +1305,11 @@ + + The available conflict handlers are: + +- ``error`` (default) +- assume option conflicts are a programming error and raise :exc:`OptionConflictError` ++ ``"error"`` (default) ++ assume option conflicts are a programming error and raise ++ :exc:`OptionConflictError` + +- ``resolve`` ++ ``"resolve"`` + resolve option conflicts intelligently (see below) + + +@@ -1302,9 +1355,10 @@ + + OptionParser instances have several cyclic references. This should not be a + problem for Python's garbage collector, but you may wish to break the cyclic +-references explicitly by calling ``destroy()`` on your OptionParser once you are +-done with it. This is particularly useful in long-running applications where +-large object graphs are reachable from your OptionParser. ++references explicitly by calling :meth:`~OptionParser.destroy` on your ++OptionParser once you are done with it. This is particularly useful in ++long-running applications where large object graphs are reachable from your ++OptionParser. + + + .. _optparse-other-methods: +@@ -1314,53 +1368,36 @@ + + OptionParser supports several other public methods: + +-* ``set_usage(usage)`` ++.. method:: OptionParser.set_usage(usage) + +- Set the usage string according to the rules described above for the ``usage`` +- constructor keyword argument. Passing ``None`` sets the default usage string; +- use ``SUPPRESS_USAGE`` to suppress a usage message. ++ Set the usage string according to the rules described above for the ``usage`` ++ constructor keyword argument. Passing ``None`` sets the default usage ++ string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message. + +-* ``enable_interspersed_args()``, ``disable_interspersed_args()`` ++.. method:: OptionParser.set_defaults(dest=value, ...) + +- Enable/disable positional arguments interspersed with options, similar to GNU +- getopt (enabled by default). For example, if ``"-a"`` and ``"-b"`` are both +- simple options that take no arguments, :mod:`optparse` normally accepts this +- syntax:: ++ Set default values for several option destinations at once. Using ++ :meth:`set_defaults` is the preferred way to set default values for options, ++ since multiple options can share the same destination. For example, if ++ several "mode" options all set the same destination, any one of them can set ++ the default, and the last one wins:: + +- prog -a arg1 -b arg2 ++ parser.add_option("--advanced", action="store_const", ++ dest="mode", const="advanced", ++ default="novice") # overridden below ++ parser.add_option("--novice", action="store_const", ++ dest="mode", const="novice", ++ default="advanced") # overrides above setting + +- and treats it as equivalent to :: ++ To avoid this confusion, use :meth:`set_defaults`:: + +- prog -a -b arg1 arg2 ++ parser.set_defaults(mode="advanced") ++ parser.add_option("--advanced", action="store_const", ++ dest="mode", const="advanced") ++ parser.add_option("--novice", action="store_const", ++ dest="mode", const="novice") + +- To disable this feature, call ``disable_interspersed_args()``. This restores +- traditional Unix syntax, where option parsing stops with the first non-option +- argument. + +-* ``set_defaults(dest=value, ...)`` +- +- Set default values for several option destinations at once. Using +- :meth:`set_defaults` is the preferred way to set default values for options, +- since multiple options can share the same destination. For example, if several +- "mode" options all set the same destination, any one of them can set the +- default, and the last one wins:: +- +- parser.add_option("--advanced", action="store_const", +- dest="mode", const="advanced", +- default="novice") # overridden below +- parser.add_option("--novice", action="store_const", +- dest="mode", const="novice", +- default="advanced") # overrides above setting +- +- To avoid this confusion, use :meth:`set_defaults`:: +- +- parser.set_defaults(mode="advanced") +- parser.add_option("--advanced", action="store_const", +- dest="mode", const="advanced") +- parser.add_option("--novice", action="store_const", +- dest="mode", const="novice") +- +- + .. _optparse-option-callbacks: + + Option Callbacks +@@ -1373,7 +1410,7 @@ + + There are two steps to defining a callback option: + +-* define the option itself using the ``callback`` action ++* define the option itself using the ``"callback"`` action + + * write the callback; this is a function (or method) that takes at least four + arguments, as described below +@@ -1385,8 +1422,8 @@ + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + + As always, the easiest way to define a callback option is by using the +-``parser.add_option()`` method. Apart from :attr:`action`, the only option +-attribute you must specify is ``callback``, the function to call:: ++:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the ++only option attribute you must specify is ``callback``, the function to call:: + + parser.add_option("-c", action="callback", callback=my_callback) + +@@ -1400,8 +1437,9 @@ + it's covered later in this section. + + :mod:`optparse` always passes four particular arguments to your callback, and it +-will only pass additional arguments if you specify them via ``callback_args`` +-and ``callback_kwargs``. Thus, the minimal callback function signature is:: ++will only pass additional arguments if you specify them via ++:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the ++minimal callback function signature is:: + + def my_callback(option, opt, value, parser): + +@@ -1410,21 +1448,22 @@ + There are several other option attributes that you can supply when you define a + callback option: + +-:attr:`!type` +- has its usual meaning: as with the ``store`` or ``append`` actions, it instructs +- :mod:`optparse` to consume one argument and convert it to :attr:`!type`. Rather +- than storing the converted value(s) anywhere, though, :mod:`optparse` passes it +- to your callback function. ++:attr:`~Option.type` ++ has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it ++ instructs :mod:`optparse` to consume one argument and convert it to ++ :attr:`~Option.type`. Rather than storing the converted value(s) anywhere, ++ though, :mod:`optparse` passes it to your callback function. + +-``nargs`` ++:attr:`~Option.nargs` + also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will +- consume ``nargs`` arguments, each of which must be convertible to :attr:`!type`. +- It then passes a tuple of converted values to your callback. ++ consume :attr:`~Option.nargs` arguments, each of which must be convertible to ++ :attr:`~Option.type`. It then passes a tuple of converted values to your ++ callback. + +-``callback_args`` ++:attr:`~Option.callback_args` + a tuple of extra positional arguments to pass to the callback + +-``callback_kwargs`` ++:attr:`~Option.callback_kwargs` + a dictionary of extra keyword arguments to pass to the callback + + +@@ -1444,45 +1483,48 @@ + + ``opt_str`` + is the option string seen on the command-line that's triggering the callback. +- (If an abbreviated long option was used, ``opt_str`` will be the full, canonical +- option string---e.g. if the user puts ``"--foo"`` on the command-line as an +- abbreviation for ``"--foobar"``, then ``opt_str`` will be ``"--foobar"``.) ++ (If an abbreviated long option was used, ``opt_str`` will be the full, ++ canonical option string---e.g. if the user puts ``"--foo"`` on the ++ command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be ++ ``"--foobar"``.) + + ``value`` + is the argument to this option seen on the command-line. :mod:`optparse` will +- only expect an argument if :attr:`!type` is set; the type of ``value`` will be +- the type implied by the option's type. If :attr:`!type` for this option is +- ``None`` (no argument expected), then ``value`` will be ``None``. If ``nargs`` ++ only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be ++ the type implied by the option's type. If :attr:`~Option.type` for this option is ++ ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs` + > 1, ``value`` will be a tuple of values of the appropriate type. + + ``parser`` +- is the OptionParser instance driving the whole thing, mainly useful because you +- can access some other interesting data through its instance attributes: ++ is the OptionParser instance driving the whole thing, mainly useful because ++ you can access some other interesting data through its instance attributes: + + ``parser.largs`` +- the current list of leftover arguments, ie. arguments that have been consumed +- but are neither options nor option arguments. Feel free to modify +- ``parser.largs``, e.g. by adding more arguments to it. (This list will become +- ``args``, the second return value of :meth:`parse_args`.) ++ the current list of leftover arguments, ie. arguments that have been ++ consumed but are neither options nor option arguments. Feel free to modify ++ ``parser.largs``, e.g. by adding more arguments to it. (This list will ++ become ``args``, the second return value of :meth:`parse_args`.) + + ``parser.rargs`` +- the current list of remaining arguments, ie. with ``opt_str`` and ``value`` (if +- applicable) removed, and only the arguments following them still there. Feel +- free to modify ``parser.rargs``, e.g. by consuming more arguments. ++ the current list of remaining arguments, ie. with ``opt_str`` and ++ ``value`` (if applicable) removed, and only the arguments following them ++ still there. Feel free to modify ``parser.rargs``, e.g. by consuming more ++ arguments. + + ``parser.values`` + the object where option values are by default stored (an instance of +- optparse.OptionValues). This lets callbacks use the same mechanism as the rest +- of :mod:`optparse` for storing option values; you don't need to mess around with +- globals or closures. You can also access or modify the value(s) of any options +- already encountered on the command-line. ++ optparse.OptionValues). This lets callbacks use the same mechanism as the ++ rest of :mod:`optparse` for storing option values; you don't need to mess ++ around with globals or closures. You can also access or modify the ++ value(s) of any options already encountered on the command-line. + + ``args`` +- is a tuple of arbitrary positional arguments supplied via the ``callback_args`` +- option attribute. ++ is a tuple of arbitrary positional arguments supplied via the ++ :attr:`~Option.callback_args` option attribute. + + ``kwargs`` +- is a dictionary of arbitrary keyword arguments supplied via ``callback_kwargs``. ++ is a dictionary of arbitrary keyword arguments supplied via ++ :attr:`~Option.callback_kwargs`. + + + .. _optparse-raising-errors-in-callback: +@@ -1490,11 +1532,11 @@ + Raising errors in a callback + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +-The callback function should raise :exc:`OptionValueError` if there are any problems +-with the option or its argument(s). :mod:`optparse` catches this and terminates +-the program, printing the error message you supply to stderr. Your message +-should be clear, concise, accurate, and mention the option at fault. Otherwise, +-the user will have a hard time figuring out what he did wrong. ++The callback function should raise :exc:`OptionValueError` if there are any ++problems with the option or its argument(s). :mod:`optparse` catches this and ++terminates the program, printing the error message you supply to stderr. Your ++message should be clear, concise, accurate, and mention the option at fault. ++Otherwise, the user will have a hard time figuring out what he did wrong. + + + .. _optparse-callback-example-1: +@@ -1510,7 +1552,7 @@ + + parser.add_option("--foo", action="callback", callback=record_foo_seen) + +-Of course, you could do that with the ``store_true`` action. ++Of course, you could do that with the ``"store_true"`` action. + + + .. _optparse-callback-example-2: +@@ -1577,12 +1619,12 @@ + + Things get slightly more interesting when you define callback options that take + a fixed number of arguments. Specifying that a callback option takes arguments +-is similar to defining a ``store`` or ``append`` option: if you define +-:attr:`!type`, then the option takes one argument that must be convertible to +-that type; if you further define ``nargs``, then the option takes ``nargs`` +-arguments. ++is similar to defining a ``"store"`` or ``"append"`` option: if you define ++:attr:`~Option.type`, then the option takes one argument that must be ++convertible to that type; if you further define :attr:`~Option.nargs`, then the ++option takes :attr:`~Option.nargs` arguments. + +-Here's an example that just emulates the standard ``store`` action:: ++Here's an example that just emulates the standard ``"store"`` action:: + + def store_value(option, opt_str, value, parser): + setattr(parser.values, option.dest, value) +@@ -1669,32 +1711,36 @@ + ^^^^^^^^^^^^^^^^ + + To add new types, you need to define your own subclass of :mod:`optparse`'s +-Option class. This class has a couple of attributes that define +-:mod:`optparse`'s types: :attr:`TYPES` and :attr:`TYPE_CHECKER`. ++:class:`Option` class. This class has a couple of attributes that define ++:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`. + +-:attr:`TYPES` is a tuple of type names; in your subclass, simply define a new +-tuple :attr:`TYPES` that builds on the standard one. ++.. attribute:: Option.TYPES + +-:attr:`TYPE_CHECKER` is a dictionary mapping type names to type-checking +-functions. A type-checking function has the following signature:: ++ A tuple of type names; in your subclass, simply define a new tuple ++ :attr:`TYPES` that builds on the standard one. + +- def check_mytype(option, opt, value) ++.. attribute:: Option.TYPE_CHECKER + +-where ``option`` is an :class:`Option` instance, ``opt`` is an option string +-(e.g., ``"-f"``), and ``value`` is the string from the command line that must be +-checked and converted to your desired type. ``check_mytype()`` should return an +-object of the hypothetical type ``mytype``. The value returned by a +-type-checking function will wind up in the OptionValues instance returned by +-:meth:`OptionParser.parse_args`, or be passed to a callback as the ``value`` +-parameter. ++ A dictionary mapping type names to type-checking functions. A type-checking ++ function has the following signature:: + +-Your type-checking function should raise :exc:`OptionValueError` if it encounters any +-problems. :exc:`OptionValueError` takes a single string argument, which is passed +-as-is to :class:`OptionParser`'s :meth:`error` method, which in turn prepends the program +-name and the string ``"error:"`` and prints everything to stderr before +-terminating the process. ++ def check_mytype(option, opt, value) + +-Here's a silly example that demonstrates adding a ``complex`` option type to ++ where ``option`` is an :class:`Option` instance, ``opt`` is an option string ++ (e.g., ``"-f"``), and ``value`` is the string from the command line that must ++ be checked and converted to your desired type. ``check_mytype()`` should ++ return an object of the hypothetical type ``mytype``. The value returned by ++ a type-checking function will wind up in the OptionValues instance returned ++ by :meth:`OptionParser.parse_args`, or be passed to a callback as the ++ ``value`` parameter. ++ ++ Your type-checking function should raise :exc:`OptionValueError` if it ++ encounters any problems. :exc:`OptionValueError` takes a single string ++ argument, which is passed as-is to :class:`OptionParser`'s :meth:`error` ++ method, which in turn prepends the program name and the string ``"error:"`` ++ and prints everything to stderr before terminating the process. ++ ++Here's a silly example that demonstrates adding a ``"complex"`` option type to + parse Python-style complex numbers on the command line. (This is even sillier + than it used to be, because :mod:`optparse` 1.3 added built-in support for + complex numbers, but never mind.) +@@ -1705,7 +1751,7 @@ + from optparse import Option, OptionValueError + + You need to define your type-checker first, since it's referred to later (in the +-:attr:`TYPE_CHECKER` class attribute of your Option subclass):: ++:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass):: + + def check_complex(option, opt, value): + try: +@@ -1722,9 +1768,9 @@ + TYPE_CHECKER["complex"] = check_complex + + (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end +-up modifying the :attr:`TYPE_CHECKER` attribute of :mod:`optparse`'s Option +-class. This being Python, nothing stops you from doing that except good manners +-and common sense.) ++up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s ++Option class. This being Python, nothing stops you from doing that except good ++manners and common sense.) + + That's it! Now you can write a script that uses the new option type just like + any other :mod:`optparse`\ -based script, except you have to instruct your +@@ -1751,45 +1797,50 @@ + + "store" actions + actions that result in :mod:`optparse` storing a value to an attribute of the +- current OptionValues instance; these options require a :attr:`dest` attribute to +- be supplied to the Option constructor ++ current OptionValues instance; these options require a :attr:`~Option.dest` ++ attribute to be supplied to the Option constructor. + + "typed" actions +- actions that take a value from the command line and expect it to be of a certain +- type; or rather, a string that can be converted to a certain type. These +- options require a :attr:`!type` attribute to the Option constructor. ++ actions that take a value from the command line and expect it to be of a ++ certain type; or rather, a string that can be converted to a certain type. ++ These options require a :attr:`~Option.type` attribute to the Option ++ constructor. + +-These are overlapping sets: some default "store" actions are ``store``, +-``store_const``, ``append``, and ``count``, while the default "typed" actions +-are ``store``, ``append``, and ``callback``. ++These are overlapping sets: some default "store" actions are ``"store"``, ++``"store_const"``, ``"append"``, and ``"count"``, while the default "typed" ++actions are ``"store"``, ``"append"``, and ``"callback"``. + + When you add an action, you need to categorize it by listing it in at least one + of the following class attributes of Option (all are lists of strings): + +-:attr:`ACTIONS` +- all actions must be listed in ACTIONS ++.. attribute:: Option.ACTIONS + +-:attr:`STORE_ACTIONS` +- "store" actions are additionally listed here ++ All actions must be listed in ACTIONS. + +-:attr:`TYPED_ACTIONS` +- "typed" actions are additionally listed here ++.. attribute:: Option.STORE_ACTIONS + +-``ALWAYS_TYPED_ACTIONS`` +- actions that always take a type (i.e. whose options always take a value) are ++ "store" actions are additionally listed here. ++ ++.. attribute:: Option.TYPED_ACTIONS ++ ++ "typed" actions are additionally listed here. ++ ++.. attribute:: Option.ALWAYS_TYPED_ACTIONS ++ ++ Actions that always take a type (i.e. whose options always take a value) are + additionally listed here. The only effect of this is that :mod:`optparse` +- assigns the default type, ``string``, to options with no explicit type whose +- action is listed in ``ALWAYS_TYPED_ACTIONS``. ++ assigns the default type, ``"string"``, to options with no explicit type ++ whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`. + + In order to actually implement your new action, you must override Option's + :meth:`take_action` method and add a case that recognizes your action. + +-For example, let's add an ``extend`` action. This is similar to the standard +-``append`` action, but instead of taking a single value from the command-line +-and appending it to an existing list, ``extend`` will take multiple values in a +-single comma-delimited string, and extend an existing list with them. That is, +-if ``"--names"`` is an ``extend`` option of type ``string``, the command line +-:: ++For example, let's add an ``"extend"`` action. This is similar to the standard ++``"append"`` action, but instead of taking a single value from the command-line ++and appending it to an existing list, ``"extend"`` will take multiple values in ++a single comma-delimited string, and extend an existing list with them. That ++is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command ++line :: + + --names=foo,bar --names blah --names ding,dong + +@@ -1816,29 +1867,30 @@ + + Features of note: + +-* ``extend`` both expects a value on the command-line and stores that value +- somewhere, so it goes in both :attr:`STORE_ACTIONS` and :attr:`TYPED_ACTIONS` ++* ``"extend"`` both expects a value on the command-line and stores that value ++ somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and ++ :attr:`~Option.TYPED_ACTIONS`. + +-* to ensure that :mod:`optparse` assigns the default type of ``string`` to +- ``extend`` actions, we put the ``extend`` action in ``ALWAYS_TYPED_ACTIONS`` as +- well ++* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to ++ ``"extend"`` actions, we put the ``"extend"`` action in ++ :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well. + + * :meth:`MyOption.take_action` implements just this one new action, and passes + control back to :meth:`Option.take_action` for the standard :mod:`optparse` +- actions ++ actions. + +-* ``values`` is an instance of the optparse_parser.Values class, which +- provides the very useful :meth:`ensure_value` method. :meth:`ensure_value` is +- essentially :func:`getattr` with a safety valve; it is called as :: ++* ``values`` is an instance of the optparse_parser.Values class, which provides ++ the very useful :meth:`ensure_value` method. :meth:`ensure_value` is ++ essentially :func:`getattr` with a safety valve; it is called as :: + + values.ensure_value(attr, value) + + If the ``attr`` attribute of ``values`` doesn't exist or is None, then +- ensure_value() first sets it to ``value``, and then returns 'value. This is very +- handy for actions like ``extend``, ``append``, and ``count``, all of which +- accumulate data in a variable and expect that variable to be of a certain type +- (a list for the first two, an integer for the latter). Using ++ ensure_value() first sets it to ``value``, and then returns 'value. This is ++ very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all ++ of which accumulate data in a variable and expect that variable to be of a ++ certain type (a list for the first two, an integer for the latter). Using + :meth:`ensure_value` means that scripts using your action don't have to worry +- about setting a default value for the option destinations in question; they can +- just leave the default as None and :meth:`ensure_value` will take care of ++ about setting a default value for the option destinations in question; they ++ can just leave the default as None and :meth:`ensure_value` will take care of + getting it right when it's needed. +Index: Doc/library/__future__.rst +=================================================================== +--- Doc/library/__future__.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/__future__.rst (.../branches/release31-maint) (Revision 76056) +@@ -10,9 +10,9 @@ + * To avoid confusing existing tools that analyze import statements and expect to + find the modules they're importing. + +-* To ensure that future_statements run under releases prior to 2.1 at least +- yield runtime exceptions (the import of :mod:`__future__` will fail, because +- there was no module of that name prior to 2.1). ++* To ensure that :ref:`future statements ` run under releases prior to ++ 2.1 at least yield runtime exceptions (the import of :mod:`__future__` will ++ fail, because there was no module of that name prior to 2.1). + + * To document when incompatible changes were introduced, and when they will be + --- or were --- made mandatory. This is a form of executable documentation, and +@@ -56,8 +56,36 @@ + dynamically compiled code. This flag is stored in the :attr:`compiler_flag` + attribute on :class:`_Feature` instances. + +-No feature description will ever be deleted from :mod:`__future__`. ++No feature description will ever be deleted from :mod:`__future__`. Since its ++introduction in Python 2.1 the following features have found their way into the ++language using this mechanism: + +++------------------+-------------+--------------+---------------------------------------------+ ++| feature | optional in | mandatory in | effect | +++==================+=============+==============+=============================================+ ++| nested_scopes | 2.1.0b1 | 2.2 | :pep:`227`: | ++| | | | *Statically Nested Scopes* | +++------------------+-------------+--------------+---------------------------------------------+ ++| generators | 2.2.0a1 | 2.3 | :pep:`255`: | ++| | | | *Simple Generators* | +++------------------+-------------+--------------+---------------------------------------------+ ++| division | 2.2.0a2 | 3.0 | :pep:`238`: | ++| | | | *Changing the Division Operator* | +++------------------+-------------+--------------+---------------------------------------------+ ++| absolute_import | 2.5.0a1 | 2.7 | :pep:`328`: | ++| | | | *Imports: Multi-Line and Absolute/Relative* | +++------------------+-------------+--------------+---------------------------------------------+ ++| with_statement | 2.5.0a1 | 2.6 | :pep:`343`: | ++| | | | *The "with" Statement* | +++------------------+-------------+--------------+---------------------------------------------+ ++| print_function | 2.6.0a2 | 3.0 | :pep:`3105`: | ++| | | | *Make print a function* | +++------------------+-------------+--------------+---------------------------------------------+ ++| unicode_literals | 2.6.0a2 | 3.0 | :pep:`3112`: | ++| | | | *Bytes literals in Python 3000* | +++------------------+-------------+--------------+---------------------------------------------+ ++ ++ + .. seealso:: + + :ref:`future` +Index: Doc/library/tty.rst +=================================================================== +--- Doc/library/tty.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/tty.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`tty` --- Terminal control functions + ========================================= + +@@ -17,14 +16,14 @@ + The :mod:`tty` module defines the following functions: + + +-.. function:: setraw(fd[, when]) ++.. function:: setraw(fd, when=termios.TCSAFLUSH) + + Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it + defaults to :const:`termios.TCSAFLUSH`, and is passed to + :func:`termios.tcsetattr`. + + +-.. function:: setcbreak(fd[, when]) ++.. function:: setcbreak(fd, when=termios.TCSAFLUSH) + + Change the mode of file descriptor *fd* to cbreak. If *when* is omitted, it + defaults to :const:`termios.TCSAFLUSH`, and is passed to +Index: Doc/library/struct.rst +=================================================================== +--- Doc/library/struct.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/struct.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,6 +1,5 @@ +- + :mod:`struct` --- Interpret bytes as packed binary data +-========================================================= ++======================================================= + + .. module:: struct + :synopsis: Interpret bytes as packed binary data. +@@ -46,7 +45,7 @@ + (``len(bytes)`` must equal ``calcsize(fmt)``). + + +-.. function:: unpack_from(fmt, buffer[,offset=0]) ++.. function:: unpack_from(fmt, buffer, offset=0) + + Unpack the *buffer* according to the given format. The result is a tuple even + if it contains exactly one item. The *buffer* must contain at least the amount +@@ -286,7 +285,7 @@ + (``len(bytes)`` must equal :attr:`self.size`). + + +- .. method:: unpack_from(buffer[, offset=0]) ++ .. method:: unpack_from(buffer, offset=0) + + Identical to the :func:`unpack_from` function, using the compiled format. + (``len(buffer[offset:])`` must be at least :attr:`self.size`). +Index: Doc/library/codecs.rst +=================================================================== +--- Doc/library/codecs.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/codecs.rst (.../branches/release31-maint) (Revision 76056) +@@ -53,7 +53,7 @@ + *incrementalencoder* and *incrementaldecoder*: These have to be factory + functions providing the following interface: + +- ``factory(errors='strict')`` ++ ``factory(errors='strict')`` + + The factory functions must return objects providing the interfaces defined by + the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`, +@@ -62,22 +62,26 @@ + *streamreader* and *streamwriter*: These have to be factory functions providing + the following interface: + +- ``factory(stream, errors='strict')`` ++ ``factory(stream, errors='strict')`` + + The factory functions must return objects providing the interfaces defined by + the base classes :class:`StreamWriter` and :class:`StreamReader`, respectively. + Stream codecs can maintain state. + +- Possible values for errors are ``'strict'`` (raise an exception in case of an +- encoding error), ``'replace'`` (replace malformed data with a suitable +- replacement marker, such as ``'?'``), ``'ignore'`` (ignore malformed data and +- continue without further notice), ``'xmlcharrefreplace'`` (replace with the +- appropriate XML character reference (for encoding only)), +- ``'backslashreplace'`` (replace with backslashed escape sequences (for +- encoding only)), ``'surrogateescape'`` (replace with surrogate U+DCxx, see +- :pep:`383`) as well as any other error handling name defined via +- :func:`register_error`. ++ Possible values for errors are + ++ * ``'strict'``: raise an exception in case of an encoding error ++ * ``'replace'``: replace malformed data with a suitable replacement marker, ++ such as ``'?'`` or ``'\ufffd'`` ++ * ``'ignore'``: ignore malformed data and continue without further notice ++ * ``'xmlcharrefreplace'``: replace with the appropriate XML character ++ reference (for encoding only) ++ * ``'backslashreplace'``: replace with backslashed escape sequences (for ++ encoding only ++ * ``'surrogateescape'``: replace with surrogate U+DCxx, see :pep:`383` ++ ++ as well as any other error handling name defined via :func:`register_error`. ++ + In case a search function cannot find a given encoding, it should return + ``None``. + +@@ -173,27 +177,33 @@ + + .. function:: strict_errors(exception) + +- Implements the ``strict`` error handling. ++ Implements the ``strict`` error handling: each encoding or decoding error ++ raises a :exc:`UnicodeError`. + + + .. function:: replace_errors(exception) + +- Implements the ``replace`` error handling. ++ Implements the ``replace`` error handling: malformed data is replaced with a ++ suitable replacement character such as ``'?'`` in bytestrings and ++ ``'\ufffd'`` in Unicode strings. + + + .. function:: ignore_errors(exception) + +- Implements the ``ignore`` error handling. ++ Implements the ``ignore`` error handling: malformed data is ignored and ++ encoding or decoding is continued without further notice. + + + .. function:: xmlcharrefreplace_errors(exception) + +- Implements the ``xmlcharrefreplace`` error handling. ++ Implements the ``xmlcharrefreplace`` error handling (for encoding only): the ++ unencodable character is replaced by an appropriate XML character reference. + + + .. function:: backslashreplace_errors(exception) + +- Implements the ``backslashreplace`` error handling. ++ Implements the ``backslashreplace`` error handling (for encoding only): the ++ unencodable character is replaced by a backslashed escape sequence. + + To simplify working with encoded files or stream, the module also defines these + utility functions: +@@ -891,7 +901,8 @@ + name, together with a few common aliases, and the languages for which the + encoding is likely used. Neither the list of aliases nor the list of languages + is meant to be exhaustive. Notice that spelling alternatives that only differ in +-case or use a hyphen instead of an underscore are also valid aliases. ++case or use a hyphen instead of an underscore are also valid aliases; therefore, ++e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec. + + Many of the character sets support the same languages. They vary in individual + characters (e.g. whether the EURO SIGN is supported or not), and in the +@@ -985,7 +996,7 @@ + +-----------------+--------------------------------+--------------------------------+ + | cp1255 | windows-1255 | Hebrew | + +-----------------+--------------------------------+--------------------------------+ +-| cp1256 | windows1256 | Arabic | ++| cp1256 | windows-1256 | Arabic | + +-----------------+--------------------------------+--------------------------------+ + | cp1257 | windows-1257 | Baltic languages | + +-----------------+--------------------------------+--------------------------------+ +Index: Doc/library/ssl.rst +=================================================================== +--- Doc/library/ssl.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/ssl.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,6 +1,5 @@ +- + :mod:`ssl` --- SSL wrapper for socket objects +-==================================================================== ++============================================= + + .. module:: ssl + :synopsis: SSL wrapper for socket objects +@@ -13,32 +12,29 @@ + + .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer + +-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 library. It is available on all modern +-Unix systems, Windows, Mac OS X, and probably additional +-platforms, as long as OpenSSL is installed on that platform. ++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 ++library. It is available on all modern Unix systems, Windows, Mac OS X, and ++probably additional platforms, as long as OpenSSL is installed on that platform. + + .. note:: + +- Some behavior may be platform dependent, since calls are made to the operating +- system socket APIs. The installed version of OpenSSL may also cause +- variations in behavior. ++ Some behavior may be platform dependent, since calls are made to the ++ operating system socket APIs. The installed version of OpenSSL may also ++ cause variations in behavior. + +-This section documents the objects and functions in the ``ssl`` module; +-for more general information about TLS, SSL, and certificates, the +-reader is referred to the documents in the "See Also" section at +-the bottom. ++This section documents the objects and functions in the ``ssl`` module; for more ++general information about TLS, SSL, and certificates, the reader is referred to ++the documents in the "See Also" section at the bottom. + +-This module provides a class, :class:`ssl.SSLSocket`, which is +-derived from the :class:`socket.socket` type, and provides +-a socket-like wrapper that also encrypts and decrypts the data +-going over the socket with SSL. It supports additional +-:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`, +-to retrieve the certificate of the other side of the connection, and +-a method, :meth:`cipher`, to retrieve the cipher being used for the +-secure connection. ++This module provides a class, :class:`ssl.SSLSocket`, which is derived from the ++:class:`socket.socket` type, and provides a socket-like wrapper that also ++encrypts and decrypts the data going over the socket with SSL. It supports ++additional :meth:`read` and :meth:`write` methods, along with a method, ++:meth:`getpeercert`, to retrieve the certificate of the other side of the ++connection, and a method, :meth:`cipher`, to retrieve the cipher being used for ++the secure connection. + + Functions, Constants, and Exceptions + ------------------------------------ +@@ -46,31 +42,33 @@ + .. exception:: SSLError + + Raised to signal an error from the underlying SSL implementation. This +- signifies some problem in the higher-level +- encryption and authentication layer that's superimposed on the underlying +- network connection. This error is a subtype of :exc:`socket.error`, which +- in turn is a subtype of :exc:`IOError`. ++ signifies some problem in the higher-level encryption and authentication ++ layer that's superimposed on the underlying network connection. This error ++ is a subtype of :exc:`socket.error`, which in turn is a subtype of ++ :exc:`IOError`. + +-.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True) ++.. function:: wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True) + +- Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype +- of :class:`socket.socket`, which wraps the underlying socket in an SSL context. +- For client-side sockets, the context construction is lazy; if the underlying socket isn't +- connected yet, the context construction will be performed after :meth:`connect` is called +- on the socket. For server-side sockets, if the socket has no remote peer, it is assumed +- to be a listening socket, and the server-side SSL wrapping is automatically performed +- on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may +- raise :exc:`SSLError`. ++ Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance ++ of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps ++ the underlying socket in an SSL context. For client-side sockets, the ++ context construction is lazy; if the underlying socket isn't connected yet, ++ the context construction will be performed after :meth:`connect` is called on ++ the socket. For server-side sockets, if the socket has no remote peer, it is ++ assumed to be a listening socket, and the server-side SSL wrapping is ++ automatically performed on client connections accepted via the :meth:`accept` ++ method. :func:`wrap_socket` may raise :exc:`SSLError`. + +- The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate +- to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates` +- for more information on how the certificate is stored in the ``certfile``. ++ The ``keyfile`` and ``certfile`` parameters specify optional files which ++ contain a certificate to be used to identify the local side of the ++ connection. See the discussion of :ref:`ssl-certificates` for more ++ information on how the certificate is stored in the ``certfile``. + +- Often the private key is stored +- in the same file as the certificate; in this case, only the ``certfile`` parameter need be +- passed. If the private key is stored in a separate file, both parameters must be used. +- If the private key is stored in the ``certfile``, it should come before the first certificate +- in the certificate chain:: ++ Often the private key is stored in the same file as the certificate; in this ++ case, only the ``certfile`` parameter need be passed. If the private key is ++ stored in a separate file, both parameters must be used. If the private key ++ is stored in the ``certfile``, it should come before the first certificate in ++ the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... +@@ -79,31 +77,33 @@ + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +- The parameter ``server_side`` is a boolean which identifies whether server-side or client-side +- behavior is desired from this socket. ++ The parameter ``server_side`` is a boolean which identifies whether ++ server-side or client-side behavior is desired from this socket. + +- The parameter ``cert_reqs`` specifies whether a certificate is +- required from the other side of the connection, and whether it will +- be validated if provided. It must be one of the three values +- :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, +- but validated if provided), or :const:`CERT_REQUIRED` (required and +- validated). If the value of this parameter is not :const:`CERT_NONE`, then +- the ``ca_certs`` parameter must point to a file of CA certificates. ++ The parameter ``cert_reqs`` specifies whether a certificate is required from ++ the other side of the connection, and whether it will be validated if ++ provided. It must be one of the three values :const:`CERT_NONE` ++ (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated ++ if provided), or :const:`CERT_REQUIRED` (required and validated). If the ++ value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs`` ++ parameter must point to a file of CA certificates. + +- The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, +- which are used to validate certificates passed from the other end of the connection. +- See the discussion of :ref:`ssl-certificates` for more information about how to arrange +- the certificates in this file. ++ The ``ca_certs`` file contains a set of concatenated "certification ++ authority" certificates, which are used to validate certificates passed from ++ the other end of the connection. See the discussion of ++ :ref:`ssl-certificates` for more information about how to arrange the ++ certificates in this file. + +- 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 versions. ++ 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 ++ versions. + +- Here's a table showing which versions in a client (down the side) +- can connect to which versions in a server (along the top): ++ Here's a table showing which versions in a client (down the side) can connect ++ to which versions in a server (along the top): + + .. table:: + +@@ -116,51 +116,52 @@ + *TLSv1* no no yes yes + ======================== ========= ========= ========== ========= + +- In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), +- an SSLv2 client could not connect to an SSLv23 server. ++ In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), an ++ SSLv2 client could not connect to an SSLv23 server. + + The parameter ``do_handshake_on_connect`` specifies whether to do the SSL + handshake automatically after doing a :meth:`socket.connect`, or whether the +- application program will call it explicitly, by invoking the :meth:`SSLSocket.do_handshake` +- method. Calling :meth:`SSLSocket.do_handshake` explicitly gives the program control over +- the blocking behavior of the socket I/O involved in the handshake. ++ application program will call it explicitly, by invoking the ++ :meth:`SSLSocket.do_handshake` method. Calling ++ :meth:`SSLSocket.do_handshake` explicitly gives the program control over the ++ blocking behavior of the socket I/O involved in the handshake. + +- The parameter ``suppress_ragged_eofs`` specifies how the :meth:`SSLSocket.read` +- method should signal unexpected EOF from the other end of the connection. If specified +- as :const:`True` (the default), it returns a normal EOF in response to unexpected +- EOF errors raised from the underlying socket; if :const:`False`, it will raise +- the exceptions back to the caller. ++ The parameter ``suppress_ragged_eofs`` specifies how the ++ :meth:`SSLSocket.read` method should signal unexpected EOF from the other end ++ of the connection. If specified as :const:`True` (the default), it returns a ++ normal EOF in response to unexpected EOF errors raised from the underlying ++ socket; if :const:`False`, it will raise the exceptions back to the caller. + + .. function:: RAND_status() + +- Returns True if the SSL pseudo-random number generator has been +- seeded with 'enough' randomness, and False otherwise. You can use +- :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness +- of the pseudo-random number generator. ++ Returns True if the SSL pseudo-random number generator has been seeded with ++ 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd` ++ and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random ++ number generator. + + .. function:: RAND_egd(path) + + If you are running an entropy-gathering daemon (EGD) somewhere, and ``path`` +- is the pathname of a socket connection open to it, this will read +- 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator +- to increase the security of generated secret keys. This is typically only +- necessary on systems without better sources of randomness. ++ is the pathname of a socket connection open to it, this will read 256 bytes ++ of randomness from the socket, and add it to the SSL pseudo-random number ++ generator to increase the security of generated secret keys. This is ++ typically only necessary on systems without better sources of randomness. + +- See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for +- sources of entropy-gathering daemons. ++ See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources ++ of entropy-gathering daemons. + + .. function:: RAND_add(bytes, entropy) + +- Mixes the given ``bytes`` into the SSL pseudo-random number generator. +- The parameter ``entropy`` (a float) is a lower bound on the entropy +- contained in string (so you can always use :const:`0.0`). +- See :rfc:`1750` for more information on sources of entropy. ++ Mixes the given ``bytes`` into the SSL pseudo-random number generator. The ++ parameter ``entropy`` (a float) is a lower bound on the entropy contained in ++ string (so you can always use :const:`0.0`). See :rfc:`1750` for more ++ information on sources of entropy. + + .. function:: cert_time_to_seconds(timestring) + +- Returns a floating-point value containing a normal seconds-after-the-epoch time +- value, given the time-string representing the "notBefore" or "notAfter" date +- from a certificate. ++ Returns a floating-point value containing a normal seconds-after-the-epoch ++ time value, given the time-string representing the "notBefore" or "notAfter" ++ date from a certificate. + + Here's an example:: + +@@ -172,50 +173,47 @@ + 'Wed May 9 00:00:00 2007' + >>> + +-.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) ++.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) + +- Given the address ``addr`` of an SSL-protected server, as a +- (*hostname*, *port-number*) pair, fetches the server's certificate, +- and returns it as a PEM-encoded string. If ``ssl_version`` is +- specified, uses that version of the SSL protocol to attempt to +- connect to the server. If ``ca_certs`` is specified, it should be +- a file containing a list of root certificates, the same format as +- used for the same parameter in :func:`wrap_socket`. The call will +- attempt to validate the server certificate against that set of root ++ Given the address ``addr`` of an SSL-protected server, as a (*hostname*, ++ *port-number*) pair, fetches the server's certificate, and returns it as a ++ PEM-encoded string. If ``ssl_version`` is specified, uses that version of ++ the SSL protocol to attempt to connect to the server. If ``ca_certs`` is ++ specified, it should be a file containing a list of root certificates, the ++ same format as used for the same parameter in :func:`wrap_socket`. The call ++ will attempt to validate the server certificate against that set of root + certificates, and will fail if the validation attempt fails. + +-.. function:: DER_cert_to_PEM_cert (DER_cert_bytes) ++.. function:: DER_cert_to_PEM_cert(DER_cert_bytes) + + Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded + string version of the same certificate. + +-.. function:: PEM_cert_to_DER_cert (PEM_cert_string) ++.. function:: PEM_cert_to_DER_cert(PEM_cert_string) + +- Given a certificate as an ASCII PEM string, returns a DER-encoded +- sequence of bytes for that same certificate. ++ Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of ++ bytes for that same certificate. + + .. data:: CERT_NONE + +- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` +- when no certificates will be required or validated from the other +- side of the socket connection. ++ Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no ++ certificates will be required or validated from the other side of the socket ++ connection. + + .. data:: CERT_OPTIONAL + +- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` +- when no certificates will be required from the other side of the +- socket connection, but if they are provided, will be validated. +- Note that use of this setting requires a valid certificate +- validation file also be passed as a value of the ``ca_certs`` +- parameter. ++ Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no ++ certificates will be required from the other side of the socket connection, ++ but if they are provided, will be validated. Note that use of this setting ++ requires a valid certificate validation file also be passed as a value of the ++ ``ca_certs`` parameter. + + .. data:: CERT_REQUIRED + +- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` +- when certificates will be required from the other side of the +- socket connection. Note that use of this setting requires a valid certificate +- validation file also be passed as a value of the ``ca_certs`` +- parameter. ++ Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when ++ certificates will be required from the other side of the socket connection. ++ Note that use of this setting requires a valid certificate validation file ++ also be passed as a value of the ``ca_certs`` parameter. + + .. data:: PROTOCOL_SSLv2 + +@@ -223,22 +221,21 @@ + + .. data:: PROTOCOL_SSLv23 + +- Selects SSL version 2 or 3 as the channel encryption protocol. +- This is a setting to use with servers for maximum compatibility +- with the other end of an SSL connection, but it may cause the +- specific ciphers chosen for the encryption to be of fairly low +- quality. ++ Selects SSL version 2 or 3 as the channel encryption protocol. This is a ++ setting to use with servers for maximum compatibility with the other end of ++ an SSL connection, but it may cause the specific ciphers chosen for the ++ encryption to be of fairly low quality. + + .. data:: PROTOCOL_SSLv3 + +- Selects SSL version 3 as the channel encryption protocol. +- For clients, this is the maximally compatible SSL variant. ++ Selects SSL version 3 as the channel encryption protocol. For clients, this ++ is the maximally compatible SSL variant. + + .. data:: PROTOCOL_TLSv1 + +- Selects TLS version 1 as the channel encryption protocol. This is +- the most modern version, and probably the best choice for maximum +- protection, if both sides can speak it. ++ Selects TLS version 1 as the channel encryption protocol. This is the most ++ modern version, and probably the best choice for maximum protection, if both ++ sides can speak it. + + + SSLSocket Objects +@@ -247,25 +244,23 @@ + .. method:: SSLSocket.read(nbytes=1024, buffer=None) + + Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them. +- If the ``buffer`` is specified, it will attempt to read into the buffer +- the minimum of the size of the buffer and ``nbytes``, if that is specified. +- If no buffer is specified, an immutable buffer is allocated and returned +- with the data read from the socket. ++ If the ``buffer`` is specified, it will attempt to read into the buffer the ++ minimum of the size of the buffer and ``nbytes``, if that is specified. If ++ no buffer is specified, an immutable buffer is allocated and returned with ++ the data read from the socket. + + .. method:: SSLSocket.write(data) + +- Writes the ``data`` to the other side of the connection, using the +- SSL channel to encrypt. Returns the number of bytes written. ++ Writes the ``data`` to the other side of the connection, using the SSL ++ channel to encrypt. Returns the number of bytes written. + + .. method:: SSLSocket.do_handshake() + +- Performs the SSL setup handshake. If the socket is non-blocking, +- this method may raise :exc:`SSLError` with the value of the exception +- instance's ``args[0]`` +- being either :const:`SSL_ERROR_WANT_READ` or +- :const:`SSL_ERROR_WANT_WRITE`, and should be called again until +- it stops raising those exceptions. Here's an example of how to do +- that:: ++ Performs the SSL setup handshake. If the socket is non-blocking, this method ++ may raise :exc:`SSLError` with the value of the exception instance's ++ ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or ++ :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops ++ raising those exceptions. Here's an example of how to do that:: + + while True: + try: +@@ -281,68 +276,62 @@ + + .. method:: SSLSocket.unwrap() + +- Performs the SSL shutdown handshake, which removes the TLS layer +- from the underlying socket, and returns the underlying socket +- object. This can be used to go from encrypted operation over a +- connection to unencrypted. The returned socket should always be +- used for further communication with the other side of the +- connection, rather than the original socket ++ Performs the SSL shutdown handshake, which removes the TLS layer from the ++ underlying socket, and returns the underlying socket object. This can be ++ used to go from encrypted operation over a connection to unencrypted. The ++ returned socket should always be used for further communication with the ++ other side of the connection, rather than the original socket + + .. method:: SSLSocket.getpeercert(binary_form=False) + +- If there is no certificate for the peer on the other end of the +- connection, returns ``None``. ++ If there is no certificate for the peer on the other end of the connection, ++ returns ``None``. + +- If the parameter ``binary_form`` is :const:`False`, and a +- certificate was received from the peer, this method returns a +- :class:`dict` instance. If the certificate was not validated, the +- dict is empty. If the certificate was validated, it returns a dict +- with the keys ``subject`` (the principal for which the certificate +- was issued), and ``notAfter`` (the time after which the certificate +- should not be trusted). The certificate was already validated, so +- the ``notBefore`` and ``issuer`` fields are not returned. If a +- certificate contains an instance of the *Subject Alternative Name* +- extension (see :rfc:`3280`), there will also be a +- ``subjectAltName`` key in the dictionary. ++ If the parameter ``binary_form`` is :const:`False`, and a certificate was ++ received from the peer, this method returns a :class:`dict` instance. If the ++ certificate was not validated, the dict is empty. If the certificate was ++ validated, it returns a dict with the keys ``subject`` (the principal for ++ which the certificate was issued), and ``notAfter`` (the time after which the ++ certificate should not be trusted). The certificate was already validated, ++ so the ``notBefore`` and ``issuer`` fields are not returned. If a ++ certificate contains an instance of the *Subject Alternative Name* extension ++ (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the ++ dictionary. + + The "subject" field is a tuple containing the sequence of relative +- distinguished names (RDNs) given in the certificate's data +- structure for the principal, and each RDN is a sequence of +- name-value pairs:: ++ distinguished names (RDNs) given in the certificate's data structure for the ++ principal, and each RDN is a sequence of name-value pairs:: + + {'notAfter': 'Feb 16 16:54:50 2013 GMT', +- 'subject': ((('countryName', u'US'),), +- (('stateOrProvinceName', u'Delaware'),), +- (('localityName', u'Wilmington'),), +- (('organizationName', u'Python Software Foundation'),), +- (('organizationalUnitName', u'SSL'),), +- (('commonName', u'somemachine.python.org'),))} ++ 'subject': ((('countryName', 'US'),), ++ (('stateOrProvinceName', 'Delaware'),), ++ (('localityName', 'Wilmington'),), ++ (('organizationName', 'Python Software Foundation'),), ++ (('organizationalUnitName', 'SSL'),), ++ (('commonName', 'somemachine.python.org'),))} + +- If the ``binary_form`` parameter is :const:`True`, and a +- certificate was provided, this method returns the DER-encoded form +- of the entire certificate as a sequence of bytes, or :const:`None` if the +- peer did not provide a certificate. This return +- value is independent of validation; if validation was required +- (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have ++ If the ``binary_form`` parameter is :const:`True`, and a certificate was ++ provided, this method returns the DER-encoded form of the entire certificate ++ as a sequence of bytes, or :const:`None` if the peer did not provide a ++ certificate. This return value is independent of validation; if validation ++ was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have + been validated, but if :const:`CERT_NONE` was used to establish the + connection, the certificate, if present, will not have been validated. + + .. method:: SSLSocket.cipher() + +- Returns a three-value tuple containing the name of the cipher being +- used, the version of the SSL protocol that defines its use, and the +- number of secret bits being used. If no connection has been +- established, returns ``None``. ++ Returns a three-value tuple containing the name of the cipher being used, the ++ version of the SSL protocol that defines its use, and the number of secret ++ bits being used. If no connection has been established, returns ``None``. + + + .. method:: SSLSocket.unwrap() + +- Performs the SSL shutdown handshake, which removes the TLS layer +- from the underlying socket, and returns the underlying socket +- object. This can be used to go from encrypted operation over a +- connection to unencrypted. The returned socket should always be +- used for further communication with the other side of the +- connection, rather than the original socket ++ Performs the SSL shutdown handshake, which removes the TLS layer from the ++ underlying socket, and returns the underlying socket object. This can be ++ used to go from encrypted operation over a connection to unencrypted. The ++ returned socket should always be used for further communication with the ++ other side of the connection, rather than the original socket. + + .. index:: single: certificates + +@@ -353,57 +342,54 @@ + Certificates + ------------ + +-Certificates in general are part of a public-key / private-key system. In this system, each *principal*, +-(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. +-One part of the key is public, and is called the *public key*; the other part is kept secret, and is called +-the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can +-decrypt it with the other part, and **only** with the other part. ++Certificates in general are part of a public-key / private-key system. In this ++system, each *principal*, (which may be a machine, or a person, or an ++organization) is assigned a unique two-part encryption key. One part of the key ++is public, and is called the *public key*; the other part is kept secret, and is ++called the *private key*. The two parts are related, in that if you encrypt a ++message with one of the parts, you can decrypt it with the other part, and ++**only** with the other part. + +-A certificate contains information about two principals. It contains +-the name of a *subject*, and the subject's public key. It also +-contains a statement by a second principal, the *issuer*, that the +-subject is who he claims to be, and that this is indeed the subject's +-public key. The issuer's statement is signed with the issuer's +-private key, which only the issuer knows. However, anyone can verify +-the issuer's statement by finding the issuer's public key, decrypting +-the statement with it, and comparing it to the other information in +-the certificate. The certificate also contains information about the +-time period over which it is valid. This is expressed as two fields, +-called "notBefore" and "notAfter". ++A certificate contains information about two principals. It contains the name ++of a *subject*, and the subject's public key. It also contains a statement by a ++second principal, the *issuer*, that the subject is who he claims to be, and ++that this is indeed the subject's public key. The issuer's statement is signed ++with the issuer's private key, which only the issuer knows. However, anyone can ++verify the issuer's statement by finding the issuer's public key, decrypting the ++statement with it, and comparing it to the other information in the certificate. ++The certificate also contains information about the time period over which it is ++valid. This is expressed as two fields, called "notBefore" and "notAfter". + +-In the Python use of certificates, a client or server +-can use a certificate to prove who they are. The other +-side of a network connection can also be required to produce a certificate, +-and that certificate can be validated to the satisfaction +-of the client or server that requires such validation. +-The connection attempt can be set to raise an exception if +-the validation fails. Validation is done +-automatically, by the underlying OpenSSL framework; the +-application need not concern itself with its mechanics. +-But the application does usually need to provide +-sets of certificates to allow this process to take place. ++In the Python use of certificates, a client or server can use a certificate to ++prove who they are. The other side of a network connection can also be required ++to produce a certificate, and that certificate can be validated to the ++satisfaction of the client or server that requires such validation. The ++connection attempt can be set to raise an exception if the validation fails. ++Validation is done automatically, by the underlying OpenSSL framework; the ++application need not concern itself with its mechanics. But the application ++does usually need to provide sets of certificates to allow this process to take ++place. + +-Python uses files to contain certificates. They should be formatted +-as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped +-with a header line and a footer line:: ++Python uses files to contain certificates. They should be formatted as "PEM" ++(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line ++and a footer line:: + + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + +-The Python files which contain certificates can contain a sequence +-of certificates, sometimes called a *certificate chain*. This chain +-should start with the specific certificate for the principal who "is" +-the client or server, and then the certificate for the issuer of that +-certificate, and then the certificate for the issuer of *that* certificate, +-and so on up the chain till you get to a certificate which is *self-signed*, +-that is, a certificate which has the same subject and issuer, +-sometimes called a *root certificate*. The certificates should just +-be concatenated together in the certificate file. For example, suppose +-we had a three certificate chain, from our server certificate to the +-certificate of the certification authority that signed our server certificate, +-to the root certificate of the agency which issued the certification authority's +-certificate:: ++The Python files which contain certificates can contain a sequence of ++certificates, sometimes called a *certificate chain*. This chain should start ++with the specific certificate for the principal who "is" the client or server, ++and then the certificate for the issuer of that certificate, and then the ++certificate for the issuer of *that* certificate, and so on up the chain till ++you get to a certificate which is *self-signed*, that is, a certificate which ++has the same subject and issuer, sometimes called a *root certificate*. The ++certificates should just be concatenated together in the certificate file. For ++example, suppose we had a three certificate chain, from our server certificate ++to the certificate of the certification authority that signed our server ++certificate, to the root certificate of the agency which issued the ++certification authority's certificate:: + + -----BEGIN CERTIFICATE----- + ... (certificate for your server)... +@@ -417,32 +403,29 @@ + + If you are going to require validation of the other side of the connection's + certificate, you need to provide a "CA certs" file, filled with the certificate +-chains for each issuer you are willing to trust. Again, this file just +-contains these chains concatenated together. For validation, Python will +-use the first chain it finds in the file which matches. +-Some "standard" root certificates are available from various certification +-authorities: +-`CACert.org `_, +-`Thawte `_, +-`Verisign `_, +-`Positive SSL `_ (used by python.org), +-`Equifax and GeoTrust `_. ++chains for each issuer you are willing to trust. Again, this file just contains ++these chains concatenated together. For validation, Python will use the first ++chain it finds in the file which matches. Some "standard" root certificates are ++available from various certification authorities: `CACert.org ++`_, `Thawte ++`_, `Verisign ++`_, `Positive SSL ++`_ ++(used by python.org), `Equifax and GeoTrust ++`_. + +-In general, if you are using +-SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file; +-you only need the root certificates, and the remote peer is supposed to +-furnish the other certificates necessary to chain from its certificate to +-a root certificate. +-See :rfc:`4158` for more discussion of the way in which +-certification chains can be built. ++In general, if you are using SSL3 or TLS1, you don't need to put the full chain ++in your "CA certs" file; you only need the root certificates, and the remote ++peer is supposed to furnish the other certificates necessary to chain from its ++certificate to a root certificate. See :rfc:`4158` for more discussion of the ++way in which certification chains can be built. + +-If you are going to create a server that provides SSL-encrypted +-connection services, you will need to acquire a certificate for that +-service. There are many ways of acquiring appropriate certificates, +-such as buying one from a certification authority. Another common +-practice is to generate a self-signed certificate. The simplest +-way to do this is with the OpenSSL package, using something like +-the following:: ++If you are going to create a server that provides SSL-encrypted connection ++services, you will need to acquire a certificate for that service. There are ++many ways of acquiring appropriate certificates, such as buying one from a ++certification authority. Another common practice is to generate a self-signed ++certificate. The simplest way to do this is with the OpenSSL package, using ++something like the following:: + + % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem + Generating a 1024 bit RSA private key +@@ -466,9 +449,9 @@ + Email Address []:ops@myserver.mygroup.myorganization.com + % + +-The disadvantage of a self-signed certificate is that it is its +-own root certificate, and no one else will have it in their cache +-of known (and trusted) root certificates. ++The disadvantage of a self-signed certificate is that it is its own root ++certificate, and no one else will have it in their cache of known (and trusted) ++root certificates. + + + Examples +@@ -477,7 +460,8 @@ + Testing for SSL support + ^^^^^^^^^^^^^^^^^^^^^^^ + +-To test for the presence of SSL support in a Python installation, user code should use the following idiom:: ++To test for the presence of SSL support in a Python installation, user code ++should use the following idiom:: + + try: + import ssl +@@ -489,8 +473,8 @@ + Client-side operation + ^^^^^^^^^^^^^^^^^^^^^ + +-This example connects to an SSL server, prints the server's address and certificate, +-sends some bytes, and reads part of the response:: ++This example connects to an SSL server, prints the server's address and ++certificate, sends some bytes, and reads part of the response:: + + import socket, ssl, pprint + +@@ -518,33 +502,33 @@ + # note that closing the SSLSocket will also close the underlying socket + ssl_sock.close() + +-As of September 6, 2007, the certificate printed by this program +-looked like this:: ++As of September 6, 2007, the certificate printed by this program looked like ++this:: + + {'notAfter': 'May 8 23:59:59 2009 GMT', +- 'subject': ((('serialNumber', u'2497886'),), +- (('1.3.6.1.4.1.311.60.2.1.3', u'US'),), +- (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),), +- (('countryName', u'US'),), +- (('postalCode', u'94043'),), +- (('stateOrProvinceName', u'California'),), +- (('localityName', u'Mountain View'),), +- (('streetAddress', u'487 East Middlefield Road'),), +- (('organizationName', u'VeriSign, Inc.'),), ++ 'subject': ((('serialNumber', '2497886'),), ++ (('1.3.6.1.4.1.311.60.2.1.3', 'US'),), ++ (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), ++ (('countryName', 'US'),), ++ (('postalCode', '94043'),), ++ (('stateOrProvinceName', 'California'),), ++ (('localityName', 'Mountain View'),), ++ (('streetAddress', '487 East Middlefield Road'),), ++ (('organizationName', 'VeriSign, Inc.'),), + (('organizationalUnitName', +- u'Production Security Services'),), ++ 'Production Security Services'),), + (('organizationalUnitName', +- u'Terms of use at www.verisign.com/rpa (c)06'),), +- (('commonName', u'www.verisign.com'),))} ++ 'Terms of use at www.verisign.com/rpa (c)06'),), ++ (('commonName', 'www.verisign.com'),))} + + which is a fairly poorly-formed ``subject`` field. + + Server-side operation + ^^^^^^^^^^^^^^^^^^^^^ + +-For server operation, typically you'd need to have a server certificate, and private key, each in a file. +-You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients +-to connect:: ++For server operation, typically you'd need to have a server certificate, and ++private key, each in a file. You'd open a socket, bind it to a port, call ++:meth:`listen` on it, then start waiting for clients to connect:: + + import socket, ssl + +@@ -552,8 +536,9 @@ + bindsocket.bind(('myaddr.mydomain.com', 10023)) + bindsocket.listen(5) + +-When one did, you'd call :meth:`accept` on the socket to get the new socket from the other +-end, and use :func:`wrap_socket` to create a server-side SSL context for it:: ++When one did, you'd call :meth:`accept` on the socket to get the new socket from ++the other end, and use :func:`wrap_socket` to create a server-side SSL context ++for it:: + + while True: + newsocket, fromaddr = bindsocket.accept() +@@ -564,7 +549,8 @@ + ssl_version=ssl.PROTOCOL_TLSv1) + deal_with_client(connstream) + +-Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: ++Then you'd read data from the ``connstream`` and do something with it till you ++are finished with the client (or the client is finished with you):: + + def deal_with_client(connstream): + +Index: Doc/library/uuid.rst +=================================================================== +--- Doc/library/uuid.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/uuid.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`uuid` --- UUID objects according to RFC 4122 + ================================================== + +@@ -18,7 +17,7 @@ + random UUID. + + +-.. class:: UUID([hex[, bytes[, bytes_le[, fields[, int[, version]]]]]]) ++.. class:: UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) + + Create a UUID from either a string of 32 hexadecimal digits, a string of 16 + bytes as the *bytes* argument, a string of 16 bytes in little-endian order as +@@ -43,9 +42,9 @@ + variant and version number set according to RFC 4122, overriding bits in the + given *hex*, *bytes*, *bytes_le*, *fields*, or *int*. + ++ + :class:`UUID` instances have these read-only attributes: + +- + .. attribute:: UUID.bytes + + The UUID as a 16-byte string (containing the six integer fields in big-endian +@@ -126,7 +125,7 @@ + .. index:: single: getnode + + +-.. function:: uuid1([node[, clock_seq]]) ++.. function:: uuid1(node=None, clock_seq=None) + + Generate a UUID from a host ID, sequence number, and the current time. If *node* + is not given, :func:`getnode` is used to obtain the hardware address. If +Index: Doc/library/modulefinder.rst +=================================================================== +--- Doc/library/modulefinder.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/modulefinder.rst (.../branches/release31-maint) (Revision 76056) +@@ -84,7 +84,7 @@ + print('Loaded modules:') + for name, mod in finder.modules.items(): + print('%s: ' % name, end='') +- print(','.join(mod.globalnames.keys()[:3])) ++ print(','.join(list(mod.globalnames.keys())[:3])) + + print('-'*50) + print('Modules not imported:') +Index: Doc/library/syslog.rst +=================================================================== +--- Doc/library/syslog.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/syslog.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`syslog` --- Unix syslog library routines + ============================================== + +Index: Doc/library/telnetlib.rst +=================================================================== +--- Doc/library/telnetlib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/telnetlib.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`telnetlib` --- Telnet client + ================================== + +@@ -23,7 +22,7 @@ + Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin). + + +-.. class:: Telnet([host[, port[, timeout]]]) ++.. class:: Telnet(host=None, port=0[, timeout]) + + :class:`Telnet` represents a connection to a Telnet server. The instance is + initially not connected by default; the :meth:`open` method must be used to +@@ -60,7 +59,7 @@ + :class:`Telnet` instances have the following methods: + + +-.. method:: Telnet.read_until(expected[, timeout]) ++.. method:: Telnet.read_until(expected, timeout=None) + + Read until a given byte string, *expected*, is encountered or until *timeout* + seconds have passed. +@@ -123,7 +122,7 @@ + This method never blocks. + + +-.. method:: Telnet.open(host[, port[, timeout]]) ++.. method:: Telnet.open(host, port=0[, timeout]) + + Connect to a host. The optional second argument is the port number, which + defaults to the standard Telnet port (23). The optional *timeout* parameter +@@ -133,7 +132,7 @@ + Do not try to reopen an already connected instance. + + +-.. method:: Telnet.msg(msg[, *args]) ++.. method:: Telnet.msg(msg, *args) + + Print a debug message when the debug level is ``>`` 0. If extra arguments are + present, they are substituted in the message using the standard string +@@ -178,7 +177,7 @@ + Multithreaded version of :meth:`interact`. + + +-.. method:: Telnet.expect(list[, timeout]) ++.. method:: Telnet.expect(list, timeout=None) + + Read until one from a list of a regular expressions matches. + +Index: Doc/library/weakref.rst +=================================================================== +--- Doc/library/weakref.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/weakref.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`weakref` --- Weak references + ================================== + +@@ -70,6 +69,11 @@ + + obj = Dict(red=1, green=2, blue=3) # this object is weak referenceable + ++.. impl-detail:: ++ ++ Other built-in types such as :class:`tuple` and :class:`long` do not support ++ weak references even when subclassed. ++ + Extension types can easily be made to support weak references; see + :ref:`weakref-support`. + +@@ -92,10 +96,10 @@ + but cannot be propagated; they are handled in exactly the same way as exceptions + raised from an object's :meth:`__del__` method. + +- Weak references are :term:`hashable` if the *object* is hashable. They will maintain +- their hash value even after the *object* was deleted. If :func:`hash` is called +- the first time only after the *object* was deleted, the call will raise +- :exc:`TypeError`. ++ Weak references are :term:`hashable` if the *object* is hashable. They will ++ maintain their hash value even after the *object* was deleted. If ++ :func:`hash` is called the first time only after the *object* was deleted, ++ the call will raise :exc:`TypeError`. + + Weak references support tests for equality, but not ordering. If the referents + are still alive, two references have the same equality relationship as their +Index: Doc/library/shelve.rst +=================================================================== +--- Doc/library/shelve.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/shelve.rst (.../branches/release31-maint) (Revision 76056) +@@ -27,28 +27,40 @@ + + Because of Python semantics, a shelf cannot know when a mutable + persistent-dictionary entry is modified. By default modified objects are +- written only when assigned to the shelf (see :ref:`shelve-example`). If +- the optional *writeback* parameter is set to *True*, all entries accessed +- are cached in memory, and written back at close time; this can make it +- handier to mutate mutable entries in the persistent dictionary, but, if +- many entries are accessed, it can consume vast amounts of memory for the +- cache, and it can make the close operation very slow since all accessed +- entries are written back (there is no way to determine which accessed +- entries are mutable, nor which ones were actually mutated). ++ written only when assigned to the shelf (see :ref:`shelve-example`). If the ++ optional *writeback* parameter is set to *True*, all entries accessed are ++ cached in memory, and written back on :meth:`sync` and :meth:`close`; this ++ can make it handier to mutate mutable entries in the persistent dictionary, ++ but, if many entries are accessed, it can consume vast amounts of memory for ++ the cache, and it can make the close operation very slow since all accessed ++ entries are written back (there is no way to determine which accessed entries ++ are mutable, nor which ones were actually mutated). + ++ .. note:: ++ ++ 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`. ++ ++ + Shelf objects support all methods supported by dictionaries. This eases the + transition from dictionary based scripts to those requiring persistent storage. + +-One additional method is supported: ++Two additional methods are supported: + +- + .. method:: Shelf.sync() + +- Write back all entries in the cache if the shelf was opened with *writeback* set +- to *True*. Also empty the cache and synchronize the persistent dictionary on +- disk, if feasible. This is called automatically when the shelf is closed with +- :meth:`close`. ++ Write back all entries in the cache if the shelf was opened with *writeback* ++ set to :const:`True`. Also empty the cache and synchronize the persistent ++ dictionary on disk, if feasible. This is called automatically when the shelf ++ is closed with :meth:`close`. + ++.. method:: Shelf.close() ++ ++ Synchronize and close the persistent *dict* object. Operations on a closed ++ shelf will fail with a :exc:`ValueError`. ++ ++ + .. seealso:: + + `Persistent dictionary recipe `_ +@@ -71,11 +83,6 @@ + database should be fairly small, and in rare cases key collisions may cause + the database to refuse updates. + +-* Depending on the implementation, closing a persistent dictionary may or may +- not be necessary to flush changes to disk. The :meth:`__del__` method of the +- :class:`Shelf` class calls the :meth:`close` method, so the programmer generally +- need not do this explicitly. +- + * The :mod:`shelve` module does not support *concurrent* read/write access to + shelved objects. (Multiple simultaneous read accesses are safe.) When a + program has a shelf open for writing, no other program should have it open for +@@ -141,8 +148,8 @@ + # such key) + del d[key] # delete data stored at key (raises KeyError + # if no such key) +- flag = key in d # true if the key exists +- klist = d.keys() # a list of all existing keys (slow!) ++ flag = key in d # true if the key exists ++ klist = list(d.keys()) # a list of all existing keys (slow!) + + # as d was opened WITHOUT writeback=True, beware: + d['xx'] = range(4) # this works as expected, but... +Index: Doc/library/marshal.rst +=================================================================== +--- Doc/library/marshal.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/marshal.rst (.../branches/release31-maint) (Revision 76056) +@@ -36,12 +36,14 @@ + + Not all Python object types are supported; in general, only objects whose value + is independent from a particular invocation of Python can be written and read by +-this module. The following types are supported: ``None``, integers, +-floating point numbers, strings, bytes, bytearrays, tuples, lists, sets, +-dictionaries, and code objects, where it should be understood that tuples, lists +-and dictionaries are only supported as long as the values contained therein are +-themselves supported; and recursive lists and dictionaries should not be written +-(they will cause infinite loops). ++this module. The following types are supported: booleans, integers, floating ++point numbers, complex numbers, strings, bytes, bytearrays, tuples, lists, sets, ++frozensets, dictionaries, and code objects, where it should be understood that ++tuples, lists, sets, frozensets and dictionaries are only supported as long as ++the values contained therein are themselves supported; and recursive lists, sets ++and dictionaries should not be written (they will cause infinite loops). The ++singletons :const:`None`, :const:`Ellipsis` and :exc:`StopIteration` can also be ++marshalled and unmarshalled. + + There are functions that read/write files as well as functions operating on + strings. +Index: Doc/library/strings.rst +=================================================================== +--- Doc/library/strings.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/strings.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + .. _stringservices: + + *************** +Index: Doc/library/xml.sax.reader.rst +=================================================================== +--- Doc/library/xml.sax.reader.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.sax.reader.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.sax.xmlreader` --- Interface for XML parsers + ====================================================== + +@@ -48,7 +47,7 @@ + methods may return ``None``. + + +-.. class:: InputSource([systemId]) ++.. class:: InputSource(system_id=None) + + Encapsulation of the information needed by the :class:`XMLReader` to read + entities. +Index: Doc/library/zipfile.rst +=================================================================== +--- Doc/library/zipfile.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/zipfile.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`zipfile` --- Work with ZIP archives + ========================================= + +@@ -49,7 +48,7 @@ + Class for creating ZIP archives containing Python libraries. + + +-.. class:: ZipInfo([filename[, date_time]]) ++.. class:: ZipInfo(filename='NoName', date_time=(1980,1,1,0,0,0)) + + Class used to represent information about a member of an archive. Instances + of this class are returned by the :meth:`getinfo` and :meth:`infolist` +@@ -98,7 +97,7 @@ + --------------- + + +-.. class:: ZipFile(file[, mode[, compression[, allowZip64]]]) ++.. class:: ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=False) + + Open a ZIP file, where *file* can be either a path to a file (a string) or a + file-like object. The *mode* parameter should be ``'r'`` to read an existing +@@ -149,7 +148,7 @@ + Return a list of archive members by name. + + +-.. method:: ZipFile.open(name[, mode[, pwd]]) ++.. method:: ZipFile.open(name, mode='r', pwd=None) + + Extract a member from the archive as a file-like object (ZipExtFile). *name* is + the name of the file in the archive, or a :class:`ZipInfo` object. The *mode* +@@ -182,7 +181,7 @@ + ZIP file that contains members with duplicate names. + + +-.. method:: ZipFile.extract(member[, path[, pwd]]) ++.. method:: ZipFile.extract(member, path=None, pwd=None) + + Extract a member from the archive to the current working directory; *member* + must be its full name or a :class:`ZipInfo` object). Its file information is +@@ -191,7 +190,7 @@ + *pwd* is the password used for encrypted files. + + +-.. method:: ZipFile.extractall([path[, members[, pwd]]]) ++.. method:: ZipFile.extractall(path=None, members=None, pwd=None) + + Extract all members from the archive to the current working directory. *path* + specifies a different directory to extract to. *members* is optional and must +@@ -209,7 +208,7 @@ + Set *pwd* as default password to extract encrypted files. + + +-.. method:: ZipFile.read(name[, pwd]) ++.. method:: ZipFile.read(name, pwd=None) + + Return the bytes of the file *name* in the archive. *name* is the name of the + file in the archive, or a :class:`ZipInfo` object. The archive must be open for +@@ -225,7 +224,7 @@ + :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`. + + +-.. method:: ZipFile.write(filename[, arcname[, compress_type]]) ++.. method:: ZipFile.write(filename, arcname=None, compress_type=None) + + Write the file named *filename* to the archive, giving it the archive name + *arcname* (by default, this will be the same as *filename*, but without a drive +@@ -297,7 +296,7 @@ + :class:`ZipFile` objects. + + +-.. method:: PyZipFile.writepy(pathname[, basename]) ++.. method:: PyZipFile.writepy(pathname, basename='') + + Search for files :file:`\*.py` and add the corresponding file to the archive. + The corresponding file is a :file:`\*.pyo` file if available, else a +Index: Doc/library/curses.rst +=================================================================== +--- Doc/library/curses.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/curses.rst (.../branches/release31-maint) (Revision 76056) +@@ -4,10 +4,10 @@ + .. module:: curses + :synopsis: An interface to the curses library, providing portable + terminal handling. ++ :platform: Unix + .. sectionauthor:: Moshe Zadka + .. sectionauthor:: Eric Raymond + +- + The :mod:`curses` module provides an interface to the curses library, the + de-facto standard for portable advanced terminal handling. + +Index: Doc/library/wsgiref.rst +=================================================================== +--- Doc/library/wsgiref.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/wsgiref.rst (.../branches/release31-maint) (Revision 76056) +@@ -57,7 +57,7 @@ + found, and "http" otherwise. + + +-.. function:: request_uri(environ [, include_query=1]) ++.. function:: request_uri(environ, include_query=True) + + Return the full request URI, optionally including the query string, using the + algorithm found in the "URL Reconstruction" section of :pep:`333`. If +@@ -146,7 +146,7 @@ + :rfc:`2616`. + + +-.. class:: FileWrapper(filelike [, blksize=8192]) ++.. class:: FileWrapper(filelike, blksize=8192) + + A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects + support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for +@@ -269,7 +269,7 @@ + :mod:`wsgiref.util`.) + + +-.. function:: make_server(host, port, app [, server_class=WSGIServer [, handler_class=WSGIRequestHandler]]) ++.. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler) + + Create a new WSGI server listening on *host* and *port*, accepting connections + for *app*. The return value is an instance of the supplied *server_class*, and +@@ -458,7 +458,7 @@ + environment. + + +-.. class:: BaseCGIHandler(stdin, stdout, stderr, environ [, multithread=True [, multiprocess=False]]) ++.. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) + + Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and + :mod:`os` modules, the CGI environment and I/O streams are specified explicitly. +@@ -473,7 +473,7 @@ + instead of :class:`SimpleHandler`. + + +-.. class:: SimpleHandler(stdin, stdout, stderr, environ [,multithread=True [, multiprocess=False]]) ++.. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False) + + Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin + servers. If you are writing an HTTP server implementation, you will probably +Index: Doc/library/xml.sax.handler.rst +=================================================================== +--- Doc/library/xml.sax.handler.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/xml.sax.handler.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`xml.sax.handler` --- Base classes for SAX handlers + ======================================================== + +Index: Doc/library/hashlib.rst +=================================================================== +--- Doc/library/hashlib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/hashlib.rst (.../branches/release31-maint) (Revision 76056) +@@ -86,11 +86,11 @@ + returned by the constructors: + + +-.. data:: digest_size ++.. data:: hash.digest_size + + The size of the resulting hash in bytes. + +-.. data:: block_size ++.. data:: hash.block_size + + The internal block size of the hash algorithm in bytes. + +Index: Doc/library/msilib.rst +=================================================================== +--- Doc/library/msilib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/msilib.rst (.../branches/release31-maint) (Revision 76056) +@@ -394,10 +394,10 @@ + + .. seealso:: + +- `Directory Table `_ +- `File Table `_ +- `Component Table `_ +- `FeatureComponents Table `_ ++ `Directory Table `_ ++ `File Table `_ ++ `Component Table `_ ++ `FeatureComponents Table `_ + + .. _features: + +@@ -422,7 +422,7 @@ + + .. seealso:: + +- `Feature Table `_ ++ `Feature Table `_ + + .. _msi-gui: + +@@ -516,13 +516,13 @@ + + .. seealso:: + +- `Dialog Table `_ +- `Control Table `_ +- `Control Types `_ +- `ControlCondition Table `_ +- `ControlEvent Table `_ +- `EventMapping Table `_ +- `RadioButton Table `_ ++ `Dialog Table `_ ++ `Control Table `_ ++ `Control Types `_ ++ `ControlCondition Table `_ ++ `ControlEvent Table `_ ++ `EventMapping Table `_ ++ `RadioButton Table `_ + + .. _msi-tables: + +@@ -551,5 +551,3 @@ + + This module contains definitions for the UIText and ActionText tables, for the + standard installer actions. +- +- +Index: Doc/library/stdtypes.rst +=================================================================== +--- Doc/library/stdtypes.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/stdtypes.rst (.../branches/release31-maint) (Revision 76056) +@@ -772,15 +772,17 @@ + If *k* is ``None``, it is treated like ``1``. + + (6) +- If *s* and *t* are both strings, some Python implementations such as CPython can +- usually perform an in-place optimization for assignments of the form ``s=s+t`` +- or ``s+=t``. When applicable, this optimization makes quadratic run-time much +- less likely. This optimization is both version and implementation dependent. +- For performance sensitive code, it is preferable to use the :meth:`str.join` +- method which assures consistent linear concatenation performance across versions +- and implementations. ++ .. impl-detail:: + ++ If *s* and *t* are both strings, some Python implementations such as ++ CPython can usually perform an in-place optimization for assignments of ++ the form ``s = s + t`` or ``s += t``. When applicable, this optimization ++ makes quadratic run-time much less likely. This optimization is both ++ version and implementation dependent. For performance sensitive code, it ++ is preferable to use the :meth:`str.join` method which assures consistent ++ linear concatenation performance across versions and implementations. + ++ + .. _string-methods: + + String Methods +@@ -950,12 +952,12 @@ + least one cased character, false otherwise. + + +-.. method:: str.join(seq) ++.. method:: str.join(iterable) + +- Return a string which is the concatenation of the strings in the sequence +- *seq*. A :exc:`TypeError` will be raised if there are any non-string values +- in *seq*, including :class:`bytes` objects. The separator between elements +- is the string providing this method. ++ Return a string which is the concatenation of the strings in the ++ :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are ++ any non-string values in *seq*, including :class:`bytes` objects. The ++ separator between elements is the string providing this method. + + + .. method:: str.ljust(width[, fillchar]) +@@ -1125,10 +1127,30 @@ + + .. method:: str.title() + +- Return a titlecased version of the string: words start with uppercase +- characters, all remaining cased characters are lowercase. ++ Return a titlecased version of the string where words start with an uppercase ++ character and the remaining characters are lowercase. + ++ The algorithm uses a simple language-independent definition of a word as ++ groups of consecutive letters. The definition works in many contexts but ++ it means that apostrophes in contractions and possessives form word ++ boundaries, which may not be the desired result:: + ++ >>> "they're bill's friends from the UK".title() ++ "They'Re Bill'S Friends From The Uk" ++ ++ A workaround for apostrophes can be constructed using regular expressions:: ++ ++ >>> import re ++ >>> def titlecase(s): ++ return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", ++ lambda mo: mo.group(0)[0].upper() + ++ mo.group(0)[1:].lower(), ++ s) ++ ++ >>> titlecase("they're bill's friends.") ++ "They're Bill's Friends." ++ ++ + .. method:: str.translate(map) + + Return a copy of the *s* where all characters have been mapped through the +@@ -1489,14 +1511,17 @@ + that compare equal --- this is helpful for sorting in multiple passes (for + example, sort by department, then by salary grade). + +- While a list is being sorted, the effect of attempting to mutate, or even +- inspect, the list is undefined. The C implementation +- makes the list appear empty for the duration, and raises :exc:`ValueError` if it +- can detect that the list has been mutated during a sort. ++ .. impl-detail:: + ++ While a list is being sorted, the effect of attempting to mutate, or even ++ inspect, the list is undefined. The C implementation of Python makes the ++ list appear empty for the duration, and raises :exc:`ValueError` if it can ++ detect that the list has been mutated during a sort. ++ + (8) + :meth:`sort` is not supported by :class:`bytearray` objects. + ++ + .. _bytes-methods: + + Bytes and Byte Array Methods +@@ -1724,12 +1749,12 @@ + .. method:: update(other, ...) + set |= other | ... + +- Update the set, adding elements from *other*. ++ Update the set, adding elements from all others. + + .. method:: intersection_update(other, ...) + set &= other & ... + +- Update the set, keeping only elements found in it and *other*. ++ Update the set, keeping only elements found in it and all others. + + .. method:: difference_update(other, ...) + set -= other | ... +@@ -1938,7 +1963,7 @@ + + :meth:`update` accepts either another dictionary object or an iterable of + key/value pairs (as a tuple or other iterable of length two). If keyword +- arguments are specified, the dictionary is then is updated with those ++ arguments are specified, the dictionary is then updated with those + key/value pairs: ``d.update(red=1, blue=2)``. + + .. method:: values() +@@ -2478,9 +2503,9 @@ + their implementation of the context management protocol. See the + :mod:`contextlib` module for some examples. + +-Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator` ++Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator` + provide a convenient way to implement these protocols. If a generator function is +-decorated with the ``contextlib.contextfactory`` decorator, it will return a ++decorated with the ``contextlib.contextmanager`` decorator, it will return a + context manager implementing the necessary :meth:`__enter__` and + :meth:`__exit__` methods, rather than the iterator produced by an undecorated + generator function. +Index: Doc/library/token.rst +=================================================================== +--- Doc/library/token.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/token.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`token` --- Constants used with Python parse trees + ======================================================= + +Index: Doc/library/tkinter.tix.rst +=================================================================== +--- Doc/library/tkinter.tix.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/tkinter.tix.rst (.../branches/release31-maint) (Revision 76056) +@@ -45,7 +45,7 @@ + --------- + + +-.. class:: Tix(screenName[, baseName[, className]]) ++.. class:: Tk(screenName=None, baseName=None, className='Tix') + + Toplevel widget of Tix which represents mostly the main window of an + application. It has an associated Tcl interpreter. +Index: Doc/library/othergui.rst +=================================================================== +--- Doc/library/othergui.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/othergui.rst (.../branches/release31-maint) (Revision 76056) +@@ -43,7 +43,7 @@ + `PythonCAD `_. An online `tutorial + `_ is available. + +- `PyQt `_ ++ `PyQt `_ + PyQt is a :program:`sip`\ -wrapped binding to the Qt toolkit. Qt is an + extensive C++ GUI application development framework that is + available for Unix, Windows and Mac OS X. :program:`sip` is a tool +Index: Doc/library/cmath.rst +=================================================================== +--- Doc/library/cmath.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/cmath.rst (.../branches/release31-maint) (Revision 76056) +@@ -94,10 +94,7 @@ + specified, returns the natural logarithm of *x*. There is one branch cut, from 0 + along the negative real axis to -∞, continuous from above. + +- .. versionchanged:: 2.4 +- *base* argument added. + +- + .. function:: log10(x) + + Return the base-10 logarithm of *x*. This has the same branch cut as +Index: Doc/library/tempfile.rst +=================================================================== +--- Doc/library/tempfile.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/tempfile.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`tempfile` --- Generate temporary files and directories + ============================================================ + +@@ -29,7 +28,7 @@ + The module defines the following user-callable functions: + + +-.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]) ++.. function:: TemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) + + Return a file-like object that can be used as a temporary storage area. + The file is created using :func:`mkstemp`. It will be destroyed as soon +@@ -53,7 +52,7 @@ + :keyword:`with` statement, just like a normal file. + + +-.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]]) ++.. function:: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True) + + This function operates exactly as :func:`TemporaryFile` does, except that + the file is guaranteed to have a visible name in the file system (on +@@ -68,7 +67,7 @@ + be used in a :keyword:`with` statement, just like a normal file. + + +-.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]]) ++.. function:: SpooledTemporaryFile(max_size=0, mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None) + + This function operates exactly as :func:`TemporaryFile` does, except that + data is spooled in memory until the file size exceeds *max_size*, or +@@ -85,7 +84,7 @@ + used in a :keyword:`with` statement, just like a normal file. + + +-.. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]]) ++.. function:: mkstemp(suffix='', prefix='tmp', dir=None, text=False) + + Creates a temporary file in the most secure manner possible. There are + no race conditions in the file's creation, assuming that the platform +@@ -123,7 +122,7 @@ + of that file, in that order. + + +-.. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]]) ++.. function:: mkdtemp(suffix='', prefix='tmp', dir=None) + + Creates a temporary directory in the most secure manner possible. There + are no race conditions in the directory's creation. The directory is +@@ -138,7 +137,7 @@ + :func:`mkdtemp` returns the absolute pathname of the new directory. + + +-.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]]) ++.. function:: mktemp(suffix='', prefix='tmp', dir=None) + + .. deprecated:: 2.3 + Use :func:`mkstemp` instead. +Index: Doc/library/collections.rst +=================================================================== +--- Doc/library/collections.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/collections.rst (.../branches/release31-maint) (Revision 76056) +@@ -538,7 +538,7 @@ + >>> for k, v in s: + ... d[k].append(v) + ... +- >>> d.items() ++ >>> list(d.items()) + [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] + + When each key is encountered for the first time, it is not already in the +@@ -553,7 +553,7 @@ + >>> for k, v in s: + ... d.setdefault(k, []).append(v) + ... +- >>> d.items() ++ >>> list(d.items()) + [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] + + Setting the :attr:`default_factory` to :class:`int` makes the +@@ -565,7 +565,7 @@ + >>> for k in s: + ... d[k] += 1 + ... +- >>> d.items() ++ >>> list(d.items()) + [('i', 4), ('p', 2), ('s', 4), ('m', 1)] + + When a letter is first encountered, it is missing from the mapping, so the +@@ -592,7 +592,7 @@ + >>> for k, v in s: + ... d[k].add(v) + ... +- >>> d.items() ++ >>> list(d.items()) + [('blue', set([2, 4])), ('red', set([1, 3]))] + + +@@ -669,7 +669,7 @@ + 'Return a new Point object replacing specified fields with new values' + result = _self._make(map(kwds.pop, ('x', 'y'), _self)) + if kwds: +- raise ValueError('Got unexpected field names: %r' % kwds.keys()) ++ raise ValueError('Got unexpected field names: %r' % list(kwds.keys())) + return result + + def __getnewargs__(self): +Index: Doc/library/os.rst +=================================================================== +--- Doc/library/os.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/os.rst (.../branches/release31-maint) (Revision 76056) +@@ -396,7 +396,7 @@ + Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive), + ignoring errors. Availability: Unix, Windows. Equivalent to:: + +- for fd in xrange(fd_low, fd_high): ++ for fd in range(fd_low, fd_high): + try: + os.close(fd) + except OSError: +@@ -589,7 +589,7 @@ + :func:`~os.open` function. They can be combined using the bitwise OR operator + ``|``. Some of them are not available on all platforms. For descriptions of + their availability and use, consult the :manpage:`open(2)` manual page on Unix +-or `the MSDN ` on Windows. ++or `the MSDN `_ on Windows. + + + .. data:: O_RDONLY +@@ -947,12 +947,12 @@ + + .. function:: remove(path) + +- Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see +- :func:`rmdir` below to remove a directory. This is identical to the +- :func:`unlink` function documented below. On Windows, attempting to remove a +- file that is in use causes an exception to be raised; on Unix, the directory +- entry is removed but the storage allocated to the file is not made available +- until the original file is no longer in use. Availability: Unix, ++ Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is ++ raised; see :func:`rmdir` below to remove a directory. This is identical to ++ the :func:`unlink` function documented below. On Windows, attempting to ++ remove a file that is in use causes an exception to be raised; on Unix, the ++ directory entry is removed but the storage allocated to the file is not made ++ available until the original file is no longer in use. Availability: Unix, + Windows. + + +@@ -997,7 +997,10 @@ + + .. function:: rmdir(path) + +- Remove the directory *path*. Availability: Unix, Windows. ++ Remove (delete) the directory *path*. Only works when the directory is ++ empty, otherwise, :exc:`OSError` is raised. In order to remove whole ++ directory trees, :func:`shutil.rmtree` can be used. Availability: Unix, ++ Windows. + + + .. function:: stat(path) +@@ -1099,9 +1102,9 @@ + + .. function:: unlink(path) + +- Remove the file *path*. This is the same function as :func:`remove`; the +- :func:`unlink` name is its traditional Unix name. Availability: Unix, +- Windows. ++ Remove (delete) the file *path*. This is the same function as ++ :func:`remove`; the :func:`unlink` name is its traditional Unix ++ name. Availability: Unix, Windows. + + + .. function:: utime(path, times) +@@ -1575,9 +1578,9 @@ + .. 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. Changes +- to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the +- environment of the executed command. ++ the Standard C function :cfunc:`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 +Index: Doc/library/platform.rst +=================================================================== +--- Doc/library/platform.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/platform.rst (.../branches/release31-maint) (Revision 76056) +@@ -94,7 +94,7 @@ + .. function:: python_implementation() + + Returns a string identifying the Python implementation. Possible return values +- are: 'CPython', 'IronPython', 'Jython' ++ are: 'CPython', 'IronPython', 'Jython'. + + + .. function:: python_revision() +Index: Doc/library/winreg.rst +=================================================================== +--- Doc/library/winreg.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/winreg.rst (.../branches/release31-maint) (Revision 76056) +@@ -130,12 +130,12 @@ + +-------+--------------------------------------------+ + + +-.. function:: ExpandEnvironmentStrings(unicode) ++.. function:: ExpandEnvironmentStrings(str) + +- Expands environment strings %NAME% in unicode string like const:`REG_EXPAND_SZ`:: ++ Expands environment strings %NAME% in unicode string like :const:`REG_EXPAND_SZ`:: + +- >>> ExpandEnvironmentStrings(u"%windir%") +- u"C:\\Windows" ++ >>> ExpandEnvironmentStrings('%windir%') ++ 'C:\\Windows' + + + .. function:: FlushKey(key) +@@ -183,7 +183,7 @@ + :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true. + + +-.. function:: OpenKey(key, sub_key[, res=0][, sam=KEY_READ]) ++.. function:: OpenKey(key, sub_key, res=0, sam=KEY_READ) + + Opens the specified key, returning a :dfn:`handle object` + +@@ -195,7 +195,7 @@ + *res* is a reserved integer, and must be zero. The default is zero. + + *sam* is an integer that specifies an access mask that describes the desired +- security access for the key. Default is :const:`KEY_READ` ++ security access for the key. Default is :const:`KEY_READ`. + + The result is a new handle to the specified key. + +Index: Doc/library/traceback.rst +=================================================================== +--- Doc/library/traceback.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/traceback.rst (.../branches/release31-maint) (Revision 76056) +@@ -20,7 +20,7 @@ + The module defines the following functions: + + +-.. function:: print_tb(traceback[, limit[, file]]) ++.. function:: print_tb(traceback, limit=None, file=None) + + Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted + or ``None``, all entries are printed. If *file* is omitted or ``None``, the +@@ -28,7 +28,7 @@ + object to receive the output. + + +-.. function:: print_exception(type, value, traceback[, limit[, file[, chain]]]) ++.. function:: print_exception(type, value, traceback, limit=None, file=None, chain=True) + + Print exception information and up to *limit* stack trace entries from + *traceback* to *file*. This differs from :func:`print_tb` in the following +@@ -47,19 +47,19 @@ + exception. + + +-.. function:: print_exc([limit[, file[, chain]]]) ++.. function:: print_exc(limit=None, file=None, chain=True) + + This is a shorthand for ``print_exception(*sys.exc_info())``. + + +-.. function:: print_last([limit[, file[, chain]]]) ++.. function:: print_last(limit=None, file=None, chain=True) + + This is a shorthand for ``print_exception(sys.last_type, sys.last_value, + sys.last_traceback, limit, file)``. In general it will work only after + an exception has reached an interactive prompt (see :data:`sys.last_type`). + + +-.. function:: print_stack([f[, limit[, file]]]) ++.. function:: print_stack(f=None, limit=None, file=None) + + This function prints a stack trace from its invocation point. The optional *f* + argument can be used to specify an alternate stack frame to start. The optional +@@ -67,7 +67,7 @@ + :func:`print_exception`. + + +-.. function:: extract_tb(traceback[, limit]) ++.. function:: extract_tb(traceback, limit=None) + + Return a list of up to *limit* "pre-processed" stack trace entries extracted + from the traceback object *traceback*. It is useful for alternate formatting of +@@ -78,7 +78,7 @@ + stripped; if the source is not available it is ``None``. + + +-.. function:: extract_stack([f[, limit]]) ++.. function:: extract_stack(f=None, limit=None) + + Extract the raw traceback from the current stack frame. The return value has + the same format as for :func:`extract_tb`. The optional *f* and *limit* +@@ -105,7 +105,7 @@ + occurred is the always last string in the list. + + +-.. function:: format_exception(type, value, tb[, limit[, chain]]) ++.. function:: format_exception(type, value, tb, limit=None, chain=True) + + Format a stack trace and the exception information. The arguments have the + same meaning as the corresponding arguments to :func:`print_exception`. The +@@ -114,18 +114,18 @@ + same text is printed as does :func:`print_exception`. + + +-.. function:: format_exc([limit[, chain]]) ++.. function:: format_exc(limit=None, chain=True) + + This is like ``print_exc(limit)`` but returns a string instead of printing to a + file. + + +-.. function:: format_tb(tb[, limit]) ++.. function:: format_tb(tb, limit=None) + + A shorthand for ``format_list(extract_tb(tb, limit))``. + + +-.. function:: format_stack([f[, limit]]) ++.. function:: format_stack(f=None, limit=None) + + A shorthand for ``format_list(extract_stack(f, limit))``. + +Index: Doc/library/urllib.request.rst +=================================================================== +--- Doc/library/urllib.request.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/urllib.request.rst (.../branches/release31-maint) (Revision 76056) +@@ -14,7 +14,7 @@ + The :mod:`urllib.request` module defines the following functions: + + +-.. function:: urlopen(url[, data][, timeout]) ++.. function:: urlopen(url, data=None[, timeout]) + + Open the URL *url*, which can be either a string or a + :class:`Request` object. +@@ -49,6 +49,9 @@ + the default installed global :class:`OpenerDirector` uses + :class:`UnknownHandler` to ensure this never happens). + ++ In addition, default installed :class:`ProxyHandler` makes sure the requests ++ are handled through the proxy when they are set. ++ + The legacy ``urllib.urlopen`` function from Python 2.6 and earlier has been + discontinued; :func:`urlopen` corresponds to the old ``urllib2.urlopen``. + Proxy handling, which was done by passing a dictionary parameter to +@@ -75,14 +78,15 @@ + :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`, + :class:`HTTPErrorProcessor`. + +- If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported), +- :class:`HTTPSHandler` will also be added. ++ If the Python installation has SSL support (i.e., if the :mod:`ssl` module ++ can be imported), :class:`HTTPSHandler` will also be added. + + A :class:`BaseHandler` subclass may also change its :attr:`handler_order` + member variable to modify its position in the handlers list. + +-.. function:: urlretrieve(url[, filename[, reporthook[, data]]]) + ++.. function:: urlretrieve(url, filename=None, reporthook=None, data=None) ++ + Copy a network object denoted by a URL to a local file, if necessary. If the URL + points to a local file, or a valid cached copy of the object exists, the object + is not copied. Return a tuple ``(filename, headers)`` where *filename* is the +@@ -160,9 +164,10 @@ + path. This does not accept a complete URL. This function uses :func:`unquote` + to decode *path*. + ++ + The following classes are provided: + +-.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable]) ++.. class:: Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False) + + This class is an abstraction of a URL request. + +@@ -205,8 +210,9 @@ + document, and the user had no option to approve the automatic + fetching of the image, this should be true. + +-.. class:: URLopener([proxies[, **x509]]) + ++.. class:: URLopener(proxies=None, **x509) ++ + Base class for opening and reading URLs. Unless you need to support opening + objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`, + you probably want to use :class:`FancyURLopener`. +@@ -230,7 +236,7 @@ + :class:`URLopener` objects will raise an :exc:`IOError` exception if the server + returns an error code. + +- .. method:: open(fullurl[, data]) ++ .. method:: open(fullurl, data=None) + + Open *fullurl* using the appropriate protocol. This method sets up cache and + proxy information, then calls the appropriate open method with its input +@@ -239,12 +245,12 @@ + :func:`urlopen`. + + +- .. method:: open_unknown(fullurl[, data]) ++ .. method:: open_unknown(fullurl, data=None) + + Overridable interface to open unknown URL types. + + +- .. method:: retrieve(url[, filename[, reporthook[, data]]]) ++ .. method:: retrieve(url, filename=None, reporthook=None, data=None) + + Retrieves the contents of *url* and places it in *filename*. The return value + is a tuple consisting of a local filename and either a +@@ -337,16 +343,21 @@ + A class to handle redirections. + + +-.. class:: HTTPCookieProcessor([cookiejar]) ++.. class:: HTTPCookieProcessor(cookiejar=None) + + A class to handle HTTP Cookies. + + +-.. class:: ProxyHandler([proxies]) ++.. class:: ProxyHandler(proxies=None) + + Cause requests to go through a proxy. If *proxies* is given, it must be a + dictionary mapping protocol names to URLs of proxies. The default is to read the + list of proxies from the environment variables :envvar:`_proxy`. ++ If no proxy environment variables are set, in a Windows environment, proxy ++ settings are obtained from the registry's Internet Settings section and in a ++ Mac OS X environment, proxy information is retrieved from the OS X System ++ Configuration Framework. ++ + To disable autodetected proxy pass an empty dictionary. + + +@@ -362,7 +373,7 @@ + fits. + + +-.. class:: AbstractBasicAuthHandler([password_mgr]) ++.. class:: AbstractBasicAuthHandler(password_mgr=None) + + This is a mixin class that helps with HTTP authentication, both to the remote + host and to a proxy. *password_mgr*, if given, should be something that is +@@ -371,7 +382,7 @@ + supported. + + +-.. class:: HTTPBasicAuthHandler([password_mgr]) ++.. class:: HTTPBasicAuthHandler(password_mgr=None) + + Handle authentication with the remote host. *password_mgr*, if given, should be + something that is compatible with :class:`HTTPPasswordMgr`; refer to section +@@ -379,7 +390,7 @@ + supported. + + +-.. class:: ProxyBasicAuthHandler([password_mgr]) ++.. class:: ProxyBasicAuthHandler(password_mgr=None) + + Handle authentication with the proxy. *password_mgr*, if given, should be + something that is compatible with :class:`HTTPPasswordMgr`; refer to section +@@ -387,7 +398,7 @@ + supported. + + +-.. class:: AbstractDigestAuthHandler([password_mgr]) ++.. class:: AbstractDigestAuthHandler(password_mgr=None) + + This is a mixin class that helps with HTTP authentication, both to the remote + host and to a proxy. *password_mgr*, if given, should be something that is +@@ -396,7 +407,7 @@ + supported. + + +-.. class:: HTTPDigestAuthHandler([password_mgr]) ++.. class:: HTTPDigestAuthHandler(password_mgr=None) + + Handle authentication with the remote host. *password_mgr*, if given, should be + something that is compatible with :class:`HTTPPasswordMgr`; refer to section +@@ -404,7 +415,7 @@ + supported. + + +-.. class:: ProxyDigestAuthHandler([password_mgr]) ++.. class:: ProxyDigestAuthHandler(password_mgr=None) + + Handle authentication with the proxy. *password_mgr*, if given, should be + something that is compatible with :class:`HTTPPasswordMgr`; refer to section +@@ -597,7 +608,7 @@ + post-process *protocol* responses. + + +-.. method:: OpenerDirector.open(url[, data][, timeout]) ++.. method:: OpenerDirector.open(url, data=None[, timeout]) + + Open the given *url* (which can be a request object or a string), optionally + passing the given *data*. Arguments, return values and exceptions raised are +@@ -609,7 +620,7 @@ + HTTP, HTTPS, FTP and FTPS connections). + + +-.. method:: OpenerDirector.error(proto[, arg[, ...]]) ++.. method:: OpenerDirector.error(proto, *args) + + Handle an error of the given protocol. This will call the registered error + handlers for the given protocol with the given arguments (which are protocol +Index: Doc/library/readline.rst +=================================================================== +--- Doc/library/readline.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/readline.rst (.../branches/release31-maint) (Revision 76056) +@@ -206,7 +206,7 @@ + class HistoryConsole(code.InteractiveConsole): + def __init__(self, locals=None, filename="", + histfile=os.path.expanduser("~/.console-history")): +- code.InteractiveConsole.__init__(self) ++ code.InteractiveConsole.__init__(self, locals, filename) + self.init_history(histfile) + + def init_history(self, histfile): +Index: Doc/library/io.rst +=================================================================== +--- Doc/library/io.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/io.rst (.../branches/release31-maint) (Revision 76056) +@@ -208,6 +208,9 @@ + + IOBase (and its subclasses) support the iterator protocol, meaning that an + :class:`IOBase` object can be iterated over yielding the lines in a stream. ++ Lines are defined slightly differently depending on whether the stream is ++ a binary stream (yielding bytes), or a text stream (yielding character ++ strings). See :meth:`readline` below. + + IOBase is also a context manager and therefore supports the + :keyword:`with` statement. In this example, *file* is closed after the +@@ -314,16 +317,24 @@ + Base class for raw binary I/O. It inherits :class:`IOBase`. There is no + public constructor. + ++ Raw binary I/O typically provides low-level access to an underlying OS ++ device or API, and does not try to encapsulate it in high-level primitives ++ (this is left to Buffered I/O and Text I/O, described later in this page). ++ + In addition to the attributes and methods from :class:`IOBase`, + RawIOBase provides the following methods: + + .. method:: read(n=-1) + +- Read and return all the bytes from the stream until EOF, or if *n* is +- specified, up to *n* bytes. Only one system call is ever made. An empty +- bytes object is returned on EOF; ``None`` is returned if the object is set +- not to block and has no data to read. ++ Read up to *n* bytes from the object and return them. As a convenience, ++ if *n* is unspecified or -1, :meth:`readall` is called. Otherwise, ++ only one system call is ever made. Fewer than *n* bytes may be ++ returned if the operating system call returns fewer than *n* bytes. + ++ If 0 bytes are returned, and *n* was not 0, this indicates end of file. ++ If the object is in non-blocking mode and no bytes are available, ++ ``None`` is returned. ++ + .. method:: readall() + + Read and return all the bytes from the stream until EOF, using multiple +@@ -337,28 +348,35 @@ + .. method:: write(b) + + Write the given bytes or bytearray object, *b*, to the underlying raw +- stream and return the number of bytes written (This is never less than +- ``len(b)``, since if the write fails, an :exc:`IOError` will be raised). ++ stream and return the number of bytes written. This can be less than ++ ``len(b)``, depending on specifics of the underlying raw stream, and ++ especially if it is in non-blocking mode. ``None`` is returned if the ++ raw stream is set not to block and no single byte could be readily ++ written to it. + + + .. class:: BufferedIOBase + +- Base class for streams that support buffering. It inherits :class:`IOBase`. +- There is no public constructor. ++ Base class for binary streams that support some kind of buffering. ++ It inherits :class:`IOBase`. There is no public constructor. + +- The main difference with :class:`RawIOBase` is that the :meth:`read` method +- supports omitting the *size* argument, and does not have a default ++ The main difference with :class:`RawIOBase` is that methods :meth:`read`, ++ :meth:`readinto` and :meth:`write` will try (respectively) to read as much ++ input as requested or to consume all given output, at the expense of ++ making perhaps more than one system call. ++ ++ In addition, those methods can raise :exc:`BlockingIOError` if the ++ underlying raw stream is in non-blocking mode and cannot take or give ++ enough data; unlike their :class:`RawIOBase` counterparts, they will ++ never return ``None``. ++ ++ Besides, the :meth:`read` method does not have a default + implementation that defers to :meth:`readinto`. + +- In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise +- :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode +- and not ready; unlike their raw counterparts, they will never return +- ``None``. ++ A typical :class:`BufferedIOBase` implementation should not inherit from a ++ :class:`RawIOBase` implementation, but wrap one, like ++ :class:`BufferedWriter` and :class:`BufferedReader` do. + +- A typical implementation should not inherit from a :class:`RawIOBase` +- implementation, but wrap one like :class:`BufferedWriter` and +- :class:`BufferedReader`. +- + :class:`BufferedIOBase` provides or overrides these members in addition to + those from :class:`IOBase`: + +@@ -393,13 +411,15 @@ + one raw read will be issued, and a short result does not imply that EOF is + imminent. + +- A :exc:`BlockingIOError` is raised if the underlying raw stream has no +- data at the moment. ++ A :exc:`BlockingIOError` is raised if the underlying raw stream is in ++ non blocking-mode, and has no data available at the moment. + + .. method:: read1(n=-1) + + Read and return up to *n* bytes, with at most one call to the underlying +- raw stream's :meth:`~RawIOBase.read` method. ++ raw stream's :meth:`~RawIOBase.read` method. This can be useful if you ++ are implementing your own buffering on top of a :class:`BufferedIOBase` ++ object. + + .. method:: readinto(b) + +@@ -407,19 +427,22 @@ + read. + + Like :meth:`read`, multiple reads may be issued to the underlying raw +- stream, unless the latter is 'interactive.' ++ stream, unless the latter is 'interactive'. + +- A :exc:`BlockingIOError` is raised if the underlying raw stream has no +- data at the moment. ++ A :exc:`BlockingIOError` is raised if the underlying raw stream is in ++ non blocking-mode, and has no data available at the moment. + + .. method:: write(b) + +- Write the given bytes or bytearray object, *b*, to the underlying raw +- stream and return the number of bytes written (never less than ``len(b)``, +- since if the write fails an :exc:`IOError` will be raised). ++ Write the given bytes or bytearray object, *b* and return the number ++ of bytes written (never less than ``len(b)``, since if the write fails ++ an :exc:`IOError` will be raised). Depending on the actual ++ implementation, these bytes may be readily written to the underlying ++ stream, or held in a buffer for performance and latency reasons. + +- A :exc:`BlockingIOError` is raised if the buffer is full, and the +- underlying raw stream cannot accept more data at the moment. ++ When in non-blocking mode, a :exc:`BlockingIOError` is raised if the ++ data needed to be written to the raw stream but it couldn't accept ++ all the data without blocking. + + + Raw File I/O +@@ -427,15 +450,25 @@ + + .. class:: FileIO(name, mode='r', closefd=True) + +- :class:`FileIO` represents a file containing bytes data. It implements +- the :class:`RawIOBase` interface (and therefore the :class:`IOBase` +- interface, too). ++ :class:`FileIO` represents an OS-level file containing bytes data. ++ It implements the :class:`RawIOBase` interface (and therefore the ++ :class:`IOBase` interface, too). + ++ The *name* can be one of two things: ++ ++ * a character string or bytes object representing the path to the file ++ which will be opened; ++ * an integer representing the number of an existing OS-level file descriptor ++ to which the resulting :class:`FileIO` object will give access. ++ + The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing, + or appending. The file will be created if it doesn't exist when opened for + writing or appending; it will be truncated when opened for writing. Add a + ``'+'`` to the mode to allow simultaneous reading and writing. + ++ The :meth:`read` (when called with a positive argument), :meth:`readinto` ++ and :meth:`write` methods on this class will only make one system call. ++ + In addition to the attributes and methods from :class:`IOBase` and + :class:`RawIOBase`, :class:`FileIO` provides the following data + attributes and methods: +@@ -449,29 +482,13 @@ + The file name. This is the file descriptor of the file when no name is + given in the constructor. + +- .. method:: read(n=-1) + +- Read and return at most *n* bytes. Only one system call is made, so it is +- possible that less data than was requested is returned. Use :func:`len` +- on the returned bytes object to see how many bytes were actually returned. +- (In non-blocking mode, ``None`` is returned when no data is available.) +- +- .. method:: readall() +- +- Read and return the entire file's contents in a single bytes object. As +- much as immediately available is returned in non-blocking mode. If the +- EOF has been reached, ``b''`` is returned. +- +- .. method:: write(b) +- +- Write the bytes or bytearray object, *b*, to the file, and return +- the number actually written. Only one system call is made, so it +- is possible that only some of the data is written. +- +- + Buffered Streams + ---------------- + ++In many situations, buffered I/O streams will provide higher performance ++(bandwidth and latency) than raw I/O streams. Their API is also more usable. ++ + .. class:: BytesIO([initial_bytes]) + + A stream implementation using an in-memory bytes buffer. It inherits +@@ -498,8 +515,11 @@ + + .. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE) + +- A buffer for a readable, sequential :class:`RawIOBase` object. It inherits +- :class:`BufferedIOBase`. ++ A buffer providing higher-level access to a readable, sequential ++ :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`. ++ When reading data from this object, a larger amount of data may be ++ requested from the underlying raw stream, and kept in an internal buffer. ++ The buffered data can then be returned directly on subsequent reads. + + The constructor creates a :class:`BufferedReader` for the given readable + *raw* stream and *buffer_size*. If *buffer_size* is omitted, +@@ -528,9 +548,17 @@ + + .. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE) + +- A buffer for a writeable sequential RawIO object. It inherits +- :class:`BufferedIOBase`. ++ A buffer providing higher-level access to a writeable, sequential ++ :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`. ++ When writing to this object, data is normally held into an internal ++ buffer. The buffer will be written out to the underlying :class:`RawIOBase` ++ object under various conditions, including: + ++ * when the buffer gets too small for all pending data; ++ * when :meth:`flush()` is called; ++ * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects); ++ * when the :class:`BufferedWriter` object is closed or destroyed. ++ + The constructor creates a :class:`BufferedWriter` for the given writeable + *raw* stream. If the *buffer_size* is not given, it defaults to + :data:`DEFAULT_BUFFER_SIZE`. +@@ -547,17 +575,17 @@ + + .. method:: write(b) + +- Write the bytes or bytearray object, *b*, onto the raw stream and return +- the number of bytes written. A :exc:`BlockingIOError` is raised when the +- raw stream blocks. ++ Write the bytes or bytearray object, *b* and return the number of bytes ++ written. When in non-blocking mode, a :exc:`BlockingIOError` is raised ++ if the buffer needs to be written out but the raw stream blocks. + + +-.. class:: BufferedRWPair(reader, writer, buffer_size, max_buffer_size=DEFAULT_BUFFER_SIZE) ++.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE) + +- A combined buffered writer and reader object for a raw stream that can be +- written to and read from. It has and supports both :meth:`read`, :meth:`write`, +- and their variants. This is useful for sockets and two-way pipes. +- It inherits :class:`BufferedIOBase`. ++ 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 +@@ -574,7 +602,8 @@ + .. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE) + + A buffered interface to random access streams. It inherits +- :class:`BufferedReader` and :class:`BufferedWriter`. ++ :class:`BufferedReader` and :class:`BufferedWriter`, and further supports ++ :meth:`seek` and :meth:`tell` functionality. + + The constructor creates a reader and writer for a seekable raw stream, given + in the first argument. If the *buffer_size* is omitted it defaults to +@@ -611,7 +640,8 @@ + .. attribute:: newlines + + A string, a tuple of strings, or ``None``, indicating the newlines +- translated so far. ++ translated so far. Depending on the implementation and the initial ++ constructor flags, this may not be available. + + .. attribute:: buffer + +@@ -621,7 +651,8 @@ + + .. method:: detach() + +- Separate the underlying buffer from the :class:`TextIOBase` and return it. ++ Separate the underlying binary buffer from the :class:`TextIOBase` and ++ return it. + + After the underlying buffer has been detached, the :class:`TextIOBase` is + in an unusable state. +@@ -635,7 +666,7 @@ + .. method:: read(n) + + Read and return at most *n* characters from the stream as a single +- :class:`str`. If *n* is negative or ``None``, reads to EOF. ++ :class:`str`. If *n* is negative or ``None``, reads until EOF. + + .. method:: readline() + +@@ -650,7 +681,7 @@ + + .. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False) + +- A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*. ++ A buffered text stream over a :class:`BufferedIOBase` binary stream. + It inherits :class:`TextIOBase`. + + *encoding* gives the name of the encoding that the stream will be decoded or +Index: Doc/library/functions.rst +=================================================================== +--- Doc/library/functions.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/functions.rst (.../branches/release31-maint) (Revision 76056) +@@ -489,15 +489,22 @@ + expression. If *x* is not a Python :class:`int` object, it has to define an + :meth:`__index__` method that returns an integer. + ++ .. note:: + ++ To obtain a hexadecimal string representation for a float, use the ++ :meth:`float.hex` method. ++ ++ + .. function:: id(object) + + Return the "identity" of an object. This is an integer which + is guaranteed to be unique and constant for this object during its lifetime. +- Two objects with non-overlapping lifetimes may have the same :func:`id` value. +- (Implementation note: this is the address of the object.) ++ Two objects with non-overlapping lifetimes may have the same :func:`id` ++ value. + ++ .. impl-detail:: This is the address of the object. + ++ + .. function:: input([prompt]) + + If the *prompt* argument is present, it is written to standard output without +@@ -595,17 +602,13 @@ + .. function:: locals() + + Update and return a dictionary representing the current local symbol table. ++ Free variables are returned by :func:`locals` when it is called in function ++ blocks, but not in class blocks. + + .. note:: +- + The contents of this dictionary should not be modified; changes may not +- affect the values of local variables used by the interpreter. ++ affect the values of local and free variables used by the interpreter. + +- Free variables are returned by :func:`locals` when it is called in a function +- block. Modifications of free variables may not affect the values used by the +- interpreter. Free variables are not returned in class blocks. +- +- + .. function:: map(function, iterable, ...) + + Return an iterator that applies *function* to every item of *iterable*, +@@ -1167,11 +1170,11 @@ + + .. function:: vars([object]) + +- Without arguments, return a dictionary corresponding to the current local symbol +- table. With a module, class or class instance object as argument (or anything +- else that has a :attr:`__dict__` attribute), returns a dictionary corresponding +- to the object's symbol table. ++ Without an argument, act like :func:`locals`. + ++ With a module, class or class instance object as argument (or anything else that ++ has a :attr:`__dict__` attribute), return that attribute. ++ + .. note:: + The returned dictionary should not be modified: + the effects on the corresponding symbol table are undefined. [#]_ +Index: Doc/library/stat.rst +=================================================================== +--- Doc/library/stat.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/stat.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,9 +1,9 @@ +- + :mod:`stat` --- Interpreting :func:`stat` results + ================================================= + + .. module:: stat +- :synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat(). ++ :synopsis: Utilities for interpreting the results of os.stat(), ++ os.lstat() and os.fstat(). + .. sectionauthor:: Skip Montanaro + + +Index: Doc/library/tkinter.ttk.rst +=================================================================== +--- Doc/library/tkinter.ttk.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/tkinter.ttk.rst (.../branches/release31-maint) (Revision 76056) +@@ -262,7 +262,7 @@ + *x* and *y* are pixel coordinates relative to the widget. + + +- .. method:: instate(statespec[, callback=None[, *args[, **kw]]]) ++ .. method:: instate(statespec, callback=None, *args, **kw) + + Test the widget's state. If a callback is not specified, returns True + if the widget state matches *statespec* and False otherwise. If callback +@@ -270,7 +270,7 @@ + *statespec*. + + +- .. method:: state([statespec=None]) ++ .. method:: state(statespec=None) + + Modify or inquire widget state. If *statespec* is specified, sets the + widget state according to it and return a new *statespec* indicating +@@ -349,7 +349,7 @@ + + .. class:: Combobox + +- .. method:: current([newindex=None]) ++ .. method:: current(newindex=None) + + If *newindex* is specified, sets the combobox value to the element + position *newindex*. Otherwise, returns the index of the current value or +@@ -510,7 +510,7 @@ + See `Tab Options`_ for the list of available options. + + +- .. method:: select([tab_id]) ++ .. method:: select(tab_id=None) + + Selects the specified *tab_id*. + +@@ -519,7 +519,7 @@ + omitted, returns the widget name of the currently selected pane. + + +- .. method:: tab(tab_id[, option=None[, **kw]]) ++ .. method:: tab(tab_id, option=None, **kw) + + Query or modify the options of the specific *tab_id*. + +@@ -600,14 +600,14 @@ + + .. class:: Progressbar + +- .. method:: start([interval]) ++ .. method:: start(interval=None) + + Begin autoincrement mode: schedules a recurring timer event that calls + :meth:`Progressbar.step` every *interval* milliseconds. If omitted, + *interval* defaults to 50 milliseconds. + + +- .. method:: step([amount]) ++ .. method:: step(amount=None) + + Increments the progress bar's value by *amount*. + +@@ -842,7 +842,7 @@ + + .. class:: Treeview + +- .. method:: bbox(item[, column=None]) ++ .. method:: bbox(item, column=None) + + Returns the bounding box (relative to the treeview widget's window) of + the specified *item* in the form (x, y, width, height). +@@ -852,7 +852,7 @@ + scrolled offscreen), returns an empty string. + + +- .. method:: get_children([item]) ++ .. method:: get_children(item=None) + + Returns the list of children belonging to *item*. + +@@ -869,7 +869,7 @@ + *item*'s children. + + +- .. method:: column(column[, option=None[, **kw]]) ++ .. method:: column(column, option=None, **kw) + + Query or modify the options for the specified *column*. + +@@ -918,13 +918,13 @@ + Returns True if the specified *item* is present in the tree. + + +- .. method:: focus([item=None]) ++ .. method:: focus(item=None) + + If *item* is specified, sets the focus item to *item*. Otherwise, returns + the current focus item, or '' if there is none. + + +- .. method:: heading(column[, option=None[, **kw]]) ++ .. method:: heading(column, option=None, **kw) + + Query or modify the heading options for the specified *column*. + +@@ -997,7 +997,7 @@ + Returns the integer index of *item* within its parent's list of children. + + +- .. method:: insert(parent, index[, iid=None[, **kw]]) ++ .. method:: insert(parent, index, iid=None, **kw) + + Creates a new item and returns the item identifier of the newly created + item. +@@ -1014,7 +1014,7 @@ + See `Item Options`_ for the list of available points. + + +- .. method:: item(item[, option[, **kw]]) ++ .. method:: item(item, option=None, **kw) + + Query or modify the options for the specified *item*. + +@@ -1066,7 +1066,7 @@ + the tree. + + +- .. method:: selection([selop=None[, items=None]]) ++ .. method:: selection(selop=None, items=None) + + If *selop* is not specified, returns selected items. Otherwise, it will + act according to the following selection methods. +@@ -1092,7 +1092,7 @@ + Toggle the selection state of each item in *items*. + + +- .. method:: set(item[, column=None[, value=None]]) ++ .. method:: set(item, column=None, value=None) + + With one argument, returns a dictionary of column/value pairs for the + specified *item*. With two arguments, returns the current value of the +@@ -1100,14 +1100,14 @@ + *column* in given *item* to the specified *value*. + + +- .. method:: tag_bind(tagname[, sequence=None[, callback=None]]) ++ .. method:: tag_bind(tagname, sequence=None, callback=None) + + Bind a callback for the given event *sequence* to the tag *tagname*. + When an event is delivered to an item, the callbacks for each of the + item's tags option are called. + + +- .. method:: tag_configure(tagname[, option=None[, **kw]]) ++ .. method:: tag_configure(tagname, option=None, **kw) + + Query or modify the options for the specified *tagname*. + +@@ -1117,7 +1117,7 @@ + corresponding values for the given *tagname*. + + +- .. method:: tag_has(tagname[, item]) ++ .. method:: tag_has(tagname, item=None) + + If *item* is specified, returns 1 or 0 depending on whether the specified + *item* has the given *tagname*. Otherwise, returns a list of all items +@@ -1216,7 +1216,7 @@ + blue foreground when the widget were in active or pressed states. + + +- .. method:: lookup(style, option[, state=None[, default=None]]) ++ .. method:: lookup(style, option, state=None, default=None) + + Returns the value specified for *option* in *style*. + +@@ -1228,10 +1228,10 @@ + + from tkinter import ttk + +- print ttk.Style().lookup("TButton", "font") ++ print(ttk.Style().lookup("TButton", "font")) + + +- .. method:: layout(style[, layoutspec=None]) ++ .. method:: layout(style, layoutspec=None) + + Define the widget layout for given *style*. If *layoutspec* is omitted, + return the layout specification for given style. +@@ -1314,7 +1314,7 @@ + Returns the list of *elementname*'s options. + + +- .. method:: theme_create(themename[, parent=None[, settings=None]]) ++ .. method:: theme_create(themename, parent=None, settings=None) + + Create a new theme. + +@@ -1366,7 +1366,7 @@ + Returns a list of all known themes. + + +- .. method:: theme_use([themename]) ++ .. method:: theme_use(themename=None) + + If *themename* is not given, returns the theme in use. Otherwise, sets + the current theme to *themename*, refreshes all widgets and emits a +Index: Doc/library/zlib.rst +=================================================================== +--- Doc/library/zlib.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/zlib.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,10 +1,9 @@ +- + :mod:`zlib` --- Compression compatible with :program:`gzip` + =========================================================== + + .. module:: zlib +- :synopsis: Low-level interface to compression and decompression routines compatible with +- gzip. ++ :synopsis: Low-level interface to compression and decompression routines ++ compatible with gzip. + + + For applications that require data compression, the functions in this module +Index: Doc/library/copy.rst +=================================================================== +--- Doc/library/copy.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/copy.rst (.../branches/release31-maint) (Revision 76056) +@@ -4,22 +4,26 @@ + .. module:: copy + :synopsis: Shallow and deep copy operations. + ++This module provides generic (shallow and deep) copying operations. + +-.. index:: +- single: copy() (in copy) +- single: deepcopy() (in copy) + +-This module provides generic (shallow and deep) copying operations. ++Interface summary: + +-Interface summary:: ++.. function:: copy(x) + +- import copy ++ Return a shallow copy of *x*. + +- x = copy.copy(y) # make a shallow copy of y +- x = copy.deepcopy(y) # make a deep copy of y + +-For module specific errors, :exc:`copy.error` is raised. ++.. function:: deepcopy(x) + ++ Return a deep copy of *x*. ++ ++ ++.. exception:: error ++ ++ Raised for module specific errors. ++ ++ + The difference between shallow and deep copying is only relevant for compound + objects (objects that contain other objects, like lists or class instances): + +Index: Doc/library/signal.rst +=================================================================== +--- Doc/library/signal.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/signal.rst (.../branches/release31-maint) (Revision 76056) +@@ -157,13 +157,14 @@ + + The old values are returned as a tuple: (delay, interval). + +- Attempting to pass an invalid interval timer will cause a +- :exc:`ItimerError`. ++ Attempting to pass an invalid interval timer will cause an ++ :exc:`ItimerError`. Availability: Unix. + + + .. function:: getitimer(which) + + Returns current value of a given interval timer specified by *which*. ++ Availability: Unix. + + + .. function:: set_wakeup_fd(fd) +@@ -182,14 +183,14 @@ + + .. function:: siginterrupt(signalnum, flag) + +- Change system call restart behaviour: if *flag* is :const:`False`, system calls +- will be restarted when interrupted by signal *signalnum*, otherwise system calls will +- be interrupted. Returns nothing. Availability: Unix (see the man page +- :manpage:`siginterrupt(3)` for further information). ++ Change system call restart behaviour: if *flag* is :const:`False`, system ++ calls will be restarted when interrupted by signal *signalnum*, otherwise ++ system calls will be interrupted. Returns nothing. Availability: Unix (see ++ the man page :manpage:`siginterrupt(3)` for further information). + +- 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. ++ 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. + + + .. function:: signal(signalnum, handler) +@@ -205,9 +206,9 @@ + exception to be raised. + + The *handler* is called with two arguments: the signal number and the current +- stack frame (``None`` or a frame object; for a description of frame objects, see +- the reference manual section on the standard type hierarchy or see the attribute +- descriptions in the :mod:`inspect` module). ++ stack frame (``None`` or a frame object; for a description of frame objects, ++ see the :ref:`description in the type hierarchy ` or see the ++ attribute descriptions in the :mod:`inspect` module). + + + .. _signal-example: +Index: Doc/library/exceptions.rst +=================================================================== +--- Doc/library/exceptions.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/exceptions.rst (.../branches/release31-maint) (Revision 76056) +@@ -52,7 +52,7 @@ + + The base class for all built-in exceptions. It is not meant to be directly + inherited by user-defined classes (for that use :exc:`Exception`). If +- :func:`str` or :func:`unicode` is called on an instance of this class, the ++ :func:`bytes` or :func:`str` is called on an instance of this class, the + representation of the argument(s) to the instance are returned or the empty + string when there were no arguments. All arguments are stored in :attr:`args` + as a tuple. +Index: Doc/library/webbrowser.rst +=================================================================== +--- Doc/library/webbrowser.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/webbrowser.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + :mod:`webbrowser` --- Convenient Web-browser controller + ======================================================= + +@@ -46,7 +45,7 @@ + The following functions are defined: + + +-.. function:: open(url[, new=0[, autoraise=True]]) ++.. function:: open(url, new=0, autoraise=True) + + Display *url* using the default browser. If *new* is 0, the *url* is opened + in the same browser window if possible. If *new* is 1, a new browser window +@@ -72,14 +71,14 @@ + equivalent to :func:`open_new`. + + +-.. function:: get([name]) ++.. function:: get(using=None) + +- Return a controller object for the browser type *name*. If *name* is empty, +- return a controller for a default browser appropriate to the caller's +- environment. ++ Return a controller object for the browser type *using*. If *using* is ++ ``None``, return a controller for a default browser appropriate to the ++ caller's environment. + + +-.. function:: register(name, constructor[, instance]) ++.. function:: register(name, constructor, instance=None) + + Register the browser type *name*. Once a browser type is registered, the + :func:`get` function can return a controller for that browser type. If +@@ -175,7 +174,7 @@ + module-level convenience functions: + + +-.. method:: controller.open(url[, new[, autoraise=True]]) ++.. method:: controller.open(url, new=0, autoraise=True) + + Display *url* using the browser handled by this controller. If *new* is 1, a new + browser window is opened if possible. If *new* is 2, a new browser page ("tab") +Index: Doc/library/http.client.rst +=================================================================== +--- Doc/library/http.client.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/http.client.rst (.../branches/release31-maint) (Revision 76056) +@@ -384,7 +384,7 @@ + Set the debugging level (the amount of debugging output printed). The default + debug level is ``0``, meaning no debugging output is printed. + +- .. versionadded:: 2.7 ++ .. versionadded:: 3.1 + + + .. method:: HTTPConnection.connect() +Index: Doc/library/getopt.rst +=================================================================== +--- Doc/library/getopt.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/getopt.rst (.../branches/release31-maint) (Revision 76056) +@@ -36,12 +36,13 @@ + *longopts*, if specified, must be a list of strings with the names of the + long options which should be supported. The leading ``'--'`` characters + should not be included in the option name. Long options which require an +- argument should be followed by an equal sign (``'='``). To accept only long +- options, *shortopts* should be an empty string. Long options on the command line +- can be recognized so long as they provide a prefix of the option name that +- matches exactly one of the accepted options. For example, if *longopts* is +- ``['foo', 'frob']``, the option :option:`--fo` will match as :option:`--foo`, +- but :option:`--f` will not match uniquely, so :exc:`GetoptError` will be raised. ++ argument should be followed by an equal sign (``'='``). Optional arguments ++ are not supported. To accept only long options, *shortopts* should be an ++ empty string. Long options on the command line can be recognized so long as ++ they provide a prefix of the option name that matches exactly one of the ++ accepted options. For example, if *longopts* is ``['foo', 'frob']``, the ++ option :option:`--fo` will match as :option:`--foo`, but :option:`--f` will ++ not match uniquely, so :exc:`GetoptError` will be raised. + + The return value consists of two elements: the first is a list of ``(option, + value)`` pairs; the second is the list of program arguments left after the +Index: Doc/library/_thread.rst +=================================================================== +--- Doc/library/_thread.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/_thread.rst (.../branches/release31-maint) (Revision 76056) +@@ -147,7 +147,7 @@ + module is available, interrupts always go to the main thread.) + + * Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is +- equivalent to calling :func:`exit`. ++ equivalent to calling :func:`_thread.exit`. + + * Not all built-in functions that may block waiting for I/O allow other threads + to run. (The most popular ones (:func:`time.sleep`, :meth:`file.read`, +Index: Doc/library/unix.rst +=================================================================== +--- Doc/library/unix.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/unix.rst (.../branches/release31-maint) (Revision 76056) +@@ -1,4 +1,3 @@ +- + .. _unix: + + ********************** +Index: Doc/library/math.rst +=================================================================== +--- Doc/library/math.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/math.rst (.../branches/release31-maint) (Revision 76056) +@@ -150,10 +150,12 @@ + + .. function:: log(x[, base]) + +- Return the logarithm of *x* to the given *base*. If the *base* is not specified, +- return the natural logarithm of *x* (that is, the logarithm to base *e*). ++ With one argument, return the natural logarithm of *x* (to base *e*). + ++ With two arguments, return the logarithm of *x* to the given *base*, ++ calculated as ``log(x)/log(base)``. + ++ + .. function:: log1p(x) + + Return the natural logarithm of *1+x* (base *e*). The +@@ -162,7 +164,8 @@ + + .. function:: log10(x) + +- Return the base-10 logarithm of *x*. ++ Return the base-10 logarithm of *x*. This is usually more accurate ++ than ``log(x, 10)``. + + + .. function:: pow(x, y) +@@ -288,7 +291,7 @@ + The mathematical constant *e*. + + +-.. note:: ++.. impl-detail:: + + The :mod:`math` module consists mostly of thin wrappers around the platform C + math library functions. Behavior in exceptional cases is loosely specified +Index: Doc/library/cgi.rst +=================================================================== +--- Doc/library/cgi.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/cgi.rst (.../branches/release31-maint) (Revision 76056) +@@ -208,7 +208,7 @@ + provide valid input to your scripts. For example, if a curious user appends + another ``user=foo`` pair to the query string, then the script would crash, + because in this situation the ``getvalue("user")`` method call returns a list +-instead of a string. Calling the :meth:`toupper` method on a list is not valid ++instead of a string. Calling the :meth:`~str.upper` method on a list is not valid + (since lists do not have a method of this name) and results in an + :exc:`AttributeError` exception. + +Index: Doc/library/threading.rst +=================================================================== +--- Doc/library/threading.rst (.../tags/r311) (Revision 76056) ++++ Doc/library/threading.rst (.../branches/release31-maint) (Revision 76056) +@@ -23,7 +23,7 @@ + .. function:: active_count() + + Return the number of :class:`Thread` objects currently alive. The returned +- count is equal to the length of the list returned by :func:`enumerate`. ++ count is equal to the length of the list returned by :func:`.enumerate`. + + + .. function:: Condition() +@@ -89,7 +89,7 @@ + thread must release it once for each time it has acquired it. + + +-.. function:: Semaphore([value]) ++.. function:: Semaphore(value=1) + :noindex: + + A factory function that returns a new semaphore object. A semaphore manages a +@@ -99,7 +99,7 @@ + given, *value* defaults to 1. + + +-.. function:: BoundedSemaphore([value]) ++.. function:: BoundedSemaphore(value=1) + + A factory function that returns a new bounded semaphore object. A bounded + semaphore checks to make sure its current value doesn't exceed its initial +@@ -253,7 +253,7 @@ + the *target* argument, if any, with sequential and keyword arguments taken + from the *args* and *kwargs* arguments, respectively. + +- .. method:: join([timeout]) ++ .. method:: join(timeout=None) + + Wait until the thread terminates. This blocks the calling thread until the + thread whose :meth:`join` method is called terminates -- either normally +@@ -301,7 +301,7 @@ + + Roughly, a thread is alive from the moment the :meth:`start` method + returns until its :meth:`run` method terminates. The module function +- :func:`enumerate` returns a list of all alive threads. ++ :func:`.enumerate` returns a list of all alive threads. + + .. attribute:: daemon + +@@ -349,7 +349,7 @@ + All methods are executed atomically. + + +-.. method:: Lock.acquire([blocking=1]) ++.. method:: Lock.acquire(blocking=True) + + Acquire a lock, blocking or non-blocking. + +@@ -396,7 +396,7 @@ + :meth:`acquire` to proceed. + + +-.. method:: RLock.acquire([blocking=1]) ++.. method:: RLock.acquire(blocking=True) + + Acquire a lock, blocking or non-blocking. + +@@ -487,7 +487,7 @@ + needs to wake up one consumer thread. + + +-.. class:: Condition([lock]) ++.. class:: Condition(lock=None) + + If the *lock* argument is given and not ``None``, it must be a :class:`Lock` + or :class:`RLock` object, and it is used as the underlying lock. Otherwise, +@@ -503,7 +503,7 @@ + Release the underlying lock. This method calls the corresponding method on + the underlying lock; there is no return value. + +- .. method:: wait([timeout]) ++ .. method:: wait(timeout=None) + + Wait until notified or until a timeout occurs. If the calling thread has + not acquired the lock when this method is called, a :exc:`RuntimeError` is +@@ -566,13 +566,13 @@ + waiting until some other thread calls :meth:`release`. + + +-.. class:: Semaphore([value]) ++.. class:: Semaphore(value=1) + + The optional argument gives the initial *value* for the internal counter; it + defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is + raised. + +- .. method:: acquire([blocking]) ++ .. method:: acquire(blocking=True) + + Acquire a semaphore. + +@@ -659,7 +659,7 @@ + :meth:`wait` will block until :meth:`.set` is called to set the internal + flag to true again. + +- .. method:: wait([timeout]) ++ .. method:: wait(timeout=None) + + Block until the internal flag is true. If the internal flag is true on + entry, return immediately. Otherwise, block until another thread calls +Index: Doc/contents.rst +=================================================================== +--- Doc/contents.rst (.../tags/r311) (Revision 76056) ++++ Doc/contents.rst (.../branches/release31-maint) (Revision 76056) +@@ -15,6 +15,7 @@ + install/index.rst + documenting/index.rst + howto/index.rst ++ faq/index.rst + glossary.rst + + about.rst +Index: Doc/includes/mp_pool.py +=================================================================== +--- Doc/includes/mp_pool.py (.../tags/r311) (Revision 76056) ++++ Doc/includes/mp_pool.py (.../branches/release31-maint) (Revision 76056) +@@ -98,17 +98,17 @@ + + t = time.time() + A = list(map(pow3, range(N))) +- print('\tmap(pow3, xrange(%d)):\n\t\t%s seconds' % \ ++ print('\tmap(pow3, range(%d)):\n\t\t%s seconds' % \ + (N, time.time() - t)) + + t = time.time() + B = pool.map(pow3, range(N)) +- print('\tpool.map(pow3, xrange(%d)):\n\t\t%s seconds' % \ ++ print('\tpool.map(pow3, range(%d)):\n\t\t%s seconds' % \ + (N, time.time() - t)) + + t = time.time() + C = list(pool.imap(pow3, range(N), chunksize=N//8)) +- print('\tlist(pool.imap(pow3, xrange(%d), chunksize=%d)):\n\t\t%s' \ ++ print('\tlist(pool.imap(pow3, range(%d), chunksize=%d)):\n\t\t%s' \ + ' seconds' % (N, N//8, time.time() - t)) + + assert A == B == C, (len(A), len(B), len(C)) +Index: Doc/includes/shoddy.c +=================================================================== +--- Doc/includes/shoddy.c (.../tags/r311) (Revision 76056) ++++ Doc/includes/shoddy.c (.../branches/release31-maint) (Revision 76056) +@@ -95,4 +95,5 @@ + + Py_INCREF(&ShoddyType); + PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType); ++ return m; + } +Index: Doc/install/index.rst +=================================================================== +--- Doc/install/index.rst (.../tags/r311) (Revision 76056) ++++ Doc/install/index.rst (.../branches/release31-maint) (Revision 76056) +@@ -703,7 +703,8 @@ + (2) + On Unix, if the :envvar:`HOME` environment variable is not defined, the user's + home directory will be determined with the :func:`getpwuid` function from the +- standard :mod:`pwd` module. ++ standard :mod:`pwd` module. This is done by the :func:`os.path.expanduser` ++ function used by Distutils. + + (3) + I.e., in the current directory (usually the location of the setup script). +@@ -718,9 +719,10 @@ + 1.5.2 installation under Windows. + + (5) +- On Windows, if the :envvar:`HOME` environment variable is not defined, no +- personal configuration file will be found or used. (In other words, the +- Distutils make no attempt to guess your home directory on Windows.) ++ On Windows, if the :envvar:`HOME` environment variable is not defined, ++ :envvar:`USERPROFILE` then :envvar:`HOMEDRIVE` and :envvar:`HOMEPATH` will ++ be tried. This is done by the :func:`os.path.expanduser` function used ++ by Distutils. + + + .. _inst-config-syntax: +@@ -935,7 +937,8 @@ + These compilers require some special libraries. This task is more complex than + for Borland's C++, because there is no program to convert the library. First + you have to create a list of symbols which the Python DLL exports. (You can find +-a good program for this task at http://www.emmestech.com/software/cygwin/pexports-0.43/download_pexports.html) ++a good program for this task at ++http://www.emmestech.com/software/pexports-0.43/download_pexports.html). + + .. I don't understand what the next line means. --amk + .. (inclusive the references on data structures.) +Index: Doc/faq/design.rst +=================================================================== +--- Doc/faq/design.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/design.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,925 @@ ++====================== ++Design and History FAQ ++====================== ++ ++Why does Python use indentation for grouping of statements? ++----------------------------------------------------------- ++ ++Guido van Rossum believes 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 awhile. ++ ++Since there are no begin/end brackets there cannot be a disagreement between ++grouping perceived by the parser and the human reader. Occasionally C ++programmers will encounter a fragment of code like this:: ++ ++ if (x <= y) ++ x++; ++ y--; ++ z++; ++ ++Only the ``x++`` statement is executed if the condition is true, but the ++indentation leads you to believe otherwise. Even experienced C programmers will ++sometimes stare at it a long time wondering why ``y`` is being decremented even ++for ``x > y``. ++ ++Because there are no begin/end brackets, Python is much less prone to ++coding-style conflicts. In C there are many different ways to place the braces. ++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 of a program. Ideally, a function should fit on one ++screen (say, 20-30 lines). 20 lines of Python can do a lot more work than 20 ++lines of C. This is not solely due to the lack of begin/end brackets -- the ++lack of declarations and the high-level data types are also responsible -- but ++the indentation-based syntax certainly helps. ++ ++ ++Why am I getting strange results with simple arithmetic operations? ++------------------------------------------------------------------- ++ ++See the next question. ++ ++ ++Why are floating point calculations so inaccurate? ++-------------------------------------------------- ++ ++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. This has nothing to do with Python, ++but with how the underlying C platform handles floating point numbers, and ++ultimately with the inaccuracies introduced when writing down numbers as a ++string of a fixed number of digits. ++ ++The internal representation of floating point numbers uses a fixed number of ++binary digits to represent a decimal number. Some decimal numbers can't be ++represented exactly in binary, resulting in small roundoff errors. ++ ++In decimal math, there are many numbers that can't be represented with a fixed ++number of decimal digits, e.g. 1/3 = 0.3333333333....... ++ ++In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc. .2 equals 2/10 equals 1/5, ++resulting in the binary fractional number 0.001100110011001... ++ ++Floating point numbers only have 32 or 64 bits of precision, so the digits are ++cut off at some point, and the resulting number is 0.199999999999999996 in ++decimal, not 0.2. ++ ++A floating point number's ``repr()`` function prints as many digits are ++necessary to make ``eval(repr(f)) == f`` true for any float f. The ``str()`` ++function prints fewer digits and this often results in the more sensible number ++that was probably intended:: ++ ++ >>> 0.2 ++ 0.20000000000000001 ++ >>> print 0.2 ++ 0.2 ++ ++One of the consequences of this is that it is error-prone to compare the result ++of some computation to a float with ``==``. Tiny inaccuracies may mean that ++``==`` fails. Instead, you have to check that the difference between the two ++numbers is less than a certain threshold:: ++ ++ epsilon = 0.0000000000001 # Tiny allowed error ++ expected_result = 0.4 ++ ++ if expected_result-epsilon <= computation() <= expected_result+epsilon: ++ ... ++ ++Please see the chapter on :ref:`floating point arithmetic ` in ++the Python tutorial for more information. ++ ++ ++Why are Python strings immutable? ++--------------------------------- ++ ++There are several advantages. ++ ++One is performance: knowing that a string is immutable means we can allocate ++space for it at creation time, and the storage requirements are fixed and ++unchanging. This is also one of the reasons for the distinction between tuples ++and lists. ++ ++Another advantage 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. ++ ++ ++.. _why-self: ++ ++Why must 'self' be used explicitly in method definitions and calls? ++------------------------------------------------------------------- ++ ++The idea was borrowed from Modula-3. It turns out to be very useful, for a ++variety of reasons. ++ ++First, it's 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. Some C++ and Java coding standards ++call for instance attributes to have an ``m_`` prefix, so this explicitness is ++still useful in those languages, too. ++ ++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 a base class which is overridden in a derived class, you have ++to use the ``::`` operator -- in Python you can write baseclass.methodname(self, ++). This is particularly useful for :meth:`__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. ++ ++Finally, 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. To put it another way, local variables ++and instance variables live in two different namespaces, and you need to tell ++Python which namespace to use. ++ ++ ++Why can't I use an assignment in an expression? ++----------------------------------------------- ++ ++Many people used to C or Perl complain that they want to use this C idiom: ++ ++.. code-block:: c ++ ++ while (line = readline(f)) { ++ // do something with line ++ } ++ ++where in Python you're forced to write this:: ++ ++ while True: ++ line = f.readline() ++ if not line: ++ break ++ ... # do something with line ++ ++The reason for not allowing assignment in Python expressions is a common, ++hard-to-find bug in those other languages, caused by this construct: ++ ++.. code-block:: c ++ ++ if (x = 0) { ++ // error handling ++ } ++ else { ++ // code that only works for nonzero x ++ } ++ ++The error is a simple typo: ``x = 0``, which assigns 0 to the variable ``x``, ++was written while the comparison ``x == 0`` is certainly what was intended. ++ ++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 for ++language change proposals: it should intuitively suggest the proper meaning to a ++human reader who has not yet been introduced to the construct. ++ ++An interesting phenomenon is that most experienced Python programmers recognize ++the ``while True`` idiom and don't seem to be missing the assignment in ++expression construct much; it's only newcomers who express a strong desire to ++add this to the language. ++ ++There's an alternative way of spelling this that seems attractive but is ++generally less robust than the "while True" 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 occurrence ++is hidden at the bottom of the loop. ++ ++The best approach is to use iterators, making it possible to loop through ++objects using the ``for`` statement. For example, in the current version of ++Python file objects support the iterator protocol, so you can now write simply:: ++ ++ for line in f: ++ ... # do something with line... ++ ++ ++ ++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. 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 ++make such fundamental changes now. The functions have to remain to avoid massive ++code breakage. ++ ++.. XXX talk about protocols? ++ ++Note that for string operations Python has moved from external functions (the ++``string`` module) to methods. However, ``len()`` is still a function. ++ ++ ++Why is join() a string method instead of a list or tuple method? ++---------------------------------------------------------------- ++ ++Strings became much more like other standard types starting in Python 1.6, when ++methods were added which give the same functionality that has always been ++available using the functions of the string module. Most of 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 common 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. ++ ++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 :meth:`~str.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. ++ ++:meth:`~str.join` is a string method because in using it you are telling the ++separator string to iterate over a sequence of strings and insert itself between ++adjacent elements. This method can be used with any argument which obeys the ++rules for sequence objects, including 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. ++ ++.. XXX remove next paragraph eventually ++ ++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'], ", ") ++ ++ ++How fast are exceptions? ++------------------------ ++ ++A try/except block is extremely efficient. Actually catching an exception is ++expensive. In versions of Python prior to 2.0 it was common to use this idiom:: ++ ++ try: ++ value = dict[key] ++ except KeyError: ++ dict[key] = getvalue(key) ++ value = dict[key] ++ ++This only made sense when you expected the dict to have the key almost all the ++time. If that wasn't the case, 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, you can code this as ``value = dict.setdefault(key, ++getvalue(key))``.) ++ ++ ++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. See :pep:`275` for ++complete details and the current status. ++ ++For cases where you need to choose from a very large number of possibilities, ++you can create a dictionary mapping case values to functions to call. For ++example:: ++ ++ def function_1(...): ++ ... ++ ++ functions = {'a': function_1, ++ 'b': function_2, ++ 'c': self.method_1, ...} ++ ++ func = functions[value] ++ func() ++ ++For calling methods on objects, you can simplify yet further by using the ++:func:`getattr` built-in to retrieve methods with a particular name:: ++ ++ def visit_a(self, ...): ++ ... ++ ... ++ ++ def dispatch(self, value): ++ method_name = 'visit_' + str(value) ++ method = getattr(self, method_name) ++ method() ++ ++It's suggested that you use a prefix for the method names, such as ``visit_`` in ++this example. Without such a prefix, if values are coming from an untrusted ++source, an attacker would be able to call any method on your object. ++ ++ ++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. ++ ++ ++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! ++ ++ ++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 :func:`eval` or :keyword:`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). Jython 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 proceedings ++from the `1997 Python conference ++`_ for more information.) ++ ++Internally, Python source code is always translated into a bytecode ++representation, and this bytecode is then executed by the Python virtual ++machine. In order to avoid the overhead of repeatedly parsing and translating ++modules that rarely change, this byte code is written into a file whose name ++ends in ".pyc" whenever a module is parsed. When the corresponding .py file is ++changed, it is parsed and translated again and the .pyc file is rewritten. ++ ++There is no performance difference once the .pyc file has been loaded, as the ++bytecode read from the .pyc file is exactly the same as the bytecode created by ++direct translation. The only difference is that loading code from a .pyc file ++is faster than parsing and translating a .py file, so the presence of ++precompiled .pyc files improves the start-up time of Python scripts. If ++desired, the Lib/compileall.py module can be used to create valid .pyc files for ++a given set of modules. ++ ++Note that the main script executed by Python, even if its filename ends in .py, ++is not compiled to a .pyc file. It is compiled to bytecode, but the bytecode is ++not saved to a file. Usually main scripts are quite short, so this doesn't cost ++much speed. ++ ++.. XXX check which of these projects are still alive ++ ++There are also several programs which make it easier to intermingle Python and C ++code in various ways to increase performance. See, for example, `Psyco ++`_, `Pyrex ++`_, `PyInline ++`_, `Py2Cmod ++`_, and `Weave ++`_. ++ ++ ++How does Python manage memory? ++------------------------------ ++ ++The details of Python memory management depend on the implementation. The ++standard C implementation of Python uses reference counting to detect ++inaccessible objects, and another mechanism to collect reference cycles, ++periodically executing a cycle detection algorithm which looks for inaccessible ++cycles and deletes the objects involved. The :mod:`gc` module provides functions ++to perform a garbage collection, obtain debugging statistics, and tune the ++collector's parameters. ++ ++Jython relies on the Java runtime so the JVM's garbage collector is used. This ++difference can cause some subtle porting problems if your Python code depends on ++the behavior of the reference counting implementation. ++ ++Sometimes objects get stuck in tracebacks temporarily and hence are not ++deallocated when you might expect. Clear the tracebacks with:: ++ ++ import sys ++ sys.exc_clear() ++ sys.exc_traceback = sys.last_traceback = None ++ ++Tracebacks are used for reporting errors, implementing debuggers and related ++things. They contain a portion of the program state extracted during the ++handling of an exception (usually the most recent exception). ++ ++In the absence of circularities and tracebacks, Python programs need not ++explicitly manage memory. ++ ++Why doesn't Python use a more traditional garbage collection scheme? For one ++thing, this is not a C standard feature and hence it's not portable. (Yes, we ++know about the Boehm GC library. It has bits of assembler code for *most* ++common platforms, not for all of them, and although it is mostly transparent, it ++isn't completely transparent; patches are required to get Python to work with ++it.) ++ ++Traditional GC also becomes a problem when Python is embedded into other ++applications. While in a standalone Python it's fine to replace the standard ++malloc() and free() with versions provided by the GC library, an application ++embedding Python may want to have its *own* substitute for malloc() and free(), ++and may not want Python's. Right now, Python works with anything that ++implements malloc() and free() properly. ++ ++In Jython, the following code (which is fine in CPython) will probably run out ++of file descriptors long before it runs out of memory:: ++ ++ for file in : ++ f = open(file) ++ c = f.read(1) ++ ++Using the current reference counting and destructor scheme, each new assignment ++to f closes the previous file. Using GC, this is not guaranteed. If you want ++to write code that will work with any Python implementation, you should ++explicitly close the file; this will work regardless of GC:: ++ ++ for file in : ++ f = open(file) ++ c = f.read(1) ++ f.close() ++ ++ ++Why isn't all memory freed when Python exits? ++--------------------------------------------- ++ ++Objects referenced from the global namespaces of Python modules are not always ++deallocated when Python exits. This may happen if there are circular ++references. 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). Python is, however, aggressive about cleaning up memory on exit and ++does try to destroy every single object. ++ ++If you want to force Python to delete certain things on deallocation use the ++:mod:`atexit` module to run a function that will force those deletions. ++ ++ ++Why are there separate tuple and list data types? ++------------------------------------------------- ++ ++Lists and tuples, while similar in many respects, are generally used in ++fundamentally different ways. Tuples can be thought of as being similar to ++Pascal records or C structs; they're small collections of related data which may ++be of different types which are operated on as a group. For example, a ++Cartesian coordinate is appropriately represented as a tuple of two or three ++numbers. ++ ++Lists, on the other hand, are more like arrays in other languages. They tend to ++hold a varying number of objects all of which have the same type and which are ++operated on one-by-one. For example, ``os.listdir('.')`` returns a list of ++strings representing the files in the current directory. Functions which ++operate on this output would generally not break if you added another file or ++two to the directory. ++ ++Tuples are immutable, meaning that once a tuple has been created, you can't ++replace any of its elements with a new value. Lists are mutable, meaning that ++you can always change a list's elements. Only immutable elements can be used as ++dictionary keys, and hence only tuples and not lists can be used as keys. ++ ++ ++How are lists implemented? ++-------------------------- ++ ++Python's lists are really variable-length arrays, not Lisp-style linked lists. ++The implementation uses a contiguous array of references to other objects, and ++keeps a pointer to this array and the array's 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. ++ ++ ++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. ++ ++Dictionaries work by computing a hash code for each key stored in the dictionary ++using the :func:`hash` built-in function. The hash code varies widely depending ++on the key; for example, "Python" hashes to -539294296 while "python", a string ++that differs by a single bit, hashes to 1142331976. The hash code is then used ++to calculate a location in an internal array where the value will be stored. ++Assuming that you're storing keys that all have different hash values, this ++means that dictionaries take constant time -- O(1), in computer science notation ++-- to retrieve a key. It also means that no sorted order of the keys is ++maintained, and traversing the array as the ``.keys()`` and ``.items()`` do will ++output the dictionary's content in some arbitrary jumbled order. ++ ++ ++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 also change. But since whoever changes ++the key object can't tell that it was being used as a dictionary key, 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 because its hash value is different. ++If you tried to look up the old value it wouldn't be found either, because the ++value of the object found in that hash bin would be different. ++ ++If you want a dictionary indexed with a list, simply convert the list to a tuple ++first; the function ``tuple(L)`` creates a tuple with the same entries as the ++list ``L``. Tuples are immutable and can therefore be used as dictionary keys. ++ ++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]] ++ ++ would 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 :keyword:`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 when you forgot or modified a list by ++ accident. It also 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. ++ ++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 ++:meth:`__cmp_` and a :meth:`__hash__` method. You must then 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). :: ++ ++ 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. ++ ++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 will misbehave. ++ ++In the case of ListWrapper, 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. Consider yourself warned. ++ ++ ++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, :meth:`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. ++ ++In Python 2.4 a new builtin -- :func:`sorted` -- has been added. This function ++creates a new list from a provided iterable, sorts it and returns it. For ++example, here's how to iterate over the keys of a dictionary in sorted order:: ++ ++ for key in sorted(dict.iterkeys()): ++ ... # do whatever with dict[key]... ++ ++ ++How do you specify and enforce an interface spec in Python? ++----------------------------------------------------------- ++ ++An interface 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 helps in the ++construction of large programs. ++ ++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 ++:class:`Iterable`, :class:`Container`, and :class:`MutableMapping`. ++ ++For Python, many of the advantages of interface specifications can be obtained ++by an appropriate test discipline for components. There is also a tool, ++PyChecker, which can be used to find problems due to subclassing. ++ ++A good test suite for a module can both provide a regression test and serve as a ++module interface specification and a set of examples. Many Python modules can ++be run as a script to provide 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. The :mod:`doctest` and ++:mod:`unittest` modules or third-party test frameworks can be used to construct ++exhaustive test suites that exercise every line of code in a module. ++ ++An appropriate testing discipline can help build large complex applications in ++Python as well as having interface specifications would. In fact, it can be ++better because an interface specification cannot test certain properties of a ++program. For example, the :meth:`append` method is expected to add new elements ++to the end of some internal list; an interface specification cannot test that ++your :meth:`append` implementation will actually do this correctly, but it's ++trivial to check this property in a test suite. ++ ++Writing test suites is very helpful, and you might want to design your code with ++an eye to making it easily tested. One increasingly popular technique, ++test-directed development, calls for writing parts of the test suite first, ++before you write any of the actual code. Of course Python allows you to be ++sloppy and not write test cases at all. ++ ++ ++Why are default values shared between objects? ++---------------------------------------------- ++ ++This type of bug commonly bites neophyte programmers. Consider this function:: ++ ++ def foo(D={}): # Danger: shared reference to one dict for all calls ++ ... compute something ... ++ D[key] = value ++ return D ++ ++The first time you call this function, ``D`` contains a single item. The second ++time, ``D`` contains two items because when ``foo()`` begins executing, ``D`` ++starts out with an item already in it. ++ ++It is often expected that a function call creates new objects for default ++values. This is not what happens. Default values are created exactly once, when ++the function is defined. If that object is changed, like the dictionary in this ++example, subsequent calls to the function will refer to this changed object. ++ ++By definition, immutable objects such as numbers, strings, tuples, and ``None``, ++are safe from change. Changes to mutable objects such as dictionaries, lists, ++and class instances can lead to confusion. ++ ++Because of this feature, it is good programming practice to not use mutable ++objects as default values. Instead, use ``None`` as the default value and ++inside the function, check if the parameter is ``None`` and create a new ++list/dictionary/whatever if it is. For example, don't write:: ++ ++ def foo(dict={}): ++ ... ++ ++but:: ++ ++ def foo(dict=None): ++ if dict is None: ++ dict = {} # create a new dict for local namespace ++ ++This feature can be useful. When you have a function that's time-consuming to ++compute, a common technique is to cache the parameters and the resulting value ++of each call to the function, and return the cached value if the same value is ++requested again. This is called "memoizing", and can be implemented like this:: ++ ++ # Callers will never provide a third parameter for this function. ++ def expensive (arg1, arg2, _cache={}): ++ if _cache.has_key((arg1, arg2)): ++ return _cache[(arg1, arg2)] ++ ++ # Calculate the value ++ result = ... expensive computation ... ++ _cache[(arg1, arg2)] = result # Store result in the cache ++ return result ++ ++You could use a global variable containing a dictionary instead of the default ++value; it's a matter of taste. ++ ++ ++Why is there no goto? ++--------------------- ++ ++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. ++ ++ ++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\\" ++ ++ ++Why doesn't Python have a "with" statement for attribute assignments? ++--------------------------------------------------------------------- ++ ++Python has a 'with' statement that wraps the execution of a block, calling code ++on the entrance and exit from the block. Some language have a construct that ++looks like this:: ++ ++ with obj: ++ a = 1 # equivalent to obj.a = 1 ++ total = total + 1 # obj.total = obj.total + 1 ++ ++In Python, such a construct would be ambiguous. ++ ++Other languages, such as Object Pascal, Delphi, and C++, use static types, so ++it's possible to know, in an unambiguous way, what member is being assigned ++to. This is the main point of static typing -- 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 makes 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 incomplete snippet:: ++ ++ def foo(a): ++ with a: ++ print x ++ ++The snippet assumes that "a" must have a member attribute called "x". However, ++there is nothing in Python that tells the interpreter this. What should happen ++if "a" is, let us say, an integer? If there is a global variable named "x", ++will it be 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 ++ ++write this:: ++ ++ ref = function(args).dict[index][index] ++ ref.a = 21 ++ ref.b = 42 ++ ref.c = 63 ++ ++This also has the side-effect of increasing execution speed because name ++bindings are resolved at run-time in Python, and the second version 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. ++ ++ ++Why are colons required for the if/while/def/class statements? ++-------------------------------------------------------------- ++ ++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 this FAQ answer; it's a standard usage in English. ++ ++Another minor reason is that the colon makes it easier for editors with syntax ++highlighting; they can look for colons to decide when indentation needs to be ++increased instead of having to do a more elaborate parsing of the program text. ++ ++ ++Why does Python allow commas at the end of lists and tuples? ++------------------------------------------------------------ ++ ++Python lets you add a trailing comma at the end of lists, tuples, and ++dictionaries:: ++ ++ [1, 2, 3,] ++ ('a', 'b', 'c',) ++ d = { ++ "A": [1, 5], ++ "B": [6, 7], # last trailing comma is optional but good style ++ } ++ ++ ++There are several reasons to allow this. ++ ++When you have a literal value for a list, tuple, or dictionary spread across ++multiple lines, it's easier to add more elements because you don't have to ++remember to add a comma to the previous line. The lines can also be sorted in ++your editor without creating a syntax error. ++ ++Accidentally omitting the comma can lead to errors that are hard to diagnose. ++For example:: ++ ++ x = [ ++ "fee", ++ "fie" ++ "foo", ++ "fum" ++ ] ++ ++This list looks like it has four elements, but it actually contains three: ++"fee", "fiefoo" and "fum". Always adding the comma avoids this source of error. ++ ++Allowing the trailing comma may also make programmatic code generation easier. + +Eigenschaftsänderungen: Doc/faq/design.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/windows.rst +=================================================================== +--- Doc/faq/windows.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/windows.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,607 @@ ++:tocdepth: 2 ++ ++.. _windows-faq: ++ ++===================== ++Python on Windows FAQ ++===================== ++ ++.. contents:: ++ ++How do I run a Python program under Windows? ++-------------------------------------------- ++ ++This is not necessarily a straightforward question. If you are already familiar ++with running programs from the Windows command line then everything will seem ++obvious; otherwise, you might need a little more guidance. There are also ++differences between Windows 95, 98, NT, ME, 2000 and XP which can add to the ++confusion. ++ ++.. sidebar:: |Python Development on XP|_ ++ :subtitle: `Python Development on XP`_ ++ ++ This series of screencasts aims to get you up and running with Python on ++ Windows XP. The knowledge is distilled into 1.5 hours and will get you up ++ and running with the right Python distribution, coding in your choice of IDE, ++ and debugging and writing solid code with unit-tests. ++ ++.. |Python Development on XP| image:: python-video-icon.png ++.. _`Python Development on XP`: ++ http://www.showmedo.com/videos/series?name=pythonOzsvaldPyNewbieSeries ++ ++Unless you use some sort of integrated development environment, 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 the menu selection is :menuselection:`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 called the Python interpreter. The interpreter reads your script, ++compiles it into bytecodes, 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. You should 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. ++ >>> ++ ++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. Check it ++by entering a few expressions of your choice and seeing the results:: ++ ++ >>> print "Hello" ++ Hello ++ >>> "Hello" * 3 ++ HelloHelloHello ++ ++Many people use the interactive mode as a convenient yet highly programmable ++calculator. When you want to end your interactive Python session, 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 :menuselection:`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 Ctrl-Z character; Windows is running a single "python" ++command in the window, and closes it 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. ++ ++.. sidebar:: |Adding Python to DOS Path|_ ++ :subtitle: `Adding Python to DOS Path`_ ++ ++ Python is not added to the DOS path by default. This screencast will walk ++ you through the steps to add the correct entry to the `System Path`, allowing ++ Python to be executed from the command-line by all users. ++ ++.. |Adding Python to DOS Path| image:: python-video-icon.png ++.. _`Adding Python to DOS Path`: ++ http://showmedo.com/videos/video?name=960000&fromSeriesID=96 ++ ++ ++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 PATH, which is ++a list of directories where Windows will look for programs. ++ ++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; the usual location is something ++like ``C:\Python23``. Otherwise you will be reduced to a search of your whole ++disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search` ++button and look for "python.exe". Supposing you discover that Python is ++installed in the ``C:\Python23`` directory (the default at the time of writing), ++you should make sure that entering the command :: ++ ++ c:\Python23\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:\Python23;%PATH% ++ ++For Windows NT, 2000 and (I assume) XP, you will need to add a string such as :: ++ ++ ;C:\Python23 ++ ++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 want to reboot your system to make absolutely sure the new ++setting has taken effect. You probably won't need to reboot 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. ++ ++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. Take a look at :: ++ ++ python --help ++ ++ if your needs are complex. ++ ++4. Interactive mode (where you see the ``>>>`` prompt) is best used for checking ++ that individual statements and expressions do what you think they will, and ++ for developing code by experiment. ++ ++ ++How do I make python scripts executable? ++---------------------------------------- ++ ++On Windows 2000, the standard Python 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. ++ ++On Windows NT, the steps taken by the installer as described above allow you to ++run a script with 'foo.py', but a longtime 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. ++ ++The 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 ++ ++ ++Why does Python sometimes take so long to start? ++------------------------------------------------ ++ ++Usually Python starts very quickly on Windows, but occasionally there are bug ++reports that Python suddenly begins to take a long time to start up. This is ++made even more puzzling because Python will work fine on other Windows systems ++which appear to be configured identically. ++ ++The problem may be caused by a misconfiguration of virus checking software on ++the problem machine. Some virus scanners have been known to introduce startup ++overhead of two orders of magnitude when the scanner is configured to monitor ++all reads from the filesystem. Try checking the configuration of virus scanning ++software on your systems to ensure that they are indeed configured identically. ++McAfee, when configured to scan all file system read activity, is a particular ++offender. ++ ++ ++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, at least 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/source). The freeze program is in the ++``Tools\freeze`` subdirectory of the source tree. ++ ++You need the Microsoft VC++ compiler, and you probably need to build Python. ++The required project files are in the PCbuild directory. ++ ++ ++Is a ``*.pyd`` file the same as a DLL? ++-------------------------------------- ++ ++.. XXX update for py3k (PyInit_foo) ++ ++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. ++ ++ ++How can I embed Python into a Windows application? ++-------------------------------------------------- ++ ++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 :file:`python{NN}.dll`; it is ++ typically installed in ``C:\Windows\System``. NN is the Python version, a ++ number such as "23" for Python 2.3. ++ ++ You can link to Python statically or dynamically. Linking statically means ++ linking against :file:`python{NN}.lib`, while dynamically linking means ++ linking against :file:`python{NN}.dll`. The drawback to dynamic linking is ++ that your app won't run if :file:`python{NN}.dll` does not exist on your ++ system. (General note: :file:`python{NN}.lib` is the so-called "import lib" ++ corresponding to :file:`python.dll`. It merely defines symbols for the ++ linker.) ++ ++ Linking dynamically greatly simplifies link options; everything happens at ++ run time. Your code must load :file:`python{NN}.dll` using the Windows ++ ``LoadLibraryEx()`` routine. The code must also use access routines and data ++ in :file:`python{NN}.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. ++ ++ Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe ++ first. ++ ++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. ++ ++ .. code-block:: c ++ ++ #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 pythonNN.dll. ++ ++ Problem 1: The so-called "Very High Level" functions that take FILE * ++ arguments will not work in a multi-compiler environment because 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: ++ ++ .. code-block:: c ++ ++ 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 pythonNN.dll. Again, this code will ++ fail in a mult-compiler environment. Replace such code by: ++ ++ .. code-block:: c ++ ++ 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. ++ ++ ++How do I use Python for CGI? ++---------------------------- ++ ++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:\\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 ++:option:`-u` flag specifies unbuffered and binary mode for stdin - needed when ++working with binary data. ++ ++In addition, it is recommended 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). ++ ++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) ++ ++Configuring Apache is much simpler. 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. ++ ++ ++How do I keep editors from inserting tabs into my Python source? ++---------------------------------------------------------------- ++ ++The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`, ++recommends 4 spaces for distributed Python code; this is also the Emacs ++python-mode default. ++ ++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 :menuselection:`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 :option:`-t` switch or run ``Tools/Scripts/tabnanny.py`` to ++check a directory tree in batch mode. ++ ++ ++How do I check for a keypress without blocking? ++----------------------------------------------- ++ ++Use the msvcrt module. This is a standard Windows-specific extension module. ++It defines a function ``kbhit()`` which checks whether a keyboard hit is ++present, and ``getch()`` which gets one character without echoing it. ++ ++ ++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)) ++ ++ ++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 ++ ++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 ++ ++ ++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 :option:`-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 (e.g. GIF) responses may get garbled (resulting in broken images, PDF ++files, and other binary downloads failing). ++ ++ ++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() ++ ++ ++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://support.microsoft.com/. ++ ++ ++PyRun_SimpleFile() crashes on Windows but not on Unix; why? ++----------------------------------------------------------- ++ ++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``). ++ ++If you can't change compilers or flags, try using :cfunc:`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" ++appended to the base name. ++ ++ ++Importing _tkinter fails on Windows 95/98: why? ++------------------------------------------------ ++ ++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``.) ++ ++ ++How do I 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.) ++ ++ ++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). ++ ++ ++Warning about CTL3D32 version from installer ++-------------------------------------------- ++ ++The Python installer issues a warning like this:: ++ ++ This version uses ``CTL3D32.DLL`` which 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 message ++ 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/downloads.html and click on "ctl3dfix.zip". + +Eigenschaftsänderungen: Doc/faq/windows.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/general.rst +=================================================================== +--- Doc/faq/general.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/general.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,513 @@ ++:tocdepth: 2 ++ ++================== ++General Python FAQ ++================== ++ ++.. contents:: ++ ++General Information ++=================== ++ ++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 Unix variants, on the Mac, and on ++PCs under MS-DOS, Windows, Windows NT, and OS/2. ++ ++To find out more, start with :ref:`tutorial-index`. The `Beginner's Guide to ++Python `_ links to other ++introductory tutorials and resources for learning Python. ++ ++ ++What is the Python Software Foundation? ++--------------------------------------- ++ ++The Python Software Foundation is an independent non-profit organization that ++holds the copyright on Python versions 2.1 and newer. The PSF's mission is to ++advance open source technology related to the Python programming language and to ++publicize the use of Python. The PSF's home page is at ++http://www.python.org/psf/. ++ ++Donations to the PSF are tax-exempt in the US. If you use Python and find it ++helpful, please contribute via `the PSF donation page ++`_. ++ ++ ++Are there copyright restrictions on the use of Python? ++------------------------------------------------------ ++ ++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. 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 (modified or ++unmodified), or to sell products that incorporate Python in some form. We would ++still like to know about all commercial use of Python, of course. ++ ++See `the PSF license page `_ to find further ++explanations and a link to the full text of the license. ++ ++The Python logo is trademarked, and in certain cases permission is required to ++use it. Consult `the Trademark Usage Policy ++`__ for more information. ++ ++ ++Why was Python created in the first place? ++------------------------------------------ ++ ++Here's a *very* brief summary of what started it all, written by Guido van ++Rossum: ++ ++ 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 Modula-3 report. ++ Modula-3 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. ++ ++ ++What is Python good for? ++------------------------ ++ ++Python is a high-level general-purpose programming language that can be applied ++to many different classes of problems. ++ ++The language comes with a large standard library that covers areas such as ++string processing (regular expressions, Unicode, calculating differences between ++files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI ++programming), software engineering (unit testing, logging, profiling, parsing ++Python code), and operating system interfaces (system calls, filesystems, TCP/IP ++sockets). Look at the table of contents for :ref:`library-index` to get an idea ++of what's available. A wide variety of third-party extensions are also ++available. Consult `the Python Package Index `_ to ++find packages of interest to you. ++ ++ ++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 are bugfix releases. In the run-up to a new major release, a ++series of development releases are made, denoted as alpha, beta, or release ++candidate. Alphas are early releases in which interfaces aren't yet finalized; ++it's not unexpected to see an interface change between two alpha releases. ++Betas are more stable, preserving existing interfaces but possibly adding new ++modules, and release candidates are frozen, making no changes except as needed ++to fix critical bugs. ++ ++Alpha, beta and release candidate versions have an additional suffix. 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. In other words, all versions ++labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled ++2.0cN, and *those* precede 2.0. ++ ++You may also find version numbers with a "+" suffix, e.g. "2.2+". These are ++unreleased versions, built directly from the Subversion trunk. In practice, ++after a final minor release is made, the Subversion trunk is incremented to the ++next minor version, which becomes the "a0" version, ++e.g. "2.4a0". ++ ++See also the documentation for ``sys.version``, ``sys.hexversion``, and ++``sys.version_info``. ++ ++ ++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 Subversion at http://svn.python.org/projects/python/trunk. ++ ++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 ++information on getting the source code and compiling it. ++ ++ ++How do I get documentation on Python? ++------------------------------------- ++ ++.. XXX mention py3k ++ ++The standard documentation for the current stable version of Python is available ++at http://docs.python.org/. PDF, plain text, and downloadable HTML versions are ++also available at http://docs.python.org/download.html. ++ ++The documentation is written in reStructuredText and processed by `the Sphinx ++documentation tool `__. The reStructuredText source ++for the documentation is part of the Python source distribution. ++ ++ ++I've never programmed before. Is there a Python tutorial? ++--------------------------------------------------------- ++ ++There are numerous tutorials and books available. The standard documentation ++includes :ref:`tutorial-index`. ++ ++Consult `the Beginner's Guide `_ to ++find information for beginning Python programmers, including lists of tutorials. ++ ++ ++Is there a newsgroup or mailing list devoted to Python? ++------------------------------------------------------- ++ ++There is a newsgroup, :newsgroup:`comp.lang.python`, and a mailing list, ++`python-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. ++:newsgroup:`comp.lang.python` is high-traffic, receiving hundreds of postings ++every day, and Usenet readers are often more able to cope with this volume. ++ ++Announcements of new software releases and events can be found in ++comp.lang.python.announce, a low-traffic moderated list that receives about five ++postings per day. It's available as `the python-announce mailing list ++`_. ++ ++More info about other mailing lists and newsgroups ++can be found at http://www.python.org/community/lists/. ++ ++ ++How do I get a beta test version of Python? ++------------------------------------------- ++ ++Alpha and beta releases are available from http://www.python.org/download/. All ++releases are announced on the comp.lang.python and comp.lang.python.announce ++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. ++ ++ ++How do I submit bug reports and patches for Python? ++--------------------------------------------------- ++ ++To report a bug or submit a patch, please use the Roundup installation at ++http://bugs.python.org/. ++ ++You must have a Roundup account to report bugs; this makes it possible for us to ++contact you if we have follow-up questions. It will also enable Roundup to send ++you updates as we act on your bug. If you had previously used SourceForge to ++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 `_. ++ ++ ++Are there any published articles about Python that I can reference? ++------------------------------------------------------------------- ++ ++It's probably best to cite your favorite book about Python. ++ ++The very first article about Python was written in 1991 and is now quite ++outdated. ++ ++ 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. ++ ++ ++Are there any books on Python? ++------------------------------ ++ ++Yes, there are many, and more are being published. See the python.org wiki at ++http://wiki.python.org/moin/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". ++ ++ ++Where in the world is www.python.org located? ++--------------------------------------------- ++ ++It's currently in Amsterdam, graciously hosted by `XS4ALL ++`_. Thanks to Thomas Wouters for his work in arranging ++python.org's hosting. ++ ++ ++Why is it called Python? ++------------------------ ++ ++When he began implementing Python, Guido van Rossum was also reading the ++published scripts from `"Monty Python's Flying Circus" ++`__, a BBC comedy series from the 1970s. Van Rossum ++thought he needed a name that was short, unique, and slightly mysterious, so he ++decided to call the language Python. ++ ++ ++Do I have to like "Monty Python's Flying Circus"? ++------------------------------------------------- ++ ++No, but it helps. :) ++ ++ ++Python in the real world ++======================== ++ ++How stable is Python? ++--------------------- ++ ++Very stable. New, stable releases have been coming out roughly every 6 to 18 ++months since 1991, and this seems likely to continue. Currently there are ++usually around 18 months between major releases. ++ ++The developers issue "bugfix" releases of older versions, so the stability of ++existing releases gradually improves. Bugfix releases, indicated by a third ++component of the version number (e.g. 2.5.3, 2.6.2), are managed for stability; ++only fixes for known problems are included in a bugfix release, and it's ++guaranteed that interfaces will remain the same throughout a series of bugfix ++releases. ++ ++.. XXX this gets out of date pretty often ++ ++The `2.6.4 release `_ is recommended ++production-ready version at this point in time. Python 3.1 is also considered ++production-ready, but may be less useful, since currently there is more third ++party software available for Python 2 than for Python 3. Python 2 code will ++generally not run unchanged in Python 3. ++ ++ ++How many people are using Python? ++--------------------------------- ++ ++There are probably tens of thousands of users, though it's difficult to obtain ++an exact count. ++ ++Python is available for free download, so there are no sales figures, and it's ++available from many different sites and packaged with many Linux distributions, ++so download statistics don't tell the whole story either. ++ ++The comp.lang.python newsgroup is very active, but not all Python users post to ++the group or even read it. ++ ++ ++Have any significant projects been done in Python? ++-------------------------------------------------- ++ ++See http://python.org/about/success for a list of projects that use Python. ++Consulting the proceedings for `past Python conferences ++`_ will reveal contributions from many ++different companies and organizations. ++ ++High-profile Python projects include `the Mailman mailing list manager ++`_ and `the Zope application server ++`_. Several Linux distributions, most notably `Red Hat ++`_, have written part or all of their installer and ++system administration software in Python. Companies that use Python internally ++include Google, Yahoo, and Lucasfilm Ltd. ++ ++ ++What new developments are expected for Python in the future? ++------------------------------------------------------------ ++ ++See http://www.python.org/dev/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. Look for a PEP ++titled "Python X.Y Release Schedule", where X.Y is a version that hasn't been ++publicly released yet. ++ ++New development is discussed on `the python-dev mailing list ++`_. ++ ++ ++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 change 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's still the problem of updating all documentation; ++many books have been written about Python, and we don't want to invalidate them ++all at a single stroke. ++ ++Providing a gradual upgrade path is necessary if a feature has to be changed. ++:pep:`5` describes the procedure followed for introducing backward-incompatible ++changes while minimizing disruption for users. ++ ++ ++Is Python Y2K (Year 2000) Compliant? ++------------------------------------ ++ ++.. remove this question? ++ ++As of August, 2003 no major problems have been reported and Y2K compliance seems ++to be a non-issue. ++ ++Python does very few date calculations and for those it does perform relies on ++the C library functions. Python generally represents times either as seconds ++since 1970 or as a ``(year, month, day, ...)`` tuple 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, it's possible that a particular ++application written in Python makes assumptions about 2-digit years. ++ ++Because Python is available free of charge, there are no absolute guarantees. ++If there *are* unforeseen problems, liability is the user's problem rather than ++the developers', and there is nobody you can sue for damages. The Python ++copyright notice contains the following disclaimer: ++ ++ 4. PSF is making Python 2.3 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 2.3 WILL NOT INFRINGE ANY THIRD PARTY ++ RIGHTS. ++ ++ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON ++ 2.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS ++ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.3, ++ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. ++ ++The good news is that *if* you encounter a problem, you have full source ++available to track it down and fix it. This is one advantage of an open source ++programming environment. ++ ++ ++Is Python a good language for beginning programmers? ++---------------------------------------------------- ++ ++Yes. ++ ++It is still common to start students with a procedural and statically typed ++language such as Pascal, C, or a subset of C++ or Java. 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 and, most importantly, using ++Python in a beginning programming course lets students 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 probably even work with user-defined objects in their very ++first course. ++ ++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 in the long term, 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. Like Java, Python ++has a large standard library 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. Third-party ++modules such as PyGame are also helpful in extending the students' reach. ++ ++Python's interactive interpreter enables students to test language features ++while they're programming. They can keep a window with the interpreter running ++while they enter their program's 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'] ++ >>> help(L.append) ++ Help on built-in function append: ++ ++ append(...) ++ 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. IDLE is a cross-platform IDE for Python ++that is written in Python using Tkinter. PythonWin is a Windows-specific IDE. ++Emacs users will be happy to know that there is a very good Python mode for ++Emacs. All of these programming environments provide syntax highlighting, ++auto-indenting, and access to the interactive interpreter while coding. Consult ++http://www.python.org/editors/ for a full list of Python editing environments. ++ ++If you want to discuss Python's use in education, you may be interested in ++joining `the edu-sig mailing list ++`_. ++ ++ ++Upgrading Python ++================ ++ ++What is this bsddb185 module my application keeps complaining about? ++-------------------------------------------------------------------- ++ ++.. XXX remove this question? ++ ++Starting with Python2.3, the distribution includes the `PyBSDDB package ++` as a replacement for the old bsddb module. It ++includes functions which provide backward compatibility at the API level, but ++requires a newer version of the underlying `Berkeley DB ++`_ library. Files created with the older bsddb module ++can't be opened directly using the new module. ++ ++Using your old version of Python and a pair of scripts which are part of Python ++2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory) you can ++convert your old database files to the new format. Using your old Python ++version, run the db2pickle.py script to convert it to a pickle, e.g.:: ++ ++ python2.2 /db2pickley.py database.db database.pck ++ ++Rename your database file:: ++ ++ mv database.db olddatabase.db ++ ++Now convert the pickle file to a new format database:: ++ ++ python /pickle2db.py database.db database.pck ++ ++The precise commands you use will vary depending on the particulars of your ++installation. For full details about operation of these two scripts check the ++doc string at the start of each one. + +Eigenschaftsänderungen: Doc/faq/general.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/installed.rst +=================================================================== +--- Doc/faq/installed.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/installed.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,53 @@ ++============================================= ++"Why is Python Installed on my Computer?" FAQ ++============================================= ++ ++What is Python? ++--------------- ++ ++Python is a programming language. It's used for many different applications. ++It's used in some high schools and colleges as an introductory programming ++language because Python is easy to learn, but it's also used by professional ++software developers at places such as Google, NASA, and Lucasfilm Ltd. ++ ++If you wish to learn more about Python, start with the `Beginner's Guide to ++Python `_. ++ ++ ++Why is Python installed on my machine? ++-------------------------------------- ++ ++If you find Python installed on your system but don't remember installing it, ++there are several possible ways it could have gotten there. ++ ++* Perhaps another user on the computer wanted to learn programming and installed ++ it; you'll have to figure out who's been using the machine and might have ++ installed it. ++* A third-party application installed on the machine might have been written in ++ Python and included a Python installation. For a home computer, the most ++ common such application is `PySol `_, a ++ solitaire game that includes over 1000 different games and variations. ++* Some Windows machines also have Python installed. At this writing we're aware ++ of computers from Hewlett-Packard and Compaq that include Python. Apparently ++ some of HP/Compaq's administrative tools are written in Python. ++* All Apple computers running Mac OS X have Python installed; it's included in ++ the base installation. ++ ++ ++Can I delete Python? ++-------------------- ++ ++That depends on where Python came from. ++ ++If someone installed it deliberately, you can remove it without hurting ++anything. On Windows, use the Add/Remove Programs icon in the Control Panel. ++ ++If Python was installed by a third-party application, you can also remove it, ++but that application will no longer work. You should use that application's ++uninstaller rather than removing Python directly. ++ ++If Python came with your operating system, removing it is not recommended. If ++you remove it, whatever tools were written in Python will no longer run, and ++some of them might be important to you. Reinstalling the whole system would ++then be required to fix things again. ++ + +Eigenschaftsänderungen: Doc/faq/installed.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/programming.rst +=================================================================== +--- Doc/faq/programming.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/programming.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,1752 @@ ++:tocdepth: 2 ++ ++=============== ++Programming FAQ ++=============== ++ ++.. contents:: ++ ++General Questions ++================= ++ ++Is there a source code level debugger with breakpoints, single-stepping, etc.? ++------------------------------------------------------------------------------ ++ ++Yes. ++ ++The pdb module is a simple but adequate console-mode debugger for Python. It is ++part of the standard Python library, and is :mod:`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 as Tools/scripts/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 pdb. The ++Pythonwin debugger colors breakpoints and has quite a few cool features such as ++debugging non-Pythonwin programs. Pythonwin is available as part of the `Python ++for Windows Extensions `__ project and ++as a part of the ActivePython distribution (see ++http://www.activestate.com/Products/ActivePython/index.html). ++ ++`Boa Constructor `_ is an IDE and GUI ++builder that uses wxWidgets. It offers visual frame creation and manipulation, ++an object inspector, many views on the source like object browsers, inheritance ++hierarchies, doc string generated html documentation, an advanced debugger, ++integrated help, and Zope support. ++ ++`Eric `_ is an IDE built on PyQt ++and the Scintilla editing component. ++ ++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://bashdb.sourceforge.net/pydb/ and DDD can be found at ++http://www.gnu.org/software/ddd. ++ ++There are a number of commercial Python IDEs that include graphical debuggers. ++They include: ++ ++* Wing IDE (http://wingware.com/) ++* Komodo IDE (http://www.activestate.com/Products/Komodo) ++ ++ ++Is there a tool to help find bugs or perform static analysis? ++------------------------------------------------------------- ++ ++Yes. ++ ++PyChecker is a static analysis tool that finds bugs in Python source code and ++warns about code complexity and style. You can get PyChecker from ++http://pychecker.sf.net. ++ ++`Pylint `_ is another tool that checks ++if a module satisfies a coding standard, and also makes it possible to write ++plug-ins to add a custom feature. In addition to the bug checking that ++PyChecker performs, Pylint offers some additional features such as checking line ++length, whether variable names are well-formed according to your coding ++standard, whether declared interfaces are fully implemented, and more. ++http://www.logilab.org/card/pylint_manual provides a full list of Pylint's ++features. ++ ++ ++How can I create a stand-alone binary from a Python script? ++----------------------------------------------------------- ++ ++You don't need the ability to compile Python to C code if all you want is a ++stand-alone program that users can download and run without having to install ++the Python distribution first. There are a number of tools that determine the ++set of modules required by a program and bind these modules together with a ++Python binary to produce a single executable. ++ ++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; 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 turns the bytecode for modules ++written in Python into 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. ++ ++Obviously, freeze requires a C compiler. There are several other utilities ++which don't. One is Thomas Heller's py2exe (Windows only) at ++ ++ http://www.py2exe.org/ ++ ++Another is Christian Tismer's `SQFREEZE `_ ++which appends the byte code to a specially-prepared Python interpreter that can ++find the byte code in the executable. ++ ++Other tools include Fredrik Lundh's `Squeeze ++`_ and Anthony Tuininga's ++`cx_Freeze `_. ++ ++ ++Are there coding standards or a style guide for Python programs? ++---------------------------------------------------------------- ++ ++Yes. The coding style required for standard library modules is documented as ++:pep:`8`. ++ ++ ++My program is too slow. How do I speed it up? ++--------------------------------------------- ++ ++That's a tough one, in general. There are many tricks to speed up Python code; ++consider rewriting parts in C as a last resort. ++ ++In some cases it's possible to automatically translate Python to C or x86 ++assembly language, meaning that you don't have to modify your code to gain ++increased speed. ++ ++.. XXX seems to have overlap with other questions! ++ ++`Pyrex `_ can compile a ++slightly modified version of Python code into a C extension, and can be used on ++many different platforms. ++ ++`Psyco `_ is a just-in-time compiler that ++translates Python code into x86 assembly language. If you can use it, Psyco can ++provide dramatic speedups for critical functions. ++ ++The rest of this answer will discuss various tricks for squeezing a bit more ++speed out of Python code. *Never* apply any optimization tricks unless you know ++you need them, after profiling has indicated that a particular function is the ++heavily executed hot spot in the code. Optimizations almost always make the ++code less clear, and you shouldn't pay the costs of reduced clarity (increased ++development time, greater likelihood of bugs) unless the resulting performance ++benefit is worth it. ++ ++There is a page on the wiki devoted to `performance tips ++`_. ++ ++Guido van Rossum has written up an anecdote related to optimization at ++http://www.python.org/doc/essays/list2str.html. ++ ++One thing to notice is that function and (especially) method calls are rather ++expensive; if you have designed a purely OO interface with lots of tiny ++functions that don't do much more than get or set an instance variable or call ++another method, you might consider using a more direct way such as directly ++accessing instance variables. Also see the standard module :mod:`profile` which ++makes it possible to find out where your program is spending most of its time ++(if you have some patience -- the profiling itself can slow your program down by ++an order of magnitude). ++ ++Remember that many standard optimization heuristics you may know from other ++programming experience may well apply to Python. For example it may be faster ++to send output to output devices using larger writes rather than smaller ones in ++order to reduce the overhead of kernel system calls. Thus CGI scripts that ++write all output in "one shot" may be faster than those that write lots of small ++pieces of output. ++ ++Also, be sure to use Python's core features where appropriate. For example, ++slicing allows programs to chop up lists and other sequence objects in a single ++tick of the interpreter's mainloop using highly optimized C implementations. ++Thus to get the same effect as:: ++ ++ L2 = [] ++ for i in range[3]: ++ L2.append(L1[i]) ++ ++it is much shorter and far faster to use :: ++ ++ L2 = list(L1[:3]) # "list" is redundant if L1 is a list. ++ ++Note that the functionally-oriented builtins such as :func:`map`, :func:`zip`, ++and friends can be a convenient accelerator for loops that perform a single ++task. For example to pair the elements of two lists together:: ++ ++ >>> zip([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 operation completes very quickly in such cases. ++ ++Other examples 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 the copying in one pass. For ++manipulating strings, use the ``replace()`` method on string objects. Use ++regular expressions only when you're not dealing with constant string patterns. ++Consider using the string formatting operations ``string % tuple`` and ``string ++% dictionary``. ++ ++Be sure to use the :meth:`list.sort` builtin method to do sorting, and see the ++`sorting mini-HOWTO `_ for examples ++of moderately advanced usage. :meth:`list.sort` beats other techniques for ++sorting in all but the most extreme circumstances. ++ ++Another common trick is to "push loops into functions or methods." For example ++suppose you have a program that runs slowly and you use the profiler to ++determine that a Python function ``ff()`` is being called lots of times. If you ++notice that ``ff ()``:: ++ ++ def ff(x): ++ ... # do something with x computing result... ++ return result ++ ++tends to be called in loops like:: ++ ++ list = map(ff, oldlist) ++ ++or:: ++ ++ for x in sequence: ++ value = ff(x) ++ ... # do something with value... ++ ++then you can often eliminate function call overhead by rewriting ``ff()`` to:: ++ ++ def ffseq(seq): ++ resultseq = [] ++ for x in seq: ++ ... # do something with x computing result... ++ resultseq.append(result) ++ return resultseq ++ ++and rewrite the two examples to ``list = ffseq(oldlist)`` and to:: ++ ++ for value in ffseq(sequence): ++ ... # do something with value... ++ ++Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty. ++Of course this technique is not always appropriate and there are other variants ++which you can figure out. ++ ++You can gain some performance by explicitly storing the results of a function or ++method lookup into a local variable. A loop like:: ++ ++ for key in token: ++ dict[key] = dict.get(key, 0) + 1 ++ ++resolves ``dict.get`` every iteration. If the method isn't going to change, a ++slightly faster implementation is:: ++ ++ dict_get = dict.get # look up the method once ++ for key in token: ++ dict[key] = dict_get(key, 0) + 1 ++ ++Default arguments can be used to determine values once, at compile time instead ++of at run time. This can only be done for functions or objects which will not ++be changed during program execution, such as replacing :: ++ ++ def degree_sin(deg): ++ return math.sin(deg * math.pi / 180.0) ++ ++with :: ++ ++ def degree_sin(deg, factor=math.pi/180.0, sin=math.sin): ++ return sin(deg * factor) ++ ++Because this trick uses default arguments for terms which should not be changed, ++it should only be used when you are not concerned with presenting a possibly ++confusing API to your users. ++ ++ ++Core Language ++============= ++ ++How do you set a global variable in a function? ++----------------------------------------------- ++ ++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``. ++ ++The solution is to insert an explicit global declaration at the start of the ++function:: ++ ++ 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. ++ ++ ++What are the rules for local and global variables in Python? ++------------------------------------------------------------ ++ ++In Python, variables that are only referenced inside a function are implicitly ++global. If a variable is assigned a new value anywhere within the function's ++body, it's assumed to be a local. If a variable is ever assigned a new value ++inside the function, the variable is implicitly local, and you need to ++explicitly declare it as 'global'. ++ ++Though a bit surprising at first, a moment's consideration explains this. On ++one hand, requiring :keyword:`global` for assigned variables provides a bar ++against unintended side-effects. On the other hand, if ``global`` was required ++for all global references, you'd be using ``global`` all the time. 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. ++ ++ ++How do I share 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:: ++ ++ x = 0 # Default value of the 'x' configuration setting ++ ++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. ++ ++ ++What are the "best practices" for using import in a module? ++----------------------------------------------------------- ++ ++In general, don't use ``from modulename import *``. Doing so clutters the ++importer's namespace. Some people avoid this idiom even with the few modules ++that were designed to be imported in this manner. Modules designed in this ++manner include :mod:`tkinter`, and :mod:`threading`. ++ ++Import modules at the top of a file. 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, but ++using multiple imports per line uses less screen space. ++ ++It's good practice if you import modules in the following order: ++ ++1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``) ++2. third-party library modules (anything installed in Python's site-packages ++ directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc. ++3. locally-developed modules ++ ++Never use relative package imports. If you're writing code that's in the ++``package.sub.m1`` module and want to import ``package.sub.m2``, do not just ++write ``import m2``, even though it's legal. Write ``from package.sub import ++m2`` instead. Relative imports can lead to a module being initialized twice, ++leading to confusing bugs. ++ ++It is sometimes necessary to move imports to a function or class to avoid ++problems with circular imports. Gordon McMillan says: ++ ++ Circular imports are fine where both modules use the "import " 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, because the first module is ++ busy importing the 2nd. ++ ++In this case, if the second 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. ++ ++Only move imports into a local scope, such as inside a function definition, if ++it's necessary to solve a problem such as avoiding a circular import or are ++trying to reduce the initialization time of a module. 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 loading a module multiple times is virtually free, costing only a ++couple of dictionary lookups. Even if the module name has gone out of scope, ++the module is probably available in :data:`sys.modules`. ++ ++If only instances of a specific class use 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. ++ ++ ++How can I pass optional or keyword parameters from one function to another? ++--------------------------------------------------------------------------- ++ ++Collect the arguments using the ``*`` and ``**`` specifiers in the function's ++parameter list; this gives you the positional arguments as a tuple and the ++keyword arguments as a dictionary. You can then pass these arguments when ++calling another function by using ``*`` and ``**``:: ++ ++ def f(x, *args, **kwargs): ++ ... ++ kwargs['width'] = '14.3c' ++ ... ++ g(x, *args, **kwargs) ++ ++In the unlikely case that you care about Python versions older than 2.0, use ++:func:`apply`:: ++ ++ def f(x, *args, **kwargs): ++ ... ++ kwargs['width'] = '14.3c' ++ ... ++ apply(g, (x,)+args, kwargs) ++ ++ ++How do I write a function with output parameters (call by reference)? ++--------------------------------------------------------------------- ++ ++Remember 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. You can achieve the ++desired effect in a number of ways. ++ ++1) By returning a tuple of the results:: ++ ++ 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 ++ ++ This is almost always the clearest solution. ++ ++2) By using global variables. This isn't thread-safe, and is not recommended. ++ ++3) 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 ++ ++4) By passing in a dictionary that gets mutated:: ++ ++ 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 ++ ++ ++ There's almost never a good reason to get this complicated. ++ ++Your best choice is to return a tuple containing the multiple results. ++ ++ ++How do you make a higher order function in Python? ++-------------------------------------------------- ++ ++You have two choices: you can use nested scopes or you can use callable objects. ++For example, suppose you wanted to define ``linear(a,b)`` which returns a ++function ``f(x)`` that computes the value ``a*x+b``. Using nested scopes:: ++ ++ def linear(a, b): ++ def result(x): ++ return a * x + b ++ return result ++ ++Or using a callable object:: ++ ++ 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 callable object approach has the disadvantage that it is a bit slower and ++results in slightly longer code. However, note that a collection of callables ++can share their signature via inheritance:: ++ ++ class exponential(linear): ++ # __init__ inherited ++ def __call__(self, x): ++ return self.a * (x ** self.b) ++ ++Object can encapsulate state for several methods:: ++ ++ 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 counting variable. ++ ++ ++How do I copy an object in Python? ++---------------------------------- ++ ++In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case. ++Not all objects can be copied, but most can. ++ ++Some objects can be copied more easily. Dictionaries have a :meth:`~dict.copy` ++method:: ++ ++ newdict = olddict.copy() ++ ++Sequences can be copied by slicing:: ++ ++ new_l = l[:] ++ ++ ++How can I find the methods or attributes of an object? ++------------------------------------------------------ ++ ++For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized ++list of the names containing the instance attributes and methods and attributes ++defined by its class. ++ ++ ++How can my code discover the name of an object? ++----------------------------------------------- ++ ++Generally speaking, it can't, because objects don't really have names. ++Essentially, assignment always binds 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. ++ ++In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to ++this question: ++ ++ The same way as you get the name of that cat you found on your porch: the cat ++ (object) itself cannot tell you its name, and it doesn't really care -- so ++ the only way to find out what it's called is to ask all your neighbours ++ (namespaces) if it's their cat (object)... ++ ++ ....and don't be surprised if you'll find that it's known by many names, or ++ no name at all! ++ ++ ++What's up with the comma operator's precedence? ++----------------------------------------------- ++ ++Comma is not an operator in Python. Consider this session:: ++ ++ >>> "a" in "b", "a" ++ (False, '1') ++ ++Since the comma is not an operator, but a separator between expressions the ++above is evaluated as if you had entered:: ++ ++ >>> ("a" in "b"), "a" ++ ++not:: ++ ++ >>> "a" in ("5", "a") ++ ++The same is true of the various assignment operators (``=``, ``+=`` etc). They ++are not truly operators but syntactic delimiters in assignment statements. ++ ++ ++Is there an equivalent of C's "?:" ternary operator? ++---------------------------------------------------- ++ ++Yes, this feature was added in Python 2.5. The syntax would be as follows:: ++ ++ [on_true] if [expression] else [on_false] ++ ++ x, y = 50, 25 ++ ++ small = x if x < y else y ++ ++For versions previous to 2.5 the answer would be 'No'. ++ ++.. XXX remove rest? ++ ++In many cases you can mimic ``a ? b : c`` with ``a and b or c``, but there's a ++flaw: if *b* is zero (or empty, or ``None`` -- anything that tests false) then ++*c* will be selected instead. In many cases you can prove by looking at the ++code that this can't happen (e.g. because *b* is a constant or has a type that ++can never be false), but in general this can be a problem. ++ ++Tim Peters (who wishes it was Steve Majewski) suggested the following solution: ++``(a and [b] or [c])[0]``. Because ``[b]`` is a singleton list it is never ++false, so the wrong path is never taken; then applying ``[0]`` to the whole ++thing gets the *b* or *c* that you really wanted. Ugly, but it gets you there ++in the rare cases where it is really inconvenient to rewrite your code using ++'if'. ++ ++The best course is usually to write a simple ``if...else`` statement. Another ++solution is to implement the ``?:`` operator as a function:: ++ ++ def q(cond, on_true, on_false): ++ if cond: ++ if not isfunction(on_true): ++ return on_true ++ else: ++ return 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. There are ++several answers: many languages do just fine without one; it can easily lead to ++less readable code; no sufficiently "Pythonic" syntax has been discovered; a ++search of the standard library found remarkably few places where using an ++if-then-else expression would make the code more understandable. ++ ++In 2002, :pep:`308` was written proposing several possible syntaxes and the ++community was asked to vote on the issue. The vote was inconclusive. Most ++people liked one of the syntaxes, but also hated other syntaxes; many votes ++implied that people preferred no ternary operator rather than having a syntax ++they hated. ++ ++ ++Is it possible to write obfuscated one-liners in Python? ++-------------------------------------------------------- ++ ++Yes. Usually this is done by nesting :keyword:`lambda` within ++:keyword:`lambda`. 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! ++ ++ ++Numbers and strings ++=================== ++ ++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 ++ >>> 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 ++ ++ ++Why does -22 / 10 return -3? ++---------------------------- ++ ++It's primarily driven by the desire that ``i % j`` have the same sign as ``j``. ++If you want that, and also want:: ++ ++ i == (i / j) * j + (i % j) ++ ++then integer division has to return the floor. C also requires that identity to ++hold, and then compilers that truncate ``i / j`` need to make ``i % j`` have the ++same sign as ``i``. ++ ++There are few real use cases for ``i % j`` when ``j`` is negative. When ``j`` ++is positive, there are many, and in virtually all of them it's more useful for ++``i % j`` to be ``>= 0``. If the clock says 10 now, what did it say 200 hours ++ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to ++bite. ++ ++ ++How do I convert a string to a number? ++-------------------------------------- ++ ++For integers, use the built-in :func:`int` type constructor, e.g. ``int('144') ++== 144``. Similarly, :func:`float` converts to floating-point, ++e.g. ``float('144') == 144.0``. ++ ++By default, these interpret the number as decimal, so that ``int('0144') == ++144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes ++the base to convert from as a second optional argument, so ``int('0x144', 16) == ++324``. If the base is specified as 0, the number is interpreted using Python's ++rules: a leading '0' indicates octal, and '0x' indicates a hex number. ++ ++Do not use the built-in function :func:`eval` if all you need is to convert ++strings to numbers. :func:`eval` will be significantly slower and it presents a ++security risk: someone could pass you a Python expression that might have ++unwanted side effects. For example, someone could pass ++``__import__('os').system("rm -rf $HOME")`` which would erase your home ++directory. ++ ++:func:`eval` also has the effect of interpreting numbers as Python expressions, ++so that e.g. ``eval('09')`` gives a syntax error because Python regards numbers ++starting with '0' as octal (base 8). ++ ++ ++How do I convert a number to a string? ++-------------------------------------- ++ ++To convert, e.g., the number 144 to the string '144', use the built-in type ++constructor :func:`str`. If you want a hexadecimal or octal representation, use ++the built-in functions ``hex()`` or ``oct()``. For fancy formatting, use ++:ref:`the % operator ` on strings, e.g. ``"%04d" % 144`` ++yields ``'0144'`` and ``"%.3f" % (1/3.0)`` yields ``'0.333'``. See the library ++reference manual for details. ++ ++ ++How do I modify a string in place? ++---------------------------------- ++ ++You can't, because strings are immutable. If you need an object with this ++ability, try converting the string to a list or use the array module:: ++ ++ >>> s = "Hello, world" ++ >>> a = list(s) ++ >>> print a ++ ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] ++ >>> a[7:] = list("there!") ++ >>> ''.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' ++ ++ ++How do I use strings to call functions/methods? ++----------------------------------------------- ++ ++There are various techniques. ++ ++* The best is to use a dictionary that maps strings to 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 :func:`getattr`:: ++ ++ import foo ++ getattr(foo, 'bar')() ++ ++ Note that :func:`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 :func:`locals` or :func:`eval` to resolve the function name:: ++ ++ def myFunc(): ++ print "hello" ++ ++ fname = "myFunc" ++ ++ f = locals()[fname] ++ f() ++ ++ f = eval(fname) ++ f() ++ ++ Note: Using :func:`eval` is slow and dangerous. If you don't have absolute ++ control over the contents of the string, someone could pass a string that ++ resulted in an arbitrary function being executed. ++ ++Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? ++------------------------------------------------------------------------------------- ++ ++Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all ++occurences of any line terminator from the end of the string ``S`` without ++removing other trailing whitespace. If the string ``S`` represents more than ++one line, with several empty lines at the end, the line terminators for all the ++blank lines will be removed:: ++ ++ >>> lines = ("line 1 \r\n" ++ ... "\r\n" ++ ... "\r\n") ++ >>> lines.rstrip("\n\r") ++ "line 1 " ++ ++Since this is typically only desired when reading text one line at a time, using ++``S.rstrip()`` this way works well. ++ ++For older versions of Python, There are two partial substitutes: ++ ++- If you want to remove all trailing whitespace, use the ``rstrip()`` method of ++ string objects. This removes all trailing whitespace, not just a single ++ newline. ++ ++- Otherwise, if there is only one line in the string ``S``, use ++ ``S.splitlines()[0]``. ++ ++ ++Is there a scanf() or sscanf() equivalent? ++------------------------------------------ ++ ++Not as such. ++ ++For simple input parsing, the easiest approach is usually to split the line into ++whitespace-delimited words using the :meth:`~str.split` method of string objects ++and then convert decimal strings to numeric values using :func:`int` or ++:func:`float`. ``split()`` supports an optional "sep" parameter which is useful ++if the line uses something other than whitespace as a separator. ++ ++For more complicated input parsing, regular expressions more powerful than C's ++:cfunc:`sscanf` and better suited for the task. ++ ++ ++What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean? ++------------------------------------------------------------------------------------------ ++ ++This error indicates that your Python installation can handle only 7-bit ASCII ++strings. There are a couple ways to fix or work around the problem. ++ ++If your programs must handle data in arbitrary 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 example, 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 :exc:`UnicodeError` exception. ++ ++If you only want strings converted 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 ++ ++It's possible to set a default encoding in a file called ``sitecustomize.py`` ++that's part of the Python library. However, this isn't recommended because ++changing the Python-wide default encoding may cause third-party extension ++modules to fail. ++ ++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. ++ ++ ++Sequences (Tuples/Lists) ++======================== ++ ++How do I convert between tuples and lists? ++------------------------------------------ ++ ++The type constructor ``tuple(seq)`` converts any sequence (actually, any ++iterable) 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 :func:`tuple` when you ++aren't sure that an object is already a tuple. ++ ++The type constructor ``list(seq)`` converts any sequence or iterable 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. ++ ++ ++What's a negative index? ++------------------------ ++ ++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 penultimate (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 ``S[:-1]`` is all of ++the string except for its last character, which is useful for removing the ++trailing newline from a string. ++ ++ ++How do I iterate over a sequence in reverse order? ++-------------------------------------------------- ++ ++Use the :func:`reversed` builtin function, which is new in Python 2.4:: ++ ++ for x in reversed(sequence): ++ ... # do something with x... ++ ++This won't touch your original sequence, but build a new copy with reversed ++order to iterate over. ++ ++With Python 2.3, you can use an extended slice syntax:: ++ ++ for x in sequence[::-1]: ++ ... # do something with x... ++ ++ ++How do you remove duplicates from a list? ++----------------------------------------- ++ ++See the Python Cookbook for a long discussion of many ways to do this: ++ ++ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 ++ ++If you don't mind reordering the list, sort it and then scan from the end of the ++list, deleting duplicates as you go:: ++ ++ 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 (i.e. they are all ++hashable) this is often faster :: ++ ++ d = {} ++ for x in List: ++ d[x] = x ++ List = d.values() ++ ++In Python 2.5 and later, the following is possible instead:: ++ ++ List = list(set(List)) ++ ++This converts the list into a set, thereby removing duplicates, and then back ++into a list. ++ ++ ++How do you make an array in Python? ++----------------------------------- ++ ++Use a list:: ++ ++ ["this", 1, "is", "an", "array"] ++ ++Lists are equivalent to C or Pascal arrays in their time complexity; the primary ++difference is that a Python list can contain objects of many different types. ++ ++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 Numeric extensions and others define array-like structures with ++various characteristics as well. ++ ++To get Lisp-style linked lists, you can emulate cons cells using tuples:: ++ ++ lisp_list = ("like", ("this", ("example", None) ) ) ++ ++If mutability is desired, you could use lists instead of tuples. 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, because it's ++usually a lot slower than using Python lists. ++ ++ ++How do I create a multidimensional list? ++---------------------------------------- ++ ++You probably tried to make a multidimensional array like this:: ++ ++ A = [[None] * 2] * 3 ++ ++This looks correct if you print it:: ++ ++ >>> A ++ [[None, None], [None, None], [None, None]] ++ ++But when you assign a value, it shows up in multiple places: ++ ++ >>> A[0][0] = 5 ++ >>> A ++ [[5, None], [5, None], [5, None]] ++ ++The reason is that replicating a list with ``*`` doesn't create copies, it only ++creates references to the existing objects. The ``*3`` creates a list ++containing 3 references to the same list of length two. Changes to one row will ++show in all rows, which is almost certainly not what you want. ++ ++The suggested approach is to create a list of the desired length first and then ++fill in each element with a newly created list:: ++ ++ A = [None] * 3 ++ for i in range(3): ++ A[i] = [None] * 2 ++ ++This generates a list containing 3 different lists of length two. You can also ++use a list comprehension:: ++ ++ w, h = 2, 3 ++ A = [[None] * w for i in range(h)] ++ ++Or, you can use an extension that provides a matrix datatype; `Numeric Python ++`_ is the best known. ++ ++ ++How do I apply a method to a sequence of objects? ++------------------------------------------------- ++ ++Use a list comprehension:: ++ ++ result = [obj.method() for obj in List] ++ ++More generically, you can try the following function:: ++ ++ def method_map(objects, method, arguments): ++ """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]""" ++ nobjects = len(objects) ++ methods = map(getattr, objects, [method]*nobjects) ++ return map(apply, methods, [arguments]*nobjects) ++ ++ ++Dictionaries ++============ ++ ++How can I get a dictionary to display its keys in a consistent order? ++--------------------------------------------------------------------- ++ ++You can't. Dictionaries store their keys in an unpredictable order, so the ++display order of a dictionary's elements will be similarly unpredictable. ++ ++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. In this ++case, use the ``pprint`` module to pretty-print the dictionary; the items will ++be presented in order sorted by the key. ++ ++A more complicated solution is to 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. The largest flaw is that if some values in the ++dictionary are also dictionaries, their values won't be presented in any ++particular order. ++ ++ ++I want to do a complicated sort: can you do a Schwartzian Transform in Python? ++------------------------------------------------------------------------------ ++ ++The technique, attributed to Randal Schwartz of the Perl community, sorts the ++elements of a list by a metric which maps each element to its "sort value". In ++Python, just use the ``key`` argument for the ``sort()`` method:: ++ ++ Isorted = L[:] ++ Isorted.sort(key=lambda s: int(s[10:15])) ++ ++The ``key`` argument is new in Python 2.4, for older versions this kind of ++sorting is quite simple to do with list comprehensions. To sort a list of ++strings by their uppercase values:: ++ ++ tmp1 = [(x.upper(), x) for x in L] # Schwartzian transform ++ tmp1.sort() ++ Usorted = [x[1] for x in tmp1] ++ ++To sort by the integer value of a subfield extending from positions 10-15 in ++each string:: ++ ++ 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 intfield(s): ++ return int(s[10:15]) ++ ++ def Icmp(s1, s2): ++ return cmp(intfield(s1), intfield(s2)) ++ ++ Isorted = L[:] ++ Isorted.sort(Icmp) ++ ++but since this method calls ``intfield()`` many times for each element of L, it ++is slower than the Schwartzian Transform. ++ ++ ++How can I sort one list by values from another list? ++---------------------------------------------------- ++ ++Merge them into a single list of tuples, sort the resulting list, and then pick ++out the element you want. :: ++ ++ >>> 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'] ++ ++An alternative for the last step is:: ++ ++ result = [] ++ for p in pairs: result.append(p[1]) ++ ++If you find this more legible, you might prefer to use this instead of the final ++list comprehension. However, it is almost twice as slow for long lists. Why? ++First, 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 that costs quite a bit. Second, the expression "result.append" requires an ++extra attribute lookup, and third, there's a speed reduction from having to make ++all those function calls. ++ ++ ++Objects ++======= ++ ++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 (attributes) and code (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. You might have a ++generic ``Mailbox`` class that provides basic accessor methods for a mailbox, ++and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox`` ++that handle various specific mailbox formats. ++ ++ ++What is a method? ++----------------- ++ ++A method is a function on some object ``x`` that you normally call as ++``x.name(arguments...)``. Methods are defined as functions inside the class ++definition:: ++ ++ class C: ++ def meth (self, arg): ++ return arg * 2 + self.attribute ++ ++ ++What is self? ++------------- ++ ++Self is merely a conventional name for the first argument of a method. 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)``. ++ ++See also :ref:`why-self`. ++ ++ ++How do I check if an object is an instance of a given class or of a subclass of it? ++----------------------------------------------------------------------------------- ++ ++Use the built-in function ``isinstance(obj, cls)``. You can check if an object ++is an instance of any of a number of classes by providing a tuple instead of a ++single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also ++check whether an object is one of Python's built-in types, e.g. ++``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``. ++ ++Note that most programs do not use :func:`isinstance` on user-defined classes ++very often. If you are developing the classes yourself, a more proper ++object-oriented style is to define methods on the classes that encapsulate a ++particular behaviour, instead of checking the object's class and doing a ++different thing based on what class it is. For example, if you have a function ++that does something:: ++ ++ def search (obj): ++ if isinstance(obj, Mailbox): ++ # ... code to search a mailbox ++ elif isinstance(obj, Document): ++ # ... code to search a document ++ elif ... ++ ++A better approach is to define a ``search()`` method on all the classes and just ++call it:: ++ ++ class Mailbox: ++ def search(self): ++ # ... code to search a mailbox ++ ++ class Document: ++ def search(self): ++ # ... code to search a document ++ ++ obj.search() ++ ++ ++What is delegation? ++------------------- ++ ++Delegation is an object oriented technique (also called a design pattern). ++Let's say you have an object ``x`` and want to change the behaviour of just one ++of its methods. You can create a new class that provides a new implementation ++of the method you're interested in changing and delegates all other methods to ++the corresponding method of ``x``. ++ ++Python programmers can easily implement delegation. For example, the following ++class implements a class that behaves like a file but converts all written data ++to uppercase:: ++ ++ class UpperOut: ++ ++ def __init__(self, outfile): ++ self._outfile = outfile ++ ++ def write(self, s): ++ self._outfile.write(s.upper()) ++ ++ def __getattr__(self, name): ++ return getattr(self._outfile, name) ++ ++Here the ``UpperOut`` class redefines the ``write()`` method to convert the ++argument string to uppercase before calling the underlying ++``self.__outfile.write()`` method. All other methods are delegated to the ++underlying ``self.__outfile`` object. The delegation is accomplished via the ++``__getattr__`` method; consult :ref:`the language reference ` ++for more information about controlling attribute access. ++ ++Note that for more general cases delegation can get trickier. When attributes ++must be set as well as retrieved, the class must define a :meth:`__setattr__` ++method too, and it must do so carefully. The basic implementation of ++:meth:`__setattr__` is roughly equivalent to the following:: ++ ++ class X: ++ ... ++ def __setattr__(self, name, value): ++ self.__dict__[name] = value ++ ... ++ ++Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store ++local state for self without causing an infinite recursion. ++ ++ ++How do I call a method defined in a base class from a derived class that overrides it? ++-------------------------------------------------------------------------------------- ++ ++If you're using new-style classes, use the built-in :func:`super` function:: ++ ++ class Derived(Base): ++ def meth (self): ++ super(Derived, self).meth() ++ ++If you're using classic classes: For a class definition such as ``class ++Derived(Base): ...`` 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, so you need to provide the ``self`` ++argument. ++ ++ ++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 = ++ ++ class Derived(BaseAlias): ++ def meth(self): ++ BaseAlias.meth(self) ++ ... ++ ++ ++How do I create static class data and static class methods? ++----------------------------------------------------------- ++ ++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. ++ ++For static data, simply define a class attribute. To assign a new value to the ++attribute, you have to explicitly use the class name in the assignment:: ++ ++ 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, an assignment like ``self.count = 42`` creates a ++new and unrelated instance vrbl named "count" in ``self``'s own dict. Rebinding ++of a class-static data name must always specify the class whether inside a ++method or not:: ++ ++ C.count = 314 ++ ++Static methods are possible since Python 2.2:: ++ ++ class C: ++ def static(arg1, arg2, arg3): ++ # No 'self' parameter! ++ ... ++ static = staticmethod(static) ++ ++With Python 2.4's decorators, this can also be written as :: ++ ++ class C: ++ @staticmethod ++ def static(arg1, arg2, arg3): ++ # No 'self' parameter! ++ ... ++ ++However, a far more straightforward way to get the effect of a static method is ++via a simple 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. ++ ++ ++How can I overload constructors (or methods) in Python? ++------------------------------------------------------- ++ ++This answer actually applies to all methods, but the question usually comes up ++first in the context of constructors. ++ ++In C++ you'd write ++ ++.. code-block:: c ++ ++ 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. ++ ++ ++I try to use __spam and I get an error about _SomeClassName__spam. ++------------------------------------------------------------------ ++ ++Variable names with double leading underscores are "mangled" to provide a simple ++but effective way to define class private variables. Any identifier of the form ++``__spam`` (at least two leading underscores, at most one trailing underscore) ++is textually replaced with ``_classname__spam``, where ``classname`` is the ++current class name with any leading underscores stripped. ++ ++This doesn't guarantee privacy: an outside user can still deliberately access ++the "_classname__spam" attribute, and private values are visible in the object's ++``__dict__``. Many Python programmers never bother to use private variable ++names at all. ++ ++ ++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 :meth:`__del__` -- it simply ++decrements the object's reference count, and if this reaches zero ++:meth:`__del__` is called. ++ ++If your data structures contain circular links (e.g. a tree where each child has ++a parent reference and each parent has a list of children) the reference counts ++will never go back to zero. Once in a while Python runs an algorithm to detect ++such cycles, but the garbage collector might run some time after the last ++reference to your data structure vanishes, so your :meth:`__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 :meth:`__del__` ++methods are executed is arbitrary. You can run :func:`gc.collect` to force a ++collection, but there *are* pathological cases where objects will never be ++collected. ++ ++Despite the cycle collector, it's still a good idea to define an explicit ++``close()`` method on objects to be called whenever you're done with them. The ++``close()`` method can then remove attributes that refer to subobjecs. Don't ++call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and ++``close()`` should make sure that it can be called more than once for the same ++object. ++ ++Another way to avoid cyclical references is to use the :mod:`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 references (if they need them!). ++ ++If the object has ever been a local variable in 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, calling :func:`sys.exc_clear` will take care of this by clearing the ++last recorded exception. ++ ++Finally, if your :meth:`__del__` method raises an exception, a warning message ++is printed to :data:`sys.stderr`. ++ ++ ++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 by ++keeping a list of weak references to each instance. ++ ++ ++Modules ++======= ++ ++How do I create a .pyc file? ++---------------------------- ++ ++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. Creation of a .pyc ++file is automatic if you're importing a module and Python has the ability ++(permissions, free space, etc...) to write the compiled module back to the ++directory. ++ ++Running Python on a top level script is not considered an import and no ``.pyc`` ++will be created. 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.py`` ++isn't being imported. ++ ++If you need to create abc.pyc -- that is, to create a .pyc file for a module ++that is not imported -- you can, using the :mod:`py_compile` and ++:mod:`compileall` modules. ++ ++The :mod:`py_compile` module can manually compile any 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 :mod:`compileall` module. You can do it from the shell prompt by running ++``compileall.py`` and providing the path of a directory containing Python files ++to compile:: ++ ++ python -m compileall . ++ ++ ++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__'``, the program is ++running as a script. Many modules that are usually used by importing them also ++provide a command-line interface or a self-test, and only execute this code ++after checking ``__name__``:: ++ ++ def main(): ++ print 'Running test...' ++ ... ++ ++ if __name__ == '__main__': ++ main() ++ ++ ++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 interpreter will perform the following steps: ++ ++* 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 dictionary for ``foo`` is still empty. ++ ++The same thing happens when you use ``import foo``, and then try to access ++``foo.foo_var`` in global code. ++ ++There are (at least) three possible workarounds for this problem. ++ ++Guido van Rossum recommends avoiding all uses of ``from import ...``, ++and placing all code inside functions. Initializations of global variables and ++class variables should use constants or built-in functions only. This means ++everything from an imported module is referenced as ``.``. ++ ++Jim Roskind suggests performing steps in 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). ++ ++van Rossum doesn't like this approach much because the imports appear in a ++strange place, but it does work. ++ ++Matthias Urlichs recommends restructuring your code so that the recursive import ++is not necessary in the first place. ++ ++These solutions are not mutually exclusive. ++ ++ ++__import__('x.y.z') returns ; 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 s.split(".")[1:]: ++ m = getattr(m, i) ++ ++See :mod:`importlib` for a convenience function called ++:func:`~importlib.import_module`. ++ ++ ++ ++When I edit an imported module and reimport it, the changes don't show up. Why does this happen? ++------------------------------------------------------------------------------------------------- ++ ++For reasons of efficiency as well as consistency, Python only reads the module ++file on the first time a module is imported. If it didn't, in a program ++consisting of many modules where each one imports the same basic module, the ++basic module would be parsed and re-parsed many times. 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. If the ++module contains class definitions, existing class instances will *not* be ++updated to use the new class definition. This can result in the following ++paradoxical behaviour: ++ ++ >>> import cls ++ >>> c = cls.C() # Create an instance of C ++ >>> reload(cls) ++ ++ >>> isinstance(c, cls.C) # isinstance is false?!? ++ False ++ ++The nature of the problem is made clear if you print out the class objects: ++ ++ >>> c.__class__ ++ ++ >>> cls.C ++ ++ + +Eigenschaftsänderungen: Doc/faq/programming.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/gui.rst +=================================================================== +--- Doc/faq/gui.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/gui.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,161 @@ ++:tocdepth: 2 ++ ++========================== ++Graphic User Interface FAQ ++========================== ++ ++.. contents:: ++ ++General GUI Questions ++===================== ++ ++What platform-independent GUI toolkits exist for Python? ++-------------------------------------------------------- ++ ++Depending on what platform(s) you are aiming at, there are several. ++ ++.. XXX check links ++ ++Tkinter ++''''''' ++ ++Standard builds of Python include an object-oriented interface to the Tcl/Tk ++widget set, called Tkinter. This is probably the easiest to install and use. ++For more info about Tk, including pointers to the source, see the Tcl/Tk home ++page at http://www.tcl.tk. Tcl/Tk is fully portable to the MacOS, Windows, and ++Unix platforms. ++ ++wxWindows ++''''''''' ++ ++wxWindows is a portable GUI class library written in C++ that's a portable ++interface to various platform-specific libraries; wxWidgets is a Python ++interface to wxWindows. wxWindows supports Windows and MacOS; on Unix variants, ++it supports both GTk+ and Motif toolkits. 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 `_ ++for more details. ++ ++`wxWidgets `_ is an extension module that wraps many of ++the wxWindows C++ classes, and is quickly gaining popularity amongst Python ++developers. You can get wxWidgets as part of the source or CVS distribution of ++wxWindows, or directly from its home page. ++ ++Qt ++''' ++ ++There are bindings available for the Qt toolkit (`PyQt ++`_) and for KDE (PyKDE). If ++you're writing open source software, you don't need to pay for PyQt, but if you ++want to write proprietary applications, you must buy a PyQt license from ++`Riverbank Computing `_ and (up to Qt 4.4; ++Qt 4.5 upwards is licensed under the LGPL license) a Qt license from `Trolltech ++`_. ++ ++Gtk+ ++'''' ++ ++PyGtk bindings for the `Gtk+ toolkit `_ have been ++implemented by by James Henstridge; see ftp://ftp.gtk.org/pub/gtk/python/. ++ ++FLTK ++'''' ++ ++Python bindings for `the FLTK toolkit `_, a simple yet ++powerful and mature cross-platform windowing system, are available from `the ++PyFLTK project `_. ++ ++ ++FOX ++''' ++ ++A wrapper for `the FOX toolkit `_ called `FXpy ++`_ is available. FOX supports both Unix variants ++and Windows. ++ ++ ++OpenGL ++'''''' ++ ++For OpenGL bindings, see `PyOpenGL `_. ++ ++ ++What platform-specific GUI toolkits exist for Python? ++----------------------------------------------------- ++ ++`The Mac port `_ by Jack Jansen has a rich and ++ever-growing set of modules that support the native Mac toolbox calls. The port ++includes support for MacOS9 and MacOS X's Carbon libraries. By installing the ++`PyObjc Objective-C bridge `_, Python programs ++can use MacOS X's Cocoa libraries. See the documentation that comes with the Mac ++port. ++ ++:ref:`Pythonwin ` by Mark Hammond includes an interface to the ++Microsoft Foundation Classes and a Python programming environment using it ++that's written mostly in Python. ++ ++ ++Tkinter questions ++================= ++ ++How do I freeze Tkinter applications? ++------------------------------------- ++ ++Freeze is a tool to create stand-alone applications. 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 :envvar:`TCL_LIBRARY` and :envvar:`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). ++ ++ ++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 :meth:`recv` or ++:meth:`recvfrom` methods will work fine; for other files, use ++``os.read(file.fileno(), maxbytecount)``. ++ ++ ++I can't get key bindings to work in Tkinter: why? ++------------------------------------------------- ++ ++An often-heard complaint is that event handlers bound to events with the ++:meth:`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 takefocus option). ++ ++ ++ + +Eigenschaftsänderungen: Doc/faq/gui.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/library.rst +=================================================================== +--- Doc/faq/library.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/library.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,872 @@ ++:tocdepth: 2 ++ ++========================= ++Library and Extension FAQ ++========================= ++ ++.. contents:: ++ ++General Library Questions ++========================= ++ ++How do I find a module or application to perform task X? ++-------------------------------------------------------- ++ ++Check :ref:`the Library Reference ` to see if there's a relevant ++standard library module. (Eventually you'll learn what's in the standard ++library and will able to skip this step.) ++ ++For third-party packages, search the `Python Package Index ++`_ or try `Google `_ or ++another Web search engine. Searching for "Python" plus a keyword or two for ++your topic of interest will usually find something helpful. ++ ++ ++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). ++ ++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 ++ ++ ++How do I make a Python script executable on Unix? ++------------------------------------------------- ++ ++You need to do two things: the script file's mode must be executable and the ++first line must begin with ``#!`` followed by the path of 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 ways. The most straightforward way is to ++write :: ++ ++ #!/usr/local/bin/python ++ ++as the very first line of your file, using the pathname for 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. Almost all Unix variants support the ++following, assuming the python interpreter is in a directory on the user's ++$PATH:: ++ ++ #!/usr/bin/env python ++ ++*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 minor disadvantage is that this defines the script's __doc__ string. ++However, you can fix that by adding :: ++ ++ __doc__ = """...Whatever...""" ++ ++ ++ ++Is there a curses/termcap package for Python? ++--------------------------------------------- ++ ++.. XXX curses *is* built by default, isn't it? ++ ++For Unix variants: 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). ++ ++The curses module supports basic curses features as well as many additional ++functions from ncurses and SYSV curses such as colour, alternative character set ++support, pads, and mouse support. This means the module isn't 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. ++ ++For Windows: use `the consolelib module ++`_. ++ ++ ++Is there an equivalent to C's onexit() in Python? ++------------------------------------------------- ++ ++The :mod:`atexit` module provides a register function that is similar to C's ++onexit. ++ ++ ++Why don't my signal handlers 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): ++ ... ++ ++ ++Common tasks ++============ ++ ++How do I test a Python program or component? ++-------------------------------------------- ++ ++Python comes with two testing frameworks. The :mod:`doctest` module finds ++examples in the docstrings for a module and runs them, comparing the output with ++the expected output given in the docstring. ++ ++The :mod:`unittest` module is a fancier testing framework modelled on Java and ++Smalltalk testing frameworks. ++ ++For testing, it helps to write the program so that it may be easily tested by ++using good modular design. 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 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. ++ ++ ++How do I create documentation from doc strings? ++----------------------------------------------- ++ ++The :mod:`pydoc` module can create HTML from the doc strings in your Python ++source code. An alternative for creating API documentation purely from ++docstrings is `epydoc `_. `Sphinx ++`_ can also include docstring content. ++ ++ ++How do I get a single keypress at a time? ++----------------------------------------- ++ ++For Unix variants: There are several solutions. It's straightforward to do this ++using curses, but curses is a fairly large module to learn. Here's a solution ++without curses:: ++ ++ 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 :mod:`termios` and the :mod:`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. ++ ++:func:`termios.tcsetattr` turns off stdin's echoing and disables canonical mode. ++:func:`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 ++:exc:`IOError`, this error is caught and ignored. ++ ++ ++Threads ++======= ++ ++How do I program using threads? ++------------------------------- ++ ++Be sure to use the :mod:`threading` module and not the :mod:`_thread` module. ++The :mod:`threading` module builds convenient abstractions on top of the ++low-level primitives provided by the :mod:`_thread` module. ++ ++Aahz has a set of slides from his threading tutorial that are helpful; see ++http://www.pythoncraft.com/OSCON2001/. ++ ++ ++None of my threads seem to run: why? ++------------------------------------ ++ ++As soon as the main thread exits, all threads are killed. Your main thread is ++running too quickly, giving the threads no time to do any work. ++ ++A simple fix is to add a sleep to the end of the program that's long enough for ++all the threads to finish:: ++ ++ import threading, time ++ ++ def thread_task(name, n): ++ for i in range(n): print name, i ++ ++ for i in range(10): ++ T = threading.Thread(target=thread_task, args=(str(i), i)) ++ T.start() ++ ++ 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:: ++ ++ def thread_task(name, n): ++ time.sleep(0.001) # <---------------------! ++ for i in range(n): print name, i ++ ++ for i in range(10): ++ T = threading.Thread(target=thread_task, args=(str(i), i)) ++ T.start() ++ ++ time.sleep(10) ++ ++Instead of trying to guess how long a :func:`time.sleep` delay will be enough, ++it's better to use some kind of semaphore mechanism. One idea is to use the ++:mod:`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. ++ ++ ++How do I parcel out work among a bunch of worker threads? ++--------------------------------------------------------- ++ ++Use the :mod:`queue` module to create a queue containing a list of jobs. The ++:class:`~queue.Queue` class maintains a list of objects with ``.put(obj)`` to ++add an item to the queue and ``.get()`` to return an item. The class will take ++care of the locking necessary to ensure that each job is handed out exactly ++once. ++ ++Here's a trivial example:: ++ ++ import threading, Queue, time ++ ++ # The worker thread gets jobs off the queue. When the queue is empty, it ++ # assumes there will be no more work and exits. ++ # (Realistically workers will run until terminated.) ++ def worker (): ++ print 'Running worker' ++ time.sleep(0.1) ++ while True: ++ try: ++ arg = q.get(block=False) ++ except Queue.Empty: ++ print 'Worker', threading.currentThread(), ++ print 'queue empty' ++ break ++ else: ++ print 'Worker', threading.currentThread(), ++ print 'running with argument', arg ++ time.sleep(0.5) ++ ++ # Create queue ++ q = Queue.Queue() ++ ++ # Start a pool of 5 workers ++ for i in range(5): ++ t = threading.Thread(target=worker, name='worker %i' % (i+1)) ++ t.start() ++ ++ # Begin adding work to the queue ++ for i in range(50): ++ q.put(i) ++ ++ # Give threads time to run ++ print 'Main thread sleeping' ++ time.sleep(5) ++ ++When run, this will produce the following output: ++ ++ Running worker ++ Running worker ++ Running worker ++ Running worker ++ Running worker ++ Main thread sleeping ++ Worker running with argument 0 ++ Worker running with argument 1 ++ Worker running with argument 2 ++ Worker running with argument 3 ++ Worker running with argument 4 ++ Worker running with argument 5 ++ ... ++ ++Consult the module's documentation for more details; the ``Queue`` class ++provides a featureful interface. ++ ++ ++What kinds of global value mutation are thread-safe? ++---------------------------------------------------- ++ ++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 switches can ++be set via :func:`sys.setcheckinterval`. Each bytecode instruction and ++therefore all the C implementation code reached from each instruction is ++therefore atomic from the point of view of a Python program. ++ ++In theory, this means an exact accounting requires an exact understanding of the ++PVM bytecode implementation. In practice, it means that operations on shared ++variables of builtin data types (ints, lists, dicts, etc) that "look atomic" ++really are. ++ ++For example, the following operations are all 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 ++ ++Operations that replace other objects may invoke those other objects' ++:meth:`__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! ++ ++ ++Can't we get rid of the Global Interpreter Lock? ++------------------------------------------------ ++ ++.. XXX mention multiprocessing ++.. XXX link to dbeazley's talk about GIL? ++ ++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 (the "free threading" patches) that removed the GIL and replaced 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 because 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, and users who don't ++use threads would not be happy if their code ran at half at 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! ++You just have to be creative with dividing the work up between multiple ++*processes* rather than multiple *threads*. Judicious use of C extensions will ++also help; if you use a C extension to perform a time-consuming task, the ++extension can release the GIL while the thread of execution is in the C code and ++allow other threads to get some work done. ++ ++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. ++For example, small integers and short 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? ++ ++ ++Input and Output ++================ ++ ++How do I delete a file? (And other file questions...) ++----------------------------------------------------- ++ ++Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see ++the :mod:`os` module. The two functions are identical; :func:`unlink` is simply ++the name of the Unix system call for this function. ++ ++To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one. ++``os.makedirs(path)`` will create any intermediate directories in ``path`` that ++don't exist. ``os.removedirs(path)`` will remove intermediate directories as ++long as they're empty; if you want to delete an entire directory tree and its ++contents, use :func:`shutil.rmtree`. ++ ++To rename a file, use ``os.rename(old_path, new_path)``. ++ ++To truncate a file, open it using ``f = open(filename, "r+")``, and use ++``f.truncate(offset)``; offset defaults to the current seek position. There's ++also ```os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where ++``fd`` is the file descriptor (a small integer). ++ ++The :mod:`shutil` module also contains a number of functions to work on files ++including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and ++:func:`~shutil.rmtree`. ++ ++ ++How do I copy a file? ++--------------------- ++ ++The :mod:`shutil` module contains a :func:`~shutil.copyfile` function. Note ++that on MacOS 9 it doesn't copy the resource fork and Finder info. ++ ++ ++How do I read (or write) binary data? ++------------------------------------- ++ ++To read or write complex binary data formats, it's best to use the :mod:`struct` ++module. It allows you to take a string 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 big-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 thefloats), ++you can also use the :mod:`array` module. ++ ++ ++I can't seem to use os.read() on a pipe created with os.popen(); why? ++--------------------------------------------------------------------- ++ ++:func:`os.read` is a low-level function which takes a file descriptor, a small ++integer representing the opened file. :func:`os.popen` creates a high-level ++file object, the same type returned by the builtin :func:`open` function. Thus, ++to read n bytes from a pipe p created with :func:`os.popen`, you need to use ++``p.read(n)``. ++ ++ ++How do I run a subprocess with pipes connected to both input and output? ++------------------------------------------------------------------------ ++ ++.. XXX update to use subprocess ++ ++Use the :mod:`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 may 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 :func:`popen3` to read stdout ++and stderr. If one of the two is too large for the internal buffer (increasing ++the buffer size 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 ++:func:`os.waitpid` with the :data:`os.WNOHANG` option can prevent this; a good ++place to insert such a call would be before calling ``popen2`` again. ++ ++In many cases, all you really need is to run some data through a command and get ++the result back. Unless the amount of data is very large, the easiest 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 :mod:`tempfile` exports a ``mktemp()`` ++function to generate unique temporary file names. :: ++ ++ import tempfile ++ import os ++ ++ class Popen3: ++ """ ++ This is a deadlock-safe 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. Or you can use 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 `_. ++ ++ ++How do I access the serial (RS232) port? ++---------------------------------------- ++ ++For Win32, POSIX (Linux, BSD, etc.), Jython: ++ ++ http://pyserial.sourceforge.net ++ ++For Unix, see a Usenet post by Mitch Chapman: ++ ++ http://groups.google.com/groups?selm=34A04430.CF9@ohioee.com ++ ++ ++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 you create in Python via the builtin ``file`` constructor, ++``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 also happens ++automatically 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. Running ``sys.stdout.close()`` marks ++the Python-level file object as being closed, but does *not* close the ++associated C stream. ++ ++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 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 ++ ++ ++Network/Internet Programming ++============================ ++ ++What WWW tools are there for Python? ++------------------------------------ ++ ++See the chapters titled :ref:`internet` and :ref:`netdata` in the Library ++Reference Manual. Python has many modules that will help you build server-side ++and client-side web systems. ++ ++.. XXX check if wiki page is still up to date ++ ++A summary of available frameworks is maintained by Paul Boddie at ++http://wiki.python.org/moin/WebProgramming . ++ ++Cameron Laird maintains a useful set of pages about Python web technologies at ++http://phaseit.net/claird/comp.lang.python/web_python. ++ ++ ++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 POST operations, query strings must be ++quoted by using :func:`urllib.quote`. 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.' ++ ++ ++What module should I use to help with generating HTML? ++------------------------------------------------------ ++ ++.. XXX add modern template languages ++ ++There are many different modules available: ++ ++* HTMLgen is 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. ++ ++* DocumentTemplate and Zope Page Templates are two different systems that are ++ part of Zope. ++ ++* Quixote's PTL uses Python syntax to assemble strings of text. ++ ++Consult the `Web Programming wiki pages ++`_ for more links. ++ ++ ++How do I send mail from a Python script? ++---------------------------------------- ++ ++Use the standard library module :mod:`smtplib`. ++ ++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 True: ++ line = sys.stdin.readline() ++ if not line: ++ break ++ msg += line ++ ++ # The actual mail send ++ server = smtplib.SMTP('localhost') ++ server.sendmail(fromaddr, toaddrs, msg) ++ server.quit() ++ ++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: receiver@example.com\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 ++ ++ ++How do I avoid blocking in the connect() method of a socket? ++------------------------------------------------------------ ++ ++The select module is commonly used to help with asynchronous I/O on sockets. ++ ++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 error number as ``.errno``. ++``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't ++finished yet. Different OSes will return different values, so you're going to ++have to check what's returned on your system. ++ ++You can use the ``connect_ex()`` method 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 to check if it's writable. ++ ++ ++Databases ++========= ++ ++Are there any interfaces to database packages in Python? ++-------------------------------------------------------- ++ ++Yes. ++ ++Interfaces to disk-based hashes such as :mod:`DBM ` and :mod:`GDBM ++` are also included with standard Python. There is also the ++:mod:`sqlite3` module, which provides a lightweight disk-based relational ++database. ++ ++Support for most relational databases is available. See the ++`DatabaseProgramming wiki page ++`_ for details. ++ ++ ++How do you implement persistent objects in Python? ++-------------------------------------------------- ++ ++The :mod:`pickle` library module solves this in a very general way (though you ++still can't store things like open files, sockets or windows), and the ++:mod:`shelve` library module uses pickle and (g)dbm to create persistent ++mappings containing arbitrary Python objects. ++ ++A more awkward way of doing things is to use pickle's little sister, marshal. ++The :mod:`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. This often beats doing something more complex and ++general such as using gdbm with pickle/shelve. ++ ++ ++Why is cPickle so slow? ++----------------------- ++ ++.. XXX update this, default protocol is 2/3 ++ ++The default format used by the pickle module is a slow one that results in ++readable pickles. Making it the default, but it would break backward ++compatibility:: ++ ++ largeString = 'z' * (100 * 1024) ++ myPickle = cPickle.dumps(largeString, protocol=1) ++ ++ ++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 library caches database ++contents which need to be converted to on-disk form and written. ++ ++If you have initialized a new bsddb database but not written anything to it ++before the program crashes, you will often wind up with a zero-length file and ++encounter an exception the next time the file is opened. ++ ++ ++I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data? ++---------------------------------------------------------------------------------------------------------------------------- ++ ++Don't panic! Your data is probably intact. The most frequent cause for the error ++is that you tried to open an earlier Berkeley DB file with a later version of ++the Berkeley DB library. ++ ++Many Linux systems now have all three versions of Berkeley DB available. If you ++are migrating from version 1 to a newer version use db_dump185 to dump a plain ++text version of the database. If you are migrating from version 2 to version 3 ++use db2_dump to create a plain text version of the database. In either case, ++use db_load to create a new native database for the latest version installed on ++your computer. If you have version 3 of Berkeley DB installed, you should be ++able to use db2_load to create a native version 2 database. ++ ++You should move away from Berkeley DB version 1 files because the hash file code ++contains known bugs that can corrupt your data. ++ ++ ++Mathematics and Numerics ++======================== ++ ++How do I generate random numbers in Python? ++------------------------------------------- ++ ++The standard module :mod:`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)`` samples the 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 ``Random`` class you can instantiate to create independent ++multiple random number generators. + +Eigenschaftsänderungen: Doc/faq/library.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/extending.rst +=================================================================== +--- Doc/faq/extending.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/extending.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,481 @@ ++======================= ++Extending/Embedding FAQ ++======================= ++ ++.. contents:: ++ ++.. highlight:: c ++ ++ ++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 ++:ref:`extending-index`. ++ ++Most intermediate or advanced Python books will also cover this topic. ++ ++ ++Can I create my own functions in C++? ++------------------------------------- ++ ++Yes, using the C compatibility features found in C++. 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. ++ ++ ++Writing C is hard; are there any alternatives? ++---------------------------------------------- ++ ++There are a number of alternatives to writing your own C extensions, depending ++on what you're trying to do. ++ ++.. XXX make sure these all work; mention Cython ++ ++If you need more speed, `Psyco `_ generates x86 ++assembly code from Python bytecode. You can use Psyco to compile the most ++time-critical functions in your code, and gain a significant improvement with ++very little effort, as long as you're running on a machine with an ++x86-compatible processor. ++ ++`Pyrex `_ is a compiler ++that accepts a slightly modified form of Python and generates the corresponding ++C code. Pyrex makes it possible to write an extension without having to learn ++Python's C API. ++ ++If you need to interface to some C or C++ library for which no Python extension ++currently exists, you can try wrapping the library's data types and functions ++with a tool such as `SWIG `_. `SIP ++`__, `CXX ++`_ `Boost ++`_, or `Weave ++`_ are also alternatives for wrapping ++C++ libraries. ++ ++ ++How can I execute arbitrary Python statements from C? ++----------------------------------------------------- ++ ++The highest-level function to do this is :cfunc:`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 ++``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 ++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`. ++ ++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. ++ ++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. ++ ++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 ++many other useful protocols. ++ ++ ++How do I use Py_BuildValue() to create a tuple of arbitrary length? ++------------------------------------------------------------------- ++ ++You can't. Use ``t = PyTuple_New(n)`` instead, and fill it with objects using ++``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of ++``o``, so you have to :cfunc:`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. ++ ++ ++How do I call an object's method from C? ++---------------------------------------- ++ ++The :cfunc:`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 ++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 :cfunc:`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"):: ++ ++ res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0); ++ if (res == NULL) { ++ ... an exception occurred ... ++ } ++ else { ++ Py_DECREF(res); ++ } ++ ++Note that since :cfunc:`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)". ++ ++ ++How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? ++---------------------------------------------------------------------------------------- ++ ++In Python code, define an object that supports the ``write()`` method. Assign ++this object to :data:`sys.stdout` and :data:`sys.stderr`. 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! ++ ++ ++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(""); ++ ++If the module hasn't been imported yet (i.e. it is not yet present in ++:data:`sys.modules`), this initializes the module; otherwise it simply returns ++the value of ``sys.modules[""]``. Note that it doesn't enter the ++module into any namespace -- it only ensures it has been initialized and is ++stored in :data:`sys.modules`. ++ ++You can then access the module's attributes (i.e. any name defined in the ++module) as follows:: ++ ++ attr = PyObject_GetAttrString(module, ""); ++ ++Calling :cfunc:`PyObject_SetAttrString` to assign to variables in the module ++also works. ++ ++ ++How do I interface to C++ objects from Python? ++---------------------------------------------- ++ ++Depending on your requirements, there are many approaches. To do this manually, ++begin by reading :ref:`the "Extending and Embedding" document ++`. Realize that for the Python run-time system, there isn't a ++whole lot of difference between C and C++ -- so the strategy of building a new ++Python type around a C structure (pointer) type will also work for C++ objects. ++ ++For C++ libraries, you can look at `SIP ++`_, `CXX ++`_, `Boost ++`_, `Weave ++`_ or `SWIG `_ ++ ++ ++I added a module using the Setup file and the make fails; why? ++-------------------------------------------------------------- ++ ++Setup must end in a newline, if there is no newline there, the build process ++fails. (Fixing this requires some ugly shell script hackery, and this bug is so ++minor that it doesn't seem worth the effort.) ++ ++ ++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 ++ ++Then, when you run GDB:: ++ ++ $ 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 ++ ++I want to compile a Python module on my Linux system, but some files are missing. Why? ++-------------------------------------------------------------------------------------- ++ ++Most packaged versions of Python don't include the ++:file:`/usr/lib/python2.{x}/config/` directory, which contains various files ++required for compiling Python extensions. ++ ++For Red Hat, install the python-devel RPM to get the necessary files. ++ ++For Debian, run ``apt-get install python-dev``. ++ ++ ++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 extension ++module, the :exc:`SystemError` exception will be raised. ++ ++ ++How do I 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 :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 ++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 ++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`` ++equal to ``E_EOF``, which means the input is incomplete). Here's a sample code ++fragment, untested, inspired by code from Alex Farber:: ++ ++ #include ++ #include ++ #include ++ #include ++ #include ++ #include ++ ++ 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 ++:cfunc:`Py_CompileString`. If it compiles without errors, try to execute the ++returned code object by calling :cfunc:`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 ++complete example using the GNU readline library (you may want to ignore ++**SIGINT** while calling readline()):: ++ ++ #include ++ #include ++ ++ #include ++ #include ++ #include ++ #include ++ ++ 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, "", 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); ++ } ++ ++ ++How do I find undefined g++ symbols __builtin_new or __pure_virtual? ++-------------------------------------------------------------------- ++ ++To dynamically load g++ extension modules, you must recompile Python, relink it ++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``). ++ ++ ++Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)? ++---------------------------------------------------------------------------------------------------------------- ++ ++In Python 2.2, you can inherit from builtin classes such as :class:`int`, ++:class:`list`, :class:`dict`, etc. ++ ++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). ++ ++ ++When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"? ++------------------------------------------------------------------------- ++ ++You are using a version of Python that uses a 4-byte representation for Unicode ++characters, but some C extension module you are importing 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 reverse: 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, 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`. ++ ++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. ++ ++ ++ + +Eigenschaftsänderungen: Doc/faq/extending.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/index.rst +=================================================================== +--- Doc/faq/index.rst (.../tags/r311) (Revision 0) ++++ Doc/faq/index.rst (.../branches/release31-maint) (Revision 76056) +@@ -0,0 +1,18 @@ ++################################### ++ Python Frequently Asked Questions ++################################### ++ ++:Release: |version| ++:Date: |today| ++ ++.. toctree:: ++ :maxdepth: 1 ++ ++ general.rst ++ programming.rst ++ design.rst ++ library.rst ++ extending.rst ++ windows.rst ++ gui.rst ++ installed.rst + +Eigenschaftsänderungen: Doc/faq/index.rst +___________________________________________________________________ +Hinzugefügt: svn:eol-style + + native + +Index: Doc/faq/python-video-icon.png +=================================================================== +Kann nicht anzeigen: Dateityp ist als binär angegeben. +svn:mime-type = application/octet-stream + +Eigenschaftsänderungen: Doc/faq/python-video-icon.png +___________________________________________________________________ +Hinzugefügt: svn:mime-type + + application/octet-stream + +Index: Doc/documenting/markup.rst +=================================================================== +--- Doc/documenting/markup.rst (.../tags/r311) (Revision 76056) ++++ Doc/documenting/markup.rst (.../branches/release31-maint) (Revision 76056) +@@ -597,8 +597,10 @@ + 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. This should only be chosen over ``note`` for information +- regarding the possibility of crashes, data loss, or security implications. ++ 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 + +@@ -624,6 +626,24 @@ + + -------------- + ++.. 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 +Index: Doc/conf.py +=================================================================== +--- Doc/conf.py (.../tags/r311) (Revision 76056) ++++ Doc/conf.py (.../branches/release31-maint) (Revision 76056) +@@ -86,7 +86,7 @@ + } + + # Output an OpenSearch description file. +-html_use_opensearch = 'http://docs.python.org/dev/3.0' ++html_use_opensearch = 'http://docs.python.org/3.1' + + # Additional static files. + html_static_path = ['tools/sphinxext/static'] +@@ -151,6 +151,9 @@ + # Documents to append as an appendix to all manuals. + latex_appendices = ['glossary', 'about', 'license', 'copyright'] + ++# Get LaTeX to handle Unicode correctly ++latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}'} ++ + # Options for the coverage checker + # -------------------------------- + +Index: Lib/idlelib/rpc.py +=================================================================== +--- Lib/idlelib/rpc.py (.../tags/r311) (Revision 76056) ++++ Lib/idlelib/rpc.py (.../branches/release31-maint) (Revision 76056) +@@ -595,4 +595,4 @@ + + + # XXX KBK 09Sep03 We need a proper unit test for this module. Previously +-# existing test code was removed at Rev 1.27. ++# existing test code was removed at Rev 1.27 (r34098). +Index: Lib/idlelib/macosxSupport.py +=================================================================== +--- Lib/idlelib/macosxSupport.py (.../tags/r311) (Revision 76056) ++++ Lib/idlelib/macosxSupport.py (.../branches/release31-maint) (Revision 76056) +@@ -9,7 +9,7 @@ + """ + Returns True if Python is running from within an app on OSX. + If so, assume that Python was built with Aqua Tcl/Tk rather than +- X11 Tck/Tk. ++ X11 Tcl/Tk. + """ + return (sys.platform == 'darwin' and '.app' in sys.executable) + +Index: Lib/xmlrpc/client.py +=================================================================== +--- Lib/xmlrpc/client.py (.../tags/r311) (Revision 76056) ++++ Lib/xmlrpc/client.py (.../branches/release31-maint) (Revision 76056) +@@ -480,7 +480,7 @@ + # by the way, if you don't understand what's going on in here, + # that's perfectly ok. + +- def __init__(self, encoding=None, allow_none=0): ++ def __init__(self, encoding=None, allow_none=False): + self.memo = {} + self.data = None + self.encoding = encoding +@@ -653,7 +653,7 @@ + # and again, if you don't understand what's going on in here, + # that's perfectly ok. + +- def __init__(self, use_datetime=0): ++ def __init__(self, use_datetime=False): + self._type = None + self._stack = [] + self._marks = [] +@@ -886,7 +886,7 @@ + # + # return A (parser, unmarshaller) tuple. + +-def getparser(use_datetime=0): ++def getparser(use_datetime=False): + """getparser() -> parser, unmarshaller + + Create an instance of the fastest available parser, and attach it +@@ -923,7 +923,7 @@ + # @return A string containing marshalled data. + + def dumps(params, methodname=None, methodresponse=None, encoding=None, +- allow_none=0): ++ allow_none=False): + """data [,options] -> marshalled data + + Convert an argument tuple or a Fault instance to an XML-RPC +@@ -999,7 +999,7 @@ + # (None if not present). + # @see Fault + +-def loads(data, use_datetime=0): ++def loads(data, use_datetime=False): + """data -> unmarshalled data, method name + + Convert an XML-RPC packet to unmarshalled data plus a method +@@ -1040,7 +1040,7 @@ + # client identifier (may be overridden) + user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__ + +- def __init__(self, use_datetime=0): ++ def __init__(self, use_datetime=False): + self._use_datetime = use_datetime + + ## +@@ -1052,7 +1052,7 @@ + # @param verbose Debugging flag. + # @return Parsed response. + +- def request(self, host, handler, request_body, verbose=0): ++ def request(self, host, handler, request_body, verbose=False): + # issue XML-RPC request + + http_conn = self.send_request(host, handler, request_body, verbose) +@@ -1234,8 +1234,8 @@ + the given encoding. + """ + +- def __init__(self, uri, transport=None, encoding=None, verbose=0, +- allow_none=0, use_datetime=0): ++ def __init__(self, uri, transport=None, encoding=None, verbose=False, ++ allow_none=False, use_datetime=False): + # establish a "logical" server connection + + # get the url +Index: Lib/xmlrpc/server.py +=================================================================== +--- Lib/xmlrpc/server.py (.../tags/r311) (Revision 76056) ++++ Lib/xmlrpc/server.py (.../branches/release31-maint) (Revision 76056) +@@ -201,7 +201,7 @@ + self.instance = instance + self.allow_dotted_names = allow_dotted_names + +- def register_function(self, function, name = None): ++ def register_function(self, function, name=None): + """Registers a function to respond to XML-RPC requests. + + The optional name argument can be used to set a Unicode name +@@ -578,7 +578,7 @@ + sys.stdout.buffer.write(response) + sys.stdout.buffer.flush() + +- def handle_request(self, request_text = None): ++ def handle_request(self, request_text=None): + """Handle a single XML-RPC request passed through a CGI post method. + + If no XML data is given then it is read from stdin. The resulting +@@ -837,7 +837,7 @@ + """ + + def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler, +- logRequests=1, allow_none=False, encoding=None, ++ logRequests=True, allow_none=False, encoding=None, + bind_and_activate=True): + SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, + allow_none, encoding, bind_and_activate) +Index: Lib/wsgiref/util.py +=================================================================== +--- Lib/wsgiref/util.py (.../tags/r311) (Revision 76056) ++++ Lib/wsgiref/util.py (.../branches/release31-maint) (Revision 76056) +@@ -67,7 +67,7 @@ + url += quote(environ.get('SCRIPT_NAME') or '/') + return url + +-def request_uri(environ, include_query=1): ++def request_uri(environ, include_query=True): + """Return the full request URI, optionally including the query string""" + url = application_uri(environ) + from urllib.parse import quote +Index: Lib/multiprocessing/managers.py +=================================================================== +--- Lib/multiprocessing/managers.py (.../tags/r311) (Revision 76056) ++++ Lib/multiprocessing/managers.py (.../branches/release31-maint) (Revision 76056) +@@ -413,7 +413,7 @@ + self.id_to_refcount[ident] -= 1 + if self.id_to_refcount[ident] == 0: + del self.id_to_obj[ident], self.id_to_refcount[ident] +- util.debug('disposing of obj with id %d', ident) ++ util.debug('disposing of obj with id %r', ident) + finally: + self.mutex.release() + +Index: Lib/multiprocessing/queues.py +=================================================================== +--- Lib/multiprocessing/queues.py (.../tags/r311) (Revision 76056) ++++ Lib/multiprocessing/queues.py (.../branches/release31-maint) (Revision 76056) +@@ -282,10 +282,23 @@ + Queue.__setstate__(self, state[:-2]) + self._cond, self._unfinished_tasks = state[-2:] + +- def put(self, item, block=True, timeout=None): +- Queue.put(self, item, block, timeout) +- self._unfinished_tasks.release() ++ def put(self, obj, block=True, timeout=None): ++ assert not self._closed ++ if not self._sem.acquire(block, timeout): ++ raise Full + ++ self._notempty.acquire() ++ self._cond.acquire() ++ try: ++ if self._thread is None: ++ self._start_thread() ++ self._buffer.append(obj) ++ self._unfinished_tasks.release() ++ self._notempty.notify() ++ finally: ++ self._cond.release() ++ self._notempty.release() ++ + def task_done(self): + self._cond.acquire() + try: +Index: Lib/threading.py +=================================================================== +--- Lib/threading.py (.../tags/r311) (Revision 76056) ++++ Lib/threading.py (.../branches/release31-maint) (Revision 76056) +@@ -97,7 +97,7 @@ + owner and owner.name, + self._count) + +- def acquire(self, blocking=1): ++ def acquire(self, blocking=True): + me = current_thread() + if self._owner is me: + self._count = self._count + 1 +@@ -119,7 +119,7 @@ + + def release(self): + if self._owner is not current_thread(): +- raise RuntimeError("cannot release un-aquired lock") ++ raise RuntimeError("cannot release un-acquired lock") + self._count = count = self._count - 1 + if not count: + self._owner = None +@@ -211,7 +211,7 @@ + + def wait(self, timeout=None): + if not self._is_owned(): +- raise RuntimeError("cannot wait on un-aquired lock") ++ raise RuntimeError("cannot wait on un-acquired lock") + waiter = _allocate_lock() + waiter.acquire() + self._waiters.append(waiter) +@@ -253,7 +253,7 @@ + + def notify(self, n=1): + if not self._is_owned(): +- raise RuntimeError("cannot notify on un-aquired lock") ++ raise RuntimeError("cannot notify on un-acquired lock") + __waiters = self._waiters + waiters = __waiters[:n] + if not waiters: +@@ -289,7 +289,7 @@ + self._cond = Condition(Lock()) + self._value = value + +- def acquire(self, blocking=1): ++ def acquire(self, blocking=True): + rc = False + self._cond.acquire() + while self._value == 0: +Index: Lib/getpass.py +=================================================================== +--- Lib/getpass.py (.../tags/r311) (Revision 76056) ++++ Lib/getpass.py (.../branches/release31-maint) (Revision 76056) +@@ -51,7 +51,7 @@ + # If that fails, see if stdin can be controlled. + try: + fd = sys.stdin.fileno() +- except: ++ except (AttributeError, ValueError): + passwd = fallback_getpass(prompt, stream) + input = sys.stdin + if not stream: +@@ -62,12 +62,16 @@ + try: + old = termios.tcgetattr(fd) # a copy to save + new = old[:] +- new[3] &= ~termios.ECHO # 3 == 'lflags' ++ new[3] &= ~(termios.ECHO|termios.ISIG) # 3 == 'lflags' ++ tcsetattr_flags = termios.TCSAFLUSH ++ if hasattr(termios, 'TCSASOFT'): ++ tcsetattr_flags |= termios.TCSASOFT + try: +- termios.tcsetattr(fd, termios.TCSADRAIN, new) ++ termios.tcsetattr(fd, tcsetattr_flags, new) + passwd = _raw_input(prompt, stream, input=input) + finally: +- termios.tcsetattr(fd, termios.TCSADRAIN, old) ++ termios.tcsetattr(fd, tcsetattr_flags, old) ++ stream.flush() # issue7208 + except termios.error as e: + if passwd is not None: + # _raw_input succeeded. The final tcsetattr failed. Reraise +@@ -124,6 +128,7 @@ + if prompt: + stream.write(prompt) + stream.flush() ++ # NOTE: The Python C API calls flockfile() (and unlock) during readline. + line = input.readline() + if not line: + raise EOFError +Index: Lib/importlib/test/import_/test_caching.py +=================================================================== +--- Lib/importlib/test/import_/test_caching.py (.../tags/r311) (Revision 76056) ++++ Lib/importlib/test/import_/test_caching.py (.../branches/release31-maint) (Revision 76056) +@@ -17,16 +17,26 @@ + loader returns) [from cache on return]. This also applies to imports of + things contained within a package and thus get assigned as an attribute + [from cache to attribute] or pulled in thanks to a fromlist import +- [from cache for fromlist]. ++ [from cache for fromlist]. But if sys.modules contains None then ++ ImportError is raised [None in cache]. + + """ + def test_using_cache(self): + # [use cache] + module_to_use = "some module found!" +- sys.modules['some_module'] = module_to_use +- module = import_util.import_('some_module') +- self.assertEqual(id(module_to_use), id(module)) ++ with util.uncache(module_to_use): ++ sys.modules['some_module'] = module_to_use ++ module = import_util.import_('some_module') ++ self.assertEqual(id(module_to_use), id(module)) + ++ def test_None_in_cache(self): ++ #[None in cache] ++ name = 'using_None' ++ with util.uncache(name): ++ sys.modules[name] = None ++ with self.assertRaises(ImportError): ++ import_util.import_(name) ++ + def create_mock(self, *names, return_=None): + mock = util.mock_modules(*names) + original_load = mock.load_module +Index: Lib/importlib/_bootstrap.py +=================================================================== +--- Lib/importlib/_bootstrap.py (.../tags/r311) (Revision 76056) ++++ Lib/importlib/_bootstrap.py (.../branches/release31-maint) (Revision 76056) +@@ -860,7 +860,12 @@ + name = package[:dot] + with _ImportLockContext(): + try: +- return sys.modules[name] ++ module = sys.modules[name] ++ if module is None: ++ message = ("import of {} halted; " ++ "None in sys.modules".format(name)) ++ raise ImportError(message) ++ return module + except KeyError: + pass + parent = name.rpartition('.')[0] +Index: Lib/smtplib.py +=================================================================== +--- Lib/smtplib.py (.../tags/r311) (Revision 76056) ++++ Lib/smtplib.py (.../branches/release31-maint) (Revision 76056) +@@ -800,13 +800,13 @@ + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.connect(host) + except socket.error as msg: +- if self.debuglevel > 0: print>>stderr, 'connect fail:', host ++ if self.debuglevel > 0: print('connect fail:', host, file=stderr) + if self.sock: + self.sock.close() + self.sock = None + raise socket.error(msg) + (code, msg) = self.getreply() +- if self.debuglevel > 0: print>>stderr, "connect:", msg ++ if self.debuglevel > 0: print('connect:', msg, file=stderr) + return (code, msg) + + +Index: Lib/textwrap.py +=================================================================== +--- Lib/textwrap.py (.../tags/r311) (Revision 76056) ++++ Lib/textwrap.py (.../branches/release31-maint) (Revision 76056) +@@ -135,7 +135,7 @@ + """_split(text : string) -> [string] + + Split the text to wrap into indivisible chunks. Chunks are +- not quite the same as words; see wrap_chunks() for full ++ not quite the same as words; see _wrap_chunks() for full + details. As an example, the text + Look, goof-ball -- use the -b option! + breaks into the following chunks: +@@ -163,9 +163,9 @@ + space to two. + """ + i = 0 +- pat = self.sentence_end_re ++ patsearch = self.sentence_end_re.search + while i < len(chunks)-1: +- if chunks[i+1] == " " and pat.search(chunks[i]): ++ if chunks[i+1] == " " and patsearch(chunks[i]): + chunks[i+1] = " " + i += 2 + else: +Index: Lib/http/cookies.py +=================================================================== +--- Lib/http/cookies.py (.../tags/r311) (Revision 76056) ++++ Lib/http/cookies.py (.../branches/release31-maint) (Revision 76056) +@@ -535,7 +535,9 @@ + if type(rawdata) == type(""): + self.__ParseString(rawdata) + else: +- self.update(rawdata) ++ # self.update() wouldn't call our custom __setitem__ ++ for k, v in rawdata.items(): ++ self[k] = v + return + # end load() + +Index: Lib/http/client.py +=================================================================== +--- Lib/http/client.py (.../tags/r311) (Revision 76056) ++++ Lib/http/client.py (.../branches/release31-maint) (Revision 76056) +@@ -518,10 +518,7 @@ + def _read_chunked(self, amt): + assert self.chunked != _UNKNOWN + chunk_left = self.chunk_left +- value = b"" +- +- # XXX This accumulates chunks by repeated string concatenation, +- # which is not efficient as the number or size of chunks gets big. ++ value = [] + while True: + if chunk_left is None: + line = self.fp.readline() +@@ -534,22 +531,22 @@ + # close the connection as protocol synchronisation is + # probably lost + self.close() +- raise IncompleteRead(value) ++ raise IncompleteRead(b''.join(value)) + if chunk_left == 0: + break + if amt is None: +- value += self._safe_read(chunk_left) ++ value.append(self._safe_read(chunk_left)) + elif amt < chunk_left: +- value += self._safe_read(amt) ++ value.append(self._safe_read(amt)) + self.chunk_left = chunk_left - amt +- return value ++ return b''.join(value) + elif amt == chunk_left: +- value += self._safe_read(amt) ++ value.append(self._safe_read(amt)) + self._safe_read(2) # toss the CRLF at the end of the chunk + self.chunk_left = None +- return value ++ return b''.join(value) + else: +- value += self._safe_read(chunk_left) ++ value.append(self._safe_read(chunk_left)) + amt -= chunk_left + + # we read the whole chunk, get another +@@ -570,7 +567,7 @@ + # we read everything; close the "file" + self.close() + +- return value ++ return b''.join(value) + + def _safe_read(self, amt): + """Read the number of bytes requested, compensating for partial reads. +@@ -729,10 +726,17 @@ + if self.debuglevel > 0: + print("sendIng a read()able") + encode = False +- if "b" not in str.mode: +- encode = True +- if self.debuglevel > 0: +- print("encoding file using iso-8859-1") ++ try: ++ mode = str.mode ++ except AttributeError: ++ # io.BytesIO and other file-like objects don't have a `mode` ++ # attribute. ++ pass ++ else: ++ if "b" not in mode: ++ encode = True ++ if self.debuglevel > 0: ++ print("encoding file using iso-8859-1") + while 1: + data = str.read(blocksize) + if not data: +Index: Lib/tokenize.py +=================================================================== +--- Lib/tokenize.py (.../tags/r311) (Revision 76056) ++++ Lib/tokenize.py (.../branches/release31-maint) (Revision 76056) +@@ -279,6 +279,17 @@ + return out + + ++def _get_normal_name(orig_enc): ++ """Imitates get_normal_name in tokenizer.c.""" ++ # Only care about the first 12 characters. ++ enc = orig_enc[:12].lower().replace("_", "-") ++ if enc == "utf-8" or enc.startswith("utf-8-"): ++ return "utf-8" ++ if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ ++ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): ++ return "iso-8859-1" ++ return orig_enc ++ + def detect_encoding(readline): + """ + The detect_encoding() function is used to detect the encoding that should +@@ -313,7 +324,7 @@ + matches = cookie_re.findall(line_string) + if not matches: + return None +- encoding = matches[0] ++ encoding = _get_normal_name(matches[0]) + try: + codec = lookup(encoding) + except LookupError: +Index: Lib/warnings.py +=================================================================== +--- Lib/warnings.py (.../tags/r311) (Revision 76056) ++++ Lib/warnings.py (.../branches/release31-maint) (Revision 76056) +@@ -29,10 +29,17 @@ + return s + + def filterwarnings(action, message="", category=Warning, module="", lineno=0, +- append=0): ++ append=False): + """Insert an entry into the list of warnings filters (at the front). + +- Use assertions to check that all arguments have the right type.""" ++ 'action' -- one of "error", "ignore", "always", "default", "module", ++ or "once" ++ 'message' -- a regex that the warning message must match ++ 'category' -- a class that the warning must be a subclass of ++ 'module' -- a regex that the module name must match ++ 'lineno' -- an integer line number, 0 matches all warnings ++ 'append' -- if true, append to the list of filters ++ """ + import re + assert action in ("error", "ignore", "always", "default", "module", + "once"), "invalid action: %r" % (action,) +@@ -49,10 +56,15 @@ + else: + filters.insert(0, item) + +-def simplefilter(action, category=Warning, lineno=0, append=0): ++def simplefilter(action, category=Warning, lineno=0, append=False): + """Insert a simple entry into the list of warnings filters (at the front). + + A simple filter matches all modules and messages. ++ 'action' -- one of "error", "ignore", "always", "default", "module", ++ or "once" ++ 'category' -- a class that the warning must be a subclass of ++ 'lineno' -- an integer line number, 0 matches all warnings ++ 'append' -- if true, append to the list of filters + """ + assert action in ("error", "ignore", "always", "default", "module", + "once"), "invalid action: %r" % (action,) +Index: Lib/distutils/cmd.py +=================================================================== +--- Lib/distutils/cmd.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/cmd.py (.../branches/release31-maint) (Revision 76056) +@@ -157,7 +157,7 @@ + self.announce(indent + header, level=log.INFO) + indent = indent + " " + for (option, _, _) in self.user_options: +- option = longopt_xlate(option) ++ option = option.translate(longopt_xlate) + if option[-1] == "=": + option = option[:-1] + value = getattr(self, option) +Index: Lib/distutils/dist.py +=================================================================== +--- Lib/distutils/dist.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/dist.py (.../branches/release31-maint) (Revision 76056) +@@ -354,7 +354,7 @@ + parser = ConfigParser() + for filename in filenames: + if DEBUG: +- self.announce(" reading", filename) ++ self.announce(" reading %s" % filename) + parser.read(filename) + for section in parser.sections(): + options = parser.options(section) +Index: Lib/distutils/tests/test_install_lib.py +=================================================================== +--- Lib/distutils/tests/test_install_lib.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_install_lib.py (.../branches/release31-maint) (Revision 76056) +@@ -10,9 +10,9 @@ + + class InstallLibTestCase(support.TempdirManager, + support.LoggingSilencer, ++ support.EnvironGuard, + unittest.TestCase): + +- + def test_finalize_options(self): + pkg_dir, dist = self.create_dist() + cmd = install_lib(dist) +@@ -31,6 +31,8 @@ + cmd.finalize_options() + self.assertEquals(cmd.optimize, 2) + ++ @unittest.skipUnless(not sys.dont_write_bytecode, ++ 'byte-compile not supported') + def test_byte_compile(self): + pkg_dir, dist = self.create_dist() + cmd = install_lib(dist) +@@ -76,7 +78,22 @@ + # get_input should return 2 elements + self.assertEquals(len(cmd.get_inputs()), 2) + ++ def test_dont_write_bytecode(self): ++ # makes sure byte_compile is not used ++ pkg_dir, dist = self.create_dist() ++ cmd = install_lib(dist) ++ cmd.compile = 1 ++ cmd.optimize = 1 + ++ old_dont_write_bytecode = sys.dont_write_bytecode ++ sys.dont_write_bytecode = True ++ try: ++ cmd.byte_compile([]) ++ finally: ++ sys.dont_write_bytecode = old_dont_write_bytecode ++ ++ self.assertTrue('byte-compiling is disabled' in self.logs[0][1]) ++ + def test_suite(): + return unittest.makeSuite(InstallLibTestCase) + +Index: Lib/distutils/tests/test_install_data.py +=================================================================== +--- Lib/distutils/tests/test_install_data.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_install_data.py (.../branches/release31-maint) (Revision 76056) +@@ -9,6 +9,7 @@ + + class InstallDataTestCase(support.TempdirManager, + support.LoggingSilencer, ++ support.EnvironGuard, + unittest.TestCase): + + def test_simple_run(self): +Index: Lib/distutils/tests/test_install_headers.py +=================================================================== +--- Lib/distutils/tests/test_install_headers.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_install_headers.py (.../branches/release31-maint) (Revision 76056) +@@ -9,6 +9,7 @@ + + class InstallHeadersTestCase(support.TempdirManager, + support.LoggingSilencer, ++ support.EnvironGuard, + unittest.TestCase): + + def test_simple_run(self): +Index: Lib/distutils/tests/test_dist.py +=================================================================== +--- Lib/distutils/tests/test_dist.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_dist.py (.../branches/release31-maint) (Revision 76056) +@@ -37,15 +37,17 @@ + + + class DistributionTestCase(support.LoggingSilencer, ++ support.EnvironGuard, + unittest.TestCase): + + def setUp(self): + super(DistributionTestCase, self).setUp() +- self.argv = sys.argv[:] ++ self.argv = sys.argv, sys.argv[:] + del sys.argv[1:] + + def tearDown(self): +- sys.argv[:] = self.argv ++ sys.argv = self.argv[0] ++ sys.argv[:] = self.argv[1] + super(DistributionTestCase, self).tearDown() + + def create_distribution(self, configfiles=()): +@@ -149,9 +151,25 @@ + self.assertEquals(cmds, ['distutils.command', 'one', 'two']) + + ++ def test_announce(self): ++ # make sure the level is known ++ dist = Distribution() ++ args = ('ok',) ++ kwargs = {'level': 'ok2'} ++ self.assertRaises(ValueError, dist.announce, args, kwargs) ++ + class MetadataTestCase(support.TempdirManager, support.EnvironGuard, + unittest.TestCase): + ++ def setUp(self): ++ super(MetadataTestCase, self).setUp() ++ self.argv = sys.argv, sys.argv[:] ++ ++ def tearDown(self): ++ sys.argv = self.argv[0] ++ sys.argv[:] = self.argv[1] ++ super(MetadataTestCase, self).tearDown() ++ + def test_simple_metadata(self): + attrs = {"name": "package", + "version": "1.0"} +@@ -250,14 +268,14 @@ + + # linux-style + if sys.platform in ('linux', 'darwin'): +- self.environ['HOME'] = temp_dir ++ os.environ['HOME'] = temp_dir + files = dist.find_config_files() + self.assertTrue(user_filename in files) + + # win32-style + if sys.platform == 'win32': + # home drive should be found +- self.environ['HOME'] = temp_dir ++ os.environ['HOME'] = temp_dir + files = dist.find_config_files() + self.assertTrue(user_filename in files, + '%r not found in %r' % (user_filename, files)) +@@ -273,15 +291,11 @@ + def test_show_help(self): + # smoke test, just makes sure some help is displayed + dist = Distribution() +- old_argv = sys.argv + sys.argv = [] +- try: +- dist.help = 1 +- dist.script_name = 'setup.py' +- with captured_stdout() as s: +- dist.parse_command_line() +- finally: +- sys.argv = old_argv ++ dist.help = 1 ++ dist.script_name = 'setup.py' ++ with captured_stdout() as s: ++ dist.parse_command_line() + + output = [line for line in s.getvalue().split('\n') + if line.strip() != ''] +Index: Lib/distutils/tests/test_archive_util.py +=================================================================== +--- Lib/distutils/tests/test_archive_util.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_archive_util.py (.../branches/release31-maint) (Revision 76056) +@@ -8,7 +8,8 @@ + import warnings + + from distutils.archive_util import (check_archive_formats, make_tarball, +- make_zipfile, make_archive) ++ make_zipfile, make_archive, ++ ARCHIVE_FORMATS) + from distutils.spawn import find_executable, spawn + from distutils.tests import support + from test.support import check_warnings +@@ -192,6 +193,20 @@ + base_name = os.path.join(tmpdir, 'archive') + self.assertRaises(ValueError, make_archive, base_name, 'xxx') + ++ def test_make_archive_cwd(self): ++ current_dir = os.getcwd() ++ def _breaks(*args, **kw): ++ raise RuntimeError() ++ ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file') ++ try: ++ try: ++ make_archive('xxx', 'xxx', root_dir=self.mkdtemp()) ++ except: ++ pass ++ self.assertEquals(os.getcwd(), current_dir) ++ finally: ++ del ARCHIVE_FORMATS['xxx'] ++ + def test_suite(): + return unittest.makeSuite(ArchiveUtilTestCase) + +Index: Lib/distutils/tests/test_build_ext.py +=================================================================== +--- Lib/distutils/tests/test_build_ext.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_build_ext.py (.../branches/release31-maint) (Revision 76056) +@@ -32,7 +32,7 @@ + # Note that we're making changes to sys.path + super(BuildExtTestCase, self).setUp() + self.tmp_dir = self.mkdtemp() +- self.sys_path = sys.path[:] ++ self.sys_path = sys.path, sys.path[:] + sys.path.append(self.tmp_dir) + shutil.copy(_get_source_filename(), self.tmp_dir) + if sys.version > "2.6": +@@ -87,7 +87,8 @@ + def tearDown(self): + # Get everything back to normal + support.unload('xx') +- sys.path = self.sys_path ++ sys.path = self.sys_path[0] ++ sys.path[:] = self.sys_path[1] + if sys.version > "2.6": + import site + site.USER_BASE = self.old_user_base +Index: Lib/distutils/tests/test_unixccompiler.py +=================================================================== +--- Lib/distutils/tests/test_unixccompiler.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_unixccompiler.py (.../branches/release31-maint) (Revision 76056) +@@ -36,8 +36,24 @@ + + # hp-ux + sys.platform = 'hp-ux' +- self.assertEqual(self.cc.rpath_foo(), '+s -L/foo') ++ old_gcv = sysconfig.get_config_var ++ def gcv(v): ++ return 'xxx' ++ sysconfig.get_config_var = gcv ++ self.assertEqual(self.cc.rpath_foo(), ['+s', '-L/foo']) + ++ def gcv(v): ++ return 'gcc' ++ sysconfig.get_config_var = gcv ++ self.assertEqual(self.cc.rpath_foo(), ['-Wl,+s', '-L/foo']) ++ ++ def gcv(v): ++ return 'g++' ++ sysconfig.get_config_var = gcv ++ self.assertEqual(self.cc.rpath_foo(), ['-Wl,+s', '-L/foo']) ++ ++ sysconfig.get_config_var = old_gcv ++ + # irix646 + sys.platform = 'irix646' + self.assertEqual(self.cc.rpath_foo(), ['-rpath', '/foo']) +Index: Lib/distutils/tests/test_bdist_rpm.py +=================================================================== +--- Lib/distutils/tests/test_bdist_rpm.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_bdist_rpm.py (.../branches/release31-maint) (Revision 76056) +@@ -29,11 +29,12 @@ + def setUp(self): + super(BuildRpmTestCase, self).setUp() + self.old_location = os.getcwd() +- self.old_sys_argv = sys.argv[:] ++ self.old_sys_argv = sys.argv, sys.argv[:] + + def tearDown(self): + os.chdir(self.old_location) +- sys.argv = self.old_sys_argv[:] ++ sys.argv = self.old_sys_argv[0] ++ sys.argv[:] = self.old_sys_argv[1] + super(BuildRpmTestCase, self).tearDown() + + def test_quiet(self): +Index: Lib/distutils/tests/test_core.py +=================================================================== +--- Lib/distutils/tests/test_core.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_core.py (.../branches/release31-maint) (Revision 76056) +@@ -6,9 +6,10 @@ + import shutil + import sys + import test.support ++from test.support import captured_stdout + import unittest ++from distutils.tests import support + +- + # setup script that uses __file__ + setup_using___file__ = """\ + +@@ -28,15 +29,20 @@ + """ + + +-class CoreTestCase(unittest.TestCase): ++class CoreTestCase(support.EnvironGuard, unittest.TestCase): + + def setUp(self): ++ super(CoreTestCase, self).setUp() + self.old_stdout = sys.stdout + self.cleanup_testfn() ++ self.old_argv = sys.argv, sys.argv[:] + + def tearDown(self): + sys.stdout = self.old_stdout + self.cleanup_testfn() ++ sys.argv = self.old_argv[0] ++ sys.argv[:] = self.old_argv[1] ++ super(CoreTestCase, self).tearDown() + + def cleanup_testfn(self): + path = test.support.TESTFN +@@ -73,7 +79,24 @@ + output = output[:-1] + self.assertEqual(cwd, output) + ++ def test_debug_mode(self): ++ # this covers the code called when DEBUG is set ++ sys.argv = ['setup.py', '--name'] ++ with captured_stdout() as stdout: ++ distutils.core.setup(name='bar') ++ stdout.seek(0) ++ self.assertEquals(stdout.read(), 'bar\n') + ++ distutils.core.DEBUG = True ++ try: ++ with captured_stdout() as stdout: ++ distutils.core.setup(name='bar') ++ finally: ++ distutils.core.DEBUG = False ++ stdout.seek(0) ++ wanted = "options (after parsing config files):\n" ++ self.assertEquals(stdout.readlines()[0], wanted) ++ + def test_suite(): + return unittest.makeSuite(CoreTestCase) + +Index: Lib/distutils/tests/test_cmd.py +=================================================================== +--- Lib/distutils/tests/test_cmd.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_cmd.py (.../branches/release31-maint) (Revision 76056) +@@ -1,10 +1,12 @@ + """Tests for distutils.cmd.""" + import unittest + import os ++from test.support import captured_stdout + + from distutils.cmd import Command + from distutils.dist import Distribution + from distutils.errors import DistutilsOptionError ++from distutils import debug + + class MyCmd(Command): + def initialize_options(self): +@@ -102,6 +104,22 @@ + cmd.option2 = 'xxx' + self.assertRaises(DistutilsOptionError, cmd.ensure_dirname, 'option2') + ++ def test_debug_print(self): ++ cmd = self.cmd ++ with captured_stdout() as stdout: ++ cmd.debug_print('xxx') ++ stdout.seek(0) ++ self.assertEquals(stdout.read(), '') ++ ++ debug.DEBUG = True ++ try: ++ with captured_stdout() as stdout: ++ cmd.debug_print('xxx') ++ stdout.seek(0) ++ self.assertEquals(stdout.read(), 'xxx\n') ++ finally: ++ debug.DEBUG = False ++ + def test_suite(): + return unittest.makeSuite(CommandTestCase) + +Index: Lib/distutils/tests/test_sysconfig.py +=================================================================== +--- Lib/distutils/tests/test_sysconfig.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_sysconfig.py (.../branches/release31-maint) (Revision 76056) +@@ -17,8 +17,15 @@ + def tearDown(self): + if self.makefile is not None: + os.unlink(self.makefile) ++ self.cleanup_testfn() + super(SysconfigTestCase, self).tearDown() + ++ def cleanup_testfn(self): ++ if os.path.isfile(TESTFN): ++ os.remove(TESTFN) ++ elif os.path.isdir(TESTFN): ++ shutil.rmtree(TESTFN) ++ + def test_get_config_h_filename(self): + config_h = sysconfig.get_config_h_filename() + self.assertTrue(os.path.isfile(config_h), config_h) +@@ -51,8 +58,8 @@ + if get_default_compiler() != 'unix': + return + +- self.environ['AR'] = 'my_ar' +- self.environ['ARFLAGS'] = '-arflags' ++ os.environ['AR'] = 'my_ar' ++ os.environ['ARFLAGS'] = '-arflags' + + # make sure AR gets caught + class compiler: +Index: Lib/distutils/tests/test_config.py +=================================================================== +--- Lib/distutils/tests/test_config.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_config.py (.../branches/release31-maint) (Revision 76056) +@@ -55,7 +55,7 @@ + """Patches the environment.""" + super(PyPIRCCommandTestCase, self).setUp() + self.tmp_dir = self.mkdtemp() +- self.environ['HOME'] = self.tmp_dir ++ os.environ['HOME'] = self.tmp_dir + self.rc = os.path.join(self.tmp_dir, '.pypirc') + self.dist = Distribution() + +Index: Lib/distutils/tests/test_install.py +=================================================================== +--- Lib/distutils/tests/test_install.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_install.py (.../branches/release31-maint) (Revision 76056) +@@ -6,6 +6,8 @@ + import unittest + import site + ++from test.support import captured_stdout ++ + from distutils.command.install import install + from distutils.command import install as install_module + from distutils.command.install import INSTALL_SCHEMES +@@ -14,8 +16,8 @@ + + from distutils.tests import support + +- + class InstallTestCase(support.TempdirManager, ++ support.EnvironGuard, + support.LoggingSilencer, + unittest.TestCase): + +@@ -183,6 +185,17 @@ + with open(cmd.record) as f: + self.assertEquals(len(f.readlines()), 1) + ++ 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() as stdout: ++ self.test_record() ++ finally: ++ install_module.DEBUG = False ++ self.assertTrue(len(self.logs) > old_logs_len) ++ + def test_suite(): + return unittest.makeSuite(InstallTestCase) + +Index: Lib/distutils/tests/test_build_py.py +=================================================================== +--- Lib/distutils/tests/test_build_py.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_build_py.py (.../branches/release31-maint) (Revision 76056) +@@ -69,6 +69,7 @@ + open(os.path.join(testdir, "testfile"), "w").close() + + os.chdir(sources) ++ old_stdout = sys.stdout + sys.stdout = io.StringIO() + + try: +@@ -87,8 +88,24 @@ + finally: + # Restore state. + os.chdir(cwd) +- sys.stdout = sys.__stdout__ ++ sys.stdout = old_stdout + ++ def test_dont_write_bytecode(self): ++ # makes sure byte_compile is not used ++ pkg_dir, dist = self.create_dist() ++ cmd = build_py(dist) ++ cmd.compile = 1 ++ cmd.optimize = 1 ++ ++ old_dont_write_bytecode = sys.dont_write_bytecode ++ sys.dont_write_bytecode = True ++ try: ++ cmd.byte_compile([]) ++ finally: ++ sys.dont_write_bytecode = old_dont_write_bytecode ++ ++ self.assertTrue('byte-compiling is disabled' in self.logs[0][1]) ++ + def test_suite(): + return unittest.makeSuite(BuildPyTestCase) + +Index: Lib/distutils/tests/test_filelist.py +=================================================================== +--- Lib/distutils/tests/test_filelist.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_filelist.py (.../branches/release31-maint) (Revision 76056) +@@ -1,21 +1,40 @@ + """Tests for distutils.filelist.""" + import unittest +-from distutils.filelist import glob_to_re + ++from distutils.filelist import glob_to_re, FileList ++from test.support import captured_stdout ++from distutils import debug ++ + class FileListTestCase(unittest.TestCase): + + def test_glob_to_re(self): + # simple cases +- self.assertEquals(glob_to_re('foo*'), 'foo[^/]*$') +- self.assertEquals(glob_to_re('foo?'), 'foo[^/]$') +- self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]$') ++ self.assertEquals(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)') ++ self.assertEquals(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)') ++ self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)') + + # special cases +- self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*$') +- self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*$') +- self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]$') +- self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]$') ++ self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)') ++ self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)') ++ self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)') ++ self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)') + ++ def test_debug_print(self): ++ file_list = FileList() ++ with captured_stdout() as stdout: ++ file_list.debug_print('xxx') ++ stdout.seek(0) ++ self.assertEquals(stdout.read(), '') ++ ++ debug.DEBUG = True ++ try: ++ with captured_stdout() as stdout: ++ file_list.debug_print('xxx') ++ stdout.seek(0) ++ self.assertEquals(stdout.read(), 'xxx\n') ++ finally: ++ debug.DEBUG = False ++ + def test_suite(): + return unittest.makeSuite(FileListTestCase) + +Index: Lib/distutils/tests/test_bdist_dumb.py +=================================================================== +--- Lib/distutils/tests/test_bdist_dumb.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_bdist_dumb.py (.../branches/release31-maint) (Revision 76056) +@@ -19,16 +19,18 @@ + + class BuildDumbTestCase(support.TempdirManager, + support.LoggingSilencer, ++ support.EnvironGuard, + unittest.TestCase): + + def setUp(self): + super(BuildDumbTestCase, self).setUp() + self.old_location = os.getcwd() +- self.old_sys_argv = sys.argv[:] ++ self.old_sys_argv = sys.argv, sys.argv[:] + + def tearDown(self): + os.chdir(self.old_location) +- sys.argv = self.old_sys_argv[:] ++ sys.argv = self.old_sys_argv[0] ++ sys.argv[:] = self.old_sys_argv[1] + super(BuildDumbTestCase, self).tearDown() + + def test_simple_built(self): +Index: Lib/distutils/tests/support.py +=================================================================== +--- Lib/distutils/tests/support.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/support.py (.../branches/release31-maint) (Revision 76056) +@@ -2,10 +2,11 @@ + import os + import shutil + import tempfile ++from copy import deepcopy + + from distutils import log ++from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL + from distutils.core import Distribution +-from test.support import EnvironmentVarGuard + + class LoggingSilencer(object): + +@@ -25,6 +26,8 @@ + super().tearDown() + + def _log(self, level, msg, args): ++ if level not in (DEBUG, INFO, WARN, ERROR, FATAL): ++ raise ValueError('%s wrong log level' % str(level)) + self.logs.append((level, msg, args)) + + def get_logs(self, *levels): +@@ -108,8 +111,15 @@ + + def setUp(self): + super(EnvironGuard, self).setUp() +- self.environ = EnvironmentVarGuard() ++ self.old_environ = deepcopy(os.environ) + + def tearDown(self): +- self.environ.__exit__() ++ for key, value in self.old_environ.items(): ++ if os.environ.get(key) != value: ++ os.environ[key] = value ++ ++ for key in tuple(os.environ.keys()): ++ if key not in self.old_environ: ++ del os.environ[key] ++ + super(EnvironGuard, self).tearDown() +Index: Lib/distutils/tests/test_util.py +=================================================================== +--- Lib/distutils/tests/test_util.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/tests/test_util.py (.../branches/release31-maint) (Revision 76056) +@@ -1,16 +1,13 @@ + """Tests for distutils.util.""" +-# not covered yet: +-# - byte_compile +-# + import os + import sys + import unittest + from copy import copy + +-from distutils.errors import DistutilsPlatformError ++from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError + from distutils.util import (get_platform, convert_path, change_root, + check_environ, split_quoted, strtobool, +- rfc822_escape) ++ rfc822_escape, byte_compile) + from distutils import util # used to patch _environ_checked + from distutils.sysconfig import get_config_vars + from distutils import sysconfig +@@ -94,7 +91,7 @@ + ('Darwin Kernel Version 8.11.1: ' + 'Wed Oct 10 18:23:28 PDT 2007; ' + 'root:xnu-792.25.20~1/RELEASE_I386'), 'i386')) +- self.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.3' ++ os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.3' + + get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g ' + '-fwrapv -O3 -Wall -Wstrict-prototypes') +@@ -102,7 +99,7 @@ + self.assertEquals(get_platform(), 'macosx-10.3-i386') + + # macbook with fat binaries (fat, universal or fat64) +- self.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.4' ++ os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.4' + get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot ' + '/Developer/SDKs/MacOSX10.4u.sdk ' + '-fno-strict-aliasing -fno-common ' +@@ -115,15 +112,35 @@ + '-fno-strict-aliasing -fno-common ' + '-dynamic -DNDEBUG -g -O3') + ++ self.assertEquals(get_platform(), 'macosx-10.4-intel') ++ ++ get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot ' ++ '/Developer/SDKs/MacOSX10.4u.sdk ' ++ '-fno-strict-aliasing -fno-common ' ++ '-dynamic -DNDEBUG -g -O3') ++ self.assertEquals(get_platform(), 'macosx-10.4-fat3') ++ ++ get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot ' ++ '/Developer/SDKs/MacOSX10.4u.sdk ' ++ '-fno-strict-aliasing -fno-common ' ++ '-dynamic -DNDEBUG -g -O3') + self.assertEquals(get_platform(), 'macosx-10.4-universal') + +- get_config_vars()['CFLAGS'] = ('-arch x86_64 -isysroot ' ++ get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot ' + '/Developer/SDKs/MacOSX10.4u.sdk ' + '-fno-strict-aliasing -fno-common ' + '-dynamic -DNDEBUG -g -O3') + + self.assertEquals(get_platform(), 'macosx-10.4-fat64') + ++ for arch in ('ppc', 'i386', 'x86_64', 'ppc64'): ++ get_config_vars()['CFLAGS'] = ('-arch %s -isysroot ' ++ '/Developer/SDKs/MacOSX10.4u.sdk ' ++ '-fno-strict-aliasing -fno-common ' ++ '-dynamic -DNDEBUG -g -O3'%(arch,)) ++ ++ self.assertEquals(get_platform(), 'macosx-10.4-%s'%(arch,)) ++ + # linux debian sarge + os.name = 'posix' + sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) ' +@@ -203,17 +220,18 @@ + + def test_check_environ(self): + util._environ_checked = 0 ++ if 'HOME' in os.environ: ++ del os.environ['HOME'] + + # posix without HOME + if os.name == 'posix': # this test won't run on windows + check_environ() + import pwd +- self.assertEquals(self.environ['HOME'], +- pwd.getpwuid(os.getuid())[5]) ++ self.assertEquals(os.environ['HOME'], pwd.getpwuid(os.getuid())[5]) + else: + check_environ() + +- self.assertEquals(self.environ['PLAT'], get_platform()) ++ self.assertEquals(os.environ['PLAT'], get_platform()) + self.assertEquals(util._environ_checked, 1) + + def test_split_quoted(self): +@@ -237,6 +255,16 @@ + 'header%(8s)s') % {'8s': '\n'+8*' '} + self.assertEquals(res, wanted) + ++ def test_dont_write_bytecode(self): ++ # makes sure byte_compile raise a DistutilsError ++ # if sys.dont_write_bytecode is True ++ old_dont_write_bytecode = sys.dont_write_bytecode ++ sys.dont_write_bytecode = True ++ try: ++ self.assertRaises(DistutilsByteCompileError, byte_compile, []) ++ finally: ++ sys.dont_write_bytecode = old_dont_write_bytecode ++ + def test_suite(): + return unittest.makeSuite(UtilTestCase) + +Index: Lib/distutils/filelist.py +=================================================================== +--- Lib/distutils/filelist.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/filelist.py (.../branches/release31-maint) (Revision 76056) +@@ -312,7 +312,9 @@ + pattern_re = '' + + if prefix is not None: +- prefix_re = (glob_to_re(prefix))[0:-1] # ditch trailing $ ++ # 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) + else: # no prefix -- respect anchor flag + if anchor: +Index: Lib/distutils/errors.py +=================================================================== +--- Lib/distutils/errors.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/errors.py (.../branches/release31-maint) (Revision 76056) +@@ -74,6 +74,8 @@ + class DistutilsTemplateError (DistutilsError): + """Syntax error in a file list template.""" + ++class DistutilsByteCompileError(DistutilsError): ++ """Byte compile error.""" + + # Exception classes used by the CCompiler implementation classes + class CCompilerError (Exception): +Index: Lib/distutils/util.py +=================================================================== +--- Lib/distutils/util.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/util.py (.../branches/release31-maint) (Revision 76056) +@@ -11,6 +11,7 @@ + from distutils.dep_util import newer + from distutils.spawn import spawn + from distutils import log ++from distutils.errors import DistutilsByteCompileError + + def get_platform (): + """Return a string that identifies the current platform. This is used +@@ -141,12 +142,27 @@ + machine = 'fat' + cflags = get_config_vars().get('CFLAGS') + +- if '-arch x86_64' in cflags: +- if '-arch i386' in cflags: +- machine = 'universal' +- else: +- machine = 'fat64' ++ archs = re.findall('-arch\s+(\S+)', cflags) ++ archs.sort() ++ archs = tuple(archs) + ++ if len(archs) == 1: ++ machine = archs[0] ++ elif archs == ('i386', 'ppc'): ++ machine = 'fat' ++ elif archs == ('i386', 'x86_64'): ++ machine = 'intel' ++ elif archs == ('i386', 'ppc', 'x86_64'): ++ machine = 'fat3' ++ elif archs == ('ppc64', 'x86_64'): ++ machine = 'fat64' ++ elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'): ++ machine = 'universal' ++ else: ++ raise ValueError( ++ "Don't know machine value for archs=%r"%(archs,)) ++ ++ + elif machine in ('PowerPC', 'Power_Macintosh'): + # Pick a sane name for the PPC architecture. + machine = 'ppc' +@@ -428,6 +444,9 @@ + generated in indirect mode; unless you know what you're doing, leave + it set to None. + """ ++ # nothing is done if sys.dont_write_bytecode is True ++ if sys.dont_write_bytecode: ++ raise DistutilsByteCompileError('byte-compiling is disabled.') + + # First, if the caller didn't force us into direct or indirect mode, + # figure out which mode we should be in. We take a conservative +Index: Lib/distutils/archive_util.py +=================================================================== +--- Lib/distutils/archive_util.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/archive_util.py (.../branches/release31-maint) (Revision 76056) +@@ -171,10 +171,11 @@ + func = format_info[0] + for arg, val in format_info[1]: + kwargs[arg] = val +- filename = func(base_name, base_dir, **kwargs) ++ try: ++ filename = func(base_name, base_dir, **kwargs) ++ finally: ++ if root_dir is not None: ++ log.debug("changing back to '%s'", save_cwd) ++ os.chdir(save_cwd) + +- if root_dir is not None: +- log.debug("changing back to '%s'", save_cwd) +- os.chdir(save_cwd) +- + return filename +Index: Lib/distutils/log.py +=================================================================== +--- Lib/distutils/log.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/log.py (.../branches/release31-maint) (Revision 76056) +@@ -17,6 +17,9 @@ + self.threshold = threshold + + def _log(self, level, msg, args): ++ if level not in (DEBUG, INFO, WARN, ERROR, FATAL): ++ raise ValueError('%s wrong log level' % str(level)) ++ + if level >= self.threshold: + if args: + msg = msg % args +Index: Lib/distutils/unixccompiler.py +=================================================================== +--- Lib/distutils/unixccompiler.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/unixccompiler.py (.../branches/release31-maint) (Revision 76056) +@@ -283,7 +283,9 @@ + # MacOSX's linker doesn't understand the -R flag at all + return "-L" + dir + elif sys.platform[:5] == "hp-ux": +- return "+s -L" + dir ++ if "gcc" in compiler or "g++" in compiler: ++ return ["-Wl,+s", "-L" + dir] ++ return ["+s", "-L" + dir] + elif sys.platform[:7] == "irix646" or sys.platform[:6] == "osf1V5": + return ["-rpath", dir] + else: +Index: Lib/distutils/fancy_getopt.py +=================================================================== +--- Lib/distutils/fancy_getopt.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/fancy_getopt.py (.../branches/release31-maint) (Revision 76056) +@@ -26,7 +26,7 @@ + + # This is used to translate long options to legitimate Python identifiers + # (for use as attributes of some object). +-longopt_xlate = lambda s: s.replace('-', '_') ++longopt_xlate = str.maketrans('-', '_') + + class FancyGetopt: + """Wrapper around the standard 'getopt()' module that provides some +@@ -107,7 +107,7 @@ + """Translate long option name 'long_option' to the form it + has as an attribute of some object: ie., translate hyphens + to underscores.""" +- return longopt_xlate(long_option) ++ return long_option.translate(longopt_xlate) + + def _check_alias_dict(self, aliases, what): + assert isinstance(aliases, dict) +@@ -432,7 +432,7 @@ + """Convert a long option name to a valid Python identifier by + changing "-" to "_". + """ +- return longopt_xlate(opt) ++ return opt.translate(longopt_xlate) + + + class OptionDummy: +Index: Lib/distutils/command/install_lib.py +=================================================================== +--- Lib/distutils/command/install_lib.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/command/install_lib.py (.../branches/release31-maint) (Revision 76056) +@@ -6,6 +6,8 @@ + __revision__ = "$Id$" + + import os ++import sys ++ + from distutils.core import Command + from distutils.errors import DistutilsOptionError + +@@ -115,6 +117,10 @@ + return outfiles + + def byte_compile(self, files): ++ if sys.dont_write_bytecode: ++ self.warn('byte-compiling is disabled, skipping.') ++ return ++ + from distutils.util import byte_compile + + # Get the "--root" directory supplied to the "install" command, +Index: Lib/distutils/command/build_py.py +=================================================================== +--- Lib/distutils/command/build_py.py (.../tags/r311) (Revision 76056) ++++ Lib/distutils/command/build_py.py (.../branches/release31-maint) (Revision 76056) +@@ -5,6 +5,7 @@ + __revision__ = "$Id$" + + import sys, os ++import sys + from glob import glob + + from distutils.core import Command +@@ -369,6 +370,10 @@ + self.build_module(module, module_file, package) + + def byte_compile(self, files): ++ if sys.dont_write_bytecode: ++ self.warn('byte-compiling is disabled, skipping.') ++ return ++ + from distutils.util import byte_compile + prefix = self.build_lib + if prefix[-1] != os.sep: +Index: Lib/urllib/request.py +=================================================================== +--- Lib/urllib/request.py (.../tags/r311) (Revision 76056) ++++ Lib/urllib/request.py (.../branches/release31-maint) (Revision 76056) +@@ -657,6 +657,10 @@ + proxy_type, user, password, hostport = _parse_proxy(proxy) + if proxy_type is None: + proxy_type = orig_type ++ ++ if req.host and proxy_bypass(req.host): ++ return None ++ + if user and password: + user_pass = '%s:%s' % (unquote(user), + unquote(password)) +Index: Lib/urllib/parse.py +=================================================================== +--- Lib/urllib/parse.py (.../tags/r311) (Revision 76056) ++++ Lib/urllib/parse.py (.../branches/release31-maint) (Revision 76056) +@@ -329,7 +329,7 @@ + res[-1] = b''.join(pct_sequence).decode(encoding, errors) + return ''.join(res) + +-def parse_qs(qs, keep_blank_values=0, strict_parsing=0): ++def parse_qs(qs, keep_blank_values=False, strict_parsing=False): + """Parse a query given as a string argument. + + Arguments: +@@ -355,7 +355,7 @@ + dict[name] = [value] + return dict + +-def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): ++def parse_qsl(qs, keep_blank_values=False, strict_parsing=False): + """Parse a query given as a string argument. + + Arguments: +@@ -509,7 +509,7 @@ + _safe_quoters[cachekey] = quoter + return ''.join([quoter[char] for char in bs]) + +-def urlencode(query, doseq=0): ++def urlencode(query, doseq=False): + """Encode a sequence of two-element tuples or dictionary into a URL query string. + + If any values in the query arg are sequences and doseq is true, each +Index: Lib/fnmatch.py +=================================================================== +--- Lib/fnmatch.py (.../tags/r311) (Revision 76056) ++++ Lib/fnmatch.py (.../branches/release31-maint) (Revision 76056) +@@ -113,4 +113,4 @@ + res = '%s[%s]' % (res, stuff) + else: + res = res + re.escape(c) +- return res + "$" ++ return res + '\Z(?ms)' +Index: Lib/struct.py +=================================================================== +--- Lib/struct.py (.../tags/r311) (Revision 76056) ++++ Lib/struct.py (.../branches/release31-maint) (Revision 76056) +@@ -1,2 +1,3 @@ + from _struct import * + from _struct import _clearcache ++from _struct import __doc__ +Index: Lib/decimal.py +=================================================================== +--- Lib/decimal.py (.../tags/r311) (Revision 76056) ++++ Lib/decimal.py (.../branches/release31-maint) (Revision 76056) +@@ -1553,10 +1553,9 @@ + """Converts self to an int, truncating if necessary.""" + if self._is_special: + if self._isnan(): +- context = getcontext() +- return context._raise_error(InvalidContext) ++ raise ValueError("Cannot convert NaN to integer") + elif self._isinfinity(): +- raise OverflowError("Cannot convert infinity to int") ++ raise OverflowError("Cannot convert infinity to integer") + s = (-1)**self._sign + if self._exp >= 0: + return s*int(self._int)*10**self._exp +@@ -2807,6 +2806,8 @@ + value. Note that a total ordering is defined for all possible abstract + representations. + """ ++ other = _convert_other(other, raiseit=True) ++ + # if one is negative and the other is positive, it's easy + if self._sign and not other._sign: + return _NegativeOne +@@ -2819,12 +2820,15 @@ + other_nan = other._isnan() + if self_nan or other_nan: + if self_nan == other_nan: +- if self._int < other._int: ++ # compare payloads as though they're integers ++ self_key = len(self._int), self._int ++ other_key = len(other._int), other._int ++ if self_key < other_key: + if sign: + return _One + else: + return _NegativeOne +- if self._int > other._int: ++ if self_key > other_key: + if sign: + return _NegativeOne + else: +@@ -2873,6 +2877,8 @@ + + Like compare_total, but with operand's sign ignored and assumed to be 0. + """ ++ other = _convert_other(other, raiseit=True) ++ + s = self.copy_abs() + o = other.copy_abs() + return s.compare_total(o) +@@ -2998,7 +3004,7 @@ + return False + if context is None: + context = getcontext() +- return context.Emin <= self.adjusted() <= context.Emax ++ return context.Emin <= self.adjusted() + + def is_qnan(self): + """Return True if self is a quiet NaN; otherwise return False.""" +@@ -3207,7 +3213,8 @@ + # otherwise, simply return the adjusted exponent of self, as a + # Decimal. Note that no attempt is made to fit the result + # into the current context. +- return Decimal(self.adjusted()) ++ ans = Decimal(self.adjusted()) ++ return ans._fix(context) + + def _islogical(self): + """Return True if self is a logical operand. +@@ -3240,6 +3247,9 @@ + """Applies an 'and' operation between self and other's digits.""" + if context is None: + context = getcontext() ++ ++ other = _convert_other(other, raiseit=True) ++ + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + +@@ -3261,6 +3271,9 @@ + """Applies an 'or' operation between self and other's digits.""" + if context is None: + context = getcontext() ++ ++ other = _convert_other(other, raiseit=True) ++ + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + +@@ -3275,6 +3288,9 @@ + """Applies an 'xor' operation between self and other's digits.""" + if context is None: + context = getcontext() ++ ++ other = _convert_other(other, raiseit=True) ++ + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + +@@ -3488,6 +3504,8 @@ + if context is None: + context = getcontext() + ++ other = _convert_other(other, raiseit=True) ++ + ans = self._check_nans(other, context) + if ans: + return ans +@@ -3504,19 +3522,23 @@ + torot = int(other) + rotdig = self._int + topad = context.prec - len(rotdig) +- if topad: ++ if topad > 0: + rotdig = '0'*topad + rotdig ++ elif topad < 0: ++ rotdig = rotdig[-topad:] + + # let's rotate! + rotated = rotdig[torot:] + rotdig[:torot] + return _dec_from_triple(self._sign, + rotated.lstrip('0') or '0', self._exp) + +- def scaleb (self, other, context=None): ++ def scaleb(self, other, context=None): + """Returns self operand after adding the second value to its exp.""" + if context is None: + context = getcontext() + ++ other = _convert_other(other, raiseit=True) ++ + ans = self._check_nans(other, context) + if ans: + return ans +@@ -3540,6 +3562,8 @@ + if context is None: + context = getcontext() + ++ other = _convert_other(other, raiseit=True) ++ + ans = self._check_nans(other, context) + if ans: + return ans +@@ -3554,22 +3578,22 @@ + + # get values, pad if necessary + torot = int(other) +- if not torot: +- return Decimal(self) + rotdig = self._int + topad = context.prec - len(rotdig) +- if topad: ++ if topad > 0: + rotdig = '0'*topad + rotdig ++ elif topad < 0: ++ rotdig = rotdig[-topad:] + + # let's shift! + if torot < 0: +- rotated = rotdig[:torot] ++ shifted = rotdig[:torot] + else: +- rotated = rotdig + '0'*torot +- rotated = rotated[-context.prec:] ++ shifted = rotdig + '0'*torot ++ shifted = shifted[-context.prec:] + + return _dec_from_triple(self._sign, +- rotated.lstrip('0') or '0', self._exp) ++ shifted.lstrip('0') or '0', self._exp) + + # Support for pickling, copy, and deepcopy + def __reduce__(self): +@@ -5589,7 +5613,7 @@ + # if format type is 'g' or 'G' then a precision of 0 makes little + # sense; convert it to 1. Same if format type is unspecified. + if format_dict['precision'] == 0: +- if format_dict['type'] in 'gG' or format_dict['type'] is None: ++ if format_dict['type'] is None or format_dict['type'] in 'gG': + format_dict['precision'] = 1 + + # determine thousands separator, grouping, and decimal separator, and +Index: Lib/logging/__init__.py +=================================================================== +--- Lib/logging/__init__.py (.../tags/r311) (Revision 76056) ++++ Lib/logging/__init__.py (.../branches/release31-maint) (Revision 76056) +@@ -271,11 +271,14 @@ + else: + self.thread = None + self.threadName = None +- if logMultiprocessing: +- from multiprocessing import current_process +- self.processName = current_process().name ++ if not logMultiprocessing: ++ self.processName = None + else: +- self.processName = None ++ try: ++ from multiprocessing import current_process ++ self.processName = current_process().name ++ except ImportError: ++ self.processName = None + if logProcesses and hasattr(os, 'getpid'): + self.process = os.getpid() + else: +@@ -734,16 +737,16 @@ + sys.stdout or sys.stderr may be used. + """ + +- def __init__(self, strm=None): ++ def __init__(self, stream=None): + """ + Initialize the handler. + +- If strm is not specified, sys.stderr is used. ++ If stream is not specified, sys.stderr is used. + """ + Handler.__init__(self) +- if strm is None: +- strm = sys.stderr +- self.stream = strm ++ if stream is None: ++ stream = sys.stderr ++ self.stream = stream + + def flush(self): + """ +@@ -1113,7 +1116,11 @@ + Find the stack frame of the caller so that we can note the source + file name, line number and function name. + """ +- f = currentframe().f_back ++ f = currentframe() ++ #On some versions of IronPython, currentframe() returns None if ++ #IronPython isn't run with -X:Frames. ++ if f is not None: ++ f = f.f_back + rv = "(unknown file)", 0, "(unknown function)" + while hasattr(f, "f_code"): + co = f.f_code +@@ -1145,7 +1152,8 @@ + """ + if _srcfile: + #IronPython doesn't track Python frames, so findCaller throws an +- #exception. We trap it here so that IronPython can use logging. ++ #exception on some versions of IronPython. We trap it here so that ++ #IronPython can use logging. + try: + fn, lno, func = self.findCaller() + except ValueError: +Index: Lib/inspect.py +=================================================================== +--- Lib/inspect.py (.../tags/r311) (Revision 76056) ++++ Lib/inspect.py (.../branches/release31-maint) (Revision 76056) +@@ -398,12 +398,12 @@ + if ismodule(object): + if hasattr(object, '__file__'): + return object.__file__ +- raise TypeError('arg is a built-in module') ++ raise TypeError('{!r} is a built-in module'.format(object)) + if isclass(object): + object = sys.modules.get(object.__module__) + if hasattr(object, '__file__'): + return object.__file__ +- raise TypeError('arg is a built-in class') ++ raise TypeError('{!r} is a built-in class'.format(object)) + if ismethod(object): + object = object.__func__ + if isfunction(object): +@@ -414,8 +414,8 @@ + object = object.f_code + if iscode(object): + return object.co_filename +- raise TypeError('arg is not a module, class, method, ' +- 'function, traceback, frame, or code object') ++ raise TypeError('{!r} is not a module, class, method, ' ++ 'function, traceback, frame, or code object'.format(object)) + + ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') + +@@ -747,7 +747,7 @@ + names of the * and ** arguments or None.""" + + if not iscode(co): +- raise TypeError('arg is not a code object') ++ raise TypeError('{!r} is not a code object'.format(co)) + + nargs = co.co_argcount + names = co.co_varnames +@@ -811,7 +811,7 @@ + if ismethod(func): + func = func.__func__ + if not isfunction(func): +- raise TypeError('arg is not a Python function') ++ raise TypeError('{!r} is not a Python function'.format(func)) + args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__) + return FullArgSpec(args, varargs, varkw, func.__defaults__, + kwonlyargs, func.__kwdefaults__, func.__annotations__) +@@ -944,7 +944,7 @@ + else: + lineno = frame.f_lineno + if not isframe(frame): +- raise TypeError('arg is not a frame or traceback object') ++ raise TypeError('{!r} is not a frame or traceback object'.format(frame)) + + filename = getsourcefile(frame) or getfile(frame) + if context > 0: +Index: Lib/string.py +=================================================================== +--- Lib/string.py (.../tags/r311) (Revision 76056) ++++ Lib/string.py (.../branches/release31-maint) (Revision 76056) +@@ -29,15 +29,17 @@ + + # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def". + def capwords(s, sep=None): +- """capwords(s, [sep]) -> string ++ """capwords(s [,sep]) -> string + + Split the argument into words using split, capitalize each + word using capitalize, and join the capitalized words using +- join. Note that this replaces runs of whitespace characters by +- a single space. ++ join. If the optional second argument sep is absent or None, ++ runs of whitespace characters are replaced by a single space ++ and leading and trailing whitespace are removed, otherwise ++ sep is used to split and join the words. + + """ +- return (sep or ' ').join([x.capitalize() for x in s.split(sep)]) ++ return (sep or ' ').join(x.capitalize() for x in s.split(sep)) + + + # Construct a translation map for bytes.translate +Index: Lib/dbm/__init__.py +=================================================================== +--- Lib/dbm/__init__.py (.../tags/r311) (Revision 76056) ++++ Lib/dbm/__init__.py (.../branches/release31-maint) (Revision 76056) +@@ -36,7 +36,7 @@ + only if it doesn't exist; and 'n' always creates a new database. + """ + +-__all__ = ['open', 'whichdb', 'error', 'errors'] ++__all__ = ['open', 'whichdb', 'error', 'error'] + + import io + import os +Index: Lib/turtle.py +=================================================================== +--- Lib/turtle.py (.../tags/r311) (Revision 76056) ++++ Lib/turtle.py (.../branches/release31-maint) (Revision 76056) +@@ -126,7 +126,7 @@ + _tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk', + 'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'color', + 'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd', +- 'fillcolor', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly', ++ 'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly', + 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'isdown', + 'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease', 'pd', + 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', +Index: Lib/traceback.py +=================================================================== +--- Lib/traceback.py (.../tags/r311) (Revision 76056) ++++ Lib/traceback.py (.../branches/release31-maint) (Revision 76056) +@@ -70,11 +70,11 @@ + tb = tb.tb_next + n = n+1 + +-def format_tb(tb, limit = None): ++def format_tb(tb, limit=None): + """A shorthand for 'format_list(extract_stack(f, limit)).""" + return format_list(extract_tb(tb, limit)) + +-def extract_tb(tb, limit = None): ++def extract_tb(tb, limit=None): + """Return list of up to limit pre-processed entries from traceback. + + This is useful for alternate formatting of stack traces. If +@@ -304,7 +304,7 @@ + f = sys.exc_info()[2].tb_frame.f_back + return format_list(extract_stack(f, limit)) + +-def extract_stack(f=None, limit = None): ++def extract_stack(f=None, limit=None): + """Extract the raw traceback from the current stack frame. + + The return value has the same format as for extract_tb(). The +Index: Lib/ctypes/test/test_cast.py +=================================================================== +--- Lib/ctypes/test/test_cast.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_cast.py (.../branches/release31-maint) (Revision 76056) +@@ -73,7 +73,7 @@ + # This didn't work: bad argument to internal function + s = c_char_p("hiho") + self.assertEqual(cast(cast(s, c_void_p), c_char_p).value, +- "hiho") ++ b"hiho") + + try: + c_wchar_p +Index: Lib/ctypes/test/test_incomplete.py +=================================================================== +--- Lib/ctypes/test/test_incomplete.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_incomplete.py (.../branches/release31-maint) (Revision 76056) +@@ -17,9 +17,9 @@ + SetPointerType(lpcell, cell) + + c1 = cell() +- c1.name = "foo" ++ c1.name = b"foo" + c2 = cell() +- c2.name = "bar" ++ c2.name = b"bar" + + c1.next = pointer(c2) + c2.next = pointer(c1) +@@ -30,7 +30,7 @@ + for i in range(8): + result.append(p.name) + p = p.next[0] +- self.assertEqual(result, ["foo", "bar"] * 4) ++ self.assertEqual(result, [b"foo", b"bar"] * 4) + + # to not leak references, we must clean _pointer_type_cache + from ctypes import _pointer_type_cache +Index: Lib/ctypes/test/__init__.py +=================================================================== +--- Lib/ctypes/test/__init__.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/__init__.py (.../branches/release31-maint) (Revision 76056) +@@ -58,7 +58,7 @@ + if modname.split(".")[-1] in exclude: + skipped.append(modname) + if verbosity > 1: +- print >> sys.stderr, "Skipped %s: excluded" % modname ++ print("Skipped %s: excluded" % modname, file=sys.stderr) + continue + try: + mod = __import__(modname, globals(), locals(), ['*']) +Index: Lib/ctypes/test/test_parameters.py +=================================================================== +--- Lib/ctypes/test/test_parameters.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_parameters.py (.../branches/release31-maint) (Revision 76056) +@@ -97,7 +97,7 @@ + self.assertEqual(x.contents.value, 42) + self.assertEqual(LPINT(c_int(42)).contents.value, 42) + +- self.assertEqual(LPINT.from_param(None), 0) ++ self.assertEqual(LPINT.from_param(None), None) + + if c_int != c_long: + self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42))) +Index: Lib/ctypes/test/test_pointers.py +=================================================================== +--- Lib/ctypes/test/test_pointers.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_pointers.py (.../branches/release31-maint) (Revision 76056) +@@ -140,10 +140,10 @@ + func.restype = c_char_p + argv = (c_char_p * 2)() + argc = c_int( 2 ) +- argv[0] = 'hello' +- argv[1] = 'world' ++ argv[0] = b'hello' ++ argv[1] = b'world' + result = func( byref(argc), argv ) +- assert result == 'world', result ++ self.assertEqual(result, b'world') + + def test_bug_1467852(self): + # http://sourceforge.net/tracker/?func=detail&atid=532154&aid=1467852&group_id=71702 +Index: Lib/ctypes/test/test_funcptr.py +=================================================================== +--- Lib/ctypes/test/test_funcptr.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_funcptr.py (.../branches/release31-maint) (Revision 76056) +@@ -97,8 +97,8 @@ + strchr = lib.my_strchr + strchr.restype = c_char_p + strchr.argtypes = (c_char_p, c_char) +- self.assertEqual(strchr("abcdefghi", "b"), "bcdefghi") +- self.assertEqual(strchr("abcdefghi", "x"), None) ++ self.assertEqual(strchr(b"abcdefghi", b"b"), b"bcdefghi") ++ self.assertEqual(strchr(b"abcdefghi", b"x"), None) + + + strtok = lib.my_strtok +@@ -111,16 +111,16 @@ + size = len(init) + 1 + return (c_char*size)(*init) + +- s = "a\nb\nc" ++ s = b"a\nb\nc" + b = c_string(s) + + ## b = (c_char * (len(s)+1))() + ## b.value = s + + ## b = c_string(s) +- self.assertEqual(strtok(b, b"\n"), "a") +- self.assertEqual(strtok(None, b"\n"), "b") +- self.assertEqual(strtok(None, b"\n"), "c") ++ self.assertEqual(strtok(b, b"\n"), b"a") ++ self.assertEqual(strtok(None, b"\n"), b"b") ++ self.assertEqual(strtok(None, b"\n"), b"c") + self.assertEqual(strtok(None, b"\n"), None) + + if __name__ == '__main__': +Index: Lib/ctypes/test/test_structures.py +=================================================================== +--- Lib/ctypes/test/test_structures.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_structures.py (.../branches/release31-maint) (Revision 76056) +@@ -349,6 +349,25 @@ + self.assertTrue("from_address" in dir(type(Structure))) + self.assertTrue("in_dll" in dir(type(Structure))) + ++ def test_positional_args(self): ++ # see also http://bugs.python.org/issue5042 ++ class W(Structure): ++ _fields_ = [("a", c_int), ("b", c_int)] ++ class X(W): ++ _fields_ = [("c", c_int)] ++ class Y(X): ++ pass ++ class Z(Y): ++ _fields_ = [("d", c_int), ("e", c_int), ("f", c_int)] ++ ++ z = Z(1, 2, 3, 4, 5, 6) ++ self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), ++ (1, 2, 3, 4, 5, 6)) ++ z = Z(1) ++ self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), ++ (1, 0, 0, 0, 0, 0)) ++ self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) ++ + class PointerMemberTestCase(unittest.TestCase): + + def test(self): +Index: Lib/ctypes/test/test_objects.py +=================================================================== +--- Lib/ctypes/test/test_objects.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_objects.py (.../branches/release31-maint) (Revision 76056) +@@ -24,7 +24,7 @@ + >>> array._objects + {'4': b'foo bar'} + >>> array[4] +-'foo bar' ++b'foo bar' + >>> + + It gets more complicated when the ctypes instance itself is contained +Index: Lib/ctypes/test/test_random_things.py +=================================================================== +--- Lib/ctypes/test/test_random_things.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_random_things.py (.../branches/release31-maint) (Revision 76056) +@@ -69,7 +69,7 @@ + out = self.capture_stderr(cb, "spam") + self.assertEqual(out.splitlines()[-1], + "TypeError: " +- "unsupported operand type(s) for /: 'int' and 'str'") ++ "unsupported operand type(s) for /: 'int' and 'bytes'") + + if __name__ == '__main__': + unittest.main() +Index: Lib/ctypes/test/test_stringptr.py +=================================================================== +--- Lib/ctypes/test/test_stringptr.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_stringptr.py (.../branches/release31-maint) (Revision 76056) +@@ -35,10 +35,10 @@ + # c_char_p and Python string is compatible + # c_char_p and c_buffer is NOT compatible + self.assertEqual(x.str, None) +- x.str = "Hello, World" +- self.assertEqual(x.str, "Hello, World") +- b = c_buffer("Hello, World") +- self.assertRaises(TypeError, setattr, x, "str", b) ++ x.str = b"Hello, World" ++ self.assertEqual(x.str, b"Hello, World") ++ b = c_buffer(b"Hello, World") ++ self.assertRaises(TypeError, setattr, x, b"str", b) + + + def test_functions(self): +@@ -48,15 +48,15 @@ + # c_char_p and Python string is compatible + # c_char_p and c_buffer are now compatible + strchr.argtypes = c_char_p, c_char +- self.assertEqual(strchr("abcdef", "c"), "cdef") +- self.assertEqual(strchr(c_buffer("abcdef"), "c"), "cdef") ++ self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") ++ self.assertEqual(strchr(c_buffer(b"abcdef"), b"c"), b"cdef") + + # POINTER(c_char) and Python string is NOT compatible + # POINTER(c_char) and c_buffer() is compatible + strchr.argtypes = POINTER(c_char), c_char +- buf = c_buffer("abcdef") +- self.assertEqual(strchr(buf, "c"), "cdef") +- self.assertEqual(strchr("abcdef", "c"), "cdef") ++ buf = c_buffer(b"abcdef") ++ self.assertEqual(strchr(buf, b"c"), b"cdef") ++ self.assertEqual(strchr(b"abcdef", b"c"), b"cdef") + + # XXX These calls are dangerous, because the first argument + # to strchr is no longer valid after the function returns! +Index: Lib/ctypes/test/test_returnfuncptrs.py +=================================================================== +--- Lib/ctypes/test/test_returnfuncptrs.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_returnfuncptrs.py (.../branches/release31-maint) (Revision 76056) +@@ -12,12 +12,12 @@ + get_strchr = dll.get_strchr + get_strchr.restype = CFUNCTYPE(c_char_p, c_char_p, c_char) + strchr = get_strchr() +- self.assertEqual(strchr("abcdef", "b"), "bcdef") +- self.assertEqual(strchr("abcdef", "x"), None) +- self.assertEqual(strchr("abcdef", 98), "bcdef") +- self.assertEqual(strchr("abcdef", 107), None) +- self.assertRaises(ArgumentError, strchr, "abcdef", 3.0) +- self.assertRaises(TypeError, strchr, "abcdef") ++ self.assertEqual(strchr(b"abcdef", b"b"), b"bcdef") ++ self.assertEqual(strchr(b"abcdef", b"x"), None) ++ self.assertEqual(strchr(b"abcdef", 98), b"bcdef") ++ self.assertEqual(strchr(b"abcdef", 107), None) ++ self.assertRaises(ArgumentError, strchr, b"abcdef", 3.0) ++ self.assertRaises(TypeError, strchr, b"abcdef") + + def test_without_prototype(self): + dll = CDLL(_ctypes_test.__file__) +Index: Lib/ctypes/test/test_memfunctions.py +=================================================================== +--- Lib/ctypes/test/test_memfunctions.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_memfunctions.py (.../branches/release31-maint) (Revision 76056) +@@ -37,7 +37,7 @@ + + def test_cast(self): + a = (c_ubyte * 32)(*map(ord, "abcdef")) +- self.assertEqual(cast(a, c_char_p).value, "abcdef") ++ self.assertEqual(cast(a, c_char_p).value, b"abcdef") + self.assertEqual(cast(a, POINTER(c_byte))[:7], + [97, 98, 99, 100, 101, 102, 0]) + self.assertEqual(cast(a, POINTER(c_byte))[:7:], +Index: Lib/ctypes/test/test_functions.py +=================================================================== +--- Lib/ctypes/test/test_functions.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_functions.py (.../branches/release31-maint) (Revision 76056) +@@ -177,7 +177,7 @@ + f.argtypes = None + f.restype = c_char_p + result = f(b"123") +- self.assertEqual(result, "123") ++ self.assertEqual(result, b"123") + + result = f(None) + self.assertEqual(result, None) +Index: Lib/ctypes/test/test_unicode.py +=================================================================== +--- Lib/ctypes/test/test_unicode.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_unicode.py (.../branches/release31-maint) (Revision 76056) +@@ -94,15 +94,15 @@ + + def test_ascii_ignore(self): + ctypes.set_conversion_mode("ascii", "ignore") +- self.assertEqual(func("abc"), "abc") +- self.assertEqual(func("abc"), "abc") +- self.assertEqual(func("\xe4\xf6\xfc\xdf"), "") ++ self.assertEqual(func("abc"), b"abc") ++ self.assertEqual(func("abc"), b"abc") ++ self.assertEqual(func("\xe4\xf6\xfc\xdf"), b"") + + def test_ascii_replace(self): + ctypes.set_conversion_mode("ascii", "replace") +- self.assertEqual(func("abc"), "abc") +- self.assertEqual(func("abc"), "abc") +- self.assertEqual(func("\xe4\xf6\xfc\xdf"), "????") ++ self.assertEqual(func("abc"), b"abc") ++ self.assertEqual(func("abc"), b"abc") ++ self.assertEqual(func("\xe4\xf6\xfc\xdf"), b"????") + + def test_buffers(self): + ctypes.set_conversion_mode("ascii", "strict") +Index: Lib/ctypes/test/test_prototypes.py +=================================================================== +--- Lib/ctypes/test/test_prototypes.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_prototypes.py (.../branches/release31-maint) (Revision 76056) +@@ -92,14 +92,14 @@ + func.argtypes = POINTER(c_char), + + self.assertEqual(None, func(None)) +- self.assertEqual("123", func("123")) ++ self.assertEqual(b"123", func(b"123")) + self.assertEqual(None, func(c_char_p(None))) +- self.assertEqual("123", func(c_char_p("123"))) ++ self.assertEqual(b"123", func(c_char_p(b"123"))) + +- self.assertEqual("123", func(c_buffer("123"))) +- ca = c_char("a") +- self.assertEqual("a", func(pointer(ca))[0]) +- self.assertEqual("a", func(byref(ca))[0]) ++ self.assertEqual(b"123", func(c_buffer(b"123"))) ++ ca = c_char(b"a") ++ self.assertEqual(ord(b"a"), func(pointer(ca))[0]) ++ self.assertEqual(ord(b"a"), func(byref(ca))[0]) + + def test_c_char_p_arg(self): + func = testdll._testfunc_p_p +@@ -107,14 +107,14 @@ + func.argtypes = c_char_p, + + self.assertEqual(None, func(None)) +- self.assertEqual("123", func("123")) ++ self.assertEqual(b"123", func(b"123")) + self.assertEqual(None, func(c_char_p(None))) +- self.assertEqual("123", func(c_char_p("123"))) ++ self.assertEqual(b"123", func(c_char_p(b"123"))) + +- self.assertEqual("123", func(c_buffer("123"))) +- ca = c_char("a") +- self.assertEqual("a", func(pointer(ca))[0]) +- self.assertEqual("a", func(byref(ca))[0]) ++ self.assertEqual(b"123", func(c_buffer(b"123"))) ++ ca = c_char(b"a") ++ self.assertEqual(ord(b"a"), func(pointer(ca))[0]) ++ self.assertEqual(ord(b"a"), func(byref(ca))[0]) + + def test_c_void_p_arg(self): + func = testdll._testfunc_p_p +@@ -122,14 +122,14 @@ + func.argtypes = c_void_p, + + self.assertEqual(None, func(None)) +- self.assertEqual("123", func(b"123")) +- self.assertEqual("123", func(c_char_p("123"))) ++ self.assertEqual(b"123", func(b"123")) ++ self.assertEqual(b"123", func(c_char_p(b"123"))) + self.assertEqual(None, func(c_char_p(None))) + +- self.assertEqual("123", func(c_buffer("123"))) ++ self.assertEqual(b"123", func(c_buffer(b"123"))) + ca = c_char("a") +- self.assertEqual("a", func(pointer(ca))[0]) +- self.assertEqual("a", func(byref(ca))[0]) ++ self.assertEqual(ord(b"a"), func(pointer(ca))[0]) ++ self.assertEqual(ord(b"a"), func(byref(ca))[0]) + + func(byref(c_int())) + func(pointer(c_int())) +Index: Lib/ctypes/test/test_slicing.py +=================================================================== +--- Lib/ctypes/test/test_slicing.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/test/test_slicing.py (.../branches/release31-maint) (Revision 76056) +@@ -109,7 +109,7 @@ + dll.my_strdup.errcheck = errcheck + try: + res = dll.my_strdup(s) +- self.assertEqual(res, s.decode()) ++ self.assertEqual(res, s) + finally: + del dll.my_strdup.errcheck + +Index: Lib/ctypes/util.py +=================================================================== +--- Lib/ctypes/util.py (.../tags/r311) (Revision 76056) ++++ Lib/ctypes/util.py (.../branches/release31-maint) (Revision 76056) +@@ -219,8 +219,12 @@ + # XXX assuming GLIBC's ldconfig (with option -p) + expr = r'(\S+)\s+\((%s(?:, OS ABI:[^\)]*)?)\)[^/]*(/[^\(\)\s]*lib%s\.[^\(\)\s]*)' \ + % (abi_type, re.escape(name)) +- res = re.search(expr, +- os.popen('/sbin/ldconfig -p 2>/dev/null').read()) ++ f = os.popen('/sbin/ldconfig -p 2>/dev/null') ++ try: ++ data = f.read() ++ finally: ++ f.close() ++ res = re.search(expr, data) + if not res: + return None + return res.group(1) +Index: Lib/webbrowser.py +=================================================================== +--- Lib/webbrowser.py (.../tags/r311) (Revision 76056) ++++ Lib/webbrowser.py (.../branches/release31-maint) (Revision 76056) +@@ -626,7 +626,9 @@ + # and prepend to _tryorder + for cmdline in _userchoices: + if cmdline != '': +- _synthesize(cmdline, -1) ++ cmd = _synthesize(cmdline, -1) ++ if cmd[1] is None: ++ register(cmdline, None, GenericBrowser(cmdline), -1) + cmdline = None # to make del work if _userchoices was empty + del cmdline + del _userchoices +Index: Lib/csv.py +=================================================================== +--- Lib/csv.py (.../tags/r311) (Revision 76056) ++++ Lib/csv.py (.../branches/release31-maint) (Revision 76056) +@@ -165,7 +165,7 @@ + Returns a dialect (or None) corresponding to the sample + """ + +- quotechar, delimiter, skipinitialspace = \ ++ quotechar, doublequote, delimiter, skipinitialspace = \ + self._guess_quote_and_delimiter(sample, delimiters) + if not delimiter: + delimiter, skipinitialspace = self._guess_delimiter(sample, +@@ -179,8 +179,8 @@ + lineterminator = '\r\n' + quoting = QUOTE_MINIMAL + # escapechar = '' +- doublequote = False + ++ dialect.doublequote = doublequote + dialect.delimiter = delimiter + # _csv.reader won't accept a quotechar of '' + dialect.quotechar = quotechar or '"' +@@ -212,8 +212,8 @@ + break + + if not matches: +- return ('', None, 0) # (quotechar, delimiter, skipinitialspace) +- ++ # (quotechar, doublequote, delimiter, skipinitialspace) ++ return ('', False, None, 0) + quotes = {} + delims = {} + spaces = 0 +@@ -248,9 +248,21 @@ + delim = '' + skipinitialspace = 0 + +- return (quotechar, delim, skipinitialspace) ++ # if we see an extra quote between delimiters, we've got a ++ # double quoted format ++ dq_regexp = re.compile(r"((%(delim)s)|^)\W*%(quote)s[^%(delim)s\n]*%(quote)s[^%(delim)s\n]*%(quote)s\W*((%(delim)s)|$)" % \ ++ {'delim':delim, 'quote':quotechar}, re.MULTILINE) + + ++ ++ if dq_regexp.search(data): ++ doublequote = True ++ else: ++ doublequote = False ++ ++ return (quotechar, doublequote, delim, skipinitialspace) ++ ++ + def _guess_delimiter(self, data, delimiters): + """ + The delimiter /should/ occur the same number of times on +Index: Lib/pdb.py +=================================================================== +--- Lib/pdb.py (.../tags/r311) (Revision 76056) ++++ Lib/pdb.py (.../branches/release31-maint) (Revision 76056) +@@ -208,7 +208,9 @@ + """Custom displayhook for the exec in default(), which prevents + assignment of the _ variable in the builtins. + """ +- print(repr(obj)) ++ # reproduce the behavior of the standard displayhook, not printing None ++ if obj is not None: ++ print(repr(obj)) + + def default(self, line): + if line[:1] == '!': line = line[1:] +@@ -841,8 +843,7 @@ + def do_alias(self, arg): + args = arg.split() + if len(args) == 0: +- keys = self.aliases.keys() +- keys.sort() ++ keys = sorted(self.aliases.keys()) + for alias in keys: + print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout) + return +Index: Lib/pydoc.py +=================================================================== +--- Lib/pydoc.py (.../tags/r311) (Revision 76056) ++++ Lib/pydoc.py (.../branches/release31-maint) (Revision 76056) +@@ -1557,7 +1557,7 @@ + 'global': ('global', 'NAMESPACES'), + 'if': ('if', 'TRUTHVALUE'), + 'import': ('import', 'MODULES'), +- 'in': ('in', 'SEQUENCEMETHODS2'), ++ 'in': ('in', 'SEQUENCEMETHODS'), + 'is': 'COMPARISON', + 'lambda': ('lambda', 'FUNCTIONS'), + 'not': 'BOOLEAN', +@@ -1643,12 +1643,12 @@ + 'PRECEDENCE': 'EXPRESSIONS', + 'OBJECTS': ('objects', 'TYPES'), + 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS ' +- 'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS ' +- 'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'), ++ 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS ' ++ 'NUMBERMETHODS CLASSES'), + 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'), + 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'), + 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'), +- 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 ' ++ 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS ' + 'SPECIALMETHODS'), + 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'), + 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT ' +@@ -1672,8 +1672,8 @@ + 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'), + 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'), + 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'), +- 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'), +- 'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'), ++ 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'), ++ 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'), + 'CALLS': ('calls', 'EXPRESSIONS'), + 'POWER': ('power', 'EXPRESSIONS'), + 'UNARY': ('unary', 'EXPRESSIONS'), +Index: Lib/platform.py +=================================================================== +--- Lib/platform.py (.../tags/r311) (Revision 76056) ++++ Lib/platform.py (.../branches/release31-maint) (Revision 76056) +@@ -10,7 +10,7 @@ + """ + # This module is maintained by Marc-Andre Lemburg . + # If you find problems, please submit bug reports/patches via the +-# Python SourceForge Project Page and assign them to "lemburg". ++# Python bug tracker (http://bugs.python.org) and assign them to "lemburg". + # + # Still needed: + # * more support for WinCE +Index: Lib/lib2to3/main.py +=================================================================== +--- Lib/lib2to3/main.py (.../tags/r311) (Revision 76056) ++++ Lib/lib2to3/main.py (.../branches/release31-maint) (Revision 76056) +@@ -64,7 +64,7 @@ + print(line) + + def warn(msg): +- print >> sys.stderr, "WARNING: %s" % (msg,) ++ print("WARNING: %s" % (msg,), file=sys.stderr) + + + def main(fixer_pkg, args=None): +@@ -159,8 +159,8 @@ + options.processes) + except refactor.MultiprocessingUnsupported: + assert options.processes > 1 +- print >> sys.stderr, "Sorry, -j isn't " \ +- "supported on this platform." ++ print("Sorry, -j isn't supported on this platform.", ++ file=sys.stderr) + return 1 + rt.summarize() + +Index: Lib/mailbox.py +=================================================================== +--- Lib/mailbox.py (.../tags/r311) (Revision 76056) ++++ Lib/mailbox.py (.../branches/release31-maint) (Revision 76056) +@@ -234,6 +234,9 @@ + raise NoSuchMailboxError(self._path) + self._toc = {} + self._last_read = None # Records last time we read cur/new ++ # NOTE: we manually invalidate _last_read each time we do any ++ # modifications ourselves, otherwise we might get tripped up by ++ # bogus mtime behaviour on some systems (see issue #6896). + + def add(self, message): + """Add message and return assigned key.""" +@@ -267,11 +270,15 @@ + raise + if isinstance(message, MaildirMessage): + os.utime(dest, (os.path.getatime(dest), message.get_date())) ++ # Invalidate cached toc ++ self._last_read = None + return uniq + + def remove(self, key): + """Remove the keyed message; raise KeyError if it doesn't exist.""" + os.remove(os.path.join(self._path, self._lookup(key))) ++ # Invalidate cached toc (only on success) ++ self._last_read = None + + def discard(self, key): + """If the keyed message exists, remove it.""" +@@ -306,6 +313,8 @@ + if isinstance(message, MaildirMessage): + os.utime(new_path, (os.path.getatime(new_path), + message.get_date())) ++ # Invalidate cached toc ++ self._last_read = None + + def get_message(self, key): + """Return a Message representation or raise a KeyError.""" +@@ -360,7 +369,9 @@ + + def flush(self): + """Write any pending changes to disk.""" +- return # Maildir changes are always written immediately. ++ # Maildir changes are always written immediately, so there's nothing ++ # to do except invalidate our cached toc. ++ self._last_read = None + + def lock(self): + """Lock the mailbox.""" +Index: Lib/email/test/data/msg_44.txt +=================================================================== +--- Lib/email/test/data/msg_44.txt (.../tags/r311) (Revision 76056) ++++ Lib/email/test/data/msg_44.txt (.../branches/release31-maint) (Revision 76056) +@@ -16,16 +16,14 @@ + + + --h90VIIIKmx +-Content-Type: text/plain +-Content-Disposition: inline; name="msg.txt" ++Content-Type: text/plain; name="msg.txt" + Content-Transfer-Encoding: 7bit + + a simple kind of mirror + to reflect upon our own + + --h90VIIIKmx +-Content-Type: text/plain +-Content-Disposition: inline; name="msg.txt" ++Content-Type: text/plain; name="msg.txt" + Content-Transfer-Encoding: 7bit + + a simple kind of mirror +Index: Lib/email/message.py +=================================================================== +--- Lib/email/message.py (.../tags/r311) (Revision 76056) ++++ Lib/email/message.py (.../branches/release31-maint) (Revision 76056) +@@ -681,7 +681,7 @@ + missing = object() + filename = self.get_param('filename', missing, 'content-disposition') + if filename is missing: +- filename = self.get_param('name', missing, 'content-disposition') ++ filename = self.get_param('name', missing, 'content-type') + if filename is missing: + return failobj + return utils.collapse_rfc2231_value(filename).strip() +Index: Lib/zipfile.py +=================================================================== +--- Lib/zipfile.py (.../tags/r311) (Revision 76056) ++++ Lib/zipfile.py (.../branches/release31-maint) (Revision 76056) +@@ -1188,22 +1188,21 @@ + try: + filename, flag_bits = zinfo._encodeFilenameFlags() + centdir = struct.pack(structCentralDir, +- stringCentralDir, create_version, +- zinfo.create_system, extract_version, zinfo.reserved, +- flag_bits, zinfo.compress_type, dostime, dosdate, +- zinfo.CRC, compress_size, file_size, +- len(filename), len(extra_data), len(zinfo.comment), +- 0, zinfo.internal_attr, zinfo.external_attr, +- header_offset) ++ stringCentralDir, create_version, ++ zinfo.create_system, extract_version, zinfo.reserved, ++ flag_bits, zinfo.compress_type, dostime, dosdate, ++ zinfo.CRC, compress_size, file_size, ++ len(filename), len(extra_data), len(zinfo.comment), ++ 0, zinfo.internal_attr, zinfo.external_attr, ++ header_offset) + except DeprecationWarning: +- print >>sys.stderr, (structCentralDir, +- stringCentralDir, create_version, +- zinfo.create_system, extract_version, zinfo.reserved, +- zinfo.flag_bits, zinfo.compress_type, dostime, dosdate, +- zinfo.CRC, compress_size, file_size, +- len(zinfo.filename), len(extra_data), len(zinfo.comment), +- 0, zinfo.internal_attr, zinfo.external_attr, +- header_offset) ++ print((structCentralDir, stringCentralDir, create_version, ++ zinfo.create_system, extract_version, zinfo.reserved, ++ zinfo.flag_bits, zinfo.compress_type, dostime, dosdate, ++ zinfo.CRC, compress_size, file_size, ++ len(zinfo.filename), len(extra_data), len(zinfo.comment), ++ 0, zinfo.internal_attr, zinfo.external_attr, ++ header_offset), file=sys.stderr) + raise + self.fp.write(centdir) + self.fp.write(filename) +@@ -1255,7 +1254,7 @@ + class PyZipFile(ZipFile): + """Class to create ZIP archives with Python library files and packages.""" + +- def writepy(self, pathname, basename = ""): ++ def writepy(self, pathname, basename=""): + """Add all files from "pathname" to the ZIP archive. + + If pathname is a package directory, search the directory and +Index: Lib/codeop.py +=================================================================== +--- Lib/codeop.py (.../tags/r311) (Revision 76056) ++++ Lib/codeop.py (.../branches/release31-maint) (Revision 76056) +@@ -96,7 +96,7 @@ + if code: + return code + if not code1 and repr(err1) == repr(err2): +- raise SyntaxError(err1) ++ raise err1 + + def _compile(source, filename, symbol): + return compile(source, filename, symbol, PyCF_DONT_IMPLY_DEDENT) +Index: Lib/plistlib.py +=================================================================== +--- Lib/plistlib.py (.../tags/r311) (Revision 76056) ++++ Lib/plistlib.py (.../branches/release31-maint) (Revision 76056) +@@ -1,6 +1,6 @@ + r"""plistlib.py -- a tool to generate and parse MacOSX .plist files. + +-The PropertList (.plist) file format is a simple XML pickle supporting ++The property list (.plist) file format is a simple XML pickle supporting + basic object types, like dictionaries, lists, numbers and strings. + Usually the top level object is a dictionary. + +@@ -16,32 +16,31 @@ + and writePlistToBytes(). + + Values can be strings, integers, floats, booleans, tuples, lists, +-dictionaries, Data or datetime.datetime objects. String values (including +-dictionary keys) may be unicode strings -- they will be written out as +-UTF-8. ++dictionaries (but only with string keys), Data or datetime.datetime objects. ++String values (including dictionary keys) have to be unicode strings -- they ++will be written out as UTF-8. + + The plist type is supported through the Data class. This is a +-thin wrapper around a Python bytes object. ++thin wrapper around a Python bytes object. Use 'Data' if your strings ++contain control characters. + + Generate Plist example: + + pl = dict( +- aString="Doodah", +- aList=["A", "B", 12, 32.1, [1, 2, 3]], ++ aString = "Doodah", ++ aList = ["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, +- aDict=dict( +- anotherString="", +- aUnicodeValue=u'M\xe4ssig, Ma\xdf', +- aTrueValue=True, +- aFalseValue=False, ++ aDict = dict( ++ anotherString = "", ++ aUnicodeValue = "M\xe4ssig, Ma\xdf", ++ aTrueValue = True, ++ aFalseValue = False, + ), + someData = Data(b""), + someMoreData = Data(b"" * 10), + aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())), + ) +- # unicode keys are possible, but a little awkward to use: +- pl[u'\xc5benraa'] = "That was a unicode key." + writePlist(pl, fileName) + + Parse Plist example: +@@ -220,7 +219,7 @@ + elif isinstance(value, (tuple, list)): + self.writeArray(value) + else: +- raise TypeError("unsuported type: %s" % type(value)) ++ raise TypeError("unsupported type: %s" % type(value)) + + def writeData(self, data): + self.beginElement("data") +Index: Lib/test/test_csv.py +=================================================================== +--- Lib/test/test_csv.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_csv.py (.../branches/release31-maint) (Revision 76056) +@@ -767,7 +767,7 @@ + 'Harry''s':'Arlington Heights':'IL':'2/1/03':'Kimi Hayes' + 'Shark City':'Glendale Heights':'IL':'12/28/02':'Prezence' + 'Tommy''s Place':'Blue Island':'IL':'12/28/02':'Blue Sunday/White Crow' +-'Stonecutters Seafood and Chop House':'Lemont':'IL':'12/19/02':'Week Back' ++'Stonecutters ''Seafood'' and Chop House':'Lemont':'IL':'12/19/02':'Week Back' + """ + header = '''\ + "venue","city","state","date","performers" +@@ -826,6 +826,13 @@ + self.assertEqual(dialect.delimiter, "|") + self.assertEqual(dialect.quotechar, "'") + ++ def test_doublequote(self): ++ sniffer = csv.Sniffer() ++ dialect = sniffer.sniff(self.header) ++ self.assertFalse(dialect.doublequote) ++ dialect = sniffer.sniff(self.sample2) ++ self.assertTrue(dialect.doublequote) ++ + if not hasattr(sys, "gettotalrefcount"): + if support.verbose: print("*** skipping leakage tests ***") + else: +Index: Lib/test/test_urllib2_localnet.py +=================================================================== +--- Lib/test/test_urllib2_localnet.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_urllib2_localnet.py (.../branches/release31-maint) (Revision 76056) +@@ -469,14 +469,25 @@ + # Make sure proper exception is raised when connecting to a bogus + # address. + self.assertRaises(IOError, +- # SF patch 809915: In Sep 2003, VeriSign started +- # highjacking invalid .com and .net addresses to +- # boost traffic to their own site. This test +- # started failing then. One hopes the .invalid +- # domain will be spared to serve its defined +- # purpose. ++ # Given that both VeriSign and various ISPs have in ++ # the past or are presently hijacking various invalid ++ # domain name requests in an attempt to boost traffic ++ # to their own sites, finding a domain name to use ++ # for this test is difficult. RFC2606 leads one to ++ # believe that '.invalid' should work, but experience ++ # seemed to indicate otherwise. Single character ++ # TLDs are likely to remain invalid, so this seems to ++ # be the best choice. The trailing '.' prevents a ++ # related problem: The normal DNS resolver appends ++ # the domain names from the search path if there is ++ # no '.' the end and, and if one of those domains ++ # implements a '*' rule a result is returned. ++ # However, none of this will prevent the test from ++ # failing if the ISP hijacks all invalid domain ++ # requests. The real solution would be to be able to ++ # parameterize the framework with a mock resolver. + urllib.request.urlopen, +- "http://sadflkjsasf.i.nvali.d/") ++ "http://sadflkjsasf.i.nvali.d./") + + def test_main(): + support.run_unittest(ProxyAuthTests, TestUrlopen) +Index: Lib/test/test_codecs.py +=================================================================== +--- Lib/test/test_codecs.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_codecs.py (.../branches/release31-maint) (Revision 76056) +@@ -338,6 +338,12 @@ + ] + ) + ++ def test_handlers(self): ++ self.assertEqual(('\ufffd', 1), ++ codecs.utf_32_decode(b'\x01', 'replace', True)) ++ self.assertEqual(('', 1), ++ codecs.utf_32_decode(b'\x01', 'ignore', True)) ++ + def test_errors(self): + self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode, + b"\xff", "strict", True) +@@ -461,6 +467,12 @@ + ] + ) + ++ def test_handlers(self): ++ self.assertEqual(('\ufffd', 1), ++ codecs.utf_16_decode(b'\x01', 'replace', True)) ++ self.assertEqual(('', 1), ++ codecs.utf_16_decode(b'\x01', 'ignore', True)) ++ + def test_errors(self): + self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode, + b"\xff", "strict", True) +Index: Lib/test/regrtest.py +=================================================================== +--- Lib/test/regrtest.py (.../tags/r311) (Revision 76056) ++++ Lib/test/regrtest.py (.../branches/release31-maint) (Revision 76056) +@@ -598,6 +598,10 @@ + refleak = False # True if the test leaked references. + try: + save_stdout = sys.stdout ++ # Save various things that tests may mess up so we can restore ++ # them afterward. ++ save_environ = dict(os.environ) ++ save_argv = sys.argv[:] + try: + if cfp: + sys.stdout = cfp +@@ -622,6 +626,17 @@ + test_times.append((test_time, test)) + finally: + sys.stdout = save_stdout ++ # Restore what we saved if needed, but also complain if the test ++ # changed it so that the test may eventually get fixed. ++ if not os.environ == save_environ: ++ if not quiet: ++ print("Warning: os.environ was modified by", test) ++ os.environ.clear() ++ os.environ.update(save_environ) ++ if not sys.argv == save_argv: ++ if not quiet: ++ print("Warning: argv was modified by", test) ++ sys.argv[:] = save_argv + except support.ResourceDenied as msg: + if not quiet: + print(test, "skipped --", msg) +@@ -1212,11 +1227,9 @@ + # much of the testing framework relies on the globals in the + # test.support module. + mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0]))) +- i = pathlen = len(sys.path) ++ i = len(sys.path) + while i >= 0: + i -= 1 + if os.path.abspath(os.path.normpath(sys.path[i])) == mydir: + del sys.path[i] +- if len(sys.path) == pathlen: +- print('Could not find %r in sys.path to remove it' % mydir) + main() +Index: Lib/test/test_tokenize.py +=================================================================== +--- Lib/test/test_tokenize.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_tokenize.py (.../branches/release31-maint) (Revision 76056) +@@ -719,7 +719,7 @@ + b'do_something(else)\n' + ) + encoding, consumed_lines = detect_encoding(self.get_readline(lines)) +- self.assertEquals(encoding, 'latin-1') ++ self.assertEquals(encoding, 'iso-8859-1') + self.assertEquals(consumed_lines, [b'# -*- coding: latin-1 -*-\n']) + + def test_matched_bom_and_cookie_first_line(self): +@@ -775,6 +775,34 @@ + readline = self.get_readline(lines) + self.assertRaises(SyntaxError, detect_encoding, readline) + ++ def test_latin1_normalization(self): ++ # See get_normal_name() in tokenizer.c. ++ encodings = ("latin-1", "iso-8859-1", "iso-latin-1", "latin-1-unix", ++ "iso-8859-1-unix", "iso-latin-1-mac") ++ for encoding in encodings: ++ for rep in ("-", "_"): ++ enc = encoding.replace("-", rep) ++ lines = (b"#!/usr/bin/python\n", ++ b"# coding: " + enc.encode("ascii") + b"\n", ++ b"print(things)\n", ++ b"do_something += 4\n") ++ rl = self.get_readline(lines) ++ found, consumed_lines = detect_encoding(rl) ++ self.assertEquals(found, "iso-8859-1") ++ ++ def test_utf8_normalization(self): ++ # See get_normal_name() in tokenizer.c. ++ encodings = ("utf-8", "utf-8-mac", "utf-8-unix") ++ for encoding in encodings: ++ for rep in ("-", "_"): ++ enc = encoding.replace("-", rep) ++ lines = (b"#!/usr/bin/python\n", ++ b"# coding: " + enc.encode("ascii") + b"\n", ++ b"1 + 3\n") ++ rl = self.get_readline(lines) ++ found, consumed_lines = detect_encoding(rl) ++ self.assertEquals(found, "utf-8") ++ + def test_short_files(self): + readline = self.get_readline((b'print(something)\n',)) + encoding, consumed_lines = detect_encoding(readline) +Index: Lib/test/test_io.py +=================================================================== +--- Lib/test/test_io.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_io.py (.../branches/release31-maint) (Revision 76056) +@@ -2051,6 +2051,27 @@ + self.assertEqual(f.errors, "replace") + + ++ def test_threads_write(self): ++ # Issue6750: concurrent writes could duplicate data ++ event = threading.Event() ++ with self.open(support.TESTFN, "w", buffering=1) as f: ++ def run(n): ++ text = "Thread%03d\n" % n ++ event.wait() ++ f.write(text) ++ threads = [threading.Thread(target=lambda n=x: run(n)) ++ for x in range(20)] ++ for t in threads: ++ t.start() ++ time.sleep(0.02) ++ event.set() ++ for t in threads: ++ t.join() ++ with self.open(support.TESTFN) as f: ++ content = f.read() ++ for n in range(20): ++ self.assertEquals(content.count("Thread%03d\n" % n), 1) ++ + class CTextIOWrapperTest(TextIOWrapperTest): + + def test_initialization(self): +Index: Lib/test/test_descr.py +=================================================================== +--- Lib/test/test_descr.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_descr.py (.../branches/release31-maint) (Revision 76056) +@@ -1268,13 +1268,9 @@ + self.assertEqual(super(D,D).goo(), (D,)) + self.assertEqual(super(D,d).goo(), (D,)) + +- # Verify that argument is checked for callability (SF bug 753451) +- try: +- classmethod(1).__get__(1) +- except TypeError: +- pass +- else: +- self.fail("classmethod should check for callability") ++ # Verify that a non-callable will raise ++ meth = classmethod(1).__get__(1) ++ self.assertRaises(TypeError, meth) + + # Verify that classmethod() doesn't allow keyword args + try: +Index: Lib/test/test_pep263.py +=================================================================== +--- Lib/test/test_pep263.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_pep263.py (.../branches/release31-maint) (Revision 76056) +@@ -36,6 +36,14 @@ + exec(c, d) + self.assertEquals(d['\xc6'], '\xc6') + ++ def test_issue3297(self): ++ c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec") ++ d = {} ++ exec(c, d) ++ self.assertEqual(d['a'], d['b']) ++ self.assertEqual(len(d['a']), len(d['b'])) ++ self.assertEqual(ascii(d['a']), ascii(d['b'])) ++ + def test_main(): + support.run_unittest(PEP263Test) + +Index: Lib/test/test_fork1.py +=================================================================== +--- Lib/test/test_fork1.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_fork1.py (.../branches/release31-maint) (Revision 76056) +@@ -1,8 +1,14 @@ + """This test checks for correct fork() behavior. + """ + ++import errno ++import imp + import os ++import signal ++import sys + import time ++import threading ++ + from test.fork_wait import ForkWait + from test.support import run_unittest, reap_children, get_attribute + +@@ -23,6 +29,41 @@ + self.assertEqual(spid, cpid) + self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8)) + ++ def test_import_lock_fork(self): ++ import_started = threading.Event() ++ fake_module_name = "fake test module" ++ partial_module = "partial" ++ complete_module = "complete" ++ def importer(): ++ imp.acquire_lock() ++ sys.modules[fake_module_name] = partial_module ++ import_started.set() ++ time.sleep(0.01) # Give the other thread time to try and acquire. ++ sys.modules[fake_module_name] = complete_module ++ imp.release_lock() ++ t = threading.Thread(target=importer) ++ t.start() ++ import_started.wait() ++ pid = os.fork() ++ try: ++ if not pid: ++ m = __import__(fake_module_name) ++ if m == complete_module: ++ os._exit(0) ++ else: ++ os._exit(1) ++ else: ++ t.join() ++ # Exitcode 1 means the child got a partial module (bad.) No ++ # exitcode (but a hang, which manifests as 'got pid 0') ++ # means the child deadlocked (also bad.) ++ self.wait_impl(pid) ++ finally: ++ try: ++ os.kill(pid, signal.SIGKILL) ++ except OSError: ++ pass ++ + def test_main(): + run_unittest(ForkTest) + reap_children() +Index: Lib/test/test_itertools.py +=================================================================== +--- Lib/test/test_itertools.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_itertools.py (.../branches/release31-maint) (Revision 76056) +@@ -581,6 +581,46 @@ + ids = list(map(id, list(zip_longest('abc', 'def')))) + self.assertEqual(len(dict.fromkeys(ids)), len(ids)) + ++ def test_bug_7244(self): ++ ++ class Repeater: ++ # this class is similar to itertools.repeat ++ def __init__(self, o, t, e): ++ self.o = o ++ self.t = int(t) ++ self.e = e ++ def __iter__(self): # its iterator is itself ++ return self ++ def __next__(self): ++ if self.t > 0: ++ self.t -= 1 ++ return self.o ++ else: ++ raise self.e ++ ++ # Formerly this code in would fail in debug mode ++ # with Undetected Error and Stop Iteration ++ r1 = Repeater(1, 3, StopIteration) ++ r2 = Repeater(2, 4, StopIteration) ++ def run(r1, r2): ++ result = [] ++ for i, j in zip_longest(r1, r2, fillvalue=0): ++ with support.captured_output('stdout'): ++ print((i, j)) ++ result.append((i, j)) ++ return result ++ self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)]) ++ ++ # Formerly, the RuntimeError would be lost ++ # and StopIteration would stop as expected ++ r1 = Repeater(1, 3, RuntimeError) ++ r2 = Repeater(2, 4, StopIteration) ++ it = zip_longest(r1, r2, fillvalue=0) ++ self.assertEqual(next(it), (1, 2)) ++ self.assertEqual(next(it), (1, 2)) ++ self.assertEqual(next(it), (1, 2)) ++ self.assertRaises(RuntimeError, next, it) ++ + def test_product(self): + for args, result in [ + ([], [()]), # zero iterables +Index: Lib/test/test_socket.py +=================================================================== +--- Lib/test/test_socket.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_socket.py (.../branches/release31-maint) (Revision 76056) +@@ -291,7 +291,7 @@ + # On some versions, this loses a reference + orig = sys.getrefcount(__name__) + socket.getnameinfo(__name__,0) +- except SystemError: ++ except TypeError: + if sys.getrefcount(__name__) != orig: + self.fail("socket.getnameinfo loses a reference") + +Index: Lib/test/test_float.py +=================================================================== +--- Lib/test/test_float.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_float.py (.../branches/release31-maint) (Revision 76056) +@@ -34,6 +34,9 @@ + self.assertRaises(ValueError, float, ".") + self.assertRaises(ValueError, float, "-.") + self.assertEqual(float(b" \u0663.\u0661\u0664 ".decode('raw-unicode-escape')), 3.14) ++ # extra long strings should not be a problem ++ float(b'.' + b'1'*1000) ++ float('.' + '1'*1000) + + @support.run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE') + def test_float_with_comma(self): +Index: Lib/test/test_string.py +=================================================================== +--- Lib/test/test_string.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_string.py (.../branches/release31-maint) (Revision 76056) +@@ -15,6 +15,17 @@ + string.punctuation + string.printable + ++ def test_capwords(self): ++ self.assertEqual(string.capwords('abc def ghi'), 'Abc Def Ghi') ++ self.assertEqual(string.capwords('abc\tdef\nghi'), 'Abc Def Ghi') ++ self.assertEqual(string.capwords('abc\t def \nghi'), 'Abc Def Ghi') ++ self.assertEqual(string.capwords('ABC DEF GHI'), 'Abc Def Ghi') ++ self.assertEqual(string.capwords('ABC-DEF-GHI', '-'), 'Abc-Def-Ghi') ++ self.assertEqual(string.capwords('ABC-def DEF-ghi GHI'), 'Abc-def Def-ghi Ghi') ++ self.assertEqual(string.capwords(' aBc DeF '), 'Abc Def') ++ self.assertEqual(string.capwords('\taBc\tDeF\t'), 'Abc Def') ++ self.assertEqual(string.capwords('\taBc\tDeF\t', '\t'), '\tAbc\tDef\t') ++ + def test_formatter(self): + fmt = string.Formatter() + self.assertEqual(fmt.format("foo"), "foo") +Index: Lib/test/test_httplib.py +=================================================================== +--- Lib/test/test_httplib.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_httplib.py (.../branches/release31-maint) (Revision 76056) +@@ -1,6 +1,7 @@ + import errno + from http import client + import io ++import array + import socket + + from unittest import TestCase +@@ -174,6 +175,20 @@ + self.assertTrue(sock.data.startswith(expected), '%r != %r' % + (sock.data[:len(expected)], expected)) + ++ def test_send(self): ++ expected = b'this is a test this is only a test' ++ conn = client.HTTPConnection('example.com') ++ sock = FakeSocket(None) ++ conn.sock = sock ++ conn.send(expected) ++ self.assertEquals(expected, sock.data) ++ sock.data = b'' ++ conn.send(array.array('b', expected)) ++ self.assertEquals(expected, sock.data) ++ sock.data = b'' ++ conn.send(io.BytesIO(expected)) ++ self.assertEquals(expected, sock.data) ++ + def test_chunked(self): + chunked_start = ( + 'HTTP/1.1 200 OK\r\n' +Index: Lib/test/test_thread.py +=================================================================== +--- Lib/test/test_thread.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_thread.py (.../branches/release31-maint) (Revision 76056) +@@ -24,6 +24,7 @@ + self.done_mutex.acquire() + self.running_mutex = thread.allocate_lock() + self.random_mutex = thread.allocate_lock() ++ self.created = 0 + self.running = 0 + self.next_ident = 0 + +@@ -35,6 +36,7 @@ + self.next_ident += 1 + verbose_print("creating task %s" % self.next_ident) + thread.start_new_thread(self.task, (self.next_ident,)) ++ self.created += 1 + self.running += 1 + + def task(self, ident): +@@ -45,7 +47,7 @@ + verbose_print("task %s done" % ident) + with self.running_mutex: + self.running -= 1 +- if self.running == 0: ++ if self.created == NUMTASKS and self.running == 0: + self.done_mutex.release() + + def test_starting_threads(self): +@@ -87,6 +89,7 @@ + for tss in (262144, 0x100000): + verbose_print("trying stack_size = (%d)" % tss) + self.next_ident = 0 ++ self.created = 0 + for i in range(NUMTASKS): + self.newtask() + +Index: Lib/test/decimaltestdata/rounding.decTest +=================================================================== +--- Lib/test/decimaltestdata/rounding.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/rounding.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- These tests require that implementations take account of residues in + -- order to get correct results for some rounding modes. Rather than +Index: Lib/test/decimaltestdata/decDouble.decTest +=================================================================== +--- Lib/test/decimaltestdata/decDouble.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/decDouble.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- decDouble tests + dectest: ddAbs +Index: Lib/test/decimaltestdata/dqClass.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqClass.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqClass.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- [New 2006.11.27] + +Index: Lib/test/decimaltestdata/copysign.decTest +=================================================================== +--- Lib/test/decimaltestdata/copysign.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/copysign.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/decSingle.decTest +=================================================================== +--- Lib/test/decimaltestdata/decSingle.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/decSingle.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- decSingle tests + dectest: dsBase +Index: Lib/test/decimaltestdata/ddAdd.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddAdd.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddAdd.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests are for decDoubles only; all arguments are + -- representable in a decDouble +Index: Lib/test/decimaltestdata/ddCopySign.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCopySign.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCopySign.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/ddEncode.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddEncode.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddEncode.decTest (.../branches/release31-maint) (Revision 76056) +@@ -18,7 +18,7 @@ + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ + -- [Previously called decimal64.decTest] +-version: 2.58 ++version: 2.59 + + -- This set of tests is for the eight-byte concrete representation. + -- Its characteristics are: +Index: Lib/test/decimaltestdata/powersqrt.decTest +=================================================================== +--- Lib/test/decimaltestdata/powersqrt.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/powersqrt.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- These testcases are taken from squareroot.decTest but are + -- evaluated using the power operator. The differences in results +Index: Lib/test/decimaltestdata/decQuad.decTest +=================================================================== +--- Lib/test/decimaltestdata/decQuad.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/decQuad.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- decQuad tests + dectest: dqAbs +Index: Lib/test/decimaltestdata/dqPlus.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqPlus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqPlus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/dqCompare.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCompare.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCompare.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/ddInvert.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddInvert.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddInvert.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqCopySign.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCopySign.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCopySign.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/ddBase.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddBase.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddBase.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This file tests base conversions from string to a decimal number + -- and back to a string (in Scientific form) +Index: Lib/test/decimaltestdata/nextplus.decTest +=================================================================== +--- Lib/test/decimaltestdata/nextplus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/nextplus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/log10.decTest +=================================================================== +--- Lib/test/decimaltestdata/log10.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/log10.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This emphasises the testing of notable cases, as they will often + -- have unusual paths (especially the 10**n results). +Index: Lib/test/decimaltestdata/dqSameQuantum.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqSameQuantum.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqSameQuantum.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/ddMultiply.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddMultiply.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddMultiply.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests are for decDoubles only; all arguments are + -- representable in a decDouble +Index: Lib/test/decimaltestdata/dqFMA.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqFMA.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqFMA.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/ddNextPlus.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddNextPlus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddNextPlus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/minus.decTest +=================================================================== +--- Lib/test/decimaltestdata/minus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/minus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests primarily tests the existence of the operator. + -- Subtraction, rounding, and more overflows are tested elsewhere. +Index: Lib/test/decimaltestdata/power.decTest +=================================================================== +--- Lib/test/decimaltestdata/power.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/power.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- In addition to the power operator testcases here, see also the file + -- powersqrt.decTest which includes all the tests from +Index: Lib/test/decimaltestdata/nexttoward.decTest +=================================================================== +--- Lib/test/decimaltestdata/nexttoward.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/nexttoward.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/samequantum.decTest +=================================================================== +--- Lib/test/decimaltestdata/samequantum.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/samequantum.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/comparetotmag.decTest +=================================================================== +--- Lib/test/decimaltestdata/comparetotmag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/comparetotmag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that it cannot be assumed that add/subtract tests cover paths + -- for this operation adequately, here, because the code might be +Index: Lib/test/decimaltestdata/and.decTest +=================================================================== +--- Lib/test/decimaltestdata/and.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/and.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/dqMultiply.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqMultiply.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqMultiply.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests are for decQuads only; all arguments are + -- representable in a decQuad +Index: Lib/test/decimaltestdata/dqOr.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqOr.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqOr.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/ddNextToward.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddNextToward.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddNextToward.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/dqNextPlus.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqNextPlus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqNextPlus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/ddSameQuantum.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddSameQuantum.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddSameQuantum.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/xor.decTest +=================================================================== +--- Lib/test/decimaltestdata/xor.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/xor.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddFMA.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddFMA.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddFMA.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqCopyNegate.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCopyNegate.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCopyNegate.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/dqAnd.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqAnd.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqAnd.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/dqReduce.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqReduce.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqReduce.decTest (.../branches/release31-maint) (Revision 76056) +@@ -18,7 +18,7 @@ + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ + +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/dqXor.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqXor.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqXor.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/dqMaxMag.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqMaxMag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqMaxMag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/dqCopy.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCopy.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCopy.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/ddCompareSig.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCompareSig.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCompareSig.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/fma.decTest +=================================================================== +--- Lib/test/decimaltestdata/fma.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/fma.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddMinus.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddMinus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddMinus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/dqDivideInt.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqDivideInt.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqDivideInt.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/reduce.decTest +=================================================================== +--- Lib/test/decimaltestdata/reduce.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/reduce.decTest (.../branches/release31-maint) (Revision 76056) +@@ -19,7 +19,7 @@ + ------------------------------------------------------------------------ + -- [This used to be called normalize.] + +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/dqLogB.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqLogB.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqLogB.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/tointegral.decTest +=================================================================== +--- Lib/test/decimaltestdata/tointegral.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/tointegral.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests tests the extended specification 'round-to-integral + -- value' operation (from IEEE 854, later modified in 754r). +Index: Lib/test/decimaltestdata/ln.decTest +=================================================================== +--- Lib/test/decimaltestdata/ln.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ln.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 16 +Index: Lib/test/decimaltestdata/ddAnd.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddAnd.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddAnd.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqCompareTotal.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCompareTotal.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCompareTotal.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/ddToIntegral.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddToIntegral.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddToIntegral.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests tests the extended specification 'round-to-integral + -- value-exact' operations (from IEEE 854, later modified in 754r). +Index: Lib/test/decimaltestdata/ddXor.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddXor.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddXor.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/plus.decTest +=================================================================== +--- Lib/test/decimaltestdata/plus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/plus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests primarily tests the existence of the operator. + -- Addition and rounding, and most overflows, are tested elsewhere. +Index: Lib/test/decimaltestdata/dsEncode.decTest +=================================================================== +--- Lib/test/decimaltestdata/dsEncode.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dsEncode.decTest (.../branches/release31-maint) (Revision 76056) +@@ -18,7 +18,7 @@ + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ + -- [Previously called decimal32.decTest] +-version: 2.58 ++version: 2.59 + + -- This set of tests is for the four-byte concrete representation. + -- Its characteristics are: +Index: Lib/test/decimaltestdata/ddCompareTotalMag.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCompareTotalMag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCompareTotalMag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/subtract.decTest +=================================================================== +--- Lib/test/decimaltestdata/subtract.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/subtract.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/dqDivide.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqDivide.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqDivide.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/copyabs.decTest +=================================================================== +--- Lib/test/decimaltestdata/copyabs.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/copyabs.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/divide.decTest +=================================================================== +--- Lib/test/decimaltestdata/divide.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/divide.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddCopyAbs.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCopyAbs.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCopyAbs.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/maxmag.decTest +=================================================================== +--- Lib/test/decimaltestdata/maxmag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/maxmag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/dqCanonical.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCanonical.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCanonical.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This file tests that copy operations leave uncanonical operands + -- unchanged, and vice versa +Index: Lib/test/decimaltestdata/remainderNear.decTest +=================================================================== +--- Lib/test/decimaltestdata/remainderNear.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/remainderNear.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddReduce.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddReduce.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddReduce.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqNextMinus.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqNextMinus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqNextMinus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/dqMinus.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqMinus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqMinus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/ddMaxMag.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddMaxMag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddMaxMag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/dqRotate.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqRotate.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqRotate.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/dqNextToward.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqNextToward.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqNextToward.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/compare.decTest +=================================================================== +--- Lib/test/decimaltestdata/compare.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/compare.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/ddPlus.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddPlus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddPlus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/inexact.decTest +=================================================================== +--- Lib/test/decimaltestdata/inexact.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/inexact.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/exp.decTest +=================================================================== +--- Lib/test/decimaltestdata/exp.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/exp.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Tests of the exponential funtion. Currently all testcases here + -- show results which are correctly rounded (within <= 0.5 ulp). +Index: Lib/test/decimaltestdata/dqMinMag.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqMinMag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqMinMag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/rotate.decTest +=================================================================== +--- Lib/test/decimaltestdata/rotate.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/rotate.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddSubtract.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddSubtract.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddSubtract.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests are for decDoubles only; all arguments are + -- representable in a decDouble +Index: Lib/test/decimaltestdata/copy.decTest +=================================================================== +--- Lib/test/decimaltestdata/copy.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/copy.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddDivide.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddDivide.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddDivide.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +@@ -160,7 +160,7 @@ + dddiv222 divide -391 597 -> -0.6549413735343384 Inexact Rounded + dddiv223 divide -391 -597 -> 0.6549413735343384 Inexact Rounded + +--- test some cases that are close to exponent overflow ++-- test some cases that are close to exponent overflow, some with coefficient padding + dddiv270 divide 1 1e384 -> 1E-384 Subnormal + dddiv271 divide 1 0.9e384 -> 1.11111111111111E-384 Rounded Inexact Subnormal Underflow + dddiv272 divide 1 0.99e384 -> 1.01010101010101E-384 Rounded Inexact Subnormal Underflow +@@ -168,8 +168,17 @@ + dddiv274 divide 9e384 1 -> 9.000000000000000E+384 Clamped + dddiv275 divide 9.9e384 1 -> 9.900000000000000E+384 Clamped + dddiv276 divide 9.99e384 1 -> 9.990000000000000E+384 Clamped +-dddiv277 divide 9.999999999999999e384 1 -> 9.999999999999999E+384 ++dddiv277 divide 9.9999999999999e384 1 -> 9.999999999999900E+384 Clamped ++dddiv278 divide 9.99999999999999e384 1 -> 9.999999999999990E+384 Clamped ++dddiv279 divide 9.999999999999999e384 1 -> 9.999999999999999E+384 + ++dddiv285 divide 9.9e384 1.1 -> 9.000000000000000E+384 Clamped ++dddiv286 divide 9.99e384 1.1 -> 9.081818181818182E+384 Inexact Rounded ++dddiv287 divide 9.9999999999999e384 1.1 -> 9.090909090909000E+384 Clamped ++dddiv288 divide 9.99999999999999e384 1.1 -> 9.090909090909082E+384 Inexact Rounded ++dddiv289 divide 9.999999999999999e384 1.1 -> 9.090909090909090E+384 Clamped ++ ++ + -- Divide into 0 tests + dddiv301 divide 0 7 -> 0 + dddiv302 divide 0 7E-5 -> 0E+5 +Index: Lib/test/decimaltestdata/dqSubtract.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqSubtract.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqSubtract.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests are for decQuads only; all arguments are + -- representable in a decQuad +Index: Lib/test/decimaltestdata/shift.decTest +=================================================================== +--- Lib/test/decimaltestdata/shift.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/shift.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/randomBound32.decTest +=================================================================== +--- Lib/test/decimaltestdata/randomBound32.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/randomBound32.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- These testcases test calculations at precisions 31, 32, and 33, to + -- exercise the boundaries around 2**5 +Index: Lib/test/decimaltestdata/dqCompareSig.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCompareSig.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCompareSig.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/dqScaleB.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqScaleB.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqScaleB.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/divideint.decTest +=================================================================== +--- Lib/test/decimaltestdata/divideint.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/divideint.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/min.decTest +=================================================================== +--- Lib/test/decimaltestdata/min.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/min.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/ddRemainderNear.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddRemainderNear.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddRemainderNear.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/max.decTest +=================================================================== +--- Lib/test/decimaltestdata/max.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/max.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/ddDivideInt.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddDivideInt.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddDivideInt.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqRemainder.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqRemainder.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqRemainder.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/dqToIntegral.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqToIntegral.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqToIntegral.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests tests the extended specification 'round-to-integral + -- value-exact' operations (from IEEE 854, later modified in 754r). +Index: Lib/test/decimaltestdata/ddCompare.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCompare.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCompare.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/dqBase.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqBase.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqBase.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This file tests base conversions from string to a decimal number + -- and back to a string (in Scientific form) +Index: Lib/test/decimaltestdata/quantize.decTest +=================================================================== +--- Lib/test/decimaltestdata/quantize.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/quantize.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Most of the tests here assume a "regular pattern", where the + -- sign and coefficient are +1. +Index: Lib/test/decimaltestdata/dsBase.decTest +=================================================================== +--- Lib/test/decimaltestdata/dsBase.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dsBase.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This file tests base conversions from string to a decimal number + -- and back to a string (in Scientific form) +Index: Lib/test/decimaltestdata/class.decTest +=================================================================== +--- Lib/test/decimaltestdata/class.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/class.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- [New 2006.11.27] + +Index: Lib/test/decimaltestdata/abs.decTest +=================================================================== +--- Lib/test/decimaltestdata/abs.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/abs.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests primarily tests the existence of the operator. + -- Additon, subtraction, rounding, and more overflows are tested +Index: Lib/test/decimaltestdata/ddRotate.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddRotate.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddRotate.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqMin.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqMin.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqMin.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/minmag.decTest +=================================================================== +--- Lib/test/decimaltestdata/minmag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/minmag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/dqMax.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqMax.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqMax.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/ddMinMag.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddMinMag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddMinMag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/or.decTest +=================================================================== +--- Lib/test/decimaltestdata/or.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/or.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddCopy.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCopy.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCopy.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/logb.decTest +=================================================================== +--- Lib/test/decimaltestdata/logb.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/logb.decTest (.../branches/release31-maint) (Revision 76056) +@@ -1,6 +1,6 @@ + ------------------------------------------------------------------------ + -- logb.decTest -- return integral adjusted exponent as per 754r -- +--- Copyright (c) IBM Corporation, 2005, 2008. All rights reserved. -- ++-- Copyright (c) IBM Corporation, 2005, 2009. All rights reserved. -- + ------------------------------------------------------------------------ + -- Please see the document "General Decimal Arithmetic Testcases" -- + -- at http://www2.hursley.ibm.com/decimal for the description of -- +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This emphasises the testing of notable cases, as they will often + -- have unusual paths (especially the 10**n results). +@@ -143,7 +143,33 @@ + logbx1419 logb 1000E2 -> 5 + logbx1420 logb 10000E2 -> 6 + ++-- inexacts ++precision: 2 ++logbx1500 logb 10000E2 -> 6 ++logbx1501 logb 1E+99 -> 99 ++logbx1502 logb 1E-99 -> -99 ++logbx1503 logb 1E+100 -> 1.0E+2 Rounded ++logbx1504 logb 1E+999 -> 1.0E+3 Inexact Rounded ++logbx1505 logb 1E-100 -> -1.0E+2 Rounded ++logbx1506 logb 1E-999 -> -1.0E+3 Inexact Rounded ++logbx1507 logb 1E-1111 -> -1.1E+3 Inexact Rounded ++logbx1508 logb 1E-3333 -> -3.3E+3 Inexact Rounded ++logbx1509 logb 1E-6666 -> -6.7E+3 Inexact Rounded ++logbx1510 logb 1E+999999999 -> 1.0E+9 Inexact Rounded ++logbx1511 logb 1E-999999999 -> -1.0E+9 Inexact Rounded ++precision: 1 ++logbx1517 logb 1E-1111 -> -1E+3 Inexact Rounded ++logbx1518 logb 1E-3333 -> -3E+3 Inexact Rounded ++logbx1519 logb 1E-6666 -> -7E+3 Inexact Rounded ++precision: 8 ++logbx1520 logb 1E+999999999 -> 1.0000000E+9 Inexact Rounded ++logbx1521 logb 1E-999999999 -> -1.0000000E+9 Inexact Rounded ++precision: 9 ++logbx1523 logb 1E+999999999 -> 999999999 ++logbx1524 logb 1E-999999999 -> -999999999 ++ + -- special values ++precision: 9 + logbx820 logb Infinity -> Infinity + logbx821 logb -Infinity -> Infinity + logbx822 logb 0 -> -Infinity Division_by_zero +Index: Lib/test/decimaltestdata/ddShift.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddShift.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddShift.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/scaleb.decTest +=================================================================== +--- Lib/test/decimaltestdata/scaleb.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/scaleb.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +@@ -198,3 +198,12 @@ + scbx161 scaleb -9.99999999E+999 -1 -> -9.99999999E+998 + scbx162 scaleb -9E+999 +1 -> -Infinity Overflow Inexact Rounded + scbx163 scaleb -1E+999 +1 -> -Infinity Overflow Inexact Rounded ++ ++-- Krah examples ++precision: 34 ++maxExponent: 999999999 ++minExponent: -999999999 ++-- integer overflow in 3.61 or earlier ++scbx164 scaleb 1E-999999999 -1200000000 -> NaN Invalid_operation ++-- out of range ++scbx165 scaleb -1E-999999999 +1200000000 -> NaN Invalid_operation +Index: Lib/test/decimaltestdata/dqAbs.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqAbs.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqAbs.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/comparetotal.decTest +=================================================================== +--- Lib/test/decimaltestdata/comparetotal.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/comparetotal.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/nextminus.decTest +=================================================================== +--- Lib/test/decimaltestdata/nextminus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/nextminus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/ddMin.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddMin.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddMin.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/ddLogB.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddLogB.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddLogB.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/ddMax.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddMax.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddMax.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- we assume that base comparison is tested in compare.decTest, so + -- these mainly cover special cases and rounding +Index: Lib/test/decimaltestdata/ddCanonical.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCanonical.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCanonical.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This file tests that copy operations leave uncanonical operands + -- unchanged, and vice versa +Index: Lib/test/decimaltestdata/ddScaleB.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddScaleB.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddScaleB.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqRemainderNear.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqRemainderNear.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqRemainderNear.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/ddNextMinus.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddNextMinus.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddNextMinus.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/ddCompareTotal.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCompareTotal.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCompareTotal.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/dqCompareTotalMag.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCompareTotalMag.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCompareTotalMag.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Note that we cannot assume add/subtract tests cover paths adequately, + -- here, because the code might be quite different (comparison cannot +Index: Lib/test/decimaltestdata/remainder.decTest +=================================================================== +--- Lib/test/decimaltestdata/remainder.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/remainder.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/testall.decTest +=================================================================== +--- Lib/test/decimaltestdata/testall.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/testall.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- core tests (using Extended: 1) -------------------------------------- + dectest: base +Index: Lib/test/decimaltestdata/ddQuantize.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddQuantize.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddQuantize.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Most of the tests here assume a "regular pattern", where the + -- sign and coefficient are +1. +Index: Lib/test/decimaltestdata/ddAbs.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddAbs.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddAbs.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/ddClass.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddClass.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddClass.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- [New 2006.11.27] + precision: 16 +Index: Lib/test/decimaltestdata/rescale.decTest +=================================================================== +--- Lib/test/decimaltestdata/rescale.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/rescale.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- [obsolete] Quantize.decTest has the improved version + +Index: Lib/test/decimaltestdata/dqEncode.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqEncode.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqEncode.decTest (.../branches/release31-maint) (Revision 76056) +@@ -18,7 +18,7 @@ + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ + -- [Previously called decimal128.decTest] +-version: 2.58 ++version: 2.59 + + -- This set of tests is for the sixteen-byte concrete representation. + -- Its characteristics are: +Index: Lib/test/decimaltestdata/extra.decTest +=================================================================== +--- Lib/test/decimaltestdata/extra.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/extra.decTest (.../branches/release31-maint) (Revision 76056) +@@ -171,6 +171,50 @@ + extr1430 min_mag 9181716151 -NaN -> 9.18172E+9 Inexact Rounded + extr1431 min_mag NaN4 1.818180E100 -> 1.81818E+100 Rounded + ++-- Issue #6794: when comparing NaNs using compare_total, payloads ++-- should be compared as though positive integers; not ++-- lexicographically as strings. ++extr1500 comparetotal NaN123 NaN45 -> 1 ++extr1501 comparetotal sNaN123 sNaN45 -> 1 ++extr1502 comparetotal -NaN123 -NaN45 -> -1 ++extr1503 comparetotal -sNaN123 -sNaN45 -> -1 ++extr1504 comparetotal NaN45 NaN123 -> -1 ++extr1505 comparetotal sNaN45 sNaN123 -> -1 ++extr1506 comparetotal -NaN45 -NaN123 -> 1 ++extr1507 comparetotal -sNaN45 -sNaN123 -> 1 ++ ++extr1510 comparetotal -sNaN63450748854172416 -sNaN911993 -> -1 ++extr1511 comparetotmag NaN1222222222222 -NaN999999 -> 1 ++ ++-- Issue #7233: rotate and scale should truncate an argument ++-- of length greater than the current precision. ++precision: 4 ++extr1600 rotate 1234567 -5 -> NaN Invalid_operation ++extr1601 rotate 1234567 -4 -> 4567 ++extr1602 rotate 1234567 -3 -> 5674 ++extr1603 rotate 1234567 -2 -> 6745 ++extr1604 rotate 1234567 -1 -> 7456 ++extr1605 rotate 1234567 0 -> 4567 ++extr1606 rotate 1234567 1 -> 5674 ++extr1607 rotate 1234567 2 -> 6745 ++extr1608 rotate 1234567 3 -> 7456 ++extr1609 rotate 1234567 4 -> 4567 ++extr1610 rotate 1234567 5 -> NaN Invalid_operation ++ ++extr1650 shift 1234567 -5 -> NaN Invalid_operation ++extr1651 shift 1234567 -4 -> 0 ++extr1652 shift 1234567 -3 -> 4 ++extr1653 shift 1234567 -2 -> 45 ++extr1654 shift 1234567 -1 -> 456 ++extr1655 shift 1234567 0 -> 4567 ++extr1656 shift 1234567 1 -> 5670 ++extr1657 shift 1234567 2 -> 6700 ++extr1658 shift 1234567 3 -> 7000 ++extr1659 shift 1234567 4 -> 0 ++extr1660 shift 1234567 5 -> NaN Invalid_operation ++ ++ ++ + -- Tests for the is_* boolean operations + precision: 9 + maxExponent: 999 +@@ -1112,10 +1156,10 @@ + bool0933 isnormal -1E+998 -> 1 + bool0934 isnormal 1E+999 -> 1 + bool0935 isnormal -1E+999 -> 1 +-bool0936 isnormal 1E+1000 -> 0 +-bool0937 isnormal -1E+1000 -> 0 +-bool0938 isnormal 1E+2000 -> 0 +-bool0939 isnormal -1E+2000 -> 0 ++bool0936 isnormal 1E+1000 -> 1 ++bool0937 isnormal -1E+1000 -> 1 ++bool0938 isnormal 1E+2000 -> 1 ++bool0939 isnormal -1E+2000 -> 1 + bool0940 isnormal 9E-2000 -> 0 + bool0941 isnormal -9E-2000 -> 0 + bool0942 isnormal 9E-1008 -> 0 +@@ -1162,10 +1206,10 @@ + bool0983 isnormal -9E+998 -> 1 + bool0984 isnormal 9E+999 -> 1 + bool0985 isnormal -9E+999 -> 1 +-bool0986 isnormal 9E+1000 -> 0 +-bool0987 isnormal -9E+1000 -> 0 +-bool0988 isnormal 9E+2000 -> 0 +-bool0989 isnormal -9E+2000 -> 0 ++bool0986 isnormal 9E+1000 -> 1 ++bool0987 isnormal -9E+1000 -> 1 ++bool0988 isnormal 9E+2000 -> 1 ++bool0989 isnormal -9E+2000 -> 1 + bool0990 isnormal 9.99999999E-2000 -> 0 + bool0991 isnormal -9.99999999E-2000 -> 0 + bool0992 isnormal 9.99999999E-1008 -> 0 +@@ -1212,10 +1256,10 @@ + bool1033 isnormal -9.99999999E+998 -> 1 + bool1034 isnormal 9.99999999E+999 -> 1 + bool1035 isnormal -9.99999999E+999 -> 1 +-bool1036 isnormal 9.99999999E+1000 -> 0 +-bool1037 isnormal -9.99999999E+1000 -> 0 +-bool1038 isnormal 9.99999999E+2000 -> 0 +-bool1039 isnormal -9.99999999E+2000 -> 0 ++bool1036 isnormal 9.99999999E+1000 -> 1 ++bool1037 isnormal -9.99999999E+1000 -> 1 ++bool1038 isnormal 9.99999999E+2000 -> 1 ++bool1039 isnormal -9.99999999E+2000 -> 1 + bool1040 isnormal Infinity -> 0 + bool1041 isnormal -Infinity -> 0 + bool1042 isnormal NaN -> 0 +Index: Lib/test/decimaltestdata/dqCopyAbs.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqCopyAbs.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqCopyAbs.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decQuads. + extended: 1 +Index: Lib/test/decimaltestdata/dqQuantize.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqQuantize.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqQuantize.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- Most of the tests here assume a "regular pattern", where the + -- sign and coefficient are +1. +@@ -357,8 +357,6 @@ + + rounding: down + dqqua389 quantize 112233445566778899123456735236450.6 1e-2 -> NaN Invalid_operation +--- ? should that one instead have been: +--- dqqua389 quantize 112233445566778899123456735236450.6 1e-2 -> NaN Invalid_operation + rounding: half_up + + -- and a few more from e-mail discussions +Index: Lib/test/decimaltestdata/add.decTest +=================================================================== +--- Lib/test/decimaltestdata/add.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/add.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 9 + rounding: half_up +Index: Lib/test/decimaltestdata/ddOr.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddOr.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddOr.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/dqInvert.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqInvert.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqInvert.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/clamp.decTest +=================================================================== +--- Lib/test/decimaltestdata/clamp.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/clamp.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests uses the same limits as the 8-byte concrete + -- representation, but applies clamping without using format-specific +Index: Lib/test/decimaltestdata/copynegate.decTest +=================================================================== +--- Lib/test/decimaltestdata/copynegate.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/copynegate.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/tointegralx.decTest +=================================================================== +--- Lib/test/decimaltestdata/tointegralx.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/tointegralx.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests tests the extended specification 'round-to-integral + -- value' operation (from IEEE 854, later modified in 754r). +Index: Lib/test/decimaltestdata/dqShift.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqShift.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqShift.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + clamp: 1 +Index: Lib/test/decimaltestdata/randoms.decTest +=================================================================== +--- Lib/test/decimaltestdata/randoms.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/randoms.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + maxexponent: 999999999 +Index: Lib/test/decimaltestdata/squareroot.decTest +=================================================================== +--- Lib/test/decimaltestdata/squareroot.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/squareroot.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +@@ -3812,6 +3812,16 @@ + clamp: 1 + sqtx9045 squareroot 1 -> 1.00000 Clamped + ++-- other ++maxexponent: 999 ++minexponent: -999 ++precision: 16 ++sqtx9046 squareroot 10 -> 3.162277660168379 inexact rounded ++sqtx9047 squareroot 10E-1 -> 1.0 ++sqtx9048 squareroot 10E-2 -> 0.3162277660168379 inexact rounded ++sqtx9049 squareroot 10E-3 -> 0.10 ++ ++ + -- High-precision exact and inexact + maxexponent: 999 + minexponent: -999 +Index: Lib/test/decimaltestdata/ddCopyNegate.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddCopyNegate.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddCopyNegate.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- All operands and results are decDoubles. + precision: 16 +Index: Lib/test/decimaltestdata/invert.decTest +=================================================================== +--- Lib/test/decimaltestdata/invert.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/invert.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/decimaltestdata/base.decTest +=================================================================== +--- Lib/test/decimaltestdata/base.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/base.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + extended: 1 + + -- This file tests base conversions from string to a decimal number +Index: Lib/test/decimaltestdata/dqAdd.decTest +=================================================================== +--- Lib/test/decimaltestdata/dqAdd.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/dqAdd.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + -- This set of tests are for decQuads only; all arguments are + -- representable in a decQuad +@@ -637,7 +637,7 @@ + dqadd7732 add 0 0 -> 0 + dqadd7733 add 0 -0 -> 0 + dqadd7734 add -0 0 -> 0 +-dqadd7735 add -0 -0 -> -0 -- IEEE 854 special case ++dqadd7735 add -0 -0 -> -0 -- IEEE 754 special case + + dqadd7736 add 1 -1 -> 0 + dqadd7737 add -1 -1 -> -2 +Index: Lib/test/decimaltestdata/ddRemainder.decTest +=================================================================== +--- Lib/test/decimaltestdata/ddRemainder.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/ddRemainder.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + precision: 16 + maxExponent: 384 +Index: Lib/test/decimaltestdata/multiply.decTest +=================================================================== +--- Lib/test/decimaltestdata/multiply.decTest (.../tags/r311) (Revision 76056) ++++ Lib/test/decimaltestdata/multiply.decTest (.../branches/release31-maint) (Revision 76056) +@@ -17,7 +17,7 @@ + -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- + -- mfc@uk.ibm.com -- + ------------------------------------------------------------------------ +-version: 2.58 ++version: 2.59 + + extended: 1 + precision: 9 +Index: Lib/test/test_locale.py +=================================================================== +--- Lib/test/test_locale.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_locale.py (.../branches/release31-maint) (Revision 76056) +@@ -8,12 +8,10 @@ + + def get_enUS_locale(): + global enUS_locale +- if sys.platform == 'darwin': +- raise unittest.SkipTest("Locale support on MacOSX is minimal") + if sys.platform.startswith("win"): + tlocs = ("En", "English") + else: +- tlocs = ("en_US.UTF-8", "en_US.US-ASCII", "en_US") ++ tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US.US-ASCII", "en_US") + oldlocale = locale.setlocale(locale.LC_NUMERIC) + for tloc in tlocs: + try: +@@ -309,6 +307,39 @@ + grouping=True, international=True) + + ++class TestCollation(unittest.TestCase): ++ # Test string collation functions ++ ++ def test_strcoll(self): ++ self.assertLess(locale.strcoll('a', 'b'), 0) ++ self.assertEqual(locale.strcoll('a', 'a'), 0) ++ self.assertGreater(locale.strcoll('b', 'a'), 0) ++ ++ def test_strxfrm(self): ++ self.assertLess(locale.strxfrm('a'), locale.strxfrm('b')) ++ ++ ++class TestEnUSCollation(BaseLocalizedTest, TestCollation): ++ # Test string collation functions with a real English locale ++ ++ locale_type = locale.LC_ALL ++ ++ def setUp(self): ++ BaseLocalizedTest.setUp(self) ++ enc = codecs.lookup(locale.getpreferredencoding(False) or 'ascii').name ++ if enc not in ('utf-8', 'iso8859-1', 'cp1252'): ++ raise unittest.SkipTest('encoding not suitable') ++ if enc != 'iso8859-1' and (sys.platform == 'darwin' or ++ sys.platform.startswith('freebsd')): ++ raise unittest.SkipTest('wcscoll/wcsxfrm have known bugs') ++ ++ def test_strcoll_with_diacritic(self): ++ self.assertLess(locale.strcoll('à', 'b'), 0) ++ ++ def test_strxfrm_with_diacritic(self): ++ self.assertLess(locale.strxfrm('à'), locale.strxfrm('b')) ++ ++ + class TestMiscellaneous(unittest.TestCase): + def test_getpreferredencoding(self): + # Invoke getpreferredencoding to make sure it does not cause exceptions. +@@ -317,11 +348,10 @@ + # If encoding non-empty, make sure it is valid + codecs.lookup(enc) + +- if hasattr(locale, "strcoll"): +- def test_strcoll_3303(self): +- # test crasher from bug #3303 +- self.assertRaises(TypeError, locale.strcoll, "a", None) +- self.assertRaises(TypeError, locale.strcoll, b"a", None) ++ def test_strcoll_3303(self): ++ # test crasher from bug #3303 ++ self.assertRaises(TypeError, locale.strcoll, "a", None) ++ self.assertRaises(TypeError, locale.strcoll, b"a", None) + + + def test_main(): +@@ -331,6 +361,7 @@ + TestEnUSNumberFormatting, + TestCNumberFormatting, + TestFrFRNumberFormatting, ++ TestCollation + ] + # SkipTest can't be raised inside unittests, handle it manually instead + try: +@@ -339,7 +370,7 @@ + if verbose: + print("Some tests will be disabled: %s" % e) + else: +- tests += [TestNumberFormatting] ++ tests += [TestNumberFormatting, TestEnUSCollation] + run_unittest(*tests) + + if __name__ == '__main__': +Index: Lib/test/test_pdb.py +=================================================================== +--- Lib/test/test_pdb.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_pdb.py (.../branches/release31-maint) (Revision 76056) +@@ -12,6 +12,49 @@ + from test.test_doctest import _FakeInput + + ++class PdbTestInput(object): ++ """Context manager that makes testing Pdb in doctests easier.""" ++ ++ def __init__(self, input): ++ self.input = input ++ ++ def __enter__(self): ++ self.real_stdin = sys.stdin ++ sys.stdin = _FakeInput(self.input) ++ ++ def __exit__(self, *exc): ++ sys.stdin = self.real_stdin ++ ++ ++def test_pdb_displayhook(): ++ """This tests the custom displayhook for pdb. ++ ++ >>> def test_function(foo, bar): ++ ... import pdb; pdb.Pdb().set_trace() ++ ... pass ++ ++ >>> with PdbTestInput([ ++ ... 'foo', ++ ... 'bar', ++ ... 'for i in range(5): print(i)', ++ ... 'continue', ++ ... ]): ++ ... test_function(1, None) ++ > (3)test_function() ++ -> pass ++ (Pdb) foo ++ 1 ++ (Pdb) bar ++ (Pdb) for i in range(5): print(i) ++ 0 ++ 1 ++ 2 ++ 3 ++ 4 ++ (Pdb) continue ++ """ ++ ++ + def test_pdb_skip_modules(): + """This illustrates the simple case of module skipping. + +@@ -19,16 +62,12 @@ + ... import string + ... import pdb; pdb.Pdb(skip=['stri*']).set_trace() + ... string.capwords('FOO') +- >>> real_stdin = sys.stdin +- >>> sys.stdin = _FakeInput([ +- ... 'step', +- ... 'continue', +- ... ]) + +- >>> try: ++ >>> with PdbTestInput([ ++ ... 'step', ++ ... 'continue', ++ ... ]): + ... skip_module() +- ... finally: +- ... sys.stdin = real_stdin + > (4)skip_module() + -> string.capwords('FOO') + (Pdb) step +@@ -36,7 +75,7 @@ + > (4)skip_module()->None + -> string.capwords('FOO') + (Pdb) continue +-""" ++ """ + + + # Module for testing skipping of module that makes a callback +@@ -50,22 +89,19 @@ + >>> def skip_module(): + ... def callback(): + ... return None +- ... import pdb;pdb.Pdb(skip=['module_to_skip*']).set_trace() ++ ... import pdb; pdb.Pdb(skip=['module_to_skip*']).set_trace() + ... mod.foo_pony(callback) +- >>> real_stdin = sys.stdin +- >>> sys.stdin = _FakeInput([ +- ... 'step', +- ... 'step', +- ... 'step', +- ... 'step', +- ... 'step', +- ... 'continue', +- ... ]) + +- >>> try: ++ >>> with PdbTestInput([ ++ ... 'step', ++ ... 'step', ++ ... 'step', ++ ... 'step', ++ ... 'step', ++ ... 'continue', ++ ... ]): + ... skip_module() +- ... finally: +- ... sys.stdin = real_stdin ++ ... pass # provides something to "step" to + > (5)skip_module() + -> mod.foo_pony(callback) + (Pdb) step +@@ -84,10 +120,10 @@ + > (5)skip_module()->None + -> mod.foo_pony(callback) + (Pdb) step +- > (4)() +- -> sys.stdin = real_stdin ++ > (10)() ++ -> pass # provides something to "step" to + (Pdb) continue +-""" ++ """ + + + def test_main(): +Index: Lib/test/test_signal.py +=================================================================== +--- Lib/test/test_signal.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_signal.py (.../branches/release31-maint) (Revision 76056) +@@ -360,9 +360,14 @@ + signal.signal(signal.SIGVTALRM, self.sig_vtalrm) + signal.setitimer(self.itimer, 0.3, 0.2) + +- for i in range(100000000): ++ start_time = time.time() ++ while time.time() - start_time < 5.0: ++ # use up some virtual time by doing real work ++ _ = pow(12345, 67890, 10000019) + if signal.getitimer(self.itimer) == (0.0, 0.0): + break # sig_vtalrm handler stopped this itimer ++ else: ++ self.fail('timeout waiting for sig_vtalrm signal') + + # virtual itimer should be (0.0, 0.0) now + self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) +@@ -374,9 +379,14 @@ + signal.signal(signal.SIGPROF, self.sig_prof) + signal.setitimer(self.itimer, 0.2, 0.2) + +- for i in range(100000000): ++ start_time = time.time() ++ while time.time() - start_time < 5.0: ++ # do some work ++ _ = pow(12345, 67890, 10000019) + if signal.getitimer(self.itimer) == (0.0, 0.0): + break # sig_prof handler stopped this itimer ++ else: ++ self.fail('timeout waiting for sig_prof signal') + + # profiling itimer should be (0.0, 0.0) now + self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0)) +Index: Lib/test/test_marshal.py +=================================================================== +--- Lib/test/test_marshal.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_marshal.py (.../branches/release31-maint) (Revision 76056) +@@ -212,7 +212,12 @@ + testString = 'abc' * size + marshal.dumps(testString) + ++ def test_invalid_longs(self): ++ # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs ++ invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00' ++ self.assertRaises(ValueError, marshal.loads, invalid_string) + ++ + def test_main(): + support.run_unittest(IntTestCase, + FloatTestCase, +Index: Lib/test/test_bz2.py +=================================================================== +--- Lib/test/test_bz2.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_bz2.py (.../branches/release31-maint) (Revision 76056) +@@ -7,6 +7,7 @@ + import os + import subprocess + import sys ++import threading + + # Skip tests if the bz2 module doesn't exist. + bz2 = support.import_module('bz2') +@@ -282,7 +283,24 @@ + else: + self.fail("1/0 didn't raise an exception") + ++ def testThreading(self): ++ # Using a BZ2File from several threads doesn't deadlock (issue #7205). ++ data = b"1" * 2**20 ++ nthreads = 10 ++ f = bz2.BZ2File(self.filename, 'wb') ++ try: ++ def comp(): ++ for i in range(5): ++ f.write(data) ++ threads = [threading.Thread(target=comp) for i in range(nthreads)] ++ for t in threads: ++ t.start() ++ for t in threads: ++ t.join() ++ finally: ++ f.close() + ++ + class BZ2CompressorTest(BaseTest): + def testCompress(self): + # "Test BZ2Compressor.compress()/flush()" +Index: Lib/test/test_fnmatch.py +=================================================================== +--- Lib/test/test_fnmatch.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_fnmatch.py (.../branches/release31-maint) (Revision 76056) +@@ -32,11 +32,18 @@ + check('a', 'b', 0) + + # these test that '\' is handled correctly in character sets; +- # see SF bug #??? ++ # see SF bug #409651 + check('\\', r'[\]') + check('a', r'[!\]') + check('\\', r'[!\]', 0) + ++ # test that filenames with newlines in them are handled correctly. ++ # http://bugs.python.org/issue6665 ++ check('foo\nbar', 'foo*') ++ check('foo\nbar\n', 'foo*') ++ check('\nfoo', 'foo*', False) ++ check('\n', '*') ++ + def test_mix_bytes_str(self): + self.assertRaises(TypeError, fnmatch, 'test', b'*') + self.assertRaises(TypeError, fnmatch, b'test', '*') +@@ -46,7 +53,9 @@ + def test_bytes(self): + self.check_match(b'test', b'te*') + self.check_match(b'test\xff', b'te*\xff') ++ self.check_match(b'foo\nbar', b'foo*') + ++ + def test_main(): + support.run_unittest(FnmatchTestCase) + +Index: Lib/test/test_normalization.py +=================================================================== +--- Lib/test/test_normalization.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_normalization.py (.../branches/release31-maint) (Revision 76056) +@@ -40,6 +40,11 @@ + class NormalizationTest(unittest.TestCase): + def test_main(self): + part1_data = {} ++ # Hit the exception early ++ try: ++ open_urlresource(TESTDATAURL, encoding="utf-8") ++ except IOError: ++ self.skipTest("Could not retrieve " + TESTDATAURL) + for line in open_urlresource(TESTDATAURL, encoding="utf-8"): + if '#' in line: + line = line.split('#')[0] +@@ -95,8 +100,6 @@ + + + def test_main(): +- # Hit the exception early +- open_urlresource(TESTDATAURL) + run_unittest(NormalizationTest) + + if __name__ == "__main__": +Index: Lib/test/test_decimal.py +=================================================================== +--- Lib/test/test_decimal.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_decimal.py (.../branches/release31-maint) (Revision 76056) +@@ -63,6 +63,13 @@ + + skip_expected = not os.path.isdir(directory) + ++# list of individual .decTest test ids that correspond to tests that ++# we're skipping for one reason or another. ++skipped_test_ids = [ ++ 'scbx164', # skipping apparently implementation-specific scaleb ++ 'scbx165', # tests, pending clarification of scaleb rules. ++] ++ + # Make sure it actually raises errors when not expected and caught in flags + # Slower, since it runs some things several times. + EXTENDEDERRORTEST = False +@@ -262,6 +269,10 @@ + val = val.replace("'", '').replace('"', '') + val = val.replace('SingleQuote', "'").replace('DoubleQuote', '"') + return val ++ ++ if id in skipped_test_ids: ++ return ++ + fname = nameAdapter.get(funct, funct) + if fname == 'rescale': + return +@@ -749,6 +760,9 @@ + (',%', '123.456789', '12,345.6789%'), + (',e', '123456', '1.23456e+5'), + (',E', '123456', '1.23456E+5'), ++ ++ # issue 6850 ++ ('a=-7.0', '0.12345', 'aaaa0.1'), + ] + for fmt, d, result in test_values: + self.assertEqual(format(Decimal(d), fmt), result) +@@ -1515,7 +1529,54 @@ + self.assertEqual(str(Decimal(0).sqrt()), + str(c.sqrt(Decimal(0)))) + ++ def test_conversions_from_int(self): ++ # Check that methods taking a second Decimal argument will ++ # always accept an integer in place of a Decimal. ++ self.assertEqual(Decimal(4).compare(3), ++ Decimal(4).compare(Decimal(3))) ++ self.assertEqual(Decimal(4).compare_signal(3), ++ Decimal(4).compare_signal(Decimal(3))) ++ self.assertEqual(Decimal(4).compare_total(3), ++ Decimal(4).compare_total(Decimal(3))) ++ self.assertEqual(Decimal(4).compare_total_mag(3), ++ Decimal(4).compare_total_mag(Decimal(3))) ++ self.assertEqual(Decimal(10101).logical_and(1001), ++ Decimal(10101).logical_and(Decimal(1001))) ++ self.assertEqual(Decimal(10101).logical_or(1001), ++ Decimal(10101).logical_or(Decimal(1001))) ++ self.assertEqual(Decimal(10101).logical_xor(1001), ++ Decimal(10101).logical_xor(Decimal(1001))) ++ self.assertEqual(Decimal(567).max(123), ++ Decimal(567).max(Decimal(123))) ++ self.assertEqual(Decimal(567).max_mag(123), ++ Decimal(567).max_mag(Decimal(123))) ++ self.assertEqual(Decimal(567).min(123), ++ Decimal(567).min(Decimal(123))) ++ self.assertEqual(Decimal(567).min_mag(123), ++ Decimal(567).min_mag(Decimal(123))) ++ self.assertEqual(Decimal(567).next_toward(123), ++ Decimal(567).next_toward(Decimal(123))) ++ self.assertEqual(Decimal(1234).quantize(100), ++ Decimal(1234).quantize(Decimal(100))) ++ self.assertEqual(Decimal(768).remainder_near(1234), ++ Decimal(768).remainder_near(Decimal(1234))) ++ self.assertEqual(Decimal(123).rotate(1), ++ Decimal(123).rotate(Decimal(1))) ++ self.assertEqual(Decimal(1234).same_quantum(1000), ++ Decimal(1234).same_quantum(Decimal(1000))) ++ self.assertEqual(Decimal('9.123').scaleb(-100), ++ Decimal('9.123').scaleb(Decimal(-100))) ++ self.assertEqual(Decimal(456).shift(-1), ++ Decimal(456).shift(Decimal(-1))) + ++ self.assertEqual(Decimal(-12).fma(Decimal(45), 67), ++ Decimal(-12).fma(Decimal(45), Decimal(67))) ++ self.assertEqual(Decimal(-12).fma(45, 67), ++ Decimal(-12).fma(Decimal(45), Decimal(67))) ++ self.assertEqual(Decimal(-12).fma(45, Decimal(67)), ++ Decimal(-12).fma(Decimal(45), Decimal(67))) ++ ++ + class DecimalPythonAPItests(unittest.TestCase): + + def test_abc(self): +@@ -1540,6 +1601,11 @@ + r = d.to_integral(ROUND_DOWN) + self.assertEqual(Decimal(int(d)), r) + ++ self.assertRaises(ValueError, int, Decimal('-nan')) ++ self.assertRaises(ValueError, int, Decimal('snan')) ++ self.assertRaises(OverflowError, int, Decimal('inf')) ++ self.assertRaises(OverflowError, int, Decimal('-inf')) ++ + def test_trunc(self): + for x in range(-250, 250): + s = '%0.2f' % (x / 100.0) +Index: Lib/test/test_platform.py +=================================================================== +--- Lib/test/test_platform.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_platform.py (.../branches/release31-maint) (Revision 76056) +@@ -149,7 +149,13 @@ + break + fd.close() + self.assertFalse(real_ver is None) +- self.assertEquals(res[0], real_ver) ++ result_list = res[0].split('.') ++ expect_list = real_ver.split('.') ++ len_diff = len(result_list) - len(expect_list) ++ # On Snow Leopard, sw_vers reports 10.6.0 as 10.6 ++ if len_diff > 0: ++ expect_list.extend(['0'] * len_diff) ++ self.assertEquals(result_list, expect_list) + + # res[1] claims to contain + # (version, dev_stage, non_release_version) +Index: Lib/test/test_bytes.py +=================================================================== +--- Lib/test/test_bytes.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_bytes.py (.../branches/release31-maint) (Revision 76056) +@@ -452,8 +452,9 @@ + + def test_maketrans(self): + transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' +- + self.assertEqual(self.type2test.maketrans(b'abc', b'xyz'), transtable) ++ transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374xyz' ++ self.assertEqual(self.type2test.maketrans(b'\375\376\377', b'xyz'), transtable) + self.assertRaises(ValueError, self.type2test.maketrans, b'abc', b'xyzq') + self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def') + +@@ -716,6 +717,8 @@ + self.assertEqual(b.pop(-2), ord('r')) + self.assertRaises(IndexError, lambda: b.pop(10)) + self.assertRaises(OverflowError, lambda: bytearray().pop()) ++ # test for issue #6846 ++ self.assertEqual(bytearray(b'\xff').pop(), 0xff) + + def test_nosort(self): + self.assertRaises(AttributeError, lambda: bytearray().sort()) +@@ -930,7 +933,7 @@ + self.assertRaises(BytesWarning, operator.eq, bytearray(b''), '') + self.assertRaises(BytesWarning, operator.ne, bytearray(b''), '') + else: +- # raise test.support.TestSkipped("BytesWarning is needed for this test: use -bb option") ++ # self.skipTest("BytesWarning is needed for this test: use -bb option") + pass + + # Optimizations: +@@ -1070,13 +1073,10 @@ + + + def test_main(): +- test.support.run_unittest(BytesTest) +- test.support.run_unittest(ByteArrayTest) +- test.support.run_unittest(AssortedBytesTest) +- test.support.run_unittest(BytesAsStringTest) +- test.support.run_unittest(ByteArrayAsStringTest) +- test.support.run_unittest(ByteArraySubclassTest) +- test.support.run_unittest(BytearrayPEP3137Test) ++ test.support.run_unittest( ++ BytesTest, AssortedBytesTest, BytesAsStringTest, ++ ByteArrayTest, ByteArrayAsStringTest, ByteArraySubclassTest, ++ BytearrayPEP3137Test) + + if __name__ == "__main__": + test_main() +Index: Lib/test/test_curses.py +=================================================================== +--- Lib/test/test_curses.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_curses.py (.../branches/release31-maint) (Revision 76056) +@@ -259,6 +259,10 @@ + if curses.LINES != lines - 1 or curses.COLS != cols + 1: + raise RuntimeError("Expected resizeterm to update LINES and COLS") + ++def test_issue6243(stdscr): ++ curses.ungetch(1025) ++ stdscr.getkey() ++ + def main(stdscr): + curses.savetty() + try: +@@ -266,10 +270,13 @@ + window_funcs(stdscr) + test_userptr_without_set(stdscr) + test_resize_term(stdscr) ++ test_issue6243(stdscr) + finally: + curses.resetty() + + def test_main(): ++ if not sys.stdout.isatty(): ++ raise unittest.SkipTest("sys.stdout is not a tty") + # testing setupterm() inside initscr/endwin + # causes terminal breakage + curses.setupterm(fd=sys.stdout.fileno()) +Index: Lib/test/test___all__.py +=================================================================== +--- Lib/test/test___all__.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test___all__.py (.../branches/release31-maint) (Revision 76056) +@@ -1,9 +1,17 @@ + import unittest +-from test.support import run_unittest ++from test import support ++import os + import sys + import warnings + + ++class NoAll(RuntimeError): ++ pass ++ ++class FailedImport(RuntimeError): ++ pass ++ ++ + class AllTest(unittest.TestCase): + + def check_all(self, modname): +@@ -13,152 +21,97 @@ + DeprecationWarning) + try: + exec("import %s" % modname, names) +- except ImportError: ++ except: + # Silent fail here seems the best route since some modules +- # may not be available in all environments. +- return +- self.assertTrue(hasattr(sys.modules[modname], "__all__"), +- "%s has no __all__ attribute" % modname) ++ # may not be available or not initialize properly in all ++ # environments. ++ raise FailedImport(modname) ++ if not hasattr(sys.modules[modname], "__all__"): ++ raise NoAll(modname) + names = {} +- exec("from %s import *" % modname, names) ++ try: ++ exec("from %s import *" % modname, names) ++ except Exception as e: ++ # Include the module name in the exception string ++ self.fail("__all__ failure in {}: {}: {}".format( ++ modname, e.__class__.__name__, e)) + if "__builtins__" in names: + del names["__builtins__"] + keys = set(names) + all = set(sys.modules[modname].__all__) + self.assertEqual(keys, all) + ++ def walk_modules(self, basedir, modpath): ++ for fn in sorted(os.listdir(basedir)): ++ path = os.path.join(basedir, fn) ++ if os.path.isdir(path): ++ pkg_init = os.path.join(path, '__init__.py') ++ if os.path.exists(pkg_init): ++ yield pkg_init, modpath + fn ++ for p, m in self.walk_modules(path, modpath + fn + "."): ++ yield p, m ++ continue ++ if not fn.endswith('.py') or fn == '__init__.py': ++ continue ++ yield path, modpath + fn[:-3] ++ + def test_all(self): ++ # Blacklisted modules and packages ++ blacklist = set([ ++ # Will raise a SyntaxError when compiling the exec statement ++ '__future__', ++ ]) ++ + if not sys.platform.startswith('java'): + # In case _socket fails to build, make this test fail more gracefully + # than an AttributeError somewhere deep in CGIHTTPServer. + import _socket + +- self.check_all("http.server") +- self.check_all("configparser") +- self.check_all("http.cookies") +- self.check_all("queue") +- self.check_all("socketserver") +- self.check_all("aifc") +- self.check_all("base64") +- self.check_all("bdb") +- self.check_all("binhex") +- self.check_all("calendar") +- self.check_all("collections") +- self.check_all("cgi") +- self.check_all("cmd") +- self.check_all("code") +- self.check_all("codecs") +- self.check_all("codeop") +- self.check_all("colorsys") +- self.check_all("compileall") +- self.check_all("copy") +- self.check_all("copyreg") +- self.check_all("csv") +- self.check_all("dbm.bsd") +- self.check_all("decimal") +- self.check_all("difflib") +- self.check_all("dircache") +- self.check_all("dis") +- self.check_all("doctest") +- self.check_all("_dummy_thread") +- self.check_all("dummy_threading") +- self.check_all("filecmp") +- self.check_all("fileinput") +- self.check_all("fnmatch") +- self.check_all("fpformat") +- self.check_all("ftplib") +- self.check_all("getopt") +- self.check_all("getpass") +- self.check_all("gettext") +- self.check_all("glob") +- self.check_all("gzip") +- self.check_all("heapq") +- self.check_all("http.client") +- self.check_all("ihooks") +- self.check_all("io") +- self.check_all("_pyio") +- self.check_all("imaplib") +- self.check_all("imghdr") +- self.check_all("keyword") +- self.check_all("linecache") +- self.check_all("locale") +- self.check_all("macpath") +- self.check_all("macurl2path") +- self.check_all("mailbox") +- self.check_all("mailcap") +- self.check_all("mhlib") +- self.check_all("mimetypes") +- self.check_all("multifile") +- self.check_all("netrc") +- self.check_all("nntplib") +- self.check_all("ntpath") +- self.check_all("opcode") +- self.check_all("optparse") +- self.check_all("os") +- self.check_all("os2emxpath") +- self.check_all("pdb") +- self.check_all("pickle") +- self.check_all("pickletools") +- self.check_all("pipes") +- self.check_all("poplib") +- self.check_all("posixpath") +- self.check_all("pprint") +- self.check_all("profile") +- self.check_all("pstats") +- self.check_all("pty") +- self.check_all("py_compile") +- self.check_all("pyclbr") +- self.check_all("quopri") +- self.check_all("random") +- self.check_all("re") +- self.check_all("reprlib") +- self.check_all("rlcompleter") +- self.check_all("urllib.robotparser") +- self.check_all("sched") +- self.check_all("shelve") +- self.check_all("shlex") +- self.check_all("shutil") +- self.check_all("smtpd") +- self.check_all("smtplib") +- self.check_all("sndhdr") +- self.check_all("socket") +- self.check_all("_strptime") +- self.check_all("symtable") +- self.check_all("tabnanny") +- self.check_all("tarfile") +- self.check_all("telnetlib") +- self.check_all("tempfile") +- self.check_all("test.support") +- self.check_all("textwrap") +- self.check_all("threading") +- self.check_all("timeit") +- self.check_all("tokenize") +- self.check_all("traceback") +- self.check_all("tty") +- self.check_all("unittest") +- self.check_all("uu") +- self.check_all("warnings") +- self.check_all("wave") +- self.check_all("weakref") +- self.check_all("webbrowser") +- self.check_all("xdrlib") +- self.check_all("zipfile") +- + # rlcompleter needs special consideration; it import readline which + # initializes GNU readline which calls setlocale(LC_CTYPE, "")... :-( + try: +- self.check_all("rlcompleter") +- finally: ++ import rlcompleter ++ import locale ++ except ImportError: ++ pass ++ else: ++ locale.setlocale(locale.LC_CTYPE, 'C') ++ ++ ignored = [] ++ failed_imports = [] ++ lib_dir = os.path.dirname(os.path.dirname(__file__)) ++ for path, modname in self.walk_modules(lib_dir, ""): ++ m = modname ++ blacklisted = False ++ while m: ++ if m in blacklist: ++ blacklisted = True ++ break ++ m = m.rpartition('.')[0] ++ if blacklisted: ++ continue ++ if support.verbose: ++ print(modname) + try: +- import locale +- except ImportError: +- pass +- else: +- locale.setlocale(locale.LC_CTYPE, 'C') ++ # This heuristic speeds up the process by removing, de facto, ++ # most test modules (and avoiding the auto-executing ones). ++ with open(path, "rb") as f: ++ if b"__all__" not in f.read(): ++ raise NoAll(modname) ++ self.check_all(modname) ++ except NoAll: ++ ignored.append(modname) ++ except FailedImport: ++ failed_imports.append(modname) + ++ if support.verbose: ++ print('Following modules have no __all__ and have been ignored:', ++ ignored) ++ print('Following modules failed to be imported:', failed_imports) + ++ + def test_main(): +- run_unittest(AllTest) ++ support.run_unittest(AllTest) + + if __name__ == "__main__": + test_main() +Index: Lib/test/test_threading_local.py +=================================================================== +--- Lib/test/test_threading_local.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_threading_local.py (.../branches/release31-maint) (Revision 76056) +@@ -67,7 +67,46 @@ + for t in threads: + t.join() + ++ def test_derived_cycle_dealloc(self): ++ # http://bugs.python.org/issue6990 ++ class Local(threading.local): ++ pass ++ locals = None ++ passed = False ++ e1 = threading.Event() ++ e2 = threading.Event() + ++ def f(): ++ nonlocal passed ++ # 1) Involve Local in a cycle ++ cycle = [Local()] ++ cycle.append(cycle) ++ cycle[0].foo = 'bar' ++ ++ # 2) GC the cycle (triggers threadmodule.c::local_clear ++ # before local_dealloc) ++ del cycle ++ gc.collect() ++ e1.set() ++ e2.wait() ++ ++ # 4) New Locals should be empty ++ passed = all(not hasattr(local, 'foo') for local in locals) ++ ++ t = threading.Thread(target=f) ++ t.start() ++ e1.wait() ++ ++ # 3) New Locals should recycle the original's address. Creating ++ # them in the thread overwrites the thread state and avoids the ++ # bug ++ locals = [Local() for i in range(10)] ++ e2.set() ++ t.join() ++ ++ self.assertTrue(passed) ++ ++ + def test_main(): + suite = unittest.TestSuite() + suite.addTest(DocTestSuite('_threading_local')) +Index: Lib/test/test_mailbox.py +=================================================================== +--- Lib/test/test_mailbox.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_mailbox.py (.../branches/release31-maint) (Revision 76056) +@@ -673,6 +673,9 @@ + self.assertEqual(self._box._lookup(key0), os.path.join('new', key0)) + os.remove(os.path.join(self._path, 'new', key0)) + self.assertEqual(self._box._toc, {key0: os.path.join('new', key0)}) ++ # Be sure that the TOC is read back from disk (see issue #6896 ++ # about bad mtime behaviour on some systems). ++ self._box.flush() + self.assertRaises(KeyError, lambda: self._box._lookup(key0)) + self.assertEqual(self._box._toc, {}) + +Index: Lib/test/test_urllib2.py +=================================================================== +--- Lib/test/test_urllib2.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_urllib2.py (.../branches/release31-maint) (Revision 76056) +@@ -947,6 +947,22 @@ + self.assertEqual([(handlers[0], "http_open")], + [tup[0:2] for tup in o.calls]) + ++ def test_proxy_no_proxy(self): ++ os.environ['no_proxy'] = 'python.org' ++ o = OpenerDirector() ++ ph = urllib.request.ProxyHandler(dict(http="proxy.example.com")) ++ o.add_handler(ph) ++ req = Request("http://www.perl.org/") ++ self.assertEqual(req.get_host(), "www.perl.org") ++ r = o.open(req) ++ self.assertEqual(req.get_host(), "proxy.example.com") ++ req = Request("http://www.python.org") ++ self.assertEqual(req.get_host(), "www.python.org") ++ r = o.open(req) ++ self.assertEqual(req.get_host(), "www.python.org") ++ del os.environ['no_proxy'] ++ ++ + def test_proxy_https(self): + o = OpenerDirector() + ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128")) +Index: Lib/test/test_augassign.py +=================================================================== +--- Lib/test/test_augassign.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_augassign.py (.../branches/release31-maint) (Revision 76056) +@@ -19,6 +19,9 @@ + x /= 2 + self.assertEquals(x, 3.0) + ++ def test_with_unpacking(self): ++ self.assertRaises(SyntaxError, compile, "x, b += 3", "", "exec") ++ + def testInList(self): + x = [2] + x[0] += 1 +Index: Lib/test/test_threading.py +=================================================================== +--- Lib/test/test_threading.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_threading.py (.../branches/release31-maint) (Revision 76056) +@@ -286,7 +286,31 @@ + self.assertFalse(rc == 2, "interpreted was blocked") + self.assertTrue(rc == 0, "Unexpected error") + ++ def test_join_nondaemon_on_shutdown(self): ++ # Issue 1722344 ++ # Raising SystemExit skipped threading._shutdown ++ import subprocess ++ p = subprocess.Popen([sys.executable, "-c", """if 1: ++ import threading ++ from time import sleep + ++ def child(): ++ sleep(1) ++ # As a non-daemon thread we SHOULD wake up and nothing ++ # should be torn down yet ++ print("Woke up, sleep function is:", sleep) ++ ++ threading.Thread(target=child).start() ++ raise SystemExit ++ """], ++ stdout=subprocess.PIPE, ++ stderr=subprocess.PIPE) ++ stdout, stderr = p.communicate() ++ self.assertEqual(stdout.strip(), ++ b"Woke up, sleep function is: ") ++ stderr = re.sub(br"^\[\d+ refs\]", b"", stderr, re.MULTILINE).strip() ++ self.assertEqual(stderr, b"") ++ + def test_enumerate_after_join(self): + # Try hard to trigger #1703448: a thread is still returned in + # threading.enumerate() after it has been join()ed. +@@ -414,8 +438,8 @@ + # Skip platforms with known problems forking from a worker thread. + # See http://bugs.python.org/issue3863. + if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'): +- print >>sys.stderr, ('Skipping test_3_join_in_forked_from_thread' +- ' due to known OS bugs on'), sys.platform ++ print('Skipping test_3_join_in_forked_from_thread' ++ ' due to known OS bugs on', sys.platform, file=sys.stderr) + return + script = """if 1: + main_thread = threading.current_thread() +Index: Lib/test/test_multibytecodec_support.py +=================================================================== +--- Lib/test/test_multibytecodec_support.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_multibytecodec_support.py (.../branches/release31-maint) (Revision 76056) +@@ -279,7 +279,7 @@ + try: + self.open_mapping_file() # test it to report the error early + except IOError: +- raise support.TestSkipped("Could not retrieve "+self.mapfileurl) ++ self.skipTest("Could not retrieve "+self.mapfileurl) + + def open_mapping_file(self): + return support.open_urlresource(self.mapfileurl) +Index: Lib/test/test_funcattrs.py +=================================================================== +--- Lib/test/test_funcattrs.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_funcattrs.py (.../branches/release31-maint) (Revision 76056) +@@ -56,9 +56,30 @@ + self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily + + def test___globals__(self): +- self.assertEqual(self.b.__globals__, globals()) +- self.cannot_set_attr(self.b, '__globals__', 2, (AttributeError, TypeError)) ++ self.assertIs(self.b.__globals__, globals()) ++ self.cannot_set_attr(self.b, '__globals__', 2, ++ (AttributeError, TypeError)) + ++ def test___closure__(self): ++ a = 12 ++ def f(): print(a) ++ c = f.__closure__ ++ self.assertTrue(isinstance(c, tuple)) ++ self.assertEqual(len(c), 1) ++ # don't have a type object handy ++ self.assertEqual(c[0].__class__.__name__, "cell") ++ self.cannot_set_attr(f, "__closure__", c, AttributeError) ++ ++ def test_empty_cell(self): ++ def f(): print(a) ++ try: ++ f.__closure__[0].cell_contents ++ except ValueError: ++ pass ++ else: ++ self.fail("shouldn't be able to read an empty cell") ++ a = 12 ++ + def test___name__(self): + self.assertEqual(self.b.__name__, 'b') + self.b.__name__ = 'c' +@@ -90,16 +111,20 @@ + self.assertEqual(c.__code__, d.__code__) + self.assertEqual(c(), 7) + # self.assertEqual(d(), 7) +- try: b.__code__ = c.__code__ +- except ValueError: pass +- else: self.fail( +- "__code__ with different numbers of free vars should not be " +- "possible") +- try: e.__code__ = d.__code__ +- except ValueError: pass +- else: self.fail( +- "__code__ with different numbers of free vars should not be " +- "possible") ++ try: ++ b.__code__ = c.__code__ ++ except ValueError: ++ pass ++ else: ++ self.fail("__code__ with different numbers of free vars should " ++ "not be possible") ++ try: ++ e.__code__ = d.__code__ ++ except ValueError: ++ pass ++ else: ++ self.fail("__code__ with different numbers of free vars should " ++ "not be possible") + + def test_blank_func_defaults(self): + self.assertEqual(self.b.__defaults__, None) +@@ -120,14 +145,17 @@ + self.assertEqual(first_func(3, 5), 8) + del second_func.__defaults__ + self.assertEqual(second_func.__defaults__, None) +- try: second_func() +- except TypeError: pass +- else: self.fail( +- "func_defaults does not update; deleting it does not remove " +- "requirement") ++ try: ++ second_func() ++ except TypeError: ++ pass ++ else: ++ self.fail("__defaults__ does not update; deleting it does not " ++ "remove requirement") + +-class ImplicitReferencesTest(FuncAttrsTest): + ++class InstancemethodAttrTest(FuncAttrsTest): ++ + def test___class__(self): + self.assertEqual(self.fi.a.__self__.__class__, self.F) + self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError) +@@ -146,32 +174,46 @@ + self.fi.id = types.MethodType(id, self.fi) + self.assertEqual(self.fi.id(), id(self.fi)) + # Test usage +- try: self.fi.id.unknown_attr +- except AttributeError: pass +- else: self.fail("using unknown attributes should raise AttributeError") ++ try: ++ self.fi.id.unknown_attr ++ except AttributeError: ++ pass ++ else: ++ self.fail("using unknown attributes should raise AttributeError") + # Test assignment and deletion + self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError) + ++ + class ArbitraryFunctionAttrTest(FuncAttrsTest): + def test_set_attr(self): + self.b.known_attr = 7 + self.assertEqual(self.b.known_attr, 7) +- try: self.fi.a.known_attr = 7 +- except AttributeError: pass +- else: self.fail("setting attributes on methods should raise error") ++ try: ++ self.fi.a.known_attr = 7 ++ except AttributeError: ++ pass ++ else: ++ self.fail("setting attributes on methods should raise error") + + def test_delete_unknown_attr(self): +- try: del self.b.unknown_attr +- except AttributeError: pass +- else: self.fail("deleting unknown attribute should raise TypeError") ++ try: ++ del self.b.unknown_attr ++ except AttributeError: ++ pass ++ else: ++ self.fail("deleting unknown attribute should raise TypeError") + + def test_unset_attr(self): + for func in [self.b, self.fi.a]: +- try: func.non_existent_attr +- except AttributeError: pass +- else: self.fail("using unknown attributes should raise " +- "AttributeError") ++ try: ++ func.non_existent_attr ++ except AttributeError: ++ pass ++ else: ++ self.fail("using unknown attributes should raise " ++ "AttributeError") + ++ + class FunctionDictsTest(FuncAttrsTest): + def test_setting_dict_to_invalid(self): + self.cannot_set_attr(self.b, '__dict__', None, TypeError) +@@ -183,11 +225,11 @@ + d = {'known_attr': 7} + self.b.__dict__ = d + # Test assignment +- self.assertEqual(d, self.b.__dict__) ++ self.assertIs(d, self.b.__dict__) + # ... and on all the different ways of referencing the method's func + self.F.a.__dict__ = d +- self.assertEqual(d, self.fi.a.__func__.__dict__) +- self.assertEqual(d, self.fi.a.__dict__) ++ self.assertIs(d, self.fi.a.__func__.__dict__) ++ self.assertIs(d, self.fi.a.__dict__) + # Test value + self.assertEqual(self.b.known_attr, 7) + self.assertEqual(self.b.__dict__['known_attr'], 7) +@@ -196,9 +238,12 @@ + self.assertEqual(self.fi.a.known_attr, 7) + + def test_delete___dict__(self): +- try: del self.b.__dict__ +- except TypeError: pass +- else: self.fail("deleting function dictionary should raise TypeError") ++ try: ++ del self.b.__dict__ ++ except TypeError: ++ pass ++ else: ++ self.fail("deleting function dictionary should raise TypeError") + + def test_unassigned_dict(self): + self.assertEqual(self.b.__dict__, {}) +@@ -209,6 +254,7 @@ + d[self.b] = value + self.assertEqual(d[self.b], value) + ++ + class FunctionDocstringTest(FuncAttrsTest): + def test_set_docstring_attr(self): + self.assertEqual(self.b.__doc__, None) +@@ -224,6 +270,7 @@ + del self.b.__doc__ + self.assertEqual(self.b.__doc__, None) + ++ + def cell(value): + """Create a cell containing the given value.""" + def f(): +@@ -242,6 +289,7 @@ + a = 1729 + return f.__closure__[0] + ++ + class CellTest(unittest.TestCase): + def test_comparison(self): + # These tests are here simply to exercise the comparison code; +@@ -254,6 +302,7 @@ + self.assertTrue(cell(-36) == cell(-36.0)) + self.assertTrue(cell(True) > empty_cell()) + ++ + class StaticMethodAttrsTest(unittest.TestCase): + def test_func_attribute(self): + def f(): +@@ -267,7 +316,7 @@ + + + def test_main(): +- support.run_unittest(FunctionPropertiesTest, ImplicitReferencesTest, ++ support.run_unittest(FunctionPropertiesTest, InstancemethodAttrTest, + ArbitraryFunctionAttrTest, FunctionDictsTest, + FunctionDocstringTest, CellTest, + StaticMethodAttrsTest) +Index: Lib/test/support.py +=================================================================== +--- Lib/test/support.py (.../tags/r311) (Revision 76056) ++++ Lib/test/support.py (.../branches/release31-maint) (Revision 76056) +@@ -455,10 +455,17 @@ + return open(fn, *args, **kw) + + print('\tfetching %s ...' % url, file=get_original_stdout()) +- fn, _ = urllib.request.urlretrieve(url, filename) +- return open(fn, *args, **kw) ++ f = urllib.request.urlopen(url, timeout=15) ++ try: ++ with open(filename, "wb") as out: ++ s = f.read() ++ while s: ++ out.write(s) ++ s = f.read() ++ finally: ++ f.close() ++ return open(filename, *args, **kw) + +- + class WarningsRecorder(object): + """Convenience wrapper for the warnings list returned on + entry to the warnings.catch_warnings() context manager. +@@ -857,7 +864,8 @@ + elif len(result.failures) == 1 and not result.errors: + err = result.failures[0][1] + else: +- err = "errors occurred; run in verbose mode for details" ++ err = "multiple errors occurred" ++ if not verbose: err += "; run in verbose mode for details" + raise TestFailed(err) + + +Index: Lib/test/test_sys.py +=================================================================== +--- Lib/test/test_sys.py (.../tags/r311) (Revision 76056) ++++ Lib/test/test_sys.py (.../branches/release31-maint) (Revision 76056) +@@ -5,6 +5,11 @@ + import subprocess + import textwrap + ++# count the number of test runs, used to create unique ++# strings to intern in test_intern() ++numruns = 0 ++ ++ + class SysModuleTest(unittest.TestCase): + + def setUp(self): +@@ -379,8 +384,10 @@ + self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) + + def test_intern(self): ++ global numruns ++ numruns += 1 + self.assertRaises(TypeError, sys.intern) +- s = "never interned before" ++ s = "never interned before" + str(numruns) + self.assertTrue(sys.intern(s) is s) + s2 = s.swapcase().swapcase() + self.assertTrue(sys.intern(s2) is s) +Index: Lib/uu.py +=================================================================== +--- Lib/uu.py (.../tags/r311) (Revision 76056) ++++ Lib/uu.py (.../branches/release31-maint) (Revision 76056) +@@ -80,7 +80,7 @@ + out_file.write(b' \nend\n') + + +-def decode(in_file, out_file=None, mode=None, quiet=0): ++def decode(in_file, out_file=None, mode=None, quiet=False): + """Decode uuencoded file""" + # + # Open the input file, if needed. +Index: Lib/locale.py +=================================================================== +--- Lib/locale.py (.../tags/r311) (Revision 76056) ++++ Lib/locale.py (.../branches/release31-maint) (Revision 76056) +@@ -567,10 +567,21 @@ + except Error: + pass + result = nl_langinfo(CODESET) ++ if not result and sys.platform == 'darwin': ++ # nl_langinfo can return an empty string ++ # when the setting has an invalid value. ++ # Default to UTF-8 in that case because ++ # UTF-8 is the default charset on OSX and ++ # returning nothing will crash the ++ # interpreter. ++ result = 'UTF-8' + setlocale(LC_CTYPE, oldloc) +- return result + else: +- return nl_langinfo(CODESET) ++ result = nl_langinfo(CODESET) ++ if not result and sys.platform == 'darwin': ++ # See above for explanation ++ result = 'UTF-8' ++ return result + + + ### Database +Index: Lib/xml/dom/minidom.py +=================================================================== +--- Lib/xml/dom/minidom.py (.../tags/r311) (Revision 76056) ++++ Lib/xml/dom/minidom.py (.../branches/release31-maint) (Revision 76056) +@@ -43,7 +43,7 @@ + def __bool__(self): + return True + +- def toxml(self, encoding = None): ++ def toxml(self, encoding=None): + return self.toprettyxml("", "", encoding) + + def toprettyxml(self, indent="\t", newl="\n", encoding=None): +Index: Lib/xml/dom/domreg.py +=================================================================== +--- Lib/xml/dom/domreg.py (.../tags/r311) (Revision 76056) ++++ Lib/xml/dom/domreg.py (.../branches/release31-maint) (Revision 76056) +@@ -36,7 +36,7 @@ + return 0 + return 1 + +-def getDOMImplementation(name = None, features = ()): ++def getDOMImplementation(name=None, features=()): + """getDOMImplementation(name = None, features = ()) -> DOM implementation. + + Return a suitable DOM implementation. The name is either +Index: Lib/xml/sax/saxutils.py +=================================================================== +--- Lib/xml/sax/saxutils.py (.../tags/r311) (Revision 76056) ++++ Lib/xml/sax/saxutils.py (.../branches/release31-maint) (Revision 76056) +@@ -268,7 +268,7 @@ + + # --- Utility functions + +-def prepare_input_source(source, base = ""): ++def prepare_input_source(source, base=""): + """This function takes an InputSource and an optional base URL and + returns a fully resolved InputSource object ready for reading.""" + +Index: Makefile.pre.in +=================================================================== +--- Makefile.pre.in (.../tags/r311) (Revision 76056) ++++ Makefile.pre.in (.../branches/release31-maint) (Revision 76056) +@@ -1148,7 +1148,7 @@ + for i in $(SRCDIRS); do etags -a $$i/*.[ch]; done + + # Sanitation targets -- clean leaves libraries, executables and tags +-# files, which clobber removes those as well ++# files, which clobber removes as well + pycremoval: + find $(srcdir) -name '*.py[co]' -exec rm -f {} ';' + +@@ -1168,6 +1168,7 @@ + find . -name '*.s[ol]' -exec rm -f {} ';' + find build -name 'fficonfig.h' -exec rm -f {} ';' || true + find build -name 'fficonfig.py' -exec rm -f {} ';' || true ++ -rm -f Lib/lib2to3/*Grammar*.pickle + + profile-removal: + find . -name '*.gc??' -exec rm -f {} ';' +@@ -1184,7 +1185,8 @@ + # Keep configure and Python-ast.[ch], it's possible they can't be generated + distclean: clobber + -rm -f core Makefile Makefile.pre config.status \ +- Modules/Setup Modules/Setup.local Modules/Setup.config ++ Modules/Setup Modules/Setup.local Modules/Setup.config \ ++ Misc/python.pc + find $(srcdir) '(' -name '*.fdc' -o -name '*~' \ + -o -name '[@,#]*' -o -name '*.old' \ + -o -name '*.orig' -o -name '*.rej' \ +Index: Modules/bz2module.c +=================================================================== +--- Modules/bz2module.c (.../tags/r311) (Revision 76056) ++++ Modules/bz2module.c (.../branches/release31-maint) (Revision 76056) +@@ -78,7 +78,12 @@ + + + #ifdef WITH_THREAD +-#define ACQUIRE_LOCK(obj) PyThread_acquire_lock(obj->lock, 1) ++#define ACQUIRE_LOCK(obj) do { \ ++ if (!PyThread_acquire_lock(obj->lock, 0)) { \ ++ Py_BEGIN_ALLOW_THREADS \ ++ PyThread_acquire_lock(obj->lock, 1); \ ++ Py_END_ALLOW_THREADS \ ++ } } while(0) + #define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock) + #else + #define ACQUIRE_LOCK(obj) +Index: Modules/_ctypes/callproc.c +=================================================================== +--- Modules/_ctypes/callproc.c (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/callproc.c (.../branches/release31-maint) (Revision 76056) +@@ -547,6 +547,7 @@ + * C function call. + * + * 1. Python integers are converted to C int and passed by value. ++ * Py_None is converted to a C NULL pointer. + * + * 2. 3-tuples are expected to have a format character in the first + * item, which must be 'i', 'f', 'd', 'q', or 'P'. +Index: Modules/_ctypes/libffi_osx/powerpc/ppc-darwin_closure.S +=================================================================== +--- Modules/_ctypes/libffi_osx/powerpc/ppc-darwin_closure.S (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/powerpc/ppc-darwin_closure.S (.../branches/release31-maint) (Revision 76056) +@@ -1,7 +1,7 @@ + #if defined(__ppc__) + + /* ----------------------------------------------------------------------- +- darwin_closure.S - Copyright (c) 2002, 2003, 2004, Free Software Foundation, ++ ppc-darwin_closure.S - Copyright (c) 2002, 2003, 2004, Free Software Foundation, + Inc. based on ppc_closure.S + + PowerPC Assembly glue. +@@ -43,8 +43,8 @@ + + _ffi_closure_ASM: + LFB1: +- mflr r0 /* extract return address */ +- stg r0,MODE_CHOICE(8,16)(r1) /* save return address */ ++ mflr r0 // Save return address ++ stg r0,SF_RETURN(r1) + + LCFI0: + /* 24/48 bytes (Linkage Area) +@@ -54,7 +54,7 @@ + 176/232 total bytes */ + + /* skip over caller save area and keep stack aligned to 16/32. */ +- stgu r1,-SF_ROUND(MODE_CHOICE(176,248))(r1) ++ stgu r1,-SF_ROUND(176)(r1) + + LCFI1: + /* We want to build up an area for the parameters passed +@@ -67,58 +67,44 @@ + + /* Save GPRs 3 - 10 (aligned to 4/8) + in the parents outgoing area. */ +- stg r3,MODE_CHOICE(200,304)(r1) +- stg r4,MODE_CHOICE(204,312)(r1) +- stg r5,MODE_CHOICE(208,320)(r1) +- stg r6,MODE_CHOICE(212,328)(r1) +- stg r7,MODE_CHOICE(216,336)(r1) +- stg r8,MODE_CHOICE(220,344)(r1) +- stg r9,MODE_CHOICE(224,352)(r1) +- stg r10,MODE_CHOICE(228,360)(r1) ++ stg r3,200(r1) ++ stg r4,204(r1) ++ stg r5,208(r1) ++ stg r6,212(r1) ++ stg r7,216(r1) ++ stg r8,220(r1) ++ stg r9,224(r1) ++ stg r10,228(r1) + + /* Save FPRs 1 - 13. (aligned to 8) */ +- stfd f1,MODE_CHOICE(56,112)(r1) +- stfd f2,MODE_CHOICE(64,120)(r1) +- stfd f3,MODE_CHOICE(72,128)(r1) +- stfd f4,MODE_CHOICE(80,136)(r1) +- stfd f5,MODE_CHOICE(88,144)(r1) +- stfd f6,MODE_CHOICE(96,152)(r1) +- stfd f7,MODE_CHOICE(104,160)(r1) +- stfd f8,MODE_CHOICE(112,168)(r1) +- stfd f9,MODE_CHOICE(120,176)(r1) +- stfd f10,MODE_CHOICE(128,184)(r1) +- stfd f11,MODE_CHOICE(136,192)(r1) +- stfd f12,MODE_CHOICE(144,200)(r1) +- stfd f13,MODE_CHOICE(152,208)(r1) ++ stfd f1,56(r1) ++ stfd f2,64(r1) ++ stfd f3,72(r1) ++ stfd f4,80(r1) ++ stfd f5,88(r1) ++ stfd f6,96(r1) ++ stfd f7,104(r1) ++ stfd f8,112(r1) ++ stfd f9,120(r1) ++ stfd f10,128(r1) ++ stfd f11,136(r1) ++ stfd f12,144(r1) ++ stfd f13,152(r1) + +- /* Set up registers for the routine that actually does the work. +- Get the context pointer from the trampoline. */ +- mr r3,r11 +- +- /* Load the pointer to the result storage. */ +- /* current stack frame size - ((4/8 * 4) + saved registers) */ +- addi r4,r1,MODE_CHOICE(160,216) +- +- /* Load the pointer to the saved gpr registers. */ +- addi r5,r1,MODE_CHOICE(200,304) +- +- /* Load the pointer to the saved fpr registers. */ +- addi r6,r1,MODE_CHOICE(56,112) +- +- /* Make the call. */ ++ // Set up registers for the routine that actually does the work. ++ mr r3,r11 // context pointer from the trampoline ++ addi r4,r1,160 // result storage ++ addi r5,r1,200 // saved GPRs ++ addi r6,r1,56 // saved FPRs + bl Lffi_closure_helper_DARWIN$stub + +- /* Now r3 contains the return type +- so use it to look up in a table ++ /* Now r3 contains the return type. Use it to look up in a table + so we know how to deal with each type. */ +- +- /* Look the proper starting point in table +- by using return type as offset. */ +- addi r5,r1,MODE_CHOICE(160,216) // Get pointer to results area. +- bl Lget_ret_type0_addr // Get pointer to Lret_type0 into LR. +- mflr r4 // Move to r4. +- slwi r3,r3,4 // Now multiply return type by 16. +- add r3,r3,r4 // Add contents of table to table address. ++ addi r5,r1,160 // Copy result storage pointer. ++ bl Lget_ret_type0_addr // Get pointer to Lret_type0 into LR. ++ mflr r4 // Move to r4. ++ slwi r3,r3,4 // Multiply return type by 16. ++ add r3,r3,r4 // Add contents of table to table address. + mtctr r3 + bctr + +@@ -143,7 +129,7 @@ + + /* case FFI_TYPE_INT */ + Lret_type1: +- lwz r3,MODE_CHOICE(0,4)(r5) ++ lwz r3,0(r5) + b Lfinish + nop + nop +@@ -171,42 +157,42 @@ + + /* case FFI_TYPE_UINT8 */ + Lret_type5: +- lbz r3,MODE_CHOICE(3,7)(r5) ++ lbz r3,3(r5) + b Lfinish + nop + nop + + /* case FFI_TYPE_SINT8 */ + Lret_type6: +- lbz r3,MODE_CHOICE(3,7)(r5) ++ lbz r3,3(r5) + extsb r3,r3 + b Lfinish + nop + + /* case FFI_TYPE_UINT16 */ + Lret_type7: +- lhz r3,MODE_CHOICE(2,6)(r5) ++ lhz r3,2(r5) + b Lfinish + nop + nop + + /* case FFI_TYPE_SINT16 */ + Lret_type8: +- lha r3,MODE_CHOICE(2,6)(r5) ++ lha r3,2(r5) + b Lfinish + nop + nop + + /* case FFI_TYPE_UINT32 */ + Lret_type9: // same as Lret_type1 +- lwz r3,MODE_CHOICE(0,4)(r5) ++ lwz r3,0(r5) + b Lfinish + nop + nop + + /* case FFI_TYPE_SINT32 */ + Lret_type10: // same as Lret_type1 +- lwz r3,MODE_CHOICE(0,4)(r5) ++ lwz r3,0(r5) + b Lfinish + nop + nop +@@ -227,7 +213,7 @@ + + /* case FFI_TYPE_STRUCT */ + Lret_type13: +- b MODE_CHOICE(Lfinish,Lret_struct) ++ b Lfinish + nop + nop + nop +@@ -239,12 +225,13 @@ + // padded to 16 bytes. + Lret_type14: + lg r3,0(r5) ++ // fall through + + /* case done */ + Lfinish: +- addi r1,r1,SF_ROUND(MODE_CHOICE(176,248)) // Restore stack pointer. +- lg r0,MODE_CHOICE(8,16)(r1) /* Get return address. */ +- mtlr r0 /* Reset link register. */ ++ addi r1,r1,SF_ROUND(176) // Restore stack pointer. ++ lg r0,SF_RETURN(r1) // Restore return address. ++ mtlr r0 // Restore link register. + blr + + /* END(ffi_closure_ASM) */ +@@ -261,7 +248,7 @@ + .byte 0x7c ; sleb128 -4; CIE Data Alignment Factor + .byte 0x41 ; CIE RA Column + .byte 0x1 ; uleb128 0x1; Augmentation size +- .byte 0x90 ; FDE Encoding (indirect pcrel) ++ .byte 0x10 ; FDE Encoding (pcrel) + .byte 0xc ; DW_CFA_def_cfa + .byte 0x1 ; uleb128 0x1 + .byte 0x0 ; uleb128 0x0 +@@ -275,7 +262,7 @@ + + LASFDE1: + .long LASFDE1-EH_frame1 ; FDE CIE offset +- .g_long LLFB1$non_lazy_ptr-. ; FDE initial location ++ .g_long LFB1-. ; FDE initial location + .set L$set$3,LFE1-LFB1 + .g_long L$set$3 ; FDE address range + .byte 0x0 ; uleb128 0x0; Augmentation size +@@ -317,9 +304,5 @@ + .indirect_symbol _ffi_closure_helper_DARWIN + .g_long dyld_stub_binding_helper + +-.data +- .align LOG2_GPR_BYTES +-LLFB1$non_lazy_ptr: +- .g_long LFB1 + + #endif // __ppc__ +Index: Modules/_ctypes/libffi_osx/powerpc/ppc-darwin.S +=================================================================== +--- Modules/_ctypes/libffi_osx/powerpc/ppc-darwin.S (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/powerpc/ppc-darwin.S (.../branches/release31-maint) (Revision 76056) +@@ -1,7 +1,7 @@ + #if defined(__ppc__) || defined(__ppc64__) + + /* ----------------------------------------------------------------------- +- darwin.S - Copyright (c) 2000 John Hornkvist ++ ppc-darwin.S - Copyright (c) 2000 John Hornkvist + Copyright (c) 2004 Free Software Foundation, Inc. + + PowerPC Assembly glue. +@@ -294,7 +294,7 @@ + .byte 0x7c ; sleb128 -4; CIE Data Alignment Factor + .byte 0x41 ; CIE RA Column + .byte 0x1 ; uleb128 0x1; Augmentation size +- .byte 0x90 ; FDE Encoding (indirect pcrel) ++ .byte 0x10 ; FDE Encoding (pcrel) + .byte 0xc ; DW_CFA_def_cfa + .byte 0x1 ; uleb128 0x1 + .byte 0x0 ; uleb128 0x0 +@@ -308,7 +308,7 @@ + + LASFDE1: + .long LASFDE1-EH_frame1 ; FDE CIE offset +- .g_long LLFB0$non_lazy_ptr-. ; FDE initial location ++ .g_long LFB0-. ; FDE initial location + .set L$set$3,LFE1-LFB0 + .g_long L$set$3 ; FDE address range + .byte 0x0 ; uleb128 0x0; Augmentation size +@@ -338,10 +338,6 @@ + .byte 0x1c ; uleb128 0x1c + .align LOG2_GPR_BYTES + LEFDE1: +-.data +- .align LOG2_GPR_BYTES +-LLFB0$non_lazy_ptr: +- .g_long LFB0 + + #if defined(__ppc64__) + .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32 +Index: Modules/_ctypes/libffi_osx/powerpc/ppc-ffi_darwin.c +=================================================================== +--- Modules/_ctypes/libffi_osx/powerpc/ppc-ffi_darwin.c (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/powerpc/ppc-ffi_darwin.c (.../branches/release31-maint) (Revision 76056) +@@ -28,13 +28,13 @@ + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +-#include "ffi.h" +-#include "ffi_common.h" ++#include ++#include + + #include + #include + #include +-#include "ppc-darwin.h" ++#include + #include + + #if 0 +@@ -42,17 +42,14 @@ + #include // for sys_icache_invalidate() + #endif + +-#else ++#else + +-/* Explicit prototype instead of including a header to allow compilation +- * on Tiger systems. +- */ +- + #pragma weak sys_icache_invalidate + extern void sys_icache_invalidate(void *start, size_t len); + + #endif + ++ + extern void ffi_closure_ASM(void); + + // The layout of a function descriptor. A C function pointer really +@@ -760,9 +757,7 @@ + + // Flush the icache. Only necessary on Darwin. + #if defined(POWERPC_DARWIN) +- if (sys_icache_invalidate) { +- sys_icache_invalidate(closure->tramp, FFI_TRAMPOLINE_SIZE); +- } ++ sys_icache_invalidate(closure->tramp, FFI_TRAMPOLINE_SIZE); + #else + flush_range(closure->tramp, FFI_TRAMPOLINE_SIZE); + #endif +@@ -804,6 +799,12 @@ + } ldu; + #endif + ++typedef union ++{ ++ float f; ++ double d; ++} ffi_dblfl; ++ + /* The trampoline invokes ffi_closure_ASM, and on entry, r11 holds the + address of the closure. After storing the registers that could possibly + contain parameters to be passed into the stack frame and setting up space +@@ -829,7 +830,7 @@ + unsigned int nf = 0; /* number of FPRs already used. */ + unsigned int ng = 0; /* number of GPRs already used. */ + ffi_cif* cif = closure->cif; +- unsigned int avn = cif->nargs; ++ long avn = cif->nargs; + void** avalue = alloca(cif->nargs * sizeof(void*)); + ffi_type** arg_types = cif->arg_types; + +@@ -906,9 +907,9 @@ + size_al = ALIGN(arg_types[i]->size, 8); + + if (size_al < 3) +- avalue[i] = (char*)pgr + MODE_CHOICE(4,8) - size_al; ++ avalue[i] = (void*)pgr + MODE_CHOICE(4,8) - size_al; + else +- avalue[i] = (char*)pgr; ++ avalue[i] = (void*)pgr; + + ng += (size_al + 3) / sizeof(long); + pgr += (size_al + 3) / sizeof(long); +@@ -988,8 +989,8 @@ + We use a union to pass the long double to avalue[i]. */ + else if (nf == NUM_FPR_ARG_REGISTERS - 1) + { +- memcpy (&temp_ld.lb[0], pfr, sizeof(ldbits)); +- memcpy (&temp_ld.lb[1], pgr + 2, sizeof(ldbits)); ++ memcpy (&temp_ld.lb[0], pfr, sizeof(temp_ld.lb[0])); ++ memcpy (&temp_ld.lb[1], pgr + 2, sizeof(temp_ld.lb[1])); + avalue[i] = &temp_ld.ld; + } + #else +Index: Modules/_ctypes/libffi_osx/powerpc/ppc-darwin.h +=================================================================== +--- Modules/_ctypes/libffi_osx/powerpc/ppc-darwin.h (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/powerpc/ppc-darwin.h (.../branches/release31-maint) (Revision 76056) +@@ -22,7 +22,6 @@ + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +- + #define L(x) x + + #define SF_ARG9 MODE_CHOICE(56,112) +@@ -57,7 +56,6 @@ + ((x) == FFI_TYPE_UINT32 || (x) == FFI_TYPE_SINT32 ||\ + (x) == FFI_TYPE_INT || (x) == FFI_TYPE_FLOAT) + +- + #if !defined(LIBFFI_ASM) + + enum { +@@ -75,20 +73,6 @@ + FLAG_RETVAL_REFERENCE = 1 << (31 - 4) + }; + +- +-void ffi_prep_args(extended_cif* inEcif, unsigned *const stack); +- +-typedef union +-{ +- float f; +- double d; +-} ffi_dblfl; +- +-int ffi_closure_helper_DARWIN( ffi_closure* closure, +- void* rvalue, unsigned long* pgr, +- ffi_dblfl* pfr); +- +- + #if defined(__ppc64__) + void ffi64_struct_to_ram_form(const ffi_type*, const char*, unsigned int*, + const char*, unsigned int*, unsigned int*, char*, unsigned int*); +@@ -96,11 +80,6 @@ + unsigned int*, char*, unsigned int*, char*, unsigned int*); + bool ffi64_stret_needs_ptr(const ffi_type* inType, + unsigned short*, unsigned short*); +-bool ffi64_struct_contains_fp(const ffi_type* inType); +-unsigned int ffi64_data_size(const ffi_type* inType); +- +- +- + #endif + +-#endif // !defined(LIBFFI_ASM) ++#endif // !defined(LIBFFI_ASM) +\ No newline at end of file +Index: Modules/_ctypes/libffi_osx/powerpc/ppc64-darwin_closure.S +=================================================================== +--- Modules/_ctypes/libffi_osx/powerpc/ppc64-darwin_closure.S (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/powerpc/ppc64-darwin_closure.S (.../branches/release31-maint) (Revision 76056) +@@ -1,7 +1,7 @@ + #if defined(__ppc64__) + + /* ----------------------------------------------------------------------- +- darwin_closure.S - Copyright (c) 2002, 2003, 2004, Free Software Foundation, ++ ppc64-darwin_closure.S - Copyright (c) 2002, 2003, 2004, Free Software Foundation, + Inc. based on ppc_closure.S + + PowerPC Assembly glue. +@@ -297,8 +297,8 @@ + + // case done + Lfinish: +- lg r1,0(r1) // Restore stack pointer. +- ld r31,-8(r1) // Restore registers we used. ++ lg r1,0(r1) // Restore stack pointer. ++ ld r31,-8(r1) // Restore registers we used. + ld r30,-16(r1) + lg r0,SF_RETURN(r1) // Get return address. + mtlr r0 // Reset link register. +@@ -318,7 +318,7 @@ + .byte 0x7c ; sleb128 -4; CIE Data Alignment Factor + .byte 0x41 ; CIE RA Column + .byte 0x1 ; uleb128 0x1; Augmentation size +- .byte 0x90 ; FDE Encoding (indirect pcrel) ++ .byte 0x10 ; FDE Encoding (pcrel) + .byte 0xc ; DW_CFA_def_cfa + .byte 0x1 ; uleb128 0x1 + .byte 0x0 ; uleb128 0x0 +@@ -332,7 +332,7 @@ + + LASFDE1: + .long LASFDE1-EH_frame1 ; FDE CIE offset +- .g_long LLFB1$non_lazy_ptr-. ; FDE initial location ++ .g_long LFB1-. ; FDE initial location + .set L$set$3,LFE1-LFB1 + .g_long L$set$3 ; FDE address range + .byte 0x0 ; uleb128 0x0; Augmentation size +@@ -374,11 +374,6 @@ + .indirect_symbol _ffi_closure_helper_DARWIN + .g_long dyld_stub_binding_helper + +-.data +- .align LOG2_GPR_BYTES +-LLFB1$non_lazy_ptr: +- .g_long LFB1 +- + .section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32 + .align LOG2_GPR_BYTES + +Index: Modules/_ctypes/libffi_osx/x86/x86-ffi64.c +=================================================================== +--- Modules/_ctypes/libffi_osx/x86/x86-ffi64.c (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/x86/x86-ffi64.c (.../branches/release31-maint) (Revision 76056) +@@ -55,7 +55,7 @@ + /* Register class used for passing given 64bit part of the argument. + These represent classes as documented by the PS ABI, with the exception + of SSESF, SSEDF classes, that are basically SSE class, just gcc will +- use SF or DFmode move instead of DImode to avoid reformatting penalties. ++ use SF or DFmode move instead of DImode to avoid reformating penalties. + + Similary we play games with INTEGERSI_CLASS to use cheaper SImode moves + whenever possible (upper half does contain padding). */ +@@ -621,4 +621,4 @@ + return ret; + } + +-#endif /* __x86_64__ */ ++#endif /* __x86_64__ */ +\ No newline at end of file +Index: Modules/_ctypes/libffi_osx/x86/x86-darwin.S +=================================================================== +--- Modules/_ctypes/libffi_osx/x86/x86-darwin.S (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/x86/x86-darwin.S (.../branches/release31-maint) (Revision 76056) +@@ -46,23 +46,20 @@ + + .globl _ffi_prep_args + +-.align 4 ++ .align 4 + .globl _ffi_call_SYSV + + _ffi_call_SYSV: +-.LFB1: ++LFB1: + pushl %ebp +-.LCFI0: ++LCFI0: + movl %esp,%ebp +- subl $8,%esp +- ASSERT_STACK_ALIGNED +-.LCFI1: ++LCFI1: ++ subl $8,%esp + /* Make room for all of the new args. */ + movl 16(%ebp),%ecx + subl %ecx,%esp + +- ASSERT_STACK_ALIGNED +- + movl %esp,%eax + + /* Place all of the ffi_prep_args in position */ +@@ -71,171 +68,350 @@ + pushl %eax + call *8(%ebp) + +- ASSERT_STACK_ALIGNED +- + /* Return stack to previous state and call the function */ +- addl $16,%esp ++ addl $16,%esp + +- ASSERT_STACK_ALIGNED ++ call *28(%ebp) + +- call *28(%ebp) +- +- /* XXX: return returns return with 'ret $4', that upsets the stack! */ ++ /* Remove the space we pushed for the args */ + movl 16(%ebp),%ecx + addl %ecx,%esp + +- + /* Load %ecx with the return type code */ + movl 20(%ebp),%ecx + +- + /* If the return value pointer is NULL, assume no return value. */ + cmpl $0,24(%ebp) +- jne retint ++ jne Lretint + + /* Even if there is no space for the return value, we are + obliged to handle floating-point values. */ + cmpl $FFI_TYPE_FLOAT,%ecx +- jne noretval ++ jne Lnoretval + fstp %st(0) + +- jmp epilogue ++ jmp Lepilogue + +-retint: ++Lretint: + cmpl $FFI_TYPE_INT,%ecx +- jne retfloat ++ jne Lretfloat + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + movl %eax,0(%ecx) +- jmp epilogue ++ jmp Lepilogue + +-retfloat: ++Lretfloat: + cmpl $FFI_TYPE_FLOAT,%ecx +- jne retdouble ++ jne Lretdouble + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + fstps (%ecx) +- jmp epilogue ++ jmp Lepilogue + +-retdouble: ++Lretdouble: + cmpl $FFI_TYPE_DOUBLE,%ecx +- jne retlongdouble ++ jne Lretlongdouble + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + fstpl (%ecx) +- jmp epilogue ++ jmp Lepilogue + +-retlongdouble: ++Lretlongdouble: + cmpl $FFI_TYPE_LONGDOUBLE,%ecx +- jne retint64 ++ jne Lretint64 + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + fstpt (%ecx) +- jmp epilogue ++ jmp Lepilogue + +-retint64: ++Lretint64: + cmpl $FFI_TYPE_SINT64,%ecx +- jne retstruct1b ++ jne Lretstruct1b + /* Load %ecx with the pointer to storage for the return value */ + movl 24(%ebp),%ecx + movl %eax,0(%ecx) + movl %edx,4(%ecx) +- jmp epilogue ++ jmp Lepilogue ++ ++Lretstruct1b: ++ cmpl $FFI_TYPE_SINT8,%ecx ++ jne Lretstruct2b ++ /* Load %ecx with the pointer to storage for the return value */ ++ movl 24(%ebp),%ecx ++ movb %al,0(%ecx) ++ jmp Lepilogue + +-retstruct1b: +- cmpl $FFI_TYPE_SINT8,%ecx +- jne retstruct2b +- movl 24(%ebp),%ecx +- movb %al,0(%ecx) +- jmp epilogue ++Lretstruct2b: ++ cmpl $FFI_TYPE_SINT16,%ecx ++ jne Lretstruct ++ /* Load %ecx with the pointer to storage for the return value */ ++ movl 24(%ebp),%ecx ++ movw %ax,0(%ecx) ++ jmp Lepilogue + +-retstruct2b: +- cmpl $FFI_TYPE_SINT16,%ecx +- jne retstruct +- movl 24(%ebp),%ecx +- movw %ax,0(%ecx) +- jmp epilogue +- +-retstruct: +- cmpl $FFI_TYPE_STRUCT,%ecx +- jne noretval ++Lretstruct: ++ cmpl $FFI_TYPE_STRUCT,%ecx ++ jne Lnoretval + /* Nothing to do! */ ++ addl $4,%esp ++ popl %ebp ++ ret + +- subl $4,%esp ++Lnoretval: ++Lepilogue: ++ addl $8,%esp ++ movl %ebp,%esp ++ popl %ebp ++ ret ++LFE1: ++.ffi_call_SYSV_end: + +- ASSERT_STACK_ALIGNED ++ .align 4 ++FFI_HIDDEN (ffi_closure_SYSV) ++.globl _ffi_closure_SYSV + +- addl $8,%esp +- movl %ebp, %esp +- popl %ebp ++_ffi_closure_SYSV: ++LFB2: ++ pushl %ebp ++LCFI2: ++ movl %esp, %ebp ++LCFI3: ++ subl $56, %esp ++ leal -40(%ebp), %edx ++ movl %edx, -12(%ebp) /* resp */ ++ leal 8(%ebp), %edx ++ movl %edx, 4(%esp) /* args = __builtin_dwarf_cfa () */ ++ leal -12(%ebp), %edx ++ movl %edx, (%esp) /* &resp */ ++ movl %ebx, 8(%esp) ++LCFI7: ++ call L_ffi_closure_SYSV_inner$stub ++ movl 8(%esp), %ebx ++ movl -12(%ebp), %ecx ++ cmpl $FFI_TYPE_INT, %eax ++ je Lcls_retint ++ cmpl $FFI_TYPE_FLOAT, %eax ++ je Lcls_retfloat ++ cmpl $FFI_TYPE_DOUBLE, %eax ++ je Lcls_retdouble ++ cmpl $FFI_TYPE_LONGDOUBLE, %eax ++ je Lcls_retldouble ++ cmpl $FFI_TYPE_SINT64, %eax ++ je Lcls_retllong ++ cmpl $FFI_TYPE_SINT8, %eax ++ je Lcls_retstruct1 ++ cmpl $FFI_TYPE_SINT16, %eax ++ je Lcls_retstruct2 ++ cmpl $FFI_TYPE_STRUCT, %eax ++ je Lcls_retstruct ++Lcls_epilogue: ++ movl %ebp, %esp ++ popl %ebp + ret ++Lcls_retint: ++ movl (%ecx), %eax ++ jmp Lcls_epilogue ++Lcls_retfloat: ++ flds (%ecx) ++ jmp Lcls_epilogue ++Lcls_retdouble: ++ fldl (%ecx) ++ jmp Lcls_epilogue ++Lcls_retldouble: ++ fldt (%ecx) ++ jmp Lcls_epilogue ++Lcls_retllong: ++ movl (%ecx), %eax ++ movl 4(%ecx), %edx ++ jmp Lcls_epilogue ++Lcls_retstruct1: ++ movsbl (%ecx), %eax ++ jmp Lcls_epilogue ++Lcls_retstruct2: ++ movswl (%ecx), %eax ++ jmp Lcls_epilogue ++Lcls_retstruct: ++ lea -8(%ebp),%esp ++ movl %ebp, %esp ++ popl %ebp ++ ret $4 ++LFE2: + +-noretval: +-epilogue: +- ASSERT_STACK_ALIGNED +- addl $8, %esp ++#if !FFI_NO_RAW_API + ++#define RAW_CLOSURE_CIF_OFFSET ((FFI_TRAMPOLINE_SIZE + 3) & ~3) ++#define RAW_CLOSURE_FUN_OFFSET (RAW_CLOSURE_CIF_OFFSET + 4) ++#define RAW_CLOSURE_USER_DATA_OFFSET (RAW_CLOSURE_FUN_OFFSET + 4) ++#define CIF_FLAGS_OFFSET 20 + +- movl %ebp,%esp +- popl %ebp +- ret +-.ffi_call_SYSV_end: +-#if 0 +- .size ffi_call_SYSV,.ffi_call_SYSV_end-ffi_call_SYSV ++ .align 4 ++FFI_HIDDEN (ffi_closure_raw_SYSV) ++.globl _ffi_closure_raw_SYSV ++ ++_ffi_closure_raw_SYSV: ++LFB3: ++ pushl %ebp ++LCFI4: ++ movl %esp, %ebp ++LCFI5: ++ pushl %esi ++LCFI6: ++ subl $36, %esp ++ movl RAW_CLOSURE_CIF_OFFSET(%eax), %esi /* closure->cif */ ++ movl RAW_CLOSURE_USER_DATA_OFFSET(%eax), %edx /* closure->user_data */ ++ movl %edx, 12(%esp) /* user_data */ ++ leal 8(%ebp), %edx /* __builtin_dwarf_cfa () */ ++ movl %edx, 8(%esp) /* raw_args */ ++ leal -24(%ebp), %edx ++ movl %edx, 4(%esp) /* &res */ ++ movl %esi, (%esp) /* cif */ ++ call *RAW_CLOSURE_FUN_OFFSET(%eax) /* closure->fun */ ++ movl CIF_FLAGS_OFFSET(%esi), %eax /* rtype */ ++ cmpl $FFI_TYPE_INT, %eax ++ je Lrcls_retint ++ cmpl $FFI_TYPE_FLOAT, %eax ++ je Lrcls_retfloat ++ cmpl $FFI_TYPE_DOUBLE, %eax ++ je Lrcls_retdouble ++ cmpl $FFI_TYPE_LONGDOUBLE, %eax ++ je Lrcls_retldouble ++ cmpl $FFI_TYPE_SINT64, %eax ++ je Lrcls_retllong ++Lrcls_epilogue: ++ addl $36, %esp ++ popl %esi ++ popl %ebp ++ ret ++Lrcls_retint: ++ movl -24(%ebp), %eax ++ jmp Lrcls_epilogue ++Lrcls_retfloat: ++ flds -24(%ebp) ++ jmp Lrcls_epilogue ++Lrcls_retdouble: ++ fldl -24(%ebp) ++ jmp Lrcls_epilogue ++Lrcls_retldouble: ++ fldt -24(%ebp) ++ jmp Lrcls_epilogue ++Lrcls_retllong: ++ movl -24(%ebp), %eax ++ movl -20(%ebp), %edx ++ jmp Lrcls_epilogue ++LFE3: + #endif + +-#if 0 +- .section .eh_frame,EH_FRAME_FLAGS,@progbits +-.Lframe1: +- .long .LECIE1-.LSCIE1 /* Length of Common Information Entry */ +-.LSCIE1: +- .long 0x0 /* CIE Identifier Tag */ +- .byte 0x1 /* CIE Version */ +-#ifdef __PIC__ +- .ascii "zR\0" /* CIE Augmentation */ +-#else +- .ascii "\0" /* CIE Augmentation */ ++.section __IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5 ++L_ffi_closure_SYSV_inner$stub: ++ .indirect_symbol _ffi_closure_SYSV_inner ++ hlt ; hlt ; hlt ; hlt ; hlt ++ ++ ++.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support ++EH_frame1: ++ .set L$set$0,LECIE1-LSCIE1 ++ .long L$set$0 ++LSCIE1: ++ .long 0x0 ++ .byte 0x1 ++ .ascii "zR\0" ++ .byte 0x1 ++ .byte 0x7c ++ .byte 0x8 ++ .byte 0x1 ++ .byte 0x10 ++ .byte 0xc ++ .byte 0x5 ++ .byte 0x4 ++ .byte 0x88 ++ .byte 0x1 ++ .align 2 ++LECIE1: ++.globl _ffi_call_SYSV.eh ++_ffi_call_SYSV.eh: ++LSFDE1: ++ .set L$set$1,LEFDE1-LASFDE1 ++ .long L$set$1 ++LASFDE1: ++ .long LASFDE1-EH_frame1 ++ .long LFB1-. ++ .set L$set$2,LFE1-LFB1 ++ .long L$set$2 ++ .byte 0x0 ++ .byte 0x4 ++ .set L$set$3,LCFI0-LFB1 ++ .long L$set$3 ++ .byte 0xe ++ .byte 0x8 ++ .byte 0x84 ++ .byte 0x2 ++ .byte 0x4 ++ .set L$set$4,LCFI1-LCFI0 ++ .long L$set$4 ++ .byte 0xd ++ .byte 0x4 ++ .align 2 ++LEFDE1: ++.globl _ffi_closure_SYSV.eh ++_ffi_closure_SYSV.eh: ++LSFDE2: ++ .set L$set$5,LEFDE2-LASFDE2 ++ .long L$set$5 ++LASFDE2: ++ .long LASFDE2-EH_frame1 ++ .long LFB2-. ++ .set L$set$6,LFE2-LFB2 ++ .long L$set$6 ++ .byte 0x0 ++ .byte 0x4 ++ .set L$set$7,LCFI2-LFB2 ++ .long L$set$7 ++ .byte 0xe ++ .byte 0x8 ++ .byte 0x84 ++ .byte 0x2 ++ .byte 0x4 ++ .set L$set$8,LCFI3-LCFI2 ++ .long L$set$8 ++ .byte 0xd ++ .byte 0x4 ++ .align 2 ++LEFDE2: ++ ++#if !FFI_NO_RAW_API ++ ++.globl _ffi_closure_raw_SYSV.eh ++_ffi_closure_raw_SYSV.eh: ++LSFDE3: ++ .set L$set$10,LEFDE3-LASFDE3 ++ .long L$set$10 ++LASFDE3: ++ .long LASFDE3-EH_frame1 ++ .long LFB3-. ++ .set L$set$11,LFE3-LFB3 ++ .long L$set$11 ++ .byte 0x0 ++ .byte 0x4 ++ .set L$set$12,LCFI4-LFB3 ++ .long L$set$12 ++ .byte 0xe ++ .byte 0x8 ++ .byte 0x84 ++ .byte 0x2 ++ .byte 0x4 ++ .set L$set$13,LCFI5-LCFI4 ++ .long L$set$13 ++ .byte 0xd ++ .byte 0x4 ++ .byte 0x4 ++ .set L$set$14,LCFI6-LCFI5 ++ .long L$set$14 ++ .byte 0x85 ++ .byte 0x3 ++ .align 2 ++LEFDE3: ++ + #endif +- .byte 0x1 /* .uleb128 0x1; CIE Code Alignment Factor */ +- .byte 0x7c /* .sleb128 -4; CIE Data Alignment Factor */ +- .byte 0x8 /* CIE RA Column */ +-#ifdef __PIC__ +- .byte 0x1 /* .uleb128 0x1; Augmentation size */ +- .byte 0x1b /* FDE Encoding (pcrel sdata4) */ +-#endif +- .byte 0xc /* DW_CFA_def_cfa */ +- .byte 0x4 /* .uleb128 0x4 */ +- .byte 0x4 /* .uleb128 0x4 */ +- .byte 0x88 /* DW_CFA_offset, column 0x8 */ +- .byte 0x1 /* .uleb128 0x1 */ +- .align 4 +-.LECIE1: +-.LSFDE1: +- .long .LEFDE1-.LASFDE1 /* FDE Length */ +-.LASFDE1: +- .long .LASFDE1-.Lframe1 /* FDE CIE offset */ +-#ifdef __PIC__ +- .long .LFB1-. /* FDE initial location */ +-#else +- .long .LFB1 /* FDE initial location */ +-#endif +- .long .ffi_call_SYSV_end-.LFB1 /* FDE address range */ +-#ifdef __PIC__ +- .byte 0x0 /* .uleb128 0x0; Augmentation size */ +-#endif +- .byte 0x4 /* DW_CFA_advance_loc4 */ +- .long .LCFI0-.LFB1 +- .byte 0xe /* DW_CFA_def_cfa_offset */ +- .byte 0x8 /* .uleb128 0x8 */ +- .byte 0x85 /* DW_CFA_offset, column 0x5 */ +- .byte 0x2 /* .uleb128 0x2 */ +- .byte 0x4 /* DW_CFA_advance_loc4 */ +- .long .LCFI1-.LCFI0 +- .byte 0xd /* DW_CFA_def_cfa_register */ +- .byte 0x5 /* .uleb128 0x5 */ +- .align 4 +-.LEFDE1: +-#endif + + #endif /* ifndef __x86_64__ */ + +Index: Modules/_ctypes/libffi_osx/x86/x86-ffi_darwin.c +=================================================================== +--- Modules/_ctypes/libffi_osx/x86/x86-ffi_darwin.c (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/libffi_osx/x86/x86-ffi_darwin.c (.../branches/release31-maint) (Revision 76056) +@@ -27,543 +27,410 @@ + OTHER DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +-//#ifndef __x86_64__ +- + #include + #include + + #include + +-//void ffi_prep_args(char *stack, extended_cif *ecif); +- +-static inline int +-retval_on_stack( +- ffi_type* tp) +-{ +- if (tp->type == FFI_TYPE_STRUCT) +- { +-// int size = tp->size; +- +- if (tp->size > 8) +- return 1; +- +- switch (tp->size) +- { +- case 1: case 2: case 4: case 8: +- return 0; +- default: +- return 1; +- } +- } +- +- return 0; +-} +- + /* ffi_prep_args is called by the assembly routine once stack space +- has been allocated for the function's arguments */ +-/*@-exportheader@*/ +-extern void ffi_prep_args(char*, extended_cif*); +-void +-ffi_prep_args( +- char* stack, +- extended_cif* ecif) +-/*@=exportheader@*/ +-{ +- register unsigned int i; +- register void** p_argv = ecif->avalue; +- register char* argp = stack; +- register ffi_type** p_arg; ++ has been allocated for the function's arguments */ + +- if (retval_on_stack(ecif->cif->rtype)) +- { +- *(void**)argp = ecif->rvalue; +- argp += 4; +- } +- +- p_arg = ecif->cif->arg_types; +- +- for (i = ecif->cif->nargs; i > 0; i--, p_arg++, p_argv++) ++void ffi_prep_args(char *stack, extended_cif *ecif) ++{ ++ register unsigned int i; ++ register void **p_argv; ++ register char *argp; ++ register ffi_type **p_arg; ++ ++ argp = stack; ++ ++ if (ecif->cif->flags == FFI_TYPE_STRUCT) + { +- size_t z = (*p_arg)->size; +- +- /* Align if necessary */ +- if ((sizeof(int) - 1) & (unsigned)argp) +- argp = (char*)ALIGN(argp, sizeof(int)); +- +- if (z < sizeof(int)) +- { +- z = sizeof(int); +- +- switch ((*p_arg)->type) +- { +- case FFI_TYPE_SINT8: +- *(signed int*)argp = (signed int)*(SINT8*)(*p_argv); +- break; +- +- case FFI_TYPE_UINT8: +- *(unsigned int*)argp = (unsigned int)*(UINT8*)(*p_argv); +- break; +- +- case FFI_TYPE_SINT16: +- *(signed int*)argp = (signed int)*(SINT16*)(*p_argv); +- break; +- +- case FFI_TYPE_UINT16: +- *(unsigned int*)argp = (unsigned int)*(UINT16*)(*p_argv); +- break; +- +- case FFI_TYPE_SINT32: +- *(signed int*)argp = (signed int)*(SINT32*)(*p_argv); +- break; +- +- case FFI_TYPE_UINT32: +- *(unsigned int*)argp = (unsigned int)*(UINT32*)(*p_argv); +- break; +- +- case FFI_TYPE_STRUCT: +- *(unsigned int*)argp = (unsigned int)*(UINT32*)(*p_argv); +- break; +- +- default: +- FFI_ASSERT(0); +- break; +- } +- } +- else +- memcpy(argp, *p_argv, z); +- +- argp += z; +- } ++ *(void **) argp = ecif->rvalue; ++ argp += 4; ++ } ++ ++ p_argv = ecif->avalue; ++ ++ for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; ++ i != 0; ++ i--, p_arg++) ++ { ++ size_t z; ++ ++ /* Align if necessary */ ++ if ((sizeof(int) - 1) & (unsigned) argp) ++ argp = (char *) ALIGN(argp, sizeof(int)); ++ ++ z = (*p_arg)->size; ++ if (z < sizeof(int)) ++ { ++ z = sizeof(int); ++ switch ((*p_arg)->type) ++ { ++ case FFI_TYPE_SINT8: ++ *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); ++ break; ++ ++ case FFI_TYPE_UINT8: ++ *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); ++ break; ++ ++ case FFI_TYPE_SINT16: ++ *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); ++ break; ++ ++ case FFI_TYPE_UINT16: ++ *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); ++ break; ++ ++ case FFI_TYPE_SINT32: ++ *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); ++ break; ++ ++ case FFI_TYPE_UINT32: ++ *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); ++ break; ++ ++ case FFI_TYPE_STRUCT: ++ *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); ++ break; ++ ++ default: ++ FFI_ASSERT(0); ++ } ++ } ++ else ++ { ++ memcpy(argp, *p_argv, z); ++ } ++ p_argv++; ++ argp += z; ++ } ++ ++ return; + } + + /* Perform machine dependent cif processing */ +-ffi_status +-ffi_prep_cif_machdep( +- ffi_cif* cif) ++ffi_status ffi_prep_cif_machdep(ffi_cif *cif) + { +- /* Set the return type flag */ +- switch (cif->rtype->type) +- { +-#if !defined(X86_WIN32) && !defined(X86_DARWIN) +- case FFI_TYPE_STRUCT: ++ /* Set the return type flag */ ++ switch (cif->rtype->type) ++ { ++ case FFI_TYPE_VOID: ++#ifdef X86 ++ case FFI_TYPE_STRUCT: ++ case FFI_TYPE_UINT8: ++ case FFI_TYPE_UINT16: ++ case FFI_TYPE_SINT8: ++ case FFI_TYPE_SINT16: + #endif +- case FFI_TYPE_VOID: +- case FFI_TYPE_SINT64: +- case FFI_TYPE_FLOAT: +- case FFI_TYPE_DOUBLE: +- case FFI_TYPE_LONGDOUBLE: +- cif->flags = (unsigned)cif->rtype->type; +- break; +- +- case FFI_TYPE_UINT64: +- cif->flags = FFI_TYPE_SINT64; +- break; +- +-#if defined(X86_WIN32) || defined(X86_DARWIN) +- case FFI_TYPE_STRUCT: +- switch (cif->rtype->size) +- { +- case 1: +- cif->flags = FFI_TYPE_SINT8; +- break; +- +- case 2: +- cif->flags = FFI_TYPE_SINT16; +- break; +- +- case 4: +- cif->flags = FFI_TYPE_INT; +- break; +- +- case 8: +- cif->flags = FFI_TYPE_SINT64; +- break; +- +- default: +- cif->flags = FFI_TYPE_STRUCT; +- break; +- } +- +- break; ++ ++ case FFI_TYPE_SINT64: ++ case FFI_TYPE_FLOAT: ++ case FFI_TYPE_DOUBLE: ++ case FFI_TYPE_LONGDOUBLE: ++ cif->flags = (unsigned) cif->rtype->type; ++ break; ++ ++ case FFI_TYPE_UINT64: ++ cif->flags = FFI_TYPE_SINT64; ++ break; ++ ++#ifndef X86 ++ case FFI_TYPE_STRUCT: ++ if (cif->rtype->size == 1) ++ { ++ cif->flags = FFI_TYPE_SINT8; /* same as char size */ ++ } ++ else if (cif->rtype->size == 2) ++ { ++ cif->flags = FFI_TYPE_SINT16; /* same as short size */ ++ } ++ else if (cif->rtype->size == 4) ++ { ++ cif->flags = FFI_TYPE_INT; /* same as int type */ ++ } ++ else if (cif->rtype->size == 8) ++ { ++ cif->flags = FFI_TYPE_SINT64; /* same as int64 type */ ++ } ++ else ++ { ++ cif->flags = FFI_TYPE_STRUCT; ++ } ++ break; + #endif +- +- default: +- cif->flags = FFI_TYPE_INT; +- break; +- } +- +- /* Darwin: The stack needs to be aligned to a multiple of 16 bytes */ +- cif->bytes = (cif->bytes + 15) & ~0xF; +- +- return FFI_OK; ++ ++ default: ++ cif->flags = FFI_TYPE_INT; ++ break; ++ } ++ ++#ifdef X86_DARWIN ++ cif->bytes = (cif->bytes + 15) & ~0xF; ++#endif ++ ++ return FFI_OK; + } + +-/*@-declundef@*/ +-/*@-exportheader@*/ +-extern void +-ffi_call_SYSV( +- void (*)(char *, extended_cif *), +-/*@out@*/ extended_cif* , +- unsigned , +- unsigned , +-/*@out@*/ unsigned* , +- void (*fn)(void)); +-/*@=declundef@*/ +-/*@=exportheader@*/ ++extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, ++ unsigned, unsigned, unsigned *, void (*fn)()); + + #ifdef X86_WIN32 +-/*@-declundef@*/ +-/*@-exportheader@*/ +-extern void +-ffi_call_STDCALL( +- void (char *, extended_cif *), +-/*@out@*/ extended_cif* , +- unsigned , +- unsigned , +-/*@out@*/ unsigned* , +- void (*fn)(void)); +-/*@=declundef@*/ +-/*@=exportheader@*/ ++extern void ffi_call_STDCALL(void (*)(char *, extended_cif *), extended_cif *, ++ unsigned, unsigned, unsigned *, void (*fn)()); ++ + #endif /* X86_WIN32 */ + +-void +-ffi_call( +-/*@dependent@*/ ffi_cif* cif, +- void (*fn)(void), +-/*@out@*/ void* rvalue, +-/*@dependent@*/ void** avalue) ++void ffi_call(ffi_cif *cif, void (*fn)(), void *rvalue, void **avalue) + { +- extended_cif ecif; +- +- ecif.cif = cif; +- ecif.avalue = avalue; +- +- /* If the return value is a struct and we don't have a return +- value address then we need to make one. */ +- +- if ((rvalue == NULL) && retval_on_stack(cif->rtype)) +- { +- /*@-sysunrecog@*/ +- ecif.rvalue = alloca(cif->rtype->size); +- /*@=sysunrecog@*/ +- } +- else +- ecif.rvalue = rvalue; +- +- switch (cif->abi) +- { +- case FFI_SYSV: +- /*@-usedef@*/ +- /* To avoid changing the assembly code make sure the size of the argument +- block is a multiple of 16. Then add 8 to compensate for local variables +- in ffi_call_SYSV. */ +- ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, +- cif->flags, ecif.rvalue, fn); +- /*@=usedef@*/ +- break; +- ++ extended_cif ecif; ++ ++ ecif.cif = cif; ++ ecif.avalue = avalue; ++ ++ /* If the return value is a struct and we don't have a return */ ++ /* value address then we need to make one */ ++ ++ if ((rvalue == NULL) && ++ (cif->flags == FFI_TYPE_STRUCT)) ++ { ++ ecif.rvalue = alloca(cif->rtype->size); ++ } ++ else ++ ecif.rvalue = rvalue; ++ ++ ++ switch (cif->abi) ++ { ++ case FFI_SYSV: ++ ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, ++ fn); ++ break; + #ifdef X86_WIN32 +- case FFI_STDCALL: +- /*@-usedef@*/ +- ffi_call_STDCALL(ffi_prep_args, &ecif, cif->bytes, +- cif->flags, ecif.rvalue, fn); +- /*@=usedef@*/ +- break; ++ case FFI_STDCALL: ++ ffi_call_STDCALL(ffi_prep_args, &ecif, cif->bytes, cif->flags, ++ ecif.rvalue, fn); ++ break; + #endif /* X86_WIN32 */ +- +- default: +- FFI_ASSERT(0); +- break; +- } ++ default: ++ FFI_ASSERT(0); ++ break; ++ } + } + ++ + /** private members **/ + +-static void +-ffi_closure_SYSV( +- ffi_closure* closure) __attribute__((regparm(1))); ++static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, ++ void** args, ffi_cif* cif); ++void FFI_HIDDEN ffi_closure_SYSV (ffi_closure *) ++__attribute__ ((regparm(1))); ++unsigned int FFI_HIDDEN ffi_closure_SYSV_inner (ffi_closure *, void **, void *) ++__attribute__ ((regparm(1))); ++void FFI_HIDDEN ffi_closure_raw_SYSV (ffi_raw_closure *) ++__attribute__ ((regparm(1))); + +-#if !FFI_NO_RAW_API +-static void +-ffi_closure_raw_SYSV( +- ffi_raw_closure* closure) __attribute__((regparm(1))); +-#endif ++/* This function is jumped to by the trampoline */ + +-/*@-exportheader@*/ +-static inline +-void +-ffi_prep_incoming_args_SYSV( +- char* stack, +- void** rvalue, +- void** avalue, +- ffi_cif* cif) +-/*@=exportheader@*/ ++unsigned int FFI_HIDDEN ++ffi_closure_SYSV_inner (closure, respp, args) ++ffi_closure *closure; ++void **respp; ++void *args; + { +- register unsigned int i; +- register void** p_argv = avalue; +- register char* argp = stack; +- register ffi_type** p_arg; +- +- if (retval_on_stack(cif->rtype)) +- { +- *rvalue = *(void**)argp; +- argp += 4; +- } +- +- for (i = cif->nargs, p_arg = cif->arg_types; i > 0; i--, p_arg++, p_argv++) +- { +-// size_t z; +- +- /* Align if necessary */ +- if ((sizeof(int) - 1) & (unsigned)argp) +- argp = (char*)ALIGN(argp, sizeof(int)); +- +-// z = (*p_arg)->size; +- +- /* because we're little endian, this is what it turns into. */ +- *p_argv = (void*)argp; +- +- argp += (*p_arg)->size; +- } ++ // our various things... ++ ffi_cif *cif; ++ void **arg_area; ++ ++ cif = closure->cif; ++ arg_area = (void**) alloca (cif->nargs * sizeof (void*)); ++ ++ /* this call will initialize ARG_AREA, such that each ++ * element in that array points to the corresponding ++ * value on the stack; and if the function returns ++ * a structure, it will re-set RESP to point to the ++ * structure return address. */ ++ ++ ffi_prep_incoming_args_SYSV(args, respp, arg_area, cif); ++ ++ (closure->fun) (cif, *respp, arg_area, closure->user_data); ++ ++ return cif->flags; + } + +-/* This function is jumped to by the trampoline */ +-__attribute__((regparm(1))) + static void +-ffi_closure_SYSV( +- ffi_closure* closure) ++ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, void **avalue, ++ ffi_cif *cif) + { +- long double res; +- ffi_cif* cif = closure->cif; +- void** arg_area = (void**)alloca(cif->nargs * sizeof(void*)); +- void* resp = (void*)&res; +- void* args = __builtin_dwarf_cfa(); +- +- /* This call will initialize ARG_AREA, such that each +- element in that array points to the corresponding +- value on the stack; and if the function returns +- a structure, it will reset RESP to point to the +- structure return address. */ +- ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); +- +- (closure->fun)(cif, resp, arg_area, closure->user_data); +- +- /* now, do a generic return based on the value of rtype */ +- if (cif->flags == FFI_TYPE_INT) +- asm("movl (%0),%%eax" +- : : "r" (resp) : "eax"); +- else if (cif->flags == FFI_TYPE_FLOAT) +- asm("flds (%0)" +- : : "r" (resp) : "st"); +- else if (cif->flags == FFI_TYPE_DOUBLE) +- asm("fldl (%0)" +- : : "r" (resp) : "st", "st(1)"); +- else if (cif->flags == FFI_TYPE_LONGDOUBLE) +- asm("fldt (%0)" +- : : "r" (resp) : "st", "st(1)"); +- else if (cif->flags == FFI_TYPE_SINT64) +- asm("movl 0(%0),%%eax;" +- "movl 4(%0),%%edx" +- : : "r" (resp) +- : "eax", "edx"); +- +-#if defined(X86_WIN32) || defined(X86_DARWIN) +- else if (cif->flags == FFI_TYPE_SINT8) /* 1-byte struct */ +- asm("movsbl (%0),%%eax" +- : : "r" (resp) : "eax"); +- else if (cif->flags == FFI_TYPE_SINT16) /* 2-bytes struct */ +- asm("movswl (%0),%%eax" +- : : "r" (resp) : "eax"); +-#endif +- +- else if (cif->flags == FFI_TYPE_STRUCT) +- asm("lea -8(%ebp),%esp;" +- "pop %esi;" +- "pop %edi;" +- "pop %ebp;" +- "ret $4"); ++ register unsigned int i; ++ register void **p_argv; ++ register char *argp; ++ register ffi_type **p_arg; ++ ++ argp = stack; ++ ++ if ( cif->flags == FFI_TYPE_STRUCT ) { ++ *rvalue = *(void **) argp; ++ argp += 4; ++ } ++ ++ p_argv = avalue; ++ ++ for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) ++ { ++ size_t z; ++ ++ /* Align if necessary */ ++ if ((sizeof(int) - 1) & (unsigned) argp) { ++ argp = (char *) ALIGN(argp, sizeof(int)); ++ } ++ ++ z = (*p_arg)->size; ++ ++ /* because we're little endian, this is what it turns into. */ ++ ++ *p_argv = (void*) argp; ++ ++ p_argv++; ++ argp += z; ++ } ++ ++ return; + } + +- + /* How to make a trampoline. Derived from gcc/config/i386/i386.c. */ +-#define FFI_INIT_TRAMPOLINE(TRAMP, FUN, CTX) \ +- ({ \ +- unsigned char* __tramp = (unsigned char*)(TRAMP); \ +- unsigned int __fun = (unsigned int)(FUN); \ +- unsigned int __ctx = (unsigned int)(CTX); \ +- unsigned int __dis = __fun - ((unsigned int)__tramp + FFI_TRAMPOLINE_SIZE); \ +- *(unsigned char*)&__tramp[0] = 0xb8; \ +- *(unsigned int*)&__tramp[1] = __ctx; /* movl __ctx, %eax */ \ +- *(unsigned char*)&__tramp[5] = 0xe9; \ +- *(unsigned int*)&__tramp[6] = __dis; /* jmp __fun */ \ +- }) + ++#define FFI_INIT_TRAMPOLINE(TRAMP,FUN,CTX) \ ++({ unsigned char *__tramp = (unsigned char*)(TRAMP); \ ++unsigned int __fun = (unsigned int)(FUN); \ ++unsigned int __ctx = (unsigned int)(CTX); \ ++unsigned int __dis = __fun - (__ctx + FFI_TRAMPOLINE_SIZE); \ ++*(unsigned char*) &__tramp[0] = 0xb8; \ ++*(unsigned int*) &__tramp[1] = __ctx; /* movl __ctx, %eax */ \ ++*(unsigned char *) &__tramp[5] = 0xe9; \ ++*(unsigned int*) &__tramp[6] = __dis; /* jmp __fun */ \ ++}) ++ ++ + /* the cif must already be prep'ed */ + ffi_status +-ffi_prep_closure( +- ffi_closure* closure, +- ffi_cif* cif, +- void (*fun)(ffi_cif*,void*,void**,void*), +- void* user_data) ++ffi_prep_closure (ffi_closure* closure, ++ ffi_cif* cif, ++ void (*fun)(ffi_cif*,void*,void**,void*), ++ void *user_data) + { +-// FFI_ASSERT(cif->abi == FFI_SYSV); + if (cif->abi != FFI_SYSV) + return FFI_BAD_ABI; +- +- FFI_INIT_TRAMPOLINE(closure->tramp, &ffi_closure_SYSV, (void*)closure); +- +- closure->cif = cif; +- closure->user_data = user_data; +- closure->fun = fun; +- +- return FFI_OK; ++ ++ FFI_INIT_TRAMPOLINE (&closure->tramp[0], \ ++ &ffi_closure_SYSV, \ ++ (void*)closure); ++ ++ closure->cif = cif; ++ closure->user_data = user_data; ++ closure->fun = fun; ++ ++ return FFI_OK; + } + + /* ------- Native raw API support -------------------------------- */ + + #if !FFI_NO_RAW_API + +-__attribute__((regparm(1))) +-static void +-ffi_closure_raw_SYSV( +- ffi_raw_closure* closure) +-{ +- long double res; +- ffi_raw* raw_args = (ffi_raw*)__builtin_dwarf_cfa(); +- ffi_cif* cif = closure->cif; +- unsigned short rtype = cif->flags; +- void* resp = (void*)&res; +- +- (closure->fun)(cif, resp, raw_args, closure->user_data); +- +- /* now, do a generic return based on the value of rtype */ +- if (rtype == FFI_TYPE_INT) +- asm("movl (%0),%%eax" +- : : "r" (resp) : "eax"); +- else if (rtype == FFI_TYPE_FLOAT) +- asm("flds (%0)" +- : : "r" (resp) : "st"); +- else if (rtype == FFI_TYPE_DOUBLE) +- asm("fldl (%0)" +- : : "r" (resp) : "st", "st(1)"); +- else if (rtype == FFI_TYPE_LONGDOUBLE) +- asm("fldt (%0)" +- : : "r" (resp) : "st", "st(1)"); +- else if (rtype == FFI_TYPE_SINT64) +- asm("movl 0(%0),%%eax;" +- "movl 4(%0),%%edx" +- : : "r" (resp) : "eax", "edx"); +-} +- + ffi_status +-ffi_prep_raw_closure( +- ffi_raw_closure* closure, +- ffi_cif* cif, +- void (*fun)(ffi_cif*,void*,ffi_raw*,void*), +- void* user_data) ++ffi_prep_raw_closure_loc (ffi_raw_closure* closure, ++ ffi_cif* cif, ++ void (*fun)(ffi_cif*,void*,ffi_raw*,void*), ++ void *user_data, ++ void *codeloc) + { +-// FFI_ASSERT (cif->abi == FFI_SYSV); +- if (cif->abi != FFI_SYSV) +- return FFI_BAD_ABI; +- +- int i; +- +-/* We currently don't support certain kinds of arguments for raw +- closures. This should be implemented by a separate assembly language +- routine, since it would require argument processing, something we +- don't do now for performance. */ +- for (i = cif->nargs - 1; i >= 0; i--) +- { +- FFI_ASSERT(cif->arg_types[i]->type != FFI_TYPE_STRUCT); +- FFI_ASSERT(cif->arg_types[i]->type != FFI_TYPE_LONGDOUBLE); +- } +- +- FFI_INIT_TRAMPOLINE(closure->tramp, &ffi_closure_raw_SYSV, (void*)closure); +- +- closure->cif = cif; +- closure->user_data = user_data; +- closure->fun = fun; +- +- return FFI_OK; ++ int i; ++ ++ FFI_ASSERT (cif->abi == FFI_SYSV); ++ ++ // we currently don't support certain kinds of arguments for raw ++ // closures. This should be implemented by a separate assembly language ++ // routine, since it would require argument processing, something we ++ // don't do now for performance. ++ ++ for (i = cif->nargs-1; i >= 0; i--) ++ { ++ FFI_ASSERT (cif->arg_types[i]->type != FFI_TYPE_STRUCT); ++ FFI_ASSERT (cif->arg_types[i]->type != FFI_TYPE_LONGDOUBLE); ++ } ++ ++ ++ FFI_INIT_TRAMPOLINE (&closure->tramp[0], &ffi_closure_raw_SYSV, ++ codeloc); ++ ++ closure->cif = cif; ++ closure->user_data = user_data; ++ closure->fun = fun; ++ ++ return FFI_OK; + } + + static void +-ffi_prep_args_raw( +- char* stack, +- extended_cif* ecif) ++ffi_prep_args_raw(char *stack, extended_cif *ecif) + { +- memcpy(stack, ecif->avalue, ecif->cif->bytes); ++ memcpy (stack, ecif->avalue, ecif->cif->bytes); + } + +-/* We borrow this routine from libffi (it must be changed, though, to +- actually call the function passed in the first argument. as of +- libffi-1.20, this is not the case.) */ +-//extern void +-//ffi_call_SYSV( +-// void (*)(char *, extended_cif *), +-///*@out@*/ extended_cif* , +-// unsigned , +-// unsigned , +-//*@out@*/ unsigned* , +-// void (*fn)()); ++/* we borrow this routine from libffi (it must be changed, though, to ++ * actually call the function passed in the first argument. as of ++ * libffi-1.20, this is not the case.) ++ */ + ++extern void ++ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, unsigned, ++ unsigned, unsigned *, void (*fn)()); ++ + #ifdef X86_WIN32 + extern void +-ffi_call_STDCALL( +- void (*)(char *, extended_cif *), +-/*@out@*/ extended_cif* , +- unsigned , +- unsigned , +-/*@out@*/ unsigned* , +- void (*fn)()); +-#endif // X86_WIN32 ++ffi_call_STDCALL(void (*)(char *, extended_cif *), extended_cif *, unsigned, ++ unsigned, unsigned *, void (*fn)()); ++#endif /* X86_WIN32 */ + + void +-ffi_raw_call( +-/*@dependent@*/ ffi_cif* cif, +- void (*fn)(), +-/*@out@*/ void* rvalue, +-/*@dependent@*/ ffi_raw* fake_avalue) ++ffi_raw_call(ffi_cif *cif, void (*fn)(), void *rvalue, ffi_raw *fake_avalue) + { +- extended_cif ecif; +- void **avalue = (void **)fake_avalue; +- +- ecif.cif = cif; +- ecif.avalue = avalue; +- +- /* If the return value is a struct and we don't have a return +- value address then we need to make one */ +- if ((rvalue == NULL) && retval_on_stack(cif->rtype)) +- { +- /*@-sysunrecog@*/ +- ecif.rvalue = alloca(cif->rtype->size); +- /*@=sysunrecog@*/ +- } +- else +- ecif.rvalue = rvalue; +- +- switch (cif->abi) +- { +- case FFI_SYSV: +- /*@-usedef@*/ +- ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, +- cif->flags, ecif.rvalue, fn); +- /*@=usedef@*/ +- break; ++ extended_cif ecif; ++ void **avalue = (void **)fake_avalue; ++ ++ ecif.cif = cif; ++ ecif.avalue = avalue; ++ ++ /* If the return value is a struct and we don't have a return */ ++ /* value address then we need to make one */ ++ ++ if ((rvalue == NULL) && ++ (cif->rtype->type == FFI_TYPE_STRUCT)) ++ { ++ ecif.rvalue = alloca(cif->rtype->size); ++ } ++ else ++ ecif.rvalue = rvalue; ++ ++ ++ switch (cif->abi) ++ { ++ case FFI_SYSV: ++ ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags, ++ ecif.rvalue, fn); ++ break; + #ifdef X86_WIN32 +- case FFI_STDCALL: +- /*@-usedef@*/ +- ffi_call_STDCALL(ffi_prep_args_raw, &ecif, cif->bytes, +- cif->flags, ecif.rvalue, fn); +- /*@=usedef@*/ +- break; ++ case FFI_STDCALL: ++ ffi_call_STDCALL(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags, ++ ecif.rvalue, fn); ++ break; + #endif /* X86_WIN32 */ +- default: +- FFI_ASSERT(0); +- break; ++ default: ++ FFI_ASSERT(0); ++ break; + } + } + +-#endif // !FFI_NO_RAW_API +-//#endif // !__x86_64__ +-#endif // __i386__ ++#endif ++#endif // __i386__ +\ No newline at end of file +Index: Modules/_ctypes/_ctypes.c +=================================================================== +--- Modules/_ctypes/_ctypes.c (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/_ctypes.c (.../branches/release31-maint) (Revision 76056) +@@ -936,8 +936,11 @@ + { + StgDictObject *typedict; + +- if (value == Py_None) +- return PyLong_FromLong(0); /* NULL pointer */ ++ if (value == Py_None) { ++ /* ConvParam will convert to a NULL pointer later */ ++ Py_INCREF(value); ++ return value; ++ } + + typedict = PyType_stgdict(type); + assert(typedict); /* Cannot be NULL for pointer types */ +@@ -1862,16 +1865,15 @@ + } + fmt = _ctypes_get_fielddesc(proto_str); + if (fmt == NULL) { +- Py_DECREF((PyObject *)result); + PyErr_Format(PyExc_ValueError, + "_type_ '%s' not supported", proto_str); +- return NULL; ++ goto error; + } + + stgdict = (StgDictObject *)PyObject_CallObject( + (PyObject *)&PyCStgDict_Type, NULL); + if (!stgdict) +- return NULL; ++ goto error; + + stgdict->ffi_type_pointer = *fmt->pffi_type; + stgdict->align = fmt->pffi_type->alignment; +@@ -1886,6 +1888,7 @@ + #endif + if (stgdict->format == NULL) { + Py_DECREF(result); ++ Py_DECREF(proto); + Py_DECREF((PyObject *)stgdict); + return NULL; + } +@@ -3928,90 +3931,94 @@ + /* + Struct_Type + */ ++/* ++ This function is called to initialize a Structure or Union with positional ++ arguments. It calls itself recursively for all Structure or Union base ++ classes, then retrieves the _fields_ member to associate the argument ++ position with the correct field name. ++ ++ Returns -1 on error, or the index of next argument on success. ++ */ + static int +-IBUG(char *msg) ++_init_pos_args(PyObject *self, PyTypeObject *type, ++ PyObject *args, PyObject *kwds, ++ int index) + { +- PyErr_Format(PyExc_RuntimeError, +- "inconsistent state in CDataObject (%s)", msg); +- return -1; ++ StgDictObject *dict; ++ PyObject *fields; ++ int i; ++ ++ if (PyType_stgdict((PyObject *)type->tp_base)) { ++ index = _init_pos_args(self, type->tp_base, ++ args, kwds, ++ index); ++ if (index == -1) ++ return -1; ++ } ++ ++ dict = PyType_stgdict((PyObject *)type); ++ fields = PyDict_GetItemString((PyObject *)dict, "_fields_"); ++ if (fields == NULL) ++ return index; ++ ++ for (i = 0; ++ i < dict->length && (i+index) < PyTuple_GET_SIZE(args); ++ ++i) { ++ PyObject *pair = PySequence_GetItem(fields, i); ++ PyObject *name, *val; ++ int res; ++ if (!pair) ++ return -1; ++ name = PySequence_GetItem(pair, 0); ++ if (!name) { ++ Py_DECREF(pair); ++ return -1; ++ } ++ val = PyTuple_GET_ITEM(args, i + index); ++ if (kwds && PyDict_GetItem(kwds, name)) { ++ char *field = PyBytes_AsString(name); ++ if (field == NULL) { ++ PyErr_Clear(); ++ field = "???"; ++ } ++ PyErr_Format(PyExc_TypeError, ++ "duplicate values for field '%s'", ++ field); ++ Py_DECREF(pair); ++ Py_DECREF(name); ++ return -1; ++ } ++ ++ res = PyObject_SetAttr(self, name, val); ++ Py_DECREF(pair); ++ Py_DECREF(name); ++ if (res == -1) ++ return -1; ++ } ++ return index + dict->length; + } + + static int + Struct_init(PyObject *self, PyObject *args, PyObject *kwds) + { +- int i; +- PyObject *fields; +- + /* Optimization possible: Store the attribute names _fields_[x][0] + * in C accessible fields somewhere ? + */ +- +-/* Check this code again for correctness! */ +- + if (!PyTuple_Check(args)) { + PyErr_SetString(PyExc_TypeError, + "args not a tuple?"); + return -1; + } + if (PyTuple_GET_SIZE(args)) { +- fields = PyObject_GetAttrString(self, "_fields_"); +- if (!fields) { +- PyErr_Clear(); +- fields = PyTuple_New(0); +- if (!fields) +- return -1; +- } +- +- if (PyTuple_GET_SIZE(args) > PySequence_Length(fields)) { +- Py_DECREF(fields); ++ int res = _init_pos_args(self, Py_TYPE(self), ++ args, kwds, 0); ++ if (res == -1) ++ return -1; ++ if (res < PyTuple_GET_SIZE(args)) { + PyErr_SetString(PyExc_TypeError, + "too many initializers"); + return -1; + } +- +- for (i = 0; i < PyTuple_GET_SIZE(args); ++i) { +- PyObject *pair = PySequence_GetItem(fields, i); +- PyObject *name; +- PyObject *val; +- if (!pair) { +- Py_DECREF(fields); +- return IBUG("_fields_[i] failed"); +- } +- +- name = PySequence_GetItem(pair, 0); +- if (!name) { +- Py_DECREF(pair); +- Py_DECREF(fields); +- return IBUG("_fields_[i][0] failed"); +- } +- +- if (kwds && PyDict_GetItem(kwds, name)) { +- char *field = PyBytes_AsString(name); +- if (field == NULL) { +- PyErr_Clear(); +- field = "???"; +- } +- PyErr_Format(PyExc_TypeError, +- "duplicate values for field %s", +- field); +- Py_DECREF(pair); +- Py_DECREF(name); +- Py_DECREF(fields); +- return -1; +- } +- +- val = PyTuple_GET_ITEM(args, i); +- if (-1 == PyObject_SetAttr(self, name, val)) { +- Py_DECREF(pair); +- Py_DECREF(name); +- Py_DECREF(fields); +- return -1; +- } +- +- Py_DECREF(name); +- Py_DECREF(pair); +- } +- Py_DECREF(fields); + } + + if (kwds) { +Index: Modules/_ctypes/cfield.c +=================================================================== +--- Modules/_ctypes/cfield.c (.../tags/r311) (Revision 76056) ++++ Modules/_ctypes/cfield.c (.../branches/release31-maint) (Revision 76056) +@@ -1428,7 +1428,8 @@ + return NULL; + } + #endif +- return PyUnicode_FromString(*(char **)ptr); ++ return PyBytes_FromStringAndSize(*(char **)ptr, ++ strlen(*(char **)ptr)); + } else { + Py_INCREF(Py_None); + return Py_None; +Index: Modules/_io/fileio.c +=================================================================== +--- Modules/_io/fileio.c (.../tags/r311) (Revision 76056) ++++ Modules/_io/fileio.c (.../branches/release31-maint) (Revision 76056) +@@ -45,10 +45,10 @@ + typedef struct { + PyObject_HEAD + int fd; +- unsigned readable : 1; +- unsigned writable : 1; +- int seekable : 2; /* -1 means unknown */ +- int closefd : 1; ++ unsigned int readable : 1; ++ unsigned int writable : 1; ++ signed int seekable : 2; /* -1 means unknown */ ++ unsigned int closefd : 1; + PyObject *weakreflist; + PyObject *dict; + } fileio; +Index: Modules/_io/textio.c +=================================================================== +--- Modules/_io/textio.c (.../tags/r311) (Revision 76056) ++++ Modules/_io/textio.c (.../branches/release31-maint) (Revision 76056) +@@ -190,9 +190,9 @@ + PyObject_HEAD + PyObject *decoder; + PyObject *errors; +- int pendingcr:1; +- int translate:1; +- unsigned int seennl:3; ++ signed int pendingcr: 1; ++ signed int translate: 1; ++ unsigned int seennl: 3; + } nldecoder_object; + + static int +@@ -1213,11 +1213,18 @@ + static int + _textiowrapper_writeflush(textio *self) + { +- PyObject *b, *ret; ++ PyObject *pending, *b, *ret; + + if (self->pending_bytes == NULL) + return 0; +- b = _PyBytes_Join(_PyIO_empty_bytes, self->pending_bytes); ++ ++ pending = self->pending_bytes; ++ Py_INCREF(pending); ++ self->pending_bytes_count = 0; ++ Py_CLEAR(self->pending_bytes); ++ ++ b = _PyBytes_Join(_PyIO_empty_bytes, pending); ++ Py_DECREF(pending); + if (b == NULL) + return -1; + ret = PyObject_CallMethodObjArgs(self->buffer, +@@ -1226,8 +1233,6 @@ + if (ret == NULL) + return -1; + Py_DECREF(ret); +- Py_CLEAR(self->pending_bytes); +- self->pending_bytes_count = 0; + return 0; + } + +Index: Modules/socketmodule.c +=================================================================== +--- Modules/socketmodule.c (.../tags/r311) (Revision 76056) ++++ Modules/socketmodule.c (.../branches/release31-maint) (Revision 76056) +@@ -3890,9 +3890,14 @@ + flags = flowinfo = scope_id = 0; + if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags)) + return NULL; +- if (!PyArg_ParseTuple(sa, "si|ii", +- &hostp, &port, &flowinfo, &scope_id)) ++ if (!PyTuple_Check(sa)) { ++ PyErr_SetString(PyExc_TypeError, ++ "getnameinfo() argument 1 must be a tuple"); + return NULL; ++ } ++ if (!PyArg_ParseTuple(sa, "si|ii", ++ &hostp, &port, &flowinfo, &scope_id)) ++ return NULL; + PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; +@@ -3914,9 +3919,7 @@ + switch (res->ai_family) { + case AF_INET: + { +- char *t1; +- int t2; +- if (PyArg_ParseTuple(sa, "si", &t1, &t2) == 0) { ++ if (PyTuple_GET_SIZE(sa) != 2) { + PyErr_SetString(socket_error, + "IPv4 sockaddr must be 2 tuple"); + goto fail; +Index: Modules/_localemodule.c +=================================================================== +--- Modules/_localemodule.c (.../tags/r311) (Revision 76056) ++++ Modules/_localemodule.c (.../branches/release31-maint) (Revision 76056) +@@ -9,6 +9,7 @@ + + ******************************************************************/ + ++#define PY_SSIZE_T_CLEAN + #include "Python.h" + + #include +@@ -32,10 +33,6 @@ + #include + #endif + +-#if defined(__APPLE__) +-#include +-#endif +- + #if defined(MS_WINDOWS) + #define WIN32_LEAN_AND_MEAN + #include +@@ -284,7 +281,9 @@ + wchar_t *s, *buf = NULL; + size_t n1, n2; + PyObject *result = NULL; ++#ifndef HAVE_USABLE_WCHAR_T + Py_ssize_t i; ++#endif + + if (!PyArg_ParseTuple(args, "u#:strxfrm", &s0, &n0)) + return NULL; +@@ -319,7 +318,7 @@ + result = PyUnicode_FromWideChar(buf, n2); + exit: + if (buf) PyMem_Free(buf); +-#ifdef HAVE_USABLE_WCHAR_T ++#ifndef HAVE_USABLE_WCHAR_T + PyMem_Free(s); + #endif + return result; +Index: Modules/readline.c +=================================================================== +--- Modules/readline.c (.../tags/r311) (Revision 76056) ++++ Modules/readline.c (.../branches/release31-maint) (Revision 76056) +@@ -758,6 +758,12 @@ + static char ** + flex_complete(char *text, int start, int end) + { ++#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER ++ rl_completion_append_character ='\0'; ++#endif ++#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND ++ rl_completion_suppress_append = 0; ++#endif + Py_XDECREF(begidx); + Py_XDECREF(endidx); + begidx = PyLong_FromLong((long) start); +@@ -800,9 +806,6 @@ + rl_completer_word_break_characters = + strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?"); + /* All nonalphanums except '.' */ +-#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER +- rl_completion_append_character ='\0'; +-#endif + + begidx = PyLong_FromLong(0L); + endidx = PyLong_FromLong(0L); +Index: Modules/_struct.c +=================================================================== +--- Modules/_struct.c (.../tags/r311) (Revision 76056) ++++ Modules/_struct.c (.../branches/release31-maint) (Revision 76056) +@@ -1900,18 +1900,20 @@ + PyDoc_STRVAR(module_doc, + "Functions to convert between Python values and C structs.\n\ + Python bytes objects are used to hold the data representing the C struct\n\ +-and also as format strings to describe the layout of data in the C struct.\n\ ++and also as format strings (explained below) to describe the layout of data\n\ ++in the C struct.\n\ + \n\ + The optional first format char indicates byte order, size and alignment:\n\ +- @: native order, size & alignment (default)\n\ +- =: native order, std. size & alignment\n\ +- <: little-endian, std. size & alignment\n\ +- >: big-endian, std. size & alignment\n\ +- !: same as >\n\ ++ @: native order, size & alignment (default)\n\ ++ =: native order, std. size & alignment\n\ ++ <: little-endian, std. size & alignment\n\ ++ >: big-endian, std. size & alignment\n\ ++ !: same as >\n\ + \n\ + The remaining chars indicate types of args and must match exactly;\n\ + these can be preceded by a decimal repeat count:\n\ + x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\ ++ ?: _Bool (requires C99; if not available, char is used instead)\n\ + h:short; H:unsigned short; i:int; I:unsigned int;\n\ + l:long; L:unsigned long; f:float; d:double.\n\ + Special cases (preceding decimal count indicates length):\n\ +Index: Modules/signalmodule.c +=================================================================== +--- Modules/signalmodule.c (.../tags/r311) (Revision 76056) ++++ Modules/signalmodule.c (.../branches/release31-maint) (Revision 76056) +@@ -853,7 +853,7 @@ + #endif + + /* +- * The is_stripped variable is meant to speed up the calls to ++ * The is_tripped variable is meant to speed up the calls to + * PyErr_CheckSignals (both directly or via pending calls) when no + * signal has arrived. This variable is set to 1 when a signal arrives + * and it is set to 0 here, when we know some signals arrived. This way +Index: Modules/posixmodule.c +=================================================================== +--- Modules/posixmodule.c (.../tags/r311) (Revision 76056) ++++ Modules/posixmodule.c (.../branches/release31-maint) (Revision 76056) +@@ -3831,11 +3831,21 @@ + static PyObject * + posix_fork1(PyObject *self, PyObject *noargs) + { +- pid_t pid = fork1(); ++ pid_t pid; ++ int result; ++ _PyImport_AcquireLock(); ++ pid = fork1(); ++ result = _PyImport_ReleaseLock(); + if (pid == -1) + return posix_error(); + if (pid == 0) + PyOS_AfterFork(); ++ if (result < 0) { ++ /* Don't clobber the OSError if the fork failed. */ ++ PyErr_SetString(PyExc_RuntimeError, ++ "not holding the import lock"); ++ return NULL; ++ } + return PyLong_FromPid(pid); + } + #endif +@@ -3850,11 +3860,21 @@ + static PyObject * + posix_fork(PyObject *self, PyObject *noargs) + { +- pid_t pid = fork(); ++ pid_t pid; ++ int result; ++ _PyImport_AcquireLock(); ++ pid = fork(); ++ result = _PyImport_ReleaseLock(); + if (pid == -1) + return posix_error(); + if (pid == 0) + PyOS_AfterFork(); ++ if (result < 0) { ++ /* Don't clobber the OSError if the fork failed. */ ++ PyErr_SetString(PyExc_RuntimeError, ++ "not holding the import lock"); ++ return NULL; ++ } + return PyLong_FromPid(pid); + } + #endif +@@ -3957,14 +3977,22 @@ + static PyObject * + posix_forkpty(PyObject *self, PyObject *noargs) + { +- int master_fd = -1; ++ int master_fd = -1, result; + pid_t pid; + ++ _PyImport_AcquireLock(); + pid = forkpty(&master_fd, NULL, NULL, NULL); ++ result = _PyImport_ReleaseLock(); + if (pid == -1) + return posix_error(); + if (pid == 0) + PyOS_AfterFork(); ++ if (result < 0) { ++ /* Don't clobber the OSError if the fork failed. */ ++ PyErr_SetString(PyExc_RuntimeError, ++ "not holding the import lock"); ++ return NULL; ++ } + return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd); + } + #endif +Index: Modules/_cursesmodule.c +=================================================================== +--- Modules/_cursesmodule.c (.../tags/r311) (Revision 76056) ++++ Modules/_cursesmodule.c (.../branches/release31-maint) (Revision 76056) +@@ -890,14 +890,17 @@ + /* getch() returns ERR in nodelay mode */ + PyErr_SetString(PyCursesError, "no input"); + return NULL; +- } else if (rtn<=255) ++ } else if (rtn<=255) { + return Py_BuildValue("C", rtn); +- else ++ } else { ++ const char *knp; + #if defined(__NetBSD__) +- return PyUnicode_FromString(unctrl(rtn)); ++ knp = unctrl(rtn); + #else +- return PyUnicode_FromString((const char *)keyname(rtn)); ++ knp = keyname(rtn); + #endif ++ return PyUnicode_FromString((knp == NULL) ? "" : knp); ++ } + } + + static PyObject * +Index: Modules/_threadmodule.c +=================================================================== +--- Modules/_threadmodule.c (.../tags/r311) (Revision 76056) ++++ Modules/_threadmodule.c (.../branches/release31-maint) (Revision 76056) +@@ -239,7 +239,6 @@ + static int + local_clear(localobject *self) + { +- Py_CLEAR(self->key); + Py_CLEAR(self->args); + Py_CLEAR(self->kw); + Py_CLEAR(self->dict); +@@ -261,6 +260,7 @@ + PyDict_DelItem(tstate->dict, self->key); + } + ++ Py_XDECREF(self->key); + local_clear(self); + Py_TYPE(self)->tp_free((PyObject*)self); + } +Index: Modules/main.c +=================================================================== +--- Modules/main.c (.../tags/r311) (Revision 76056) ++++ Modules/main.c (.../branches/release31-maint) (Revision 76056) +@@ -253,33 +253,6 @@ + } + + +-/* Wait until threading._shutdown completes, provided +- the threading module was imported in the first place. +- The shutdown routine will wait until all non-daemon +- "threading" threads have completed. */ +-#include "abstract.h" +-static void +-WaitForThreadShutdown(void) +-{ +-#ifdef WITH_THREAD +- PyObject *result; +- PyThreadState *tstate = PyThreadState_GET(); +- PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, +- "threading"); +- if (threading == NULL) { +- /* threading not imported */ +- PyErr_Clear(); +- return; +- } +- result = PyObject_CallMethod(threading, "_shutdown", ""); +- if (result == NULL) +- PyErr_WriteUnraisable(threading); +- else +- Py_DECREF(result); +- Py_DECREF(threading); +-#endif +-} +- + /* Main program */ + + int +@@ -647,8 +620,6 @@ + sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; + } + +- WaitForThreadShutdown(); +- + Py_Finalize(); + + #ifdef __INSURE__ +Index: Modules/itertoolsmodule.c +=================================================================== +--- Modules/itertoolsmodule.c (.../tags/r311) (Revision 76056) ++++ Modules/itertoolsmodule.c (.../branches/release31-maint) (Revision 76056) +@@ -3344,71 +3344,73 @@ + static PyObject * + zip_longest_next(ziplongestobject *lz) + { +- Py_ssize_t i; +- Py_ssize_t tuplesize = lz->tuplesize; +- PyObject *result = lz->result; +- PyObject *it; +- PyObject *item; +- PyObject *olditem; ++ Py_ssize_t i; ++ Py_ssize_t tuplesize = lz->tuplesize; ++ PyObject *result = lz->result; ++ PyObject *it; ++ PyObject *item; ++ PyObject *olditem; + +- if (tuplesize == 0) +- return NULL; ++ if (tuplesize == 0) ++ return NULL; + if (lz->numactive == 0) + return NULL; +- if (Py_REFCNT(result) == 1) { +- Py_INCREF(result); +- for (i=0 ; i < tuplesize ; i++) { +- it = PyTuple_GET_ITEM(lz->ittuple, i); ++ if (Py_REFCNT(result) == 1) { ++ Py_INCREF(result); ++ for (i=0 ; i < tuplesize ; i++) { ++ it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { +- item = (*Py_TYPE(it)->tp_iternext)(it); ++ item = PyIter_Next(it); + if (item == NULL) { +- lz->numactive -= 1; +- if (lz->numactive == 0) { ++ lz->numactive -= 1; ++ if (lz->numactive == 0 || PyErr_Occurred()) { ++ lz->numactive = 0; + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); +- item = lz->fillvalue; ++ item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } +- olditem = PyTuple_GET_ITEM(result, i); +- PyTuple_SET_ITEM(result, i, item); +- Py_DECREF(olditem); +- } +- } else { +- result = PyTuple_New(tuplesize); +- if (result == NULL) +- return NULL; +- for (i=0 ; i < tuplesize ; i++) { +- it = PyTuple_GET_ITEM(lz->ittuple, i); ++ olditem = PyTuple_GET_ITEM(result, i); ++ PyTuple_SET_ITEM(result, i, item); ++ Py_DECREF(olditem); ++ } ++ } else { ++ result = PyTuple_New(tuplesize); ++ if (result == NULL) ++ return NULL; ++ for (i=0 ; i < tuplesize ; i++) { ++ it = PyTuple_GET_ITEM(lz->ittuple, i); + if (it == NULL) { + Py_INCREF(lz->fillvalue); + item = lz->fillvalue; + } else { +- item = (*Py_TYPE(it)->tp_iternext)(it); ++ item = PyIter_Next(it); + if (item == NULL) { +- lz->numactive -= 1; +- if (lz->numactive == 0) { ++ lz->numactive -= 1; ++ if (lz->numactive == 0 || PyErr_Occurred()) { ++ lz->numactive = 0; + Py_DECREF(result); + return NULL; + } else { + Py_INCREF(lz->fillvalue); +- item = lz->fillvalue; ++ item = lz->fillvalue; + PyTuple_SET_ITEM(lz->ittuple, i, NULL); + Py_DECREF(it); + } + } + } +- PyTuple_SET_ITEM(result, i, item); +- } +- } +- return result; ++ PyTuple_SET_ITEM(result, i, item); ++ } ++ } ++ return result; + } + + PyDoc_STRVAR(zip_longest_doc, +Index: pyconfig.h.in +=================================================================== +--- pyconfig.h.in (.../tags/r311) (Revision 76056) ++++ pyconfig.h.in (.../branches/release31-maint) (Revision 76056) +@@ -5,6 +5,9 @@ + #define Py_PYCONFIG_H + + ++/* Define if building universal (internal helper macro) */ ++#undef AC_APPLE_UNIVERSAL_BUILD ++ + /* Define for AIX if your compiler is a genuine IBM xlC/xlC_r and you want + support for AIX C++ shared extension modules. */ + #undef AIX_GENUINE_CPLUSPLUS +@@ -521,6 +524,9 @@ + /* Define if you have readline 4.2 */ + #undef HAVE_RL_COMPLETION_MATCHES + ++/* Define if you have rl_completion_suppress_append */ ++#undef HAVE_RL_COMPLETION_SUPPRESS_APPEND ++ + /* Define if you have readline 4.0 */ + #undef HAVE_RL_PRE_INPUT_HOOK + +@@ -995,6 +1001,28 @@ + /* Define if you want to use computed gotos in ceval.c. */ + #undef USE_COMPUTED_GOTOS + ++/* Enable extensions on AIX 3, Interix. */ ++#ifndef _ALL_SOURCE ++# undef _ALL_SOURCE ++#endif ++/* Enable GNU extensions on systems that have them. */ ++#ifndef _GNU_SOURCE ++# undef _GNU_SOURCE ++#endif ++/* Enable threading extensions on Solaris. */ ++#ifndef _POSIX_PTHREAD_SEMANTICS ++# undef _POSIX_PTHREAD_SEMANTICS ++#endif ++/* Enable extensions on HP NonStop. */ ++#ifndef _TANDEM_SOURCE ++# undef _TANDEM_SOURCE ++#endif ++/* Enable general extensions on Solaris. */ ++#ifndef __EXTENSIONS__ ++# undef __EXTENSIONS__ ++#endif ++ ++ + /* Define if a va_list is an array of some kind */ + #undef VA_LIST_IS_ARRAY + +@@ -1032,20 +1060,21 @@ + /* Define to profile with the Pentium timestamp counter */ + #undef WITH_TSC + +-/* Define to 1 if your processor stores words with the most significant byte +- first (like Motorola and SPARC, unlike Intel and VAX). */ +-#undef WORDS_BIGENDIAN ++/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most ++ significant byte first (like Motorola and SPARC, unlike Intel). */ ++#if defined AC_APPLE_UNIVERSAL_BUILD ++# if defined __BIG_ENDIAN__ ++# define WORDS_BIGENDIAN 1 ++# endif ++#else ++# ifndef WORDS_BIGENDIAN ++# undef WORDS_BIGENDIAN ++# endif ++#endif + + /* Define if arithmetic is subject to x87-style double rounding issue */ + #undef X87_DOUBLE_ROUNDING + +-/* Define to 1 if on AIX 3. +- System headers sometimes define this. +- We just want to avoid a redefinition error message. */ +-#ifndef _ALL_SOURCE +-# undef _ALL_SOURCE +-#endif +- + /* Define on OpenBSD to activate all library features */ + #undef _BSD_SOURCE + +@@ -1064,15 +1093,25 @@ + /* This must be defined on some systems to enable large file support. */ + #undef _LARGEFILE_SOURCE + ++/* Define to 1 if on MINIX. */ ++#undef _MINIX ++ + /* Define on NetBSD to activate all library features */ + #undef _NETBSD_SOURCE + + /* Define _OSF_SOURCE to get the makedev macro. */ + #undef _OSF_SOURCE + ++/* Define to 2 if the system does not provide POSIX.1 features except with ++ this defined. */ ++#undef _POSIX_1_SOURCE ++ + /* Define to activate features from IEEE Stds 1003.1-2001 */ + #undef _POSIX_C_SOURCE + ++/* Define to 1 if you need to in order for `stat' and other things to work. */ ++#undef _POSIX_SOURCE ++ + /* Define if you have POSIX threads, and your system does not define that. */ + #undef _POSIX_THREADS + +@@ -1080,12 +1119,12 @@ + #undef _REENTRANT + + /* Define for Solaris 2.5.1 so the uint32_t typedef from , +- , or is not used. If the typedef was allowed, the ++ , or is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ + #undef _UINT32_T + + /* Define for Solaris 2.5.1 so the uint64_t typedef from , +- , or is not used. If the typedef was allowed, the ++ , or is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ + #undef _UINT64_T + + +Eigenschaftsänderungen: . +___________________________________________________________________ +Geändert: svnmerge-blocked + - /python/branches/py3k:73580-73582,73593-73594,73597,73604,73611-73613,73616-73617,73620-73622,73628,73635,73648-73651,73655,73657,73664,73678,73680,73687,73700,73716,73719,73729-73734,73737,73739-73740,73746,73759,73764,73777,73780,73803,73807,73817,73832,73843-73844,73853,73855,73860,73866,73886,73890,73893-73894,73896,73903,73909,73928,73936,73950,73956,73978,73980,73983,73992-73993,73996,74003-74004,74009,74012-74013,74015-74018,74026,74030,74035,74049-74050,74053,74059-74061,74064,74066,74068,74071,74082,74090,74096,74102-74103,74106,74110,74120,74124-74125,74129,74132-74133,74151,74156,74174,74191,74195,74198-74199,74202,74221,74236-74237,74242,74244,74257,74263,74271,74283,74313 + + /python/branches/py3k:73580-73582,73593-73594,73597,73604,73611-73613,73616-73617,73620-73622,73628,73635,73648-73651,73655,73657,73664,73678,73680,73687,73700,73716,73719,73729-73734,73737,73739-73740,73746,73759,73764,73777,73780,73803,73807,73817,73832,73843-73844,73853,73855,73860,73866,73886,73890,73893-73894,73896,73903,73909,73928,73936,73950,73956,73978,73980,73983,73992-73993,73996,74003-74004,74009,74012-74013,74015-74018,74026,74030,74035,74049-74050,74053,74059-74061,74064,74066,74068,74071,74082,74090,74096,74102-74103,74106,74110,74120,74124-74125,74129,74132-74133,74151,74156,74174,74191,74195,74198-74199,74202,74221,74236-74237,74242,74244,74257,74263,74271,74283,74313,74461,74494,74496,74504,74528-74529,74573,74577,74580,74611,74623,74628-74630,74646,74648-74649,74654,74659,74661,74669,74703,74725,74743-74744,74751,74826,74834,74851,74856,74858,74875,74897,74910,74914,74927,74939,75005,75028,75030,75045,75051,75078-75079,75086,75093,75113,75118-75119,75158,75167,75173,75177,75194,75198,75242-75245,75306,75311,75345,75347,75349,75369,75435,75439,75448,75451,75455,75471,75493,75495-75496,75504,75508,75512-75513,75522,75526,75556,75622,75625,75652,75656,75661,75665,75667-75668,75673,75676,75698,75709-75710,75712,75715-75716,75719,75721,75723,75732-75733,75737-75738,75740-75741,75744,75746,75834,75845,75847,75873,75895,75903,75937,75997 +Geändert: svnmerge-integrated + - /python/branches/py3k:1-73579,73583-73588,73590,73592,73595-73596,73598-73603,73605-73610,73614-73615,73618-73619,73623-73625,73627,73630-73634,73636-73638,73640-73644,73652-73654,73656,73658-73663,73665-73675,73677,73679,73681-73686,73688-73699,73701-73715,73717-73718,73720-73728,73735-73736,73738,73741,73743-73745,73747-73758,73760-73763,73765-73776,73778-73779,73781-73802,73804-73806,73808-73816,73818-73819,73821-73823,73828,73833-73842,73846-73852,73854,73856-73857,73862-73865,73867-73872,73874,73882,73913,73917-73919,73923,73934,73941-73949,73951-73955,73957-73960,73962-73977,73979,73981-73982,73984-73986,73988-73991,73994-73995,73997-73998,74000-74002,74005-74008,74010-74011,74014,74019-74025,74027-74029,74031-74034,74038-74040,74042-74044,74046-74048,74051-74052,74054-74058,74062-74063,74065,74067,74069,74072,74074-74081,74083,74085-74089,74091-74095,74098,74100,74104-74105,74107-74109,74111-74119,74121-74123,74126-74128,74130-74131,74134-74150,74152,74155,74157,74163-74173,74175-74190,74192-74194,74196-74197,74200-74201,74203-74220,74222-74235,74238-74241,74243,74245,74247-74256,74258-74262,74264-74270,74272-74282,74284-74312,74314-74398,74403,74405,74412,74443,74459 + + /python/branches/py3k:1-73579,73583-73588,73590,73592,73595-73596,73598-73603,73605-73610,73614-73615,73618-73619,73623-73625,73627,73630-73634,73636-73638,73640-73644,73652-73654,73656,73658-73663,73665-73675,73677,73679,73681-73686,73688-73699,73701-73715,73717-73718,73720-73728,73735-73736,73738,73741,73743-73745,73747-73758,73760-73763,73765-73776,73778-73779,73781-73802,73804-73806,73808-73816,73818-73819,73821-73823,73828,73833-73842,73846-73852,73854,73856-73857,73862-73865,73867-73872,73874,73882,73913,73917-73919,73923,73934,73941-73949,73951-73955,73957-73960,73962-73977,73979,73981-73982,73984-73986,73988-73991,73994-73995,73997-73998,74000-74002,74005-74008,74010-74011,74014,74019-74025,74027-74029,74031-74034,74038-74040,74042-74044,74046-74048,74051-74052,74054-74058,74062-74063,74065,74067,74069,74072,74074-74081,74083,74085-74089,74091-74095,74098,74100,74104-74105,74107-74109,74111-74119,74121-74123,74126-74128,74130-74131,74134-74150,74152,74155,74157,74163-74173,74175-74190,74192-74194,74196-74197,74200-74201,74203-74220,74222-74235,74238-74241,74243,74245,74247-74256,74258-74262,74264-74270,74272-74282,74284-74312,74314-74398,74403,74405,74412,74443,74459,74476,74535,74551,74566,74582,74584,74605,74609-74610,74612-74622,74624-74627,74631-74637,74640-74645,74647,74650-74653,74655-74658,74660,74662-74668,74670-74702,74704-74724,74726-74742,74745,74747-74750,74752-74754,74756-74764,74766-74774,74776-74825,74827-74833,74835-74850,74852-74854,74857,74859-74863,74865-74874,74876-74896,74898-74909,74911-74913,74915-74926,74928-74934,74936-74937,74941-74970,74972-74995,74997-75004,75006-75011,75013-75020,75022-75027,75029,75031-75044,75046-75050,75052-75077,75081,75083-75085,75087-75092,75094-75099,75101-75104,75106,75110-75112,75114-75117,75120-75127,75129-75157,75159-75160,75162,75164-75166,75168-75172,75174-75176,75178-75193,75195-75197,75199-75209,75211-75215,75217-75240,75246-75258,75260-75273,75275-75295,75299-75305,75307-75308,75312-75318,75321-75344,75346,75348,75350-75359,75373-75374,75393-75396,75398-75421,75423-75434,75436-75438,75440-75444,75446-75447,75449-75450,75452-75454,75456-75470,75472-75475,75477-75486,75489-75492,75494,75497-75499,75501-75503,75505-75507,75509-75511,75514-75521,75523-75525,75527-75537,75539-75541,75543-75555,75557-75572,75574-75585,75587-75600,75602-75621,75623-75624,75626-75648,75650-75651,75653-75655,75657-75660,75662-75664,75666,75669-75672,75674-75675,75677,75679,75681,75683,75685,75688-75697,75699-75702,75704-75708,75711,75713-75714,75717-75718,75720,75722,75724-75731,75734-75736,75739,75742-75743,75745,75747-75833,75835,75837-75838,75840-75842,75844,75846,75848-75849,75851,75853-75855,75857-75860,75862-75868,75871-75872,75874-75875,75877-75894,75896-75902,75904-75913,75915-75922,75928,75941,75947,75977,75984,75988,76010,76017,76036,76040,76043,76055 + --- python3.1-3.1.1.orig/debian/patches/disable-utimes.dpatch +++ python3.1-3.1.1/debian/patches/disable-utimes.dpatch @@ -0,0 +1,38 @@ +#! /bin/sh -e + +# DP: disable check for utimes function, which is broken in glibc-2.3.2 + +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 + autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + rm -f configure + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- configure.in~ 2003-07-24 00:17:27.000000000 +0200 ++++ configure.in 2003-08-10 11:10:00.000000000 +0200 +@@ -2051,7 +2051,7 @@ + setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ + sigaction siginterrupt sigrelse strftime strptime \ + sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ +- truncate uname unsetenv utimes waitpid wcscoll _getpty) ++ truncate uname unsetenv waitpid wcscoll _getpty) + + # For some functions, having a definition is not sufficient, since + # we want to take their address. --- python3.1-3.1.1.orig/debian/patches/locale-module.dpatch +++ python3.1-3.1.1/debian/patches/locale-module.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +# DP: * Lib/locale.py: +# DP: - Don't map 'utf8', 'utf-8' to 'utf', which is not a known encoding +# DP: for glibc. + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/locale.py~ 2006-04-02 19:06:02.349667000 +0200 ++++ Lib/locale.py 2006-04-02 19:14:00.509667000 +0200 +@@ -1170,8 +1170,8 @@ + 'uk_ua.iso88595': 'uk_UA.ISO8859-5', + 'uk_ua.koi8u': 'uk_UA.KOI8-U', + 'uk_ua.microsoftcp1251': 'uk_UA.CP1251', +- 'univ': 'en_US.utf', +- 'universal': 'en_US.utf', ++ 'univ': 'en_US.UTF-8', ++ 'universal': 'en_US.UTF-8', + 'universal.utf8@ucs4': 'en_US.UTF-8', + 'ur': 'ur_PK.CP1256', + 'ur_pk': 'ur_PK.CP1256', --- python3.1-3.1.1.orig/debian/patches/tkinter-import.dpatch +++ python3.1-3.1.1/debian/patches/tkinter-import.dpatch @@ -0,0 +1,39 @@ +#! /bin/sh -e + +# DP: suggest installation of python-tk package on failing _tkinter import + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/tkinter/__init__.py~ 2008-05-30 13:47:28.000000000 +0200 ++++ Lib/tkinter/__init__.py 2008-05-30 13:57:04.000000000 +0200 +@@ -36,7 +36,10 @@ + if sys.platform == "win32": + # Attempt to configure Tcl/Tk without requiring PATH + from tkinter import _fix +-import _tkinter # If this fails your Python may not be configured for Tk ++try: ++ import _tkinter ++except ImportError as msg: ++ raise ImportError(str(msg) + ', please install the python-tk package') + TclError = _tkinter.TclError + from tkinter.constants import * + try: --- python3.1-3.1.1.orig/debian/patches/deb-setup.dpatch +++ python3.1-3.1.1/debian/patches/deb-setup.dpatch @@ -0,0 +1,39 @@ +#! /bin/sh -e + +# DP: Don't include /usr/local/include and /usr/local/lib as gcc search paths + +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 + +--- setup.py~ 2009-06-21 22:40:40.000000000 +0200 ++++ setup.py 2009-06-21 22:41:42.000000000 +0200 +@@ -295,8 +295,9 @@ + + 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') + + # Add paths specified in the environment variables LDFLAGS and + # CPPFLAGS for header and library files. --- python3.1-3.1.1.orig/debian/patches/webbrowser.dpatch +++ python3.1-3.1.1/debian/patches/webbrowser.dpatch @@ -0,0 +1,50 @@ +#! /bin/sh -e + +# DP: Recognize other browsers: www-browser, x-www-browser, iceweasel, iceape. + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/webbrowser.py~ 2007-07-04 15:50:53.000000000 +0200 ++++ Lib/webbrowser.py 2007-08-31 16:11:12.000000000 +0200 +@@ -453,9 +453,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)) +@@ -493,6 +497,8 @@ + + # Also try console browsers + if os.environ.get("TERM"): ++ if _iscommand("www-browser"): ++ register("www-browser", None, GenericBrowser("www-browser")) + # The Links/elinks browsers + if _iscommand("links"): + register("links", None, GenericBrowser("links")) --- python3.1-3.1.1.orig/debian/patches/bdist-wininst-notfound.dpatch +++ python3.1-3.1.1/debian/patches/bdist-wininst-notfound.dpatch @@ -0,0 +1,37 @@ +#! /bin/sh -e + +# DP: suggest installation of the pythonX.Y-dev package, if bdist_wininst +# DP: cannot find the wininst-* files. + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/distutils/command/bdist_wininst.py~ 2009-04-10 14:32:32.000000000 +0200 ++++ Lib/distutils/command/bdist_wininst.py 2009-06-22 14:05:59.000000000 +0200 +@@ -340,4 +340,7 @@ + sfix = '' + + filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix)) +- return open(filename, "rb").read() ++ try: ++ return open(filename, "rb").read() ++ except IOError as e: ++ raise DistutilsFileError(str(e) + ', please install the python%s-dev package' % sys.version[:3]) --- python3.1-3.1.1.orig/debian/patches/patchlevel.dpatch +++ python3.1-3.1.1/debian/patches/patchlevel.dpatch @@ -0,0 +1,49 @@ +#! /bin/sh -e + +# DP: Set HeadURL and PY_PATCHLEVEL_REVISION. + +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 + +--- Python/sysmodule.c~ 2006-10-29 11:48:50.000000000 +0100 ++++ Python/sysmodule.c 2006-10-29 12:26:53.000000000 +0100 +@@ -960,7 +960,7 @@ + + /* Subversion branch and revision management */ + static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION; +-static const char headurl[] = "$HeadURL: svn+ssh://pythondev@svn.python.org/python/tags/r25/Python/sysmodule.c $"; ++static const char headurl[] = "$HeadURL: svn+ssh://pythondev@svn.python.org/python/branches/release25-maint/Python/sysmodule.c $"; + static int svn_initialized; + static char patchlevel_revision[50]; /* Just the number */ + static char branch[50]; +--- Include/patchlevel.h~ 2006-09-18 08:51:50.000000000 +0200 ++++ Include/patchlevel.h 2006-10-29 12:33:07.000000000 +0100 +@@ -29,7 +29,7 @@ + #define PY_VERSION "2.5" + + /* Subversion Revision number of this file (not of the repository) */ +-#define PY_PATCHLEVEL_REVISION "$Revision: 54692 $" ++#define PY_PATCHLEVEL_REVISION "$Revision: 54692 $" + + /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. + Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */ --- python3.1-3.1.1.orig/debian/patches/platform-lsbrelease.dpatch +++ python3.1-3.1.1/debian/patches/platform-lsbrelease.dpatch @@ -0,0 +1,64 @@ +#! /bin/sh -e + +# DP: Use /etc/lsb-release to identify the platform. + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/platform.py.orig 2008-10-25 17:49:17.000000000 +0200 ++++ Lib/platform.py 2009-03-19 10:50:23.000000000 +0100 +@@ -266,6 +266,10 @@ + id = '' + 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, +@@ -290,6 +294,25 @@ + args given as parameters. + + """ ++ # check for the Debian/Ubuntu /etc/lsb-release file first, needed so ++ # that the distribution doesn't get identified as Debian. ++ try: ++ etclsbrel = open("/etc/lsb-release", "rU") ++ for line in etclsbrel: ++ m = _distributor_id_file_re.search(line) ++ if m: ++ _u_distname = m.group(1).strip() ++ m = _release_file_re.search(line) ++ if m: ++ _u_version = m.group(1).strip() ++ m = _codename_file_re.search(line) ++ if m: ++ _u_id = m.group(1).strip() ++ if _u_distname and _u_version: ++ return (_u_distname, _u_version, _u_id) ++ except (EnvironmentError, UnboundLocalError): ++ pass ++ + try: + etc = os.listdir('/etc') + except os.error: --- python3.1-3.1.1.orig/debian/patches/langpack-gettext.dpatch +++ python3.1-3.1.1/debian/patches/langpack-gettext.dpatch @@ -0,0 +1,64 @@ +#! /bin/sh -e +## langpack-gettext.dpatch by +# +# 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 +#! /bin/sh /usr/share/dpatch/dpatch-run +## langpack-gettext.dpatch by +## +## All lines beginning with `## DP:' are a description of the patch. +## DP: Support language packs with pythons gettext implementation + +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 -p1 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p1 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +diff -urNad python2.4-2.4.3~/Lib/gettext.py python2.4-2.4.3/Lib/gettext.py +--- python2.4-2.4.3~/Lib/gettext.py 2004-07-22 20:44:01.000000000 +0200 ++++ python2.4-2.4.3/Lib/gettext.py 2006-08-18 12:49:07.000000000 +0200 +@@ -433,11 +433,26 @@ + if lang == 'C': + break + mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) ++ mofile_lp = os.path.join("/usr/share/locale-langpack", lang, ++ 'LC_MESSAGES', '%s.mo' % domain) ++ ++ # first look into the standard locale dir, then into the ++ # langpack locale dir ++ ++ # standard mo file + if os.path.exists(mofile): + if all: + result.append(mofile) + else: + return mofile ++ ++ # langpack mofile -> use it ++ if os.path.exists(mofile_lp): ++ if all: ++ result.append(mofile_lp) ++ else: ++ return mofile_lp ++ + return result + + --- python3.1-3.1.1.orig/debian/patches/arm-float.dpatch +++ python3.1-3.1.1/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); + } --- python3.1-3.1.1.orig/debian/patches/template.dpatch +++ python3.1-3.1.1/debian/patches/template.dpatch @@ -0,0 +1,30 @@ +#! /bin/sh -e + +# All lines beginning with `# DPATCH:' are a description of the patch. +# DP: + +# remove the next line +exit 0 + +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 + +# append the patch here and adjust the -p? flag in the patch calls. --- python3.1-3.1.1.orig/debian/patches/doc-faq.dpatch +++ python3.1-3.1.1/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 @@ +
      + + ++ ++ ++   ++ ++ ++ ++   ++ ++ ++ + + +

      --- python3.1-3.1.1.orig/debian/patches/test-sundry.dpatch +++ python3.1-3.1.1/debian/patches/test-sundry.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +# DP: test_sundry: Don't fail on import of the profile and pstats module + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/test/test_sundry.py~ 2008-05-29 16:59:25.000000000 +0200 ++++ Lib/test/test_sundry.py 2008-05-29 17:00:12.000000000 +0200 +@@ -58,7 +58,11 @@ + import opcode + import os2emxpath + import pdb +- 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 rlcompleter + import sched --- python3.1-3.1.1.orig/debian/patches/enable-fpectl.dpatch +++ python3.1-3.1.1/debian/patches/enable-fpectl.dpatch @@ -0,0 +1,37 @@ +#! /bin/sh -e + +# DP: Enable the build of the fpectl module. + +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 + +--- setup.py~ 2005-01-04 18:23:29.000000000 +0100 ++++ setup.py 2005-01-04 18:52:18.000000000 +0100 +@@ -689,6 +689,9 @@ + libraries = ['panel'] + curses_libs) ) + + ++ #fpectl fpectlmodule.c ... ++ exts.append( Extension('fpectl', ['fpectlmodule.c']) ) ++ + # Andrew Kuchling's zlib module. Note that some versions of zlib + # 1.1.3 have security problems. See CERT Advisory CA-2002-07: + # http://www.cert.org/advisories/CA-2002-07.html --- python3.1-3.1.1.orig/debian/patches/site-builddir.diff +++ python3.1-3.1.1/debian/patches/site-builddir.diff @@ -0,0 +1,32 @@ +--- site.py~ 2008-05-23 11:11:59.000000000 +0000 ++++ site.py 2008-05-23 11:22:03.000000000 +0000 +@@ -111,19 +111,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 distutils.util 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[-1]), s) +- sys.path.append(s) +- +- + def _init_pathinfo(): + """Return a set containing all existing directory entries from sys.path""" + d = set() +@@ -495,9 +482,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) --- python3.1-3.1.1.orig/debian/patches/setup-modules.dpatch +++ python3.1-3.1.1/debian/patches/setup-modules.dpatch @@ -0,0 +1,87 @@ +#! /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.orig 2009-06-21 22:58:14.000000000 +0200 ++++ Modules/_elementtree.c 2009-06-21 22:58:42.000000000 +0200 +@@ -1838,7 +1838,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.orig 2009-06-04 09:30:30.000000000 +0000 ++++ Modules/Setup.dist 2009-10-11 18:38:17.242108724 +0000 +@@ -168,7 +168,7 @@ + #_collections _collectionsmodule.c # Container types + #itertools itertoolsmodule.c # Functions creating iterators for efficient looping + #atexit atexitmodule.c # Register functions to be run at interpreter-shutdown +-#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI _elementtree.c # elementtree accelerator ++#_elementtree -I$(srcdir)/Modules/expat -DHAVE_EXPAT_CONFIG_H _elementtree.c # elementtree accelerator + #_pickle _pickle.c # pickle accelerator + #datetime datetimemodule.c # date/time type + #_bisect _bisectmodule.c # Bisection algorithms +@@ -197,10 +197,7 @@ + + # Socket module helper for SSL support; you must comment out the other + # socket line above, and possibly edit the SSL variable: +-#SSL=/usr/local/ssl +-#_ssl _ssl.c \ +-# -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ +-# -L$(SSL)/lib -lssl -lcrypto ++#_ssl _ssl.c -lssl -lcrypto + + # The crypt module is now disabled by default because it breaks builds + # on many systems (where -lcrypt is needed), e.g. Linux (I believe). +@@ -242,6 +239,7 @@ + #_sha256 sha256module.c + #_sha512 sha512module.c + ++#_hashlib _hashopenssl.c -lssl -lcrypto + + # The _tkinter module. + # +@@ -330,6 +328,7 @@ + # Fred Drake's interface to the Python parser + #parser parsermodule.c + ++#_ctypes _ctypes/_ctypes.c _ctypes/callbacks.c _ctypes/callproc.c _ctypes/stgdict.c _ctypes/cfield.c _ctypes/malloc_closure.c -Wl,-Bstatic -lffi -Wl,-Bdynamic + + # Lee Busby's SIGFPE modules. + # The library to link fpectl with is platform specific. +@@ -364,7 +363,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 + --- python3.1-3.1.1.orig/debian/patches/subprocess-eintr-safety.dpatch +++ python3.1-3.1.1/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) --- python3.1-3.1.1.orig/debian/patches/distutils-link.dpatch +++ python3.1-3.1.1/debian/patches/distutils-link.dpatch @@ -0,0 +1,42 @@ +#! /bin/sh -e + +# DP: Don't add standard library dirs to library_dirs and runtime_library_dirs. + +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/distutils/unixccompiler.py~ 2007-08-31 21:38:37.000000000 +0200 ++++ Lib/distutils/unixccompiler.py 2007-08-31 21:42:54.000000000 +0200 +@@ -209,6 +209,13 @@ + runtime_library_dirs) + libraries, library_dirs, runtime_library_dirs = fixed_args + ++ # filter out standard library paths, which are not explicitely needed ++ # for linking ++ library_dirs = [dir for dir in library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] ++ runtime_library_dirs = [dir for dir in runtime_library_dirs ++ if not dir in ('/lib', '/lib64', '/usr/lib', '/usr/lib64')] ++ + lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, + libraries) + if not isinstance(output_dir, (basestring, type(None))): --- python3.1-3.1.1.orig/debian/patches/no-large-file-support.dpatch +++ python3.1-3.1.1/debian/patches/no-large-file-support.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +# DP: disable large file support for GNU/Hurd + +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 -p1 < $0 + autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p1 < $0 + rm -f configure + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +diff -ru python2.3-2.3.2.orig/configure.in python2.3-2.3.2/configure.in +--- python2.3-2.3.2.orig/configure.in 2003-09-25 17:21:00.000000000 +0200 ++++ python2.3-2.3.2/configure.in 2003-10-05 09:38:36.000000000 +0200 +@@ -970,6 +970,9 @@ + use_lfs=no + fi + ++# Don't use largefile support anyway. ++use_lfs=no ++ + if test "$use_lfs" = "yes"; then + # Two defines needed to enable largefile support on various platforms + # These may affect some typedefs --- python3.1-3.1.1.orig/debian/patches/apport-support.dpatch +++ python3.1-3.1.1/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() + --- python3.1-3.1.1.orig/debian/patches/doc-nodownload.dpatch +++ python3.1-3.1.1/debian/patches/doc-nodownload.dpatch @@ -0,0 +1,36 @@ +#! /bin/sh -e + +# DP: Don't try to download documentation tools + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Doc/Makefile~ 2008-04-13 22:51:27.000000000 +0200 ++++ Doc/Makefile 2008-05-29 18:50:41.000000000 +0200 +@@ -49,7 +49,7 @@ + svn update tools/jinja + svn update tools/pygments + +-build: checkout ++build: + mkdir -p build/$(BUILDER) build/doctrees + $(PYTHON) tools/sphinx-build.py $(ALLSPHINXOPTS) + @echo --- python3.1-3.1.1.orig/debian/patches/deb-locations.dpatch +++ python3.1-3.1.1/debian/patches/deb-locations.dpatch @@ -0,0 +1,109 @@ +#! /bin/sh -e + +# DP: adjust locations of directories to debian policy + +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 -p1 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p1 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- ./Lib/pydoc.py~ 2008-07-15 15:01:17.000000000 +0200 ++++ ./Lib/pydoc.py 2008-07-15 15:31:06.000000000 +0200 +@@ -27,6 +27,10 @@ + + Module docs for core modules are assumed to be in + ++ /usr/share/doc/pythonX.Y/html/library ++ ++if the pythonX.Y-doc package is installed or in ++ + http://docs.python.org/library/ + + This can be overridden by setting the PYTHONDOCS environment variable +@@ -347,6 +351,9 @@ + + docloc = os.environ.get("PYTHONDOCS", + "http://docs.python.org/library") ++ docdir = '/usr/share/doc/python%s/html/library' % sys.version[:3] ++ if "PYTHONDOCS" not in os.environ and os.path.isdir(docdir): ++ docloc = docdir + basedir = os.path.join(sys.exec_prefix, "lib", + "python"+sys.version[0:3]) + if (isinstance(object, type(os)) and +--- ./Tools/faqwiz/faqconf.py.orig 2008-05-22 17:50:31.000000000 +0200 ++++ ./Tools/faqwiz/faqconf.py 2008-05-22 17:51:11.000000000 +0200 +@@ -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 +--- ./Tools/webchecker/webchecker.py.orig 2008-05-22 17:50:31.000000000 +0200 ++++ ./Tools/webchecker/webchecker.py 2008-05-22 17:51:11.000000000 +0200 +@@ -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: +--- ./Demo/tkinter/guido/ManPage.py.orig 2008-05-22 17:50:31.000000000 +0200 ++++ ./Demo/tkinter/guido/ManPage.py 2008-05-22 17:51:11.000000000 +0200 +@@ -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': +--- ./Demo/tkinter/guido/tkman.py.orig 2008-05-22 17:50:31.000000000 +0200 ++++ ./Demo/tkinter/guido/tkman.py 2008-05-22 17:51:11.000000000 +0200 +@@ -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: +--- ./Misc/python.man.orig 2008-05-22 17:50:31.000000000 +0200 ++++ ./Misc/python.man 2008-05-22 17:51:11.000000000 +0200 +@@ -294,7 +294,7 @@ + These are subject to difference depending on local installation + conventions; ${prefix} and ${exec_prefix} are installation-dependent + and should be interpreted as for GNU software; they may be the same. +-The default for both is \fI/usr/local\fP. ++On Debian GNU/{Hurd,Linux} the default for both is \fI/usr\fP. + .IP \fI${exec_prefix}/bin/python\fP + Recommended location of the interpreter. + .PP --- python3.1-3.1.1.orig/debian/patches/distutils-sysconfig.dpatch +++ python3.1-3.1.1/debian/patches/distutils-sysconfig.dpatch @@ -0,0 +1,56 @@ +#! /bin/sh -e + +# DP: Allow setting BASECFLAGS, OPT and EXTRA_LDFLAGS (like, CC, CXX, CPP, +# DP: CFLAGS, CPPFLAGS, CCSHARED, LDSHARED) from the environment. + +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/distutils/sysconfig.py~ 2009-06-21 22:43:23.000000000 +0200 ++++ Lib/distutils/sysconfig.py 2009-06-21 22:47:40.000000000 +0200 +@@ -160,8 +160,9 @@ + varies across Unices and is stored in Python's Makefile. + """ + if compiler.compiler_type == "unix": +- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ ++ (cc, cxx, opt, cflags, extra_cflags, basecflags, ccshared, ldshared, so_ext, ar, ar_flags) = \ + get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', ++ 'EXTRA_CFLAGS', 'BASECFLAGS', + 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS') + + if 'CC' in os.environ: +@@ -176,8 +177,13 @@ + cpp = cc + " -E" # not always + if 'LDFLAGS' in os.environ: + ldshared = ldshared + ' ' + os.environ['LDFLAGS'] ++ if 'BASECFLAGS' in os.environ: ++ basecflags = os.environ['BASECFLAGS'] ++ if 'OPT' in os.environ: ++ opt = os.environ['OPT'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, extra_cflags) if x) + if 'CFLAGS' in os.environ: +- cflags = opt + ' ' + os.environ['CFLAGS'] ++ cflags = ' '.join(str(x) for x in (basecflags, opt, os.environ['CFLAGS'], extra_cflags) if x) + ldshared = ldshared + ' ' + os.environ['CFLAGS'] + if 'CPPFLAGS' in os.environ: + cpp = cpp + ' ' + os.environ['CPPFLAGS'] --- python3.1-3.1.1.orig/debian/patches/pydebug-path.dpatch +++ python3.1-3.1.1/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': --- python3.1-3.1.1.orig/debian/patches/distutils-install-layout.dpatch +++ python3.1-3.1.1/debian/patches/distutils-install-layout.dpatch @@ -0,0 +1,252 @@ +#! /bin/sh -e + +# 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. + +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 -p1 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p1 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- ./Lib/site.py.orig 2009-06-21 23:22:47.000000000 +0200 ++++ ./Lib/site.py 2009-06-22 14:50:41.000000000 +0200 +@@ -248,6 +248,13 @@ + + if ENABLE_USER_SITE and os.path.isdir(USER_SITE): + addsitedir(USER_SITE, known_paths) ++ if ENABLE_USER_SITE: ++ for dist_libdir in ("lib", "local/lib"): ++ user_site = os.path.join(USER_BASE, dist_libdir, ++ "python" + sys.version[:3], ++ "dist-packages") ++ if os.path.isdir(user_site): ++ addsitedir(user_site, known_paths) + return known_paths + + +--- ./Lib/distutils/command/install_egg_info.py.orig 2009-06-22 14:32:27.000000000 +0200 ++++ ./Lib/distutils/command/install_egg_info.py 2009-06-22 14:45:49.000000000 +0200 +@@ -14,18 +14,38 @@ + description = "Install package's PKG-INFO metadata as an .egg-info file" + user_options = [ + ('install-dir=', 'd', "directory to install to"), ++ ('install-layout', None, "custom installation layout"), + ] + + def initialize_options(self): + self.install_dir = None ++ self.install_layout = None ++ self.prefix_option = None + + def finalize_options(self): + self.set_undefined_options('install_lib',('install_dir','install_dir')) +- basename = "%s-%s-py%s.egg-info" % ( +- to_filename(safe_name(self.distribution.get_name())), +- to_filename(safe_version(self.distribution.get_version())), +- sys.version[:3] +- ) ++ self.set_undefined_options('install',('install_layout','install_layout')) ++ self.set_undefined_options('install',('prefix_option','prefix_option')) ++ if self.install_layout: ++ if not self.install_layout.lower() in ['deb', 'unix']: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ no_pyver = (self.install_layout.lower() == 'deb') ++ elif self.prefix_option: ++ no_pyver = False ++ else: ++ no_pyver = True ++ if no_pyver: ++ basename = "%s-%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())) ++ ) ++ else: ++ basename = "%s-%s-py%s.egg-info" % ( ++ to_filename(safe_name(self.distribution.get_name())), ++ to_filename(safe_version(self.distribution.get_version())), ++ sys.version[:3] ++ ) + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] + +--- ./Lib/distutils/command/install.py.orig 2009-06-22 15:18:17.000000000 +0200 ++++ ./Lib/distutils/command/install.py 2009-11-02 13:06:24.338293149 +0100 +@@ -52,6 +52,20 @@ + 'scripts': '$base/bin', + 'data' : '$base', + }, ++ 'unix_local': { ++ 'purelib': '$base/local/lib/python$py_version_short/dist-packages', ++ 'platlib': '$platbase/local/lib/python$py_version_short/dist-packages', ++ 'headers': '$base/local/include/python$py_version_short/$dist_name', ++ 'scripts': '$base/local/bin', ++ 'data' : '$base/local', ++ }, ++ 'deb_system': { ++ 'purelib': '$base/lib/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', +@@ -178,6 +192,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'] +@@ -198,6 +215,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 +@@ -219,6 +237,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 + +@@ -452,6 +473,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( +@@ -466,7 +488,23 @@ + + self.install_base = self.prefix + self.install_platbase = self.exec_prefix +- self.select_scheme("unix_prefix") ++ if self.install_layout: ++ if self.install_layout.lower() in ['deb']: ++ self.select_scheme("deb_system") ++ elif self.install_layout.lower() in ['unix']: ++ self.select_scheme("unix_prefix") ++ else: ++ raise DistutilsOptionError( ++ "unknown value for --install-layout") ++ elif (self.prefix_option and os.path.normpath(self.prefix) != '/usr/local') \ ++ or 'PYTHONUSERBASE' in os.environ \ ++ or 'real_prefix' in sys.__dict__: ++ self.select_scheme("unix_prefix") ++ else: ++ if os.path.normpath(self.prefix) == '/usr/local': ++ self.prefix = self.exec_prefix = '/usr' ++ self.install_base = self.install_platbase = '/usr' ++ self.select_scheme("unix_local") + + def finalize_other(self): + """Finalizes options for non-posix platforms""" +--- ./Lib/distutils/sysconfig.py.orig 2009-06-22 14:32:27.000000000 +0200 ++++ ./Lib/distutils/sysconfig.py 2009-06-22 14:48:54.000000000 +0200 +@@ -114,6 +114,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 + +@@ -122,6 +123,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") + elif os.name == "nt": +--- ./Doc/install/index.rst.orig 2009-01-04 13:58:29.000000000 +0100 ++++ ./Doc/install/index.rst 2009-06-22 14:54:10.000000000 +0200 +@@ -237,6 +237,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) | +@@ -246,6 +248,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 +@@ -364,6 +374,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 +@@ -602,6 +621,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 --- python3.1-3.1.1.orig/debian/patches/link-opt.dpatch +++ python3.1-3.1.1/debian/patches/link-opt.dpatch @@ -0,0 +1,47 @@ +#! /bin/sh -e + +# DP: Call the linker with -O1 -Bsymbolic-functions + +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 + autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + rm -f configure + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- configure.in~ 2008-07-15 15:37:42.000000000 +0200 ++++ configure.in 2008-07-15 15:39:53.000000000 +0200 +@@ -1659,7 +1659,7 @@ + fi + fi + ;; +- Linux*|GNU*|QNX*) LDSHARED='$(CC) -shared';; ++ Linux*|GNU*|QNX*) LDSHARED='$(CC) -shared -Wl,-O1 -Wl,-Bsymbolic-functions';; + BSD/OS*/4*) LDSHARED="gcc -shared";; + FreeBSD*) + if [[ "`$CC -dM -E - &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 + +Index: Doc/tools/sphinxext/pyspecific.py +=================================================================== +--- Doc/tools/sphinxext/pyspecific.py (Revision 68983) ++++ Doc/tools/sphinxext/pyspecific.py (Revision 68984) +@@ -48,10 +48,17 @@ + from docutils.io import StringOutput + from docutils.utils import new_document + +-from sphinx.builders import Builder +-from sphinx.writers.text import TextWriter ++try: ++ from sphinx.builders import Builder ++except ImportError: ++ from sphinx.builder import Builder + ++try: ++ from sphinx.writers.text import TextWriter ++except ImportError: ++ from sphinx.textwriter import TextWriter + ++ + class PydocTopicsBuilder(Builder): + name = 'pydoc-topics' + +Index: Doc/tools/sphinxext/suspicious.py +=================================================================== +--- Doc/tools/sphinxext/suspicious.py (Revision 68983) ++++ Doc/tools/sphinxext/suspicious.py (Revision 68984) +@@ -45,8 +45,13 @@ + import csv + import re + from docutils import nodes +-from sphinx.builders import Builder + ++try: ++ from sphinx.builders import Builder ++except ImportError: ++ from sphinx.builder import Builder ++ ++ + detect_all = re.compile(ur''' + ::(?=[^=])| # two :: (but NOT ::=) + :[a-zA-Z][a-zA-Z0-9]+| # :foo --- python3.1-3.1.1.orig/debian/patches/egg-info-no-version.dpatch +++ python3.1-3.1.1/debian/patches/egg-info-no-version.dpatch @@ -0,0 +1,40 @@ +#! /bin/sh -e + +# DP: distutils: Do not encode the python version into the .egg-info name. + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/distutils/command/install_egg_info.py~ 2007-02-16 16:57:19.000000000 +0100 ++++ Lib/distutils/command/install_egg_info.py 2007-03-05 11:18:29.000000000 +0100 +@@ -21,10 +21,9 @@ + + def finalize_options(self): + self.set_undefined_options('install_lib',('install_dir','install_dir')) +- basename = "%s-%s-py%s.egg-info" % ( ++ basename = "%s-%s.egg-info" % ( + to_filename(safe_name(self.distribution.get_name())), +- to_filename(safe_version(self.distribution.get_version())), +- sys.version[:3] ++ to_filename(safe_version(self.distribution.get_version())) + ) + self.target = os.path.join(self.install_dir, basename) + self.outputs = [self.target] --- python3.1-3.1.1.orig/debian/patches/cthreads.dpatch +++ python3.1-3.1.1/debian/patches/cthreads.dpatch @@ -0,0 +1,65 @@ +#! /bin/sh -e + +# DP: Remove cthreads detection + +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 + autoconf + autoheader + ;; + -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 + +--- configure.in~ 2004-06-14 23:29:15.000000000 +0200 ++++ configure.in 2004-06-14 23:33:13.000000000 +0200 +@@ -1527,7 +1527,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, +@@ -1608,17 +1607,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], + AC_HELP_STRING(--with-pth, use GNU pth threading libraries), +@@ -1673,7 +1661,7 @@ + LIBS="$LIBS -lcma" + THREADOBJ="Python/thread.o"],[ + USE_THREAD_MODULE="#"]) +- ])])])])])])])])])]) ++ ])])])])])])])]) + + AC_CHECK_LIB(mpc, usconfig, [AC_DEFINE(WITH_THREAD) + LIBS="$LIBS -lmpc" --- python3.1-3.1.1.orig/debian/patches/no-zip-on-sys.path.dpatch +++ python3.1-3.1.1/debian/patches/no-zip-on-sys.path.dpatch @@ -0,0 +1,75 @@ +#! /bin/sh -e + +# DP: Do not add /usr/lib/pythonXY.zip on sys.path. + +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~ 2009-02-17 00:44:45.000000000 +0100 ++++ Modules/getpath.c 2009-06-22 14:24:04.000000000 +0200 +@@ -442,7 +442,9 @@ + wchar_t *path = NULL; + wchar_t *prog = Py_GetProgramName(); + wchar_t argv0_path[MAXPATHLEN+1]; ++#ifdef WITH_ZIP_PATH + wchar_t zip_path[MAXPATHLEN+1]; ++#endif + int pfound, efound; /* 1 if found; -1 if found build directory */ + wchar_t *buf; + size_t bufsz; +@@ -595,6 +597,7 @@ + else + reduce(prefix); + ++#ifdef WITH_ZIP_PATH + wcsncpy(zip_path, prefix, MAXPATHLEN); + zip_path[MAXPATHLEN] = L'\0'; + if (pfound > 0) { /* Use the reduced prefix returned by Py_GetPrefix() */ +@@ -607,6 +610,7 @@ + bufsz = wcslen(zip_path); /* Replace "00" with version */ + zip_path[bufsz - 6] = VERSION[0]; + zip_path[bufsz - 5] = VERSION[2]; ++#endif + + if (!(efound = search_for_exec_prefix(argv0_path, home))) { + if (!Py_FrozenFlag) +@@ -652,7 +656,9 @@ + defpath = delim + 1; + } + ++#ifdef WITH_ZIP_PATH + bufsz += wcslen(zip_path) + 1; ++#endif + bufsz += wcslen(exec_prefix) + 1; + + /* This is the only malloc call in this file */ +@@ -673,9 +679,11 @@ + else + buf[0] = '\0'; + ++#ifdef WITH_ZIP_PATH + /* Next is the default zip path */ + wcscat(buf, zip_path); + wcscat(buf, delimiter); ++#endif + + /* Next goes merge of compile-time $PYTHONPATH with + * dynamically located prefix. --- python3.1-3.1.1.orig/debian/patches/linecache.dpatch +++ python3.1-3.1.1/debian/patches/linecache.dpatch @@ -0,0 +1,39 @@ +#! /bin/sh -e + +# DP: Proper handling of packages in linecache.py + +dir= +if [ $# -eq 3 -a "$2" = '-d' ]; then + pdir="-d $3" + dir="$3/" +elif [ $# -ne 1 ]; then + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +fi +case "$1" in + -patch) + patch $pdir -f --no-backup-if-mismatch -p0 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p0 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- Lib/linecache.py~ 2009-06-21 22:55:02.000000000 +0200 ++++ Lib/linecache.py 2009-06-21 22:56:05.000000000 +0200 +@@ -109,6 +109,11 @@ + if os.path.isabs(filename): + return [] + ++ # Take care to handle packages. ++ if basename == '__init__.py': ++ # filename referes to a package ++ basename = filename ++ + for dirname in sys.path: + try: + fullname = os.path.join(dirname, basename) --- python3.1-3.1.1.orig/debian/patches/debug-build.dpatch +++ python3.1-3.1.1/debian/patches/debug-build.dpatch @@ -0,0 +1,187 @@ +#! /bin/sh -e + +# 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). + +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 -p1 < $0 + autoconf + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p1 < $0 + rm -f configure + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- ./Python/sysmodule.c.orig 2009-05-28 11:24:38.000000000 +0200 ++++ ./Python/sysmodule.c 2009-06-21 22:52:05.000000000 +0200 +@@ -1436,6 +1436,12 @@ + PyUnicode_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; +--- ./Python/dynload_shlib.c.orig 2008-06-14 08:18:10.000000000 +0200 ++++ ./Python/dynload_shlib.c 2009-06-21 22:52:05.000000000 +0200 +@@ -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 +--- ./Lib/distutils/command/build.py.orig 2008-05-29 15:43:16.000000000 +0200 ++++ ./Lib/distutils/command/build.py 2009-06-21 22:52:05.000000000 +0200 +@@ -92,7 +92,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) +--- ./Lib/distutils/sysconfig.py.orig 2009-06-21 22:50:28.000000000 +0200 ++++ ./Lib/distutils/sysconfig.py 2009-06-21 22:52:05.000000000 +0200 +@@ -83,7 +83,8 @@ + else: + incdir = os.path.join(get_config_var('srcdir'), 'Include') + return os.path.normpath(incdir) +- 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 == "mac": +@@ -231,7 +232,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): +--- ./Makefile.pre.in.orig 2009-06-14 19:29:12.000000000 +0200 ++++ ./Makefile.pre.in 2009-06-21 22:53:14.000000000 +0200 +@@ -99,8 +99,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 +@@ -113,6 +113,8 @@ + EXE= @EXEEXT@ + BUILDEXE= @BUILDEXEEXT@ + ++DEBUG_EXT= @DEBUG_EXT@ ++ + # Short name and location for Mac OS X Python framework + UNIVERSALSDK=@UNIVERSALSDK@ + PYTHONFRAMEWORK= @PYTHONFRAMEWORK@ +@@ -433,7 +435,7 @@ + $(AR) $(ARFLAGS) $@ $(MODOBJS) + $(RANLIB) $@ + +-libpython$(VERSION).so: $(LIBRARY_OBJS) ++libpython$(VERSION)$(DEBUG_EXT).so: $(LIBRARY_OBJS) + if test $(INSTSONAME) != $(LDLIBRARY); then \ + $(LDSHARED) $(LDFLAGS) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \ + $(LN) -f $(INSTSONAME) $@; \ +@@ -957,8 +959,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 +--- ./configure.in.orig 2009-06-21 22:50:28.000000000 +0200 ++++ ./configure.in 2009-06-21 22:52:05.000000000 +0200 +@@ -547,7 +547,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) + +@@ -691,8 +691,8 @@ + INSTSONAME="$LDLIBRARY".$SOVERSION + ;; + Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*) +- 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*) +@@ -796,6 +796,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? + +@@ -1563,7 +1569,7 @@ + esac + ;; + CYGWIN*) SO=.dll;; +- *) SO=.so;; ++ *) SO=$DEBUG_EXT.so;; + esac + else + # this might also be a termcap variable, see #610332 +--- ./Misc/python-config.in.orig 2008-05-29 15:42:59.000000000 +0200 ++++ ./Misc/python-config.in 2009-06-21 22:52:05.000000000 +0200 +@@ -44,7 +44,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' and not getvar('Py_ENABLE_SHARED'): --- python3.1-3.1.1.orig/debian/patches/site-locations.dpatch +++ python3.1-3.1.1/debian/patches/site-locations.dpatch @@ -0,0 +1,54 @@ +#! /bin/sh -e + +# DP: Set site-packages/dist-packages + +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 -p1 < $0 + ;; + -unpatch) + patch $pdir -f --no-backup-if-mismatch -R -p1 < $0 + ;; + *) + echo >&2 "usage: `basename $0`: -patch|-unpatch [-d ]" + exit 1 +esac +exit 0 + +--- ./Lib/site.py.orig 2008-10-27 22:39:36.000000000 +0100 ++++ ./Lib/site.py 2008-10-27 22:42:36.000000000 +0100 +@@ -13,6 +13,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 +@@ -260,8 +266,11 @@ + elif os.sep == '/': + sitedirs.append(os.path.join(prefix, "lib", + "python" + sys.version[:3], +- "site-packages")) +- sitedirs.append(os.path.join(prefix, "lib", "site-python")) ++ "dist-packages")) ++ sitedirs.append(os.path.join(prefix, "local/lib", ++ "python" + sys.version[:3], ++ "dist-packages")) ++ sitedirs.append(os.path.join(prefix, "lib", "dist-python")) + else: + sitedirs.append(prefix) + sitedirs.append(os.path.join(prefix, "lib", "site-packages")) --- python3.1-3.1.1.orig/debian/patches/profiled-build.dpatch +++ python3.1-3.1.1/debian/patches/profiled-build.dpatch @@ -0,0 +1,41 @@ +#! /bin/sh -e + +# DP: Fix profiled build; don't use Python/thread.gc*, gcc complains. +# DP: Ignore errors in the profile task. + +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 + +--- Makefile.pre.in.orig 2008-11-18 22:37:15.000000000 +0000 ++++ Makefile.pre.in 2008-11-23 14:49:12.000000000 +0000 +@@ -368,9 +368,11 @@ + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-generate" LIBS="$(LIBS) -lgcov" + + run_profile_task: +- ./$(BUILDPYTHON) $(PROFILE_TASK) ++ -./$(BUILDPYTHON) $(PROFILE_TASK) + + build_all_use_profile: ++ : # FIXME: gcc error ++ rm -f Python/thread.gc* Modules/_ssl.gc* + $(MAKE) all CFLAGS="$(CFLAGS) -fprofile-use" + + coverage: --- python3.1-3.1.1.orig/debian/patches/profile-doc.dpatch +++ python3.1-3.1.1/debian/patches/profile-doc.dpatch @@ -0,0 +1,57 @@ +#! /bin/sh -e + +# DP: hotshot/pstats.py: Error out on missing profile/pstats modules. +# DP: Add a note to the library documentation, that the profile and pstats +# DP: modules can be found in the python2.x-profiler package. + +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/library/profile.rst~ 2008-04-18 20:39:55.000000000 +0200 ++++ Doc/library/profile.rst 2008-05-30 11:07:19.000000000 +0200 +@@ -5,6 +5,12 @@ + The Python Profilers + ******************** + ++Debian note: The license for the :mod:`profile` and :mod:`pstats` ++modules doesn't conform to the Debian Free Software Guidelines (DFSG). ++These modules can be found in the *python-profiler* package in the ++*non-free* section of the Debian archives or in the the *multiverse* ++section of the Ubuntu archives. ++ + .. sectionauthor:: James Roskind + + +@@ -241,6 +247,12 @@ + :synopsis: Python profiler + + ++Debian note: The license for the :mod:`profile` and :mod:`pstats` ++modules doesn't conform to the Debian Free Software Guidelines (DFSG). ++These modules can be found in the *python-profiler* package in the ++*non-free* section of the Debian archives or in the the *multiverse* ++section of the Ubuntu archives. ++ + The primary entry point for the profiler is the global function + :func:`profile.run` (resp. :func:`cProfile.run`). It is typically used to create + any profile information. The reports are formatted and printed using methods of